browser_test_base.cc revision f8ee788a64d60abd8f2d742a5fdedde054ecd910
1// Copyright (c) 2011 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#include "content/public/test/browser_test_base.h"
6
7#include "base/bind.h"
8#include "base/command_line.h"
9#include "base/debug/stack_trace.h"
10#include "base/i18n/icu_util.h"
11#include "base/message_loop/message_loop.h"
12#include "base/sys_info.h"
13#include "content/public/app/content_main.h"
14#include "content/browser/renderer_host/render_process_host_impl.h"
15#include "content/public/browser/browser_thread.h"
16#include "content/public/common/content_switches.h"
17#include "content/public/common/main_function_params.h"
18#include "content/public/test/test_launcher.h"
19#include "content/public/test/test_utils.h"
20#include "net/base/net_errors.h"
21#include "net/dns/mock_host_resolver.h"
22#include "net/test/embedded_test_server/embedded_test_server.h"
23#include "ui/compositor/compositor_switches.h"
24#include "ui/gl/gl_implementation.h"
25#include "ui/gl/gl_switches.h"
26
27#if defined(OS_POSIX)
28#include "base/process/process_handle.h"
29#endif
30
31#if defined(OS_MACOSX)
32#include "base/mac/mac_util.h"
33#endif
34
35#if defined(OS_ANDROID)
36#include "base/threading/thread_restrictions.h"
37#include "content/public/browser/browser_main_runner.h"
38#include "content/public/browser/browser_thread.h"
39#endif
40
41#if defined(USE_AURA)
42#include "content/browser/compositor/image_transport_factory.h"
43#if defined(USE_X11)
44#include "ui/aura/window_tree_host_x11.h"
45#endif
46#endif
47
48namespace content {
49namespace {
50
51#if defined(OS_POSIX)
52// On SIGTERM (sent by the runner on timeouts), dump a stack trace (to make
53// debugging easier) and also exit with a known error code (so that the test
54// framework considers this a failure -- http://crbug.com/57578).
55// Note: We only want to do this in the browser process, and not forked
56// processes. That might lead to hangs because of locks inside tcmalloc or the
57// OS. See http://crbug.com/141302.
58static int g_browser_process_pid;
59static void DumpStackTraceSignalHandler(int signal) {
60  if (g_browser_process_pid == base::GetCurrentProcId()) {
61    logging::RawLog(logging::LOG_ERROR,
62                    "BrowserTestBase signal handler received SIGTERM. "
63                    "Backtrace:\n");
64    base::debug::StackTrace().Print();
65  }
66  _exit(128 + signal);
67}
68#endif  // defined(OS_POSIX)
69
70void RunTaskOnRendererThread(const base::Closure& task,
71                             const base::Closure& quit_task) {
72  task.Run();
73  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, quit_task);
74}
75
76// In many cases it may be not obvious that a test makes a real DNS lookup.
77// We generally don't want to rely on external DNS servers for our tests,
78// so this host resolver procedure catches external queries and returns a failed
79// lookup result.
80class LocalHostResolverProc : public net::HostResolverProc {
81 public:
82  LocalHostResolverProc() : HostResolverProc(NULL) {}
83
84  virtual int Resolve(const std::string& host,
85                      net::AddressFamily address_family,
86                      net::HostResolverFlags host_resolver_flags,
87                      net::AddressList* addrlist,
88                      int* os_error) OVERRIDE {
89    const char* kLocalHostNames[] = {"localhost", "127.0.0.1", "::1"};
90    bool local = false;
91
92    if (host == net::GetHostName()) {
93      local = true;
94    } else {
95      for (size_t i = 0; i < arraysize(kLocalHostNames); i++)
96        if (host == kLocalHostNames[i]) {
97          local = true;
98          break;
99        }
100    }
101
102    // To avoid depending on external resources and to reduce (if not preclude)
103    // network interactions from tests, we simulate failure for non-local DNS
104    // queries, rather than perform them.
105    // If you really need to make an external DNS query, use
106    // net::RuleBasedHostResolverProc and its AllowDirectLookup method.
107    if (!local) {
108      DVLOG(1) << "To avoid external dependencies, simulating failure for "
109          "external DNS lookup of " << host;
110      return net::ERR_NOT_IMPLEMENTED;
111    }
112
113    return ResolveUsingPrevious(host, address_family, host_resolver_flags,
114                                addrlist, os_error);
115  }
116
117 private:
118  virtual ~LocalHostResolverProc() {}
119};
120
121}  // namespace
122
123extern int BrowserMain(const MainFunctionParams&);
124
125BrowserTestBase::BrowserTestBase()
126    : expected_exit_code_(0),
127      enable_pixel_output_(false),
128      use_software_compositing_(false) {
129#if defined(OS_MACOSX)
130  base::mac::SetOverrideAmIBundled(true);
131#endif
132
133#if defined(USE_AURA) && defined(USE_X11)
134  aura::test::SetUseOverrideRedirectWindowByDefault(true);
135#endif
136
137#if defined(OS_POSIX)
138  handle_sigterm_ = true;
139#endif
140
141  // This is called through base::TestSuite initially. It'll also be called
142  // inside BrowserMain, so tell the code to ignore the check that it's being
143  // called more than once
144  base::i18n::AllowMultipleInitializeCallsForTesting();
145
146  embedded_test_server_.reset(new net::test_server::EmbeddedTestServer);
147}
148
149BrowserTestBase::~BrowserTestBase() {
150#if defined(OS_ANDROID)
151  // RemoteTestServer can cause wait on the UI thread.
152  base::ThreadRestrictions::ScopedAllowWait allow_wait;
153  test_server_.reset(NULL);
154#endif
155}
156
157void BrowserTestBase::SetUp() {
158  CommandLine* command_line = CommandLine::ForCurrentProcess();
159
160  // The tests assume that file:// URIs can freely access other file:// URIs.
161  command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
162
163  command_line->AppendSwitch(switches::kDomAutomationController);
164
165  // It is sometimes useful when looking at browser test failures to know which
166  // GPU blacklisting decisions were made.
167  command_line->AppendSwitch(switches::kLogGpuControlListDecisions);
168
169  if (use_software_compositing_) {
170    command_line->AppendSwitch(switches::kDisableGpu);
171#if defined(USE_AURA)
172    command_line->AppendSwitch(switches::kUIDisableThreadedCompositing);
173#endif
174  }
175
176#if defined(USE_AURA)
177  // Most tests do not need pixel output, so we don't produce any. The command
178  // line can override this behaviour to allow for visual debugging.
179  if (command_line->HasSwitch(switches::kEnablePixelOutputInTests))
180    enable_pixel_output_ = true;
181
182  if (command_line->HasSwitch(switches::kDisableGLDrawingForTests)) {
183    NOTREACHED() << "kDisableGLDrawingForTests should not be used as it"
184                    "is chosen by tests. Use kEnablePixelOutputInTests "
185                    "to enable pixel output.";
186  }
187
188  // Don't enable pixel output for browser tests unless they override and force
189  // us to, or it's requested on the command line.
190  if (!enable_pixel_output_ && !use_software_compositing_)
191    command_line->AppendSwitch(switches::kDisableGLDrawingForTests);
192#endif
193
194  bool use_osmesa = true;
195
196  // We usually use OSMesa as this works on all bots. The command line can
197  // override this behaviour to use hardware GL.
198  if (command_line->HasSwitch(switches::kUseGpuInTests))
199    use_osmesa = false;
200
201  // Some bots pass this flag when they want to use hardware GL.
202  if (command_line->HasSwitch("enable-gpu"))
203    use_osmesa = false;
204
205#if defined(OS_MACOSX)
206  // On Mac we always use hardware GL.
207  use_osmesa = false;
208#endif
209
210#if defined(OS_ANDROID)
211  // On Android we always use hardware GL.
212  use_osmesa = false;
213#endif
214
215#if defined(OS_CHROMEOS)
216  // If the test is running on the chromeos envrionment (such as
217  // device or vm bots), we use hardware GL.
218  if (base::SysInfo::IsRunningOnChromeOS())
219    use_osmesa = false;
220#endif
221
222  if (use_osmesa && !use_software_compositing_)
223    command_line->AppendSwitch(switches::kOverrideUseGLWithOSMesaForTests);
224
225  scoped_refptr<net::HostResolverProc> local_resolver =
226      new LocalHostResolverProc();
227  rule_based_resolver_ =
228      new net::RuleBasedHostResolverProc(local_resolver.get());
229  rule_based_resolver_->AddSimulatedFailure("wpad");
230  net::ScopedDefaultHostResolverProc scoped_local_host_resolver_proc(
231      rule_based_resolver_.get());
232  SetUpInProcessBrowserTestFixture();
233
234  base::Closure* ui_task =
235      new base::Closure(
236          base::Bind(&BrowserTestBase::ProxyRunTestOnMainThreadLoop, this));
237
238#if defined(OS_ANDROID)
239  MainFunctionParams params(*command_line);
240  params.ui_task = ui_task;
241  // TODO(phajdan.jr): Check return code, http://crbug.com/374738 .
242  BrowserMain(params);
243#else
244  GetContentMainParams()->ui_task = ui_task;
245  EXPECT_EQ(expected_exit_code_, ContentMain(*GetContentMainParams()));
246#endif
247  TearDownInProcessBrowserTestFixture();
248}
249
250void BrowserTestBase::TearDown() {
251}
252
253void BrowserTestBase::ProxyRunTestOnMainThreadLoop() {
254#if defined(OS_POSIX)
255  if (handle_sigterm_) {
256    g_browser_process_pid = base::GetCurrentProcId();
257    signal(SIGTERM, DumpStackTraceSignalHandler);
258  }
259#endif  // defined(OS_POSIX)
260  RunTestOnMainThreadLoop();
261}
262
263void BrowserTestBase::CreateTestServer(const base::FilePath& test_server_base) {
264  CHECK(!test_server_.get());
265  test_server_.reset(new net::SpawnedTestServer(
266      net::SpawnedTestServer::TYPE_HTTP,
267      net::SpawnedTestServer::kLocalhost,
268      test_server_base));
269}
270
271void BrowserTestBase::PostTaskToInProcessRendererAndWait(
272    const base::Closure& task) {
273  CHECK(CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess));
274
275  scoped_refptr<MessageLoopRunner> runner = new MessageLoopRunner;
276
277  base::MessageLoop* renderer_loop =
278      RenderProcessHostImpl::GetInProcessRendererThreadForTesting();
279  CHECK(renderer_loop);
280
281  renderer_loop->PostTask(
282      FROM_HERE,
283      base::Bind(&RunTaskOnRendererThread, task, runner->QuitClosure()));
284  runner->Run();
285}
286
287void BrowserTestBase::EnablePixelOutput() { enable_pixel_output_ = true; }
288
289void BrowserTestBase::UseSoftwareCompositing() {
290#if !defined(USE_AURA) && !defined(OS_MACOSX)
291  // TODO(danakj): Remove when GTK linux is no more.
292  NOTREACHED();
293#endif
294  use_software_compositing_ = true;
295}
296
297bool BrowserTestBase::UsingOSMesa() const {
298  CommandLine* cmd = CommandLine::ForCurrentProcess();
299  return cmd->GetSwitchValueASCII(switches::kUseGL) ==
300         gfx::kGLImplementationOSMesaName;
301}
302
303}  // namespace content
304