1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef CONTENT_PUBLIC_TEST_BROWSER_TEST_BASE_H_
6 #define CONTENT_PUBLIC_TEST_BROWSER_TEST_BASE_H_
7 
8 #include <memory>
9 
10 #include "base/callback.h"
11 #include "base/compiler_specific.h"
12 #include "base/metrics/field_trial.h"
13 #include "base/threading/thread.h"
14 #include "build/build_config.h"
15 #include "content/public/test/no_renderer_crashes_assertion.h"
16 #include "content/public/test/test_host_resolver.h"
17 #include "net/test/embedded_test_server/embedded_test_server.h"
18 #include "storage/browser/quota/quota_settings.h"
19 #include "testing/gtest/include/gtest/gtest.h"
20 
21 namespace base {
22 class CommandLine;
23 class FilePath;
24 }
25 
26 namespace content {
27 class BrowserMainParts;
28 class WebContents;
29 
30 class BrowserTestBase : public testing::Test {
31  public:
32   BrowserTestBase();
33   ~BrowserTestBase() override;
34 
35   // Configures everything for an in process browser test (e.g. thread pool,
36   // etc.) by invoking ContentMain (or manually on OS_ANDROID). As such all
37   // single-threaded initialization must be done before this step.
38   //
39   // ContentMain then ends up invoking RunTestOnMainThreadLoop with browser
40   // threads already running.
41   void SetUp() override;
42 
43   // Restores state configured in SetUp.
44   void TearDown() override;
45 
46   // Override this to add any custom setup code that needs to be done on the
47   // main thread after the browser is created and just before calling
48   // RunTestOnMainThread().
SetUpOnMainThread()49   virtual void SetUpOnMainThread() {}
50 
51   // Override this to add any custom teardown code that needs to be done on the
52   // main thread right after RunTestOnMainThread().
TearDownOnMainThread()53   virtual void TearDownOnMainThread() {}
54 
55   // Override this to add command line flags specific to your test.
SetUpCommandLine(base::CommandLine * command_line)56   virtual void SetUpCommandLine(base::CommandLine* command_line) {}
57 
58   // By default browser tests use hardcoded quota settings for consistency,
59   // instead of dynamically based on available disk space. Tests can override
60   // this if they want to use the production path.
61   virtual bool UseProductionQuotaSettings();
62 
63   // Crash the Network Service process. Should only be called when
64   // out-of-process Network Service is enabled. Re-applies any added host
65   // resolver rules, though network tasks started before the call returns may
66   // racily start before the rules have been re-applied.
67   void SimulateNetworkServiceCrash();
68 
69   // Returns the host resolver being used for the tests. Subclasses might want
70   // to configure it inside tests.
host_resolver()71   net::RuleBasedHostResolverProc* host_resolver() {
72     return test_host_resolver_ ? test_host_resolver_->host_resolver() : nullptr;
73   }
74 
75  protected:
76   // We need these special methods because SetUp is the bottom of the stack
77   // that winds up calling your test method, so it is not always an option
78   // to do what you want by overriding it and calling the superclass version.
79   //
80   // Override this for things you would normally override SetUp for. It will be
81   // called before your individual test fixture method is run, but after most
82   // of the overhead initialization has occured.
SetUpInProcessBrowserTestFixture()83   virtual void SetUpInProcessBrowserTestFixture() {}
84 
85   // Override this for things you would normally override TearDown for.
TearDownInProcessBrowserTestFixture()86   virtual void TearDownInProcessBrowserTestFixture() {}
87 
88   // Called after the BrowserMainParts have been created, and before
89   // PreEarlyInitialization() has been called.
CreatedBrowserMainParts(BrowserMainParts * browser_main_parts)90   virtual void CreatedBrowserMainParts(BrowserMainParts* browser_main_parts) {}
91 
92   // Sets flag to allow host resolutions to reach the network. Must be called
93   // before Setup() to take effect.
94   void SetAllowNetworkAccessToHostResolutions();
95 
96   // This is invoked from main after browser_init/browser_main have completed.
97   // This prepares for the test by creating a new browser and doing any other
98   // initialization.
99   // This is meant to be inherited only by the test harness.
100   virtual void PreRunTestOnMainThread() = 0;
101 
102   // Override this rather than TestBody.
103   // Note this is internally called by the browser test macros.
104   virtual void RunTestOnMainThread() = 0;
105 
106   // This is invoked from main after RunTestOnMainThread has run, to give the
107   // harness a chance for post-test cleanup.
108   // This is meant to be inherited only by the test harness.
109   virtual void PostRunTestOnMainThread() = 0;
110 
111   // Sets expected browser exit code, in case it's different than 0 (success).
set_expected_exit_code(int code)112   void set_expected_exit_code(int code) { expected_exit_code_ = code; }
113 
114   // Returns the embedded test server. Guaranteed to be non-NULL.
embedded_test_server()115   const net::EmbeddedTestServer* embedded_test_server() const {
116     return embedded_test_server_.get();
117   }
embedded_test_server()118   net::EmbeddedTestServer* embedded_test_server() {
119     return embedded_test_server_.get();
120   }
121 
set_up_called()122   bool set_up_called() { return set_up_called_; }
123 
124 #if defined(OS_POSIX)
125   // This is only needed by a test that raises SIGTERM to ensure that a specific
126   // codepath is taken.
DisableSIGTERMHandling()127   void DisableSIGTERMHandling() {
128     handle_sigterm_ = false;
129   }
130 #endif
131 
132   // This function is meant only for classes that directly derive from this
133   // class to construct the test server in their constructor. They might need to
134   // call this after setting up the paths. Actual test cases should never call
135   // this.
136   // |test_server_base| is the path, relative to src, to give to the test HTTP
137   // server.
138   void CreateTestServer(const base::FilePath& test_server_base);
139 
140   // When the test is running in --single-process mode, runs the given task on
141   // the in-process renderer thread. A nested run loop is run until it
142   // returns.
143   void PostTaskToInProcessRendererAndWait(base::OnceClosure task);
144 
145   // Call this before SetUp() to cause the test to generate pixel output. This
146   // function also sets a fixed device scale factor which a test can change.
147   // This is useful for consistent testing across devices with different
148   // display densities.
149   void EnablePixelOutput(float force_device_scale_factor = 1.f);
150 
151   // Call this before SetUp() to not use GL, but use software compositing
152   // instead.
153   void UseSoftwareCompositing();
154 
155   // Returns true if the test will be using GL acceleration via a software GL.
156   bool UsingSoftwareGL() const;
157 
158   // Should be in PreRunTestOnMainThread, with the initial WebContents for the
159   // main window. This allows the test harness to watch it for navigations so
160   // that it can sync the host_resolver() rules to the out-of-process network
161   // code necessary.
162   void SetInitialWebContents(WebContents* web_contents);
163 
164  private:
165 #if defined(OS_ANDROID)
166   // Android browser tests need to wait for async initialization in Java code.
167   // This waits for those to complete before we can continue with the test.
168   void WaitUntilJavaIsReady(base::OnceClosure quit_closure);
169 #endif
170   // Performs a bunch of setup, and then runs the browser test body.
171   void ProxyRunTestOnMainThreadLoop();
172 
173   // When using the network process, update the host resolver rules that were
174   // added in SetUpOnMainThread.
175   void InitializeNetworkProcess();
176 
177   // Embedded test server, cheap to create, started on demand.
178   std::unique_ptr<net::EmbeddedTestServer> embedded_test_server_;
179 
180   // Host resolver used during tests.
181   std::unique_ptr<TestHostResolver> test_host_resolver_;
182 
183   // A field trial list that's used to support field trials activated prior to
184   // browser start.
185   std::unique_ptr<base::FieldTrialList> field_trial_list_;
186 
187   // Expected exit code.
188   int expected_exit_code_ = 0;
189 
190   // When true, the compositor will produce pixel output that can be read back
191   // for pixel tests.
192   bool enable_pixel_output_ = false;
193 
194   // When using EnablePixelOutput, the device scale factor is forced to an
195   // explicit value to ensure consistent results. This value will be passed to
196   // the --force-device-scale-factor flag in SetUp.
197   float force_device_scale_factor_ = 0.f;
198 
199   // When true, do compositing with the software backend instead of using GL.
200   bool use_software_compositing_ = false;
201 
202   // Initial WebContents to watch for navigations during SetUpOnMainThread.
203   WebContents* initial_web_contents_ = nullptr;
204 
205   // Whether SetUp was called. This value is checked in the destructor of this
206   // class to ensure that SetUp was called. If it's not called, the test will
207   // not run and report a false positive result.
208   bool set_up_called_ = false;
209 
210   std::unique_ptr<storage::QuotaSettings> quota_settings_;
211 
212   std::unique_ptr<NoRendererCrashesAssertion> no_renderer_crashes_assertion_;
213 
214   bool initialized_network_process_ = false;
215 
216   bool allow_network_access_to_host_resolutions_ = false;
217 
218 #if defined(OS_POSIX)
219   bool handle_sigterm_;
220 #endif
221 };
222 
223 }  // namespace content
224 
225 #endif  // CONTENT_PUBLIC_TEST_BROWSER_TEST_BASE_H_
226