67555edadb3c170366b755a6abfdf21e5d7250fa
[platform/framework/web/crosswalk.git] / src / chrome / test / base / in_process_browser_test.cc
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 #include "chrome/test/base/in_process_browser_test.h"
6
7 #include "base/auto_reset.h"
8 #include "base/basictypes.h"
9 #include "base/bind.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"
52
53 #if defined(OS_MACOSX)
54 #include "base/mac/scoped_nsautorelease_pool.h"
55 #endif
56
57 #if defined(OS_WIN)
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"
63 #endif
64
65 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
66 #include "chrome/browser/captive_portal/captive_portal_service.h"
67 #endif
68
69 #if !defined(OS_ANDROID) && !defined(OS_IOS)
70 #include "components/storage_monitor/test_storage_monitor.h"
71 #endif
72
73 namespace {
74
75 // Passed as value of kTestType.
76 const char kBrowserTestType[] = "browser";
77
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 {
82  public:
83   explicit SingleDesktopTestObserver(chrome::HostDesktopType allowed_desktop);
84   virtual ~SingleDesktopTestObserver();
85
86   // chrome::BrowserListObserver:
87   virtual void OnBrowserAdded(Browser* browser) OVERRIDE;
88
89  private:
90   chrome::HostDesktopType allowed_desktop_;
91
92   DISALLOW_COPY_AND_ASSIGN(SingleDesktopTestObserver);
93 };
94
95 SingleDesktopTestObserver::SingleDesktopTestObserver(
96     chrome::HostDesktopType allowed_desktop)
97         : allowed_desktop_(allowed_desktop) {
98   BrowserList::AddObserver(this);
99 }
100
101 SingleDesktopTestObserver::~SingleDesktopTestObserver() {
102   BrowserList::RemoveObserver(this);
103 }
104
105 void SingleDesktopTestObserver::OnBrowserAdded(Browser* browser) {
106   CHECK(CalledOnValidThread());
107   CHECK_EQ(browser->host_desktop_type(), allowed_desktop_);
108 }
109
110 }  // namespace
111
112 InProcessBrowserTest::InProcessBrowserTest()
113     : browser_(NULL),
114       exit_when_last_browser_closes_(true),
115       multi_desktop_test_(false)
116 #if defined(OS_MACOSX)
117       , autorelease_pool_(NULL)
118 #endif  // OS_MACOSX
119     {
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)
132
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);
138
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));
143 }
144
145 InProcessBrowserTest::~InProcessBrowserTest() {
146 }
147
148 void InProcessBrowserTest::SetUp() {
149   // Browser tests will create their own g_browser_process later.
150   DCHECK(!g_browser_process);
151
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);
157
158   // Create a temporary user data directory if required.
159   ASSERT_TRUE(CreateUserDataDirectory())
160       << "Could not create user data directory.";
161
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.";
166
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)
172
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);
178 #endif
179
180 #if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
181   captive_portal::CaptivePortalService::set_state_for_testing(
182       captive_portal::CaptivePortalService::DISABLED_FOR_TESTING);
183 #endif
184
185   chrome_browser_net::NetErrorTabHelper::set_state_for_testing(
186       chrome_browser_net::NetErrorTabHelper::TESTING_FORCE_DISABLED);
187
188   google_util::SetMockLinkDoctorBaseURLForTesting();
189
190 #if defined(OS_WIN)
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());
200   }
201 #endif
202
203   BrowserTestBase::SetUp();
204 }
205
206 void InProcessBrowserTest::PrepareTestCommandLine(CommandLine* command_line) {
207   // Propagate commandline settings from test_launcher_utils.
208   test_launcher_utils::PrepareBrowserCommandLineForTests(command_line);
209
210   // This is a Browser test.
211   command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType);
212
213 #if defined(OS_WIN)
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);
221   }
222 #endif
223
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");
232   subprocess_path =
233       subprocess_path.Append("Versions").Append(chrome::kChromeVersion);
234   subprocess_path =
235       subprocess_path.Append(chrome::kHelperProcessExecutablePath);
236   command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,
237                                  subprocess_path);
238 #endif
239
240   // TODO(pkotwicz): Investigate if we can remove this switch.
241   if (exit_when_last_browser_closes_)
242     command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests);
243
244   if (command_line->GetArgs().empty())
245     command_line->AppendArg(content::kAboutBlankURL);
246 }
247
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();
256     } else {
257       LOG(ERROR) << "Could not create temporary user data directory \""
258                  << temp_user_data_dir_.path().value() << "\".";
259       return false;
260     }
261   }
262   return test_launcher_utils::OverrideUserDataDir(user_data_dir);
263 }
264
265 void InProcessBrowserTest::TearDown() {
266   DCHECK(!g_browser_process);
267 #if defined(OS_WIN)
268   com_initializer_.reset();
269 #endif
270   BrowserTestBase::TearDown();
271 }
272
273 void InProcessBrowserTest::AddTabAtIndexToBrowser(
274     Browser* browser,
275     int index,
276     const GURL& url,
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(&params);
282
283   content::WaitForLoadStop(params.target_contents);
284 }
285
286 void InProcessBrowserTest::AddTabAtIndex(
287     int index,
288     const GURL& url,
289     content::PageTransition transition) {
290   AddTabAtIndexToBrowser(browser(), index, url, transition);
291 }
292
293 bool InProcessBrowserTest::SetUpUserDataDirectory() {
294   return true;
295 }
296
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);
303   return browser;
304 }
305
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);
312   return incognito;
313 }
314
315 Browser* InProcessBrowserTest::CreateBrowserForPopup(Profile* profile) {
316   Browser* browser =
317       new Browser(Browser::CreateParams(Browser::TYPE_POPUP, profile,
318                   chrome::GetActiveDesktop()));
319   AddBlankTabAndShow(browser);
320   return browser;
321 }
322
323 Browser* InProcessBrowserTest::CreateBrowserForApp(
324     const std::string& app_name,
325     Profile* profile) {
326   Browser* browser = new Browser(
327       Browser::CreateParams::CreateForApp(
328           Browser::TYPE_POPUP, app_name, gfx::Rect(), profile,
329           chrome::GetActiveDesktop()));
330   AddBlankTabAndShow(browser);
331   return browser;
332 }
333
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);
340   observer.Wait();
341
342   browser->window()->Show();
343 }
344
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);
354
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);
358
359   for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
360         iter != switches.end(); ++iter) {
361     new_command_line.AppendSwitchNative((*iter).first, (*iter).second);
362   }
363   return new_command_line;
364 }
365 #endif
366
367 void InProcessBrowserTest::RunTestOnMainThreadLoop() {
368   // Pump startup related events.
369   content::RunAllPendingInMessageLoop();
370
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));
377   }
378
379   const BrowserList* active_browser_list =
380       BrowserList::GetInstance(active_desktop);
381   if (!active_browser_list->empty()) {
382     browser_ = active_browser_list->get(0);
383 #if defined(USE_ASH)
384     // There are cases where windows get created maximized by default.
385     if (browser_->window()->IsMaximized())
386       browser_->window()->Restore();
387 #endif
388     content::WaitForLoadStop(
389         browser_->tab_strip_model()->GetActiveWebContents());
390   }
391
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());
396 #endif
397
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;
407 #endif
408
409   // Pump any pending events that were created as a result of creating a
410   // browser.
411   content::RunAllPendingInMessageLoop();
412
413   SetUpOnMainThread();
414 #if defined(OS_MACOSX)
415   autorelease_pool_->Recycle();
416 #endif
417
418   if (!HasFatalFailure())
419     RunTestOnMainThread();
420 #if defined(OS_MACOSX)
421   autorelease_pool_->Recycle();
422 #endif
423
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();
429 #endif
430
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();
436
437   QuitBrowsers();
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;
443   }
444 }
445
446 void InProcessBrowserTest::QuitBrowsers() {
447   if (chrome::GetTotalBrowserCount() == 0) {
448     chrome::NotifyAppTerminating();
449     return;
450   }
451
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();
458
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.
463   //
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
468   // get deleted.
469   content::RunAllPendingInMessageLoop();
470   delete autorelease_pool_;
471   autorelease_pool_ = NULL;
472 #endif
473 }