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.
5 #include "chrome/test/base/in_process_browser_test.h"
7 #include "base/auto_reset.h"
8 #include "base/basictypes.h"
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/files/file_path.h"
13 #include "base/lazy_instance.h"
14 #include "base/path_service.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/test/test_file_util.h"
17 #include "base/threading/non_thread_safe.h"
18 #include "chrome/browser/browser_process.h"
19 #include "chrome/browser/google/google_util.h"
20 #include "chrome/browser/lifetime/application_lifetime.h"
21 #include "chrome/browser/net/net_error_tab_helper.h"
22 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/profiles/profile_manager.h"
24 #include "chrome/browser/ui/browser.h"
25 #include "chrome/browser/ui/browser_finder.h"
26 #include "chrome/browser/ui/browser_list.h"
27 #include "chrome/browser/ui/browser_list_observer.h"
28 #include "chrome/browser/ui/browser_navigator.h"
29 #include "chrome/browser/ui/browser_tabstrip.h"
30 #include "chrome/browser/ui/browser_window.h"
31 #include "chrome/browser/ui/host_desktop.h"
32 #include "chrome/browser/ui/tabs/tab_strip_model.h"
33 #include "chrome/common/chrome_constants.h"
34 #include "chrome/common/chrome_paths.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/logging_chrome.h"
37 #include "chrome/common/url_constants.h"
38 #include "chrome/renderer/chrome_content_renderer_client.h"
39 #include "chrome/test/base/chrome_test_suite.h"
40 #include "chrome/test/base/test_launcher_utils.h"
41 #include "chrome/test/base/test_switches.h"
42 #include "chrome/test/base/testing_browser_process.h"
43 #include "chrome/test/base/ui_test_utils.h"
44 #include "components/os_crypt/os_crypt.h"
45 #include "content/public/browser/notification_service.h"
46 #include "content/public/browser/notification_types.h"
47 #include "content/public/test/browser_test_utils.h"
48 #include "content/public/test/test_launcher.h"
49 #include "content/public/test/test_navigation_observer.h"
50 #include "net/test/embedded_test_server/embedded_test_server.h"
51 #include "net/test/spawned_test_server/spawned_test_server.h"
53 #if defined(OS_MACOSX)
54 #include "base/mac/scoped_nsautorelease_pool.h"
58 #include "base/win/scoped_com_initializer.h"
59 #include "base/win/windows_version.h"
60 #include "ui/base/win/atl_module.h"
61 #include "win8/test/metro_registration_helper.h"
62 #include "win8/test/test_registrar_constants.h"
65 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
66 #include "chrome/browser/captive_portal/captive_portal_service.h"
69 #if !defined(OS_ANDROID) && !defined(OS_IOS)
70 #include "components/storage_monitor/test_storage_monitor.h"
75 // Passed as value of kTestType.
76 const char kBrowserTestType[] = "browser";
78 // A BrowserListObserver that makes sure that all browsers created are on the
79 // |allowed_desktop_|.
80 class SingleDesktopTestObserver : public chrome::BrowserListObserver,
81 public base::NonThreadSafe {
83 explicit SingleDesktopTestObserver(chrome::HostDesktopType allowed_desktop);
84 virtual ~SingleDesktopTestObserver();
86 // chrome::BrowserListObserver:
87 virtual void OnBrowserAdded(Browser* browser) OVERRIDE;
90 chrome::HostDesktopType allowed_desktop_;
92 DISALLOW_COPY_AND_ASSIGN(SingleDesktopTestObserver);
95 SingleDesktopTestObserver::SingleDesktopTestObserver(
96 chrome::HostDesktopType allowed_desktop)
97 : allowed_desktop_(allowed_desktop) {
98 BrowserList::AddObserver(this);
101 SingleDesktopTestObserver::~SingleDesktopTestObserver() {
102 BrowserList::RemoveObserver(this);
105 void SingleDesktopTestObserver::OnBrowserAdded(Browser* browser) {
106 CHECK(CalledOnValidThread());
107 CHECK_EQ(browser->host_desktop_type(), allowed_desktop_);
112 InProcessBrowserTest::InProcessBrowserTest()
114 exit_when_last_browser_closes_(true),
115 multi_desktop_test_(false)
116 #if defined(OS_MACOSX)
117 , autorelease_pool_(NULL)
120 #if defined(OS_MACOSX)
121 // TODO(phajdan.jr): Make browser_tests self-contained on Mac, remove this.
122 // Before we run the browser, we have to hack the path to the exe to match
123 // what it would be if Chrome was running, because it is used to fork renderer
124 // processes, on Linux at least (failure to do so will cause a browser_test to
125 // be run instead of a renderer).
126 base::FilePath chrome_path;
127 CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
128 chrome_path = chrome_path.DirName();
129 chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
130 CHECK(PathService::Override(base::FILE_EXE, chrome_path));
131 #endif // defined(OS_MACOSX)
133 CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
134 base::FilePath src_dir;
135 CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir));
136 base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data");
137 embedded_test_server()->ServeFilesFromDirectory(test_data_dir);
139 // chrome::DIR_TEST_DATA isn't going to be setup until after we call
140 // ContentMain. However that is after tests' constructors or SetUp methods,
141 // which sometimes need it. So just override it.
142 CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir));
145 InProcessBrowserTest::~InProcessBrowserTest() {
148 void InProcessBrowserTest::SetUp() {
149 // Browser tests will create their own g_browser_process later.
150 DCHECK(!g_browser_process);
152 CommandLine* command_line = CommandLine::ForCurrentProcess();
153 // Allow subclasses to change the command line before running any tests.
154 SetUpCommandLine(command_line);
155 // Add command line arguments that are used by all InProcessBrowserTests.
156 PrepareTestCommandLine(command_line);
158 // Create a temporary user data directory if required.
159 ASSERT_TRUE(CreateUserDataDirectory())
160 << "Could not create user data directory.";
162 // Allow subclasses the opportunity to make changes to the default user data
163 // dir before running any tests.
164 ASSERT_TRUE(SetUpUserDataDirectory())
165 << "Could not set up user data directory.";
167 #if defined(OS_CHROMEOS)
168 // Make sure that the log directory exists.
169 base::FilePath log_dir = logging::GetSessionLogFile(*command_line).DirName();
170 base::CreateDirectory(log_dir);
171 #endif // defined(OS_CHROMEOS)
173 #if defined(OS_MACOSX)
174 // Always use the MockKeychain if OS encription is used (which is when
175 // anything sensitive gets stored, including Cookies). Without this,
176 // many tests will hang waiting for a user to approve KeyChain access.
177 OSCrypt::UseMockKeychain(true);
180 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
181 captive_portal::CaptivePortalService::set_state_for_testing(
182 captive_portal::CaptivePortalService::DISABLED_FOR_TESTING);
185 chrome_browser_net::NetErrorTabHelper::set_state_for_testing(
186 chrome_browser_net::NetErrorTabHelper::TESTING_FORCE_DISABLED);
188 google_util::SetMockLinkDoctorBaseURLForTesting();
191 base::win::Version version = base::win::GetVersion();
192 // Although Ash officially is only supported for users on Win7+, we still run
193 // ash_unittests on Vista builders, so we still need to initialize COM.
194 if (version >= base::win::VERSION_VISTA &&
195 CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) {
196 com_initializer_.reset(new base::win::ScopedCOMInitializer());
197 ui::win::CreateATLModuleIfNeeded();
198 if (version >= base::win::VERSION_WIN8)
199 ASSERT_TRUE(win8::MakeTestDefaultBrowserSynchronously());
203 BrowserTestBase::SetUp();
206 void InProcessBrowserTest::PrepareTestCommandLine(CommandLine* command_line) {
207 // Propagate commandline settings from test_launcher_utils.
208 test_launcher_utils::PrepareBrowserCommandLineForTests(command_line);
210 // This is a Browser test.
211 command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType);
214 if (command_line->HasSwitch(switches::kAshBrowserTests)) {
215 command_line->AppendSwitchNative(switches::kViewerLaunchViaAppId,
216 win8::test::kDefaultTestAppUserModelId);
217 // Ash already launches with a single browser opened, add kSilentLaunch to
218 // make sure StartupBrowserCreator doesn't attempt to launch a browser on
219 // the native desktop on startup.
220 command_line->AppendSwitch(switches::kSilentLaunch);
224 #if defined(OS_MACOSX)
225 // Explicitly set the path of the binary used for child processes, otherwise
226 // they'll try to use browser_tests which doesn't contain ChromeMain.
227 base::FilePath subprocess_path;
228 PathService::Get(base::FILE_EXE, &subprocess_path);
229 // Recreate the real environment, run the helper within the app bundle.
230 subprocess_path = subprocess_path.DirName().DirName();
231 DCHECK_EQ(subprocess_path.BaseName().value(), "Contents");
233 subprocess_path.Append("Versions").Append(chrome::kChromeVersion);
235 subprocess_path.Append(chrome::kHelperProcessExecutablePath);
236 command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,
240 // TODO(pkotwicz): Investigate if we can remove this switch.
241 if (exit_when_last_browser_closes_)
242 command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests);
244 if (command_line->GetArgs().empty())
245 command_line->AppendArg(content::kAboutBlankURL);
248 bool InProcessBrowserTest::CreateUserDataDirectory() {
249 CommandLine* command_line = CommandLine::ForCurrentProcess();
250 base::FilePath user_data_dir =
251 command_line->GetSwitchValuePath(switches::kUserDataDir);
252 if (user_data_dir.empty()) {
253 if (temp_user_data_dir_.CreateUniqueTempDir() &&
254 temp_user_data_dir_.IsValid()) {
255 user_data_dir = temp_user_data_dir_.path();
257 LOG(ERROR) << "Could not create temporary user data directory \""
258 << temp_user_data_dir_.path().value() << "\".";
262 return test_launcher_utils::OverrideUserDataDir(user_data_dir);
265 void InProcessBrowserTest::TearDown() {
266 DCHECK(!g_browser_process);
268 com_initializer_.reset();
270 BrowserTestBase::TearDown();
273 void InProcessBrowserTest::AddTabAtIndexToBrowser(
277 content::PageTransition transition) {
278 chrome::NavigateParams params(browser, url, transition);
279 params.tabstrip_index = index;
280 params.disposition = NEW_FOREGROUND_TAB;
281 chrome::Navigate(¶ms);
283 content::WaitForLoadStop(params.target_contents);
286 void InProcessBrowserTest::AddTabAtIndex(
289 content::PageTransition transition) {
290 AddTabAtIndexToBrowser(browser(), index, url, transition);
293 bool InProcessBrowserTest::SetUpUserDataDirectory() {
297 // Creates a browser with a single tab (about:blank), waits for the tab to
298 // finish loading and shows the browser.
299 Browser* InProcessBrowserTest::CreateBrowser(Profile* profile) {
300 Browser* browser = new Browser(
301 Browser::CreateParams(profile, chrome::GetActiveDesktop()));
302 AddBlankTabAndShow(browser);
306 Browser* InProcessBrowserTest::CreateIncognitoBrowser() {
307 // Create a new browser with using the incognito profile.
308 Browser* incognito = new Browser(
309 Browser::CreateParams(browser()->profile()->GetOffTheRecordProfile(),
310 chrome::GetActiveDesktop()));
311 AddBlankTabAndShow(incognito);
315 Browser* InProcessBrowserTest::CreateBrowserForPopup(Profile* profile) {
317 new Browser(Browser::CreateParams(Browser::TYPE_POPUP, profile,
318 chrome::GetActiveDesktop()));
319 AddBlankTabAndShow(browser);
323 Browser* InProcessBrowserTest::CreateBrowserForApp(
324 const std::string& app_name,
326 Browser* browser = new Browser(
327 Browser::CreateParams::CreateForApp(
328 Browser::TYPE_POPUP, app_name, gfx::Rect(), profile,
329 chrome::GetActiveDesktop()));
330 AddBlankTabAndShow(browser);
334 void InProcessBrowserTest::AddBlankTabAndShow(Browser* browser) {
335 content::WindowedNotificationObserver observer(
336 content::NOTIFICATION_LOAD_STOP,
337 content::NotificationService::AllSources());
338 chrome::AddSelectedTabWithURL(browser, GURL(content::kAboutBlankURL),
339 content::PAGE_TRANSITION_AUTO_TOPLEVEL);
342 browser->window()->Show();
345 #if !defined(OS_MACOSX)
346 CommandLine InProcessBrowserTest::GetCommandLineForRelaunch() {
347 CommandLine new_command_line(CommandLine::ForCurrentProcess()->GetProgram());
348 CommandLine::SwitchMap switches =
349 CommandLine::ForCurrentProcess()->GetSwitches();
350 switches.erase(switches::kUserDataDir);
351 switches.erase(content::kSingleProcessTestsFlag);
352 switches.erase(switches::kSingleProcess);
353 new_command_line.AppendSwitch(content::kLaunchAsBrowser);
355 base::FilePath user_data_dir;
356 PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
357 new_command_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir);
359 for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
360 iter != switches.end(); ++iter) {
361 new_command_line.AppendSwitchNative((*iter).first, (*iter).second);
363 return new_command_line;
367 void InProcessBrowserTest::RunTestOnMainThreadLoop() {
368 // Pump startup related events.
369 content::RunAllPendingInMessageLoop();
371 chrome::HostDesktopType active_desktop = chrome::GetActiveDesktop();
372 // Self-adds/removes itself from the BrowserList observers.
373 scoped_ptr<SingleDesktopTestObserver> single_desktop_test_observer;
374 if (!multi_desktop_test_) {
375 single_desktop_test_observer.reset(
376 new SingleDesktopTestObserver(active_desktop));
379 const BrowserList* active_browser_list =
380 BrowserList::GetInstance(active_desktop);
381 if (!active_browser_list->empty()) {
382 browser_ = active_browser_list->get(0);
384 // There are cases where windows get created maximized by default.
385 if (browser_->window()->IsMaximized())
386 browser_->window()->Restore();
388 content::WaitForLoadStop(
389 browser_->tab_strip_model()->GetActiveWebContents());
392 #if !defined(OS_ANDROID) && !defined(OS_IOS)
393 // Do not use the real StorageMonitor for tests, which introduces another
394 // source of variability and potential slowness.
395 ASSERT_TRUE(storage_monitor::TestStorageMonitor::CreateForBrowserTests());
398 #if defined(OS_MACOSX)
399 // On Mac, without the following autorelease pool, code which is directly
400 // executed (as opposed to executed inside a message loop) would autorelease
401 // objects into a higher-level pool. This pool is not recycled in-sync with
402 // the message loops' pools and causes problems with code relying on
403 // deallocation via an autorelease pool (such as browser window closure and
404 // browser shutdown). To avoid this, the following pool is recycled after each
405 // time code is directly executed.
406 autorelease_pool_ = new base::mac::ScopedNSAutoreleasePool;
409 // Pump any pending events that were created as a result of creating a
411 content::RunAllPendingInMessageLoop();
414 #if defined(OS_MACOSX)
415 autorelease_pool_->Recycle();
418 if (!HasFatalFailure())
419 RunTestOnMainThread();
420 #if defined(OS_MACOSX)
421 autorelease_pool_->Recycle();
424 // Invoke cleanup and quit even if there are failures. This is similar to
425 // gtest in that it invokes TearDown even if Setup fails.
426 CleanUpOnMainThread();
427 #if defined(OS_MACOSX)
428 autorelease_pool_->Recycle();
431 // Sometimes tests leave Quit tasks in the MessageLoop (for shame), so let's
432 // run all pending messages here to avoid preempting the QuitBrowsers tasks.
433 // TODO(jbates) Once crbug.com/134753 is fixed, this can be removed because it
434 // will not be possible to post Quit tasks.
435 content::RunAllPendingInMessageLoop();
438 // All BrowserLists should be empty at this point.
439 for (chrome::HostDesktopType t = chrome::HOST_DESKTOP_TYPE_FIRST;
440 t < chrome::HOST_DESKTOP_TYPE_COUNT;
441 t = static_cast<chrome::HostDesktopType>(t + 1)) {
442 CHECK(BrowserList::GetInstance(t)->empty()) << t;
446 void InProcessBrowserTest::QuitBrowsers() {
447 if (chrome::GetTotalBrowserCount() == 0) {
448 chrome::NotifyAppTerminating();
452 // Invoke AttemptExit on a running message loop.
453 // AttemptExit exits the message loop after everything has been
454 // shut down properly.
455 base::MessageLoopForUI::current()->PostTask(FROM_HERE,
456 base::Bind(&chrome::AttemptExit));
457 content::RunMessageLoop();
459 #if defined(OS_MACOSX)
460 // chrome::AttemptExit() will attempt to close all browsers by deleting
461 // their tab contents. The last tab contents being removed triggers closing of
462 // the browser window.
464 // On the Mac, this eventually reaches
465 // -[BrowserWindowController windowWillClose:], which will post a deferred
466 // -autorelease on itself to ultimately destroy the Browser object. The line
467 // below is necessary to pump these pending messages to ensure all Browsers
469 content::RunAllPendingInMessageLoop();
470 delete autorelease_pool_;
471 autorelease_pool_ = NULL;