ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / ui / browser_browsertest.cc
blob94ecf1181ec7b37a95490725a0e4e7e9abe253eb
1 // Copyright 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 <string>
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/compiler_specific.h"
10 #include "base/files/file_path.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/sys_info.h"
15 #include "chrome/app/chrome_command_ids.h"
16 #include "chrome/browser/chrome_content_browser_client.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/command_updater.h"
19 #include "chrome/browser/defaults.h"
20 #include "chrome/browser/devtools/devtools_window_testing.h"
21 #include "chrome/browser/extensions/extension_browsertest.h"
22 #include "chrome/browser/extensions/extension_service.h"
23 #include "chrome/browser/extensions/extension_util.h"
24 #include "chrome/browser/extensions/tab_helper.h"
25 #include "chrome/browser/first_run/first_run.h"
26 #include "chrome/browser/lifetime/application_lifetime.h"
27 #include "chrome/browser/prefs/incognito_mode_prefs.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/profiles/profile_manager.h"
30 #include "chrome/browser/search/search.h"
31 #include "chrome/browser/sessions/session_service_factory.h"
32 #include "chrome/browser/translate/chrome_translate_client.h"
33 #include "chrome/browser/translate/cld_data_harness.h"
34 #include "chrome/browser/translate/cld_data_harness_factory.h"
35 #include "chrome/browser/ui/browser.h"
36 #include "chrome/browser/ui/browser_command_controller.h"
37 #include "chrome/browser/ui/browser_commands.h"
38 #include "chrome/browser/ui/browser_finder.h"
39 #include "chrome/browser/ui/browser_iterator.h"
40 #include "chrome/browser/ui/browser_navigator.h"
41 #include "chrome/browser/ui/browser_tabstrip.h"
42 #include "chrome/browser/ui/browser_ui_prefs.h"
43 #include "chrome/browser/ui/browser_window.h"
44 #include "chrome/browser/ui/extensions/app_launch_params.h"
45 #include "chrome/browser/ui/extensions/application_launch.h"
46 #include "chrome/browser/ui/host_desktop.h"
47 #include "chrome/browser/ui/startup/startup_browser_creator.h"
48 #include "chrome/browser/ui/startup/startup_browser_creator_impl.h"
49 #include "chrome/browser/ui/tabs/pinned_tab_codec.h"
50 #include "chrome/browser/ui/tabs/tab_strip_model.h"
51 #include "chrome/common/chrome_switches.h"
52 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
53 #include "chrome/common/pref_names.h"
54 #include "chrome/common/url_constants.h"
55 #include "chrome/grit/chromium_strings.h"
56 #include "chrome/grit/generated_resources.h"
57 #include "chrome/test/base/in_process_browser_test.h"
58 #include "chrome/test/base/test_switches.h"
59 #include "chrome/test/base/ui_test_utils.h"
60 #include "components/app_modal/app_modal_dialog.h"
61 #include "components/app_modal/app_modal_dialog_queue.h"
62 #include "components/app_modal/javascript_app_modal_dialog.h"
63 #include "components/app_modal/native_app_modal_dialog.h"
64 #include "components/content_settings/core/browser/host_content_settings_map.h"
65 #include "components/sessions/base_session_service_test_helper.h"
66 #include "components/translate/core/browser/language_state.h"
67 #include "components/translate/core/common/language_detection_details.h"
68 #include "content/public/browser/favicon_status.h"
69 #include "content/public/browser/host_zoom_map.h"
70 #include "content/public/browser/interstitial_page.h"
71 #include "content/public/browser/interstitial_page_delegate.h"
72 #include "content/public/browser/navigation_entry.h"
73 #include "content/public/browser/notification_service.h"
74 #include "content/public/browser/render_frame_host.h"
75 #include "content/public/browser/render_process_host.h"
76 #include "content/public/browser/render_view_host.h"
77 #include "content/public/browser/render_widget_host_view.h"
78 #include "content/public/browser/resource_context.h"
79 #include "content/public/browser/web_contents.h"
80 #include "content/public/browser/web_contents_observer.h"
81 #include "content/public/common/frame_navigate_params.h"
82 #include "content/public/common/renderer_preferences.h"
83 #include "content/public/common/url_constants.h"
84 #include "content/public/test/browser_test_utils.h"
85 #include "content/public/test/test_navigation_observer.h"
86 #include "extensions/browser/extension_registry.h"
87 #include "extensions/browser/extension_system.h"
88 #include "extensions/browser/uninstall_reason.h"
89 #include "extensions/common/constants.h"
90 #include "extensions/common/extension.h"
91 #include "extensions/common/extension_set.h"
92 #include "net/dns/mock_host_resolver.h"
93 #include "net/test/spawned_test_server/spawned_test_server.h"
94 #include "ui/base/l10n/l10n_util.h"
95 #include "ui/base/page_transition_types.h"
97 #if defined(OS_MACOSX)
98 #include "base/mac/scoped_nsautorelease_pool.h"
99 #include "chrome/browser/ui/cocoa/run_loop_testing.h"
100 #endif
102 #if defined(OS_WIN)
103 #include "base/i18n/rtl.h"
104 #include "chrome/browser/browser_process.h"
105 #endif
107 using app_modal::AppModalDialog;
108 using app_modal::AppModalDialogQueue;
109 using app_modal::JavaScriptAppModalDialog;
110 using base::ASCIIToUTF16;
111 using content::InterstitialPage;
112 using content::HostZoomMap;
113 using content::NavigationController;
114 using content::NavigationEntry;
115 using content::OpenURLParams;
116 using content::Referrer;
117 using content::WebContents;
118 using content::WebContentsObserver;
119 using extensions::Extension;
121 namespace {
123 const char* kBeforeUnloadHTML =
124 "<html><head><title>beforeunload</title></head><body>"
125 "<script>window.onbeforeunload=function(e){return 'foo'}</script>"
126 "</body></html>";
128 const char* kOpenNewBeforeUnloadPage =
129 "w=window.open(); w.onbeforeunload=function(e){return 'foo'};";
131 const base::FilePath::CharType* kBeforeUnloadFile =
132 FILE_PATH_LITERAL("beforeunload.html");
134 const base::FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
135 const base::FilePath::CharType* kTitle2File = FILE_PATH_LITERAL("title2.html");
137 const base::FilePath::CharType kDocRoot[] =
138 FILE_PATH_LITERAL("chrome/test/data");
140 // Given a page title, returns the expected window caption string.
141 base::string16 WindowCaptionFromPageTitle(const base::string16& page_title) {
142 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
143 // On Mac or ChromeOS, we don't want to suffix the page title with
144 // the application name.
145 if (page_title.empty())
146 return l10n_util::GetStringUTF16(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);
147 return page_title;
148 #else
149 if (page_title.empty())
150 return l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
152 return l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT,
153 page_title);
154 #endif
157 // Returns the number of active RenderProcessHosts.
158 int CountRenderProcessHosts() {
159 int result = 0;
160 for (content::RenderProcessHost::iterator i(
161 content::RenderProcessHost::AllHostsIterator());
162 !i.IsAtEnd(); i.Advance())
163 ++result;
164 return result;
167 class MockTabStripModelObserver : public TabStripModelObserver {
168 public:
169 MockTabStripModelObserver() : closing_count_(0) {}
171 void TabClosingAt(TabStripModel* tab_strip_model,
172 WebContents* contents,
173 int index) override {
174 ++closing_count_;
177 int closing_count() const { return closing_count_; }
179 private:
180 int closing_count_;
182 DISALLOW_COPY_AND_ASSIGN(MockTabStripModelObserver);
185 // Causes the browser to swap processes on a redirect to an HTTPS URL.
186 class TransferHttpsRedirectsContentBrowserClient
187 : public chrome::ChromeContentBrowserClient {
188 public:
189 bool ShouldSwapProcessesForRedirect(
190 content::ResourceContext* resource_context,
191 const GURL& current_url,
192 const GURL& new_url) override {
193 return new_url.SchemeIs(url::kHttpsScheme);
197 // Used by CloseWithAppMenuOpen. Invokes CloseWindow on the supplied browser.
198 void CloseWindowCallback(Browser* browser) {
199 chrome::CloseWindow(browser);
202 // Used by CloseWithAppMenuOpen. Posts a CloseWindowCallback and shows the app
203 // menu.
204 void RunCloseWithAppMenuCallback(Browser* browser) {
205 // ShowAppMenu is modal under views. Schedule a task that closes the window.
206 base::MessageLoop::current()->PostTask(
207 FROM_HERE, base::Bind(&CloseWindowCallback, browser));
208 chrome::ShowAppMenu(browser);
211 // Displays "INTERSTITIAL" while the interstitial is attached.
212 // (InterstitialPage can be used in a test directly, but there would be no way
213 // to visually tell if it is showing or not.)
214 class TestInterstitialPage : public content::InterstitialPageDelegate {
215 public:
216 TestInterstitialPage(WebContents* tab, bool new_navigation, const GURL& url) {
217 interstitial_page_ = InterstitialPage::Create(
218 tab, new_navigation, url , this);
219 interstitial_page_->Show();
221 ~TestInterstitialPage() override {}
222 void Proceed() {
223 interstitial_page_->Proceed();
225 void DontProceed() {
226 interstitial_page_->DontProceed();
229 std::string GetHTMLContents() override { return "<h1>INTERSTITIAL</h1>"; }
231 private:
232 InterstitialPage* interstitial_page_; // Owns us.
235 class RenderViewSizeObserver : public content::WebContentsObserver {
236 public:
237 RenderViewSizeObserver(content::WebContents* web_contents,
238 BrowserWindow* browser_window)
239 : WebContentsObserver(web_contents),
240 browser_window_(browser_window) {
243 void GetSizeForRenderViewHost(
244 content::RenderViewHost* render_view_host,
245 gfx::Size* rwhv_create_size,
246 gfx::Size* rwhv_commit_size,
247 gfx::Size* wcv_commit_size) {
248 RenderViewSizes::const_iterator result = render_view_sizes_.end();
249 result = render_view_sizes_.find(render_view_host);
250 if (result != render_view_sizes_.end()) {
251 *rwhv_create_size = result->second.rwhv_create_size;
252 *rwhv_commit_size = result->second.rwhv_commit_size;
253 *wcv_commit_size = result->second.wcv_commit_size;
257 void set_wcv_resize_insets(const gfx::Size& wcv_resize_insets) {
258 wcv_resize_insets_ = wcv_resize_insets;
261 // Cache the size when RenderViewHost is first created.
262 void RenderViewCreated(content::RenderViewHost* render_view_host) override {
263 render_view_sizes_[render_view_host].rwhv_create_size =
264 render_view_host->GetView()->GetViewBounds().size();
267 // Enlarge WebContentsView by |wcv_resize_insets_| while the navigation entry
268 // is pending.
269 void DidStartNavigationToPendingEntry(
270 const GURL& url,
271 NavigationController::ReloadType reload_type) override {
272 if (wcv_resize_insets_.IsEmpty())
273 return;
274 // Resizing the main browser window by |wcv_resize_insets_| will
275 // automatically resize the WebContentsView by the same amount.
276 // Just resizing WebContentsView directly doesn't work on Linux, because the
277 // next automatic layout of the browser window will resize WebContentsView
278 // back to the previous size. To make it consistent, resize main browser
279 // window on all platforms.
280 gfx::Rect bounds(browser_window_->GetBounds());
281 gfx::Size size(bounds.size());
282 size.Enlarge(wcv_resize_insets_.width(), wcv_resize_insets_.height());
283 bounds.set_size(size);
284 browser_window_->SetBounds(bounds);
285 // Let the message loop run so that resize actually takes effect.
286 content::RunAllPendingInMessageLoop();
289 // Cache the sizes of RenderWidgetHostView and WebContentsView when the
290 // navigation entry is committed, which is before
291 // WebContentsDelegate::DidNavigateMainFramePostCommit is called.
292 void NavigationEntryCommitted(
293 const content::LoadCommittedDetails& details) override {
294 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
295 render_view_sizes_[rvh].rwhv_commit_size =
296 web_contents()->GetRenderWidgetHostView()->GetViewBounds().size();
297 render_view_sizes_[rvh].wcv_commit_size =
298 web_contents()->GetContainerBounds().size();
301 private:
302 struct Sizes {
303 gfx::Size rwhv_create_size; // Size of RenderWidgetHostView when created.
304 gfx::Size rwhv_commit_size; // Size of RenderWidgetHostView when committed.
305 gfx::Size wcv_commit_size; // Size of WebContentsView when committed.
308 typedef std::map<content::RenderViewHost*, Sizes> RenderViewSizes;
309 RenderViewSizes render_view_sizes_;
310 // Enlarge WebContentsView by this size insets in
311 // DidStartNavigationToPendingEntry.
312 gfx::Size wcv_resize_insets_;
313 BrowserWindow* browser_window_; // Weak ptr.
315 DISALLOW_COPY_AND_ASSIGN(RenderViewSizeObserver);
318 } // namespace
320 class BrowserTest : public ExtensionBrowserTest {
321 protected:
322 // In RTL locales wrap the page title with RTL embedding characters so that it
323 // matches the value returned by GetWindowTitle().
324 base::string16 LocaleWindowCaptionFromPageTitle(
325 const base::string16& expected_title) {
326 base::string16 page_title = WindowCaptionFromPageTitle(expected_title);
327 #if defined(OS_WIN)
328 std::string locale = g_browser_process->GetApplicationLocale();
329 if (base::i18n::GetTextDirectionForLocale(locale.c_str()) ==
330 base::i18n::RIGHT_TO_LEFT) {
331 base::i18n::WrapStringWithLTRFormatting(&page_title);
334 return page_title;
335 #else
336 // Do we need to use the above code on POSIX as well?
337 return page_title;
338 #endif
341 // Returns the app extension aptly named "App Test".
342 const Extension* GetExtension() {
343 extensions::ExtensionRegistry* registry =
344 extensions::ExtensionRegistry::Get(browser()->profile());
345 for (const scoped_refptr<const extensions::Extension>& extension :
346 registry->enabled_extensions()) {
347 if (extension->name() == "App Test")
348 return extension.get();
350 NOTREACHED();
351 return NULL;
355 // Launch the app on a page with no title, check that the app title was set
356 // correctly.
357 IN_PROC_BROWSER_TEST_F(BrowserTest, NoTitle) {
358 #if defined(OS_WIN) && defined(USE_ASH)
359 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
360 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
361 switches::kAshBrowserTests))
362 return;
363 #endif
365 ui_test_utils::NavigateToURL(
366 browser(), ui_test_utils::GetTestUrl(
367 base::FilePath(base::FilePath::kCurrentDirectory),
368 base::FilePath(kTitle1File)));
369 EXPECT_EQ(LocaleWindowCaptionFromPageTitle(ASCIIToUTF16("title1.html")),
370 browser()->GetWindowTitleForCurrentTab());
371 base::string16 tab_title;
372 ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
373 EXPECT_EQ(ASCIIToUTF16("title1.html"), tab_title);
376 // Launch the app, navigate to a page with a title, check that the app title
377 // was set correctly.
378 IN_PROC_BROWSER_TEST_F(BrowserTest, Title) {
379 #if defined(OS_WIN) && defined(USE_ASH)
380 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
381 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
382 switches::kAshBrowserTests))
383 return;
384 #endif
386 ui_test_utils::NavigateToURL(
387 browser(), ui_test_utils::GetTestUrl(
388 base::FilePath(base::FilePath::kCurrentDirectory),
389 base::FilePath(kTitle2File)));
390 const base::string16 test_title(ASCIIToUTF16("Title Of Awesomeness"));
391 EXPECT_EQ(LocaleWindowCaptionFromPageTitle(test_title),
392 browser()->GetWindowTitleForCurrentTab());
393 base::string16 tab_title;
394 ASSERT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &tab_title));
395 EXPECT_EQ(test_title, tab_title);
398 IN_PROC_BROWSER_TEST_F(BrowserTest, JavascriptAlertActivatesTab) {
399 GURL url(ui_test_utils::GetTestUrl(base::FilePath(
400 base::FilePath::kCurrentDirectory), base::FilePath(kTitle1File)));
401 ui_test_utils::NavigateToURL(browser(), url);
402 AddTabAtIndex(0, url, ui::PAGE_TRANSITION_TYPED);
403 EXPECT_EQ(2, browser()->tab_strip_model()->count());
404 EXPECT_EQ(0, browser()->tab_strip_model()->active_index());
405 WebContents* second_tab = browser()->tab_strip_model()->GetWebContentsAt(1);
406 ASSERT_TRUE(second_tab);
407 second_tab->GetMainFrame()->ExecuteJavaScript(
408 ASCIIToUTF16("alert('Activate!');"));
409 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
410 alert->CloseModalDialog();
411 EXPECT_EQ(2, browser()->tab_strip_model()->count());
412 EXPECT_EQ(1, browser()->tab_strip_model()->active_index());
416 #if defined(OS_WIN) && !defined(NDEBUG)
417 // http://crbug.com/114859. Times out frequently on Windows.
418 #define MAYBE_ThirtyFourTabs DISABLED_ThirtyFourTabs
419 #else
420 #define MAYBE_ThirtyFourTabs ThirtyFourTabs
421 #endif
423 // Create 34 tabs and verify that a lot of processes have been created. The
424 // exact number of processes depends on the amount of memory. Previously we
425 // had a hard limit of 31 processes and this test is mainly directed at
426 // verifying that we don't crash when we pass this limit.
427 // Warning: this test can take >30 seconds when running on a slow (low
428 // memory?) Mac builder.
429 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_ThirtyFourTabs) {
430 GURL url(ui_test_utils::GetTestUrl(base::FilePath(
431 base::FilePath::kCurrentDirectory), base::FilePath(kTitle2File)));
433 // There is one initial tab.
434 const int kTabCount = 34;
435 for (int ix = 0; ix != (kTabCount - 1); ++ix) {
436 chrome::AddSelectedTabWithURL(browser(), url,
437 ui::PAGE_TRANSITION_TYPED);
439 EXPECT_EQ(kTabCount, browser()->tab_strip_model()->count());
441 // See GetMaxRendererProcessCount() in
442 // content/browser/renderer_host/render_process_host_impl.cc
443 // for the algorithm to decide how many processes to create.
444 const int kExpectedProcessCount =
445 #if defined(ARCH_CPU_64_BITS)
447 #else
449 #endif
450 if (base::SysInfo::AmountOfPhysicalMemoryMB() >= 2048) {
451 EXPECT_GE(CountRenderProcessHosts(), kExpectedProcessCount);
452 } else {
453 EXPECT_LT(CountRenderProcessHosts(), kExpectedProcessCount);
457 // Test that a browser-initiated navigation to an aborted URL load leaves around
458 // a pending entry if we start from the NTP but not from a normal page.
459 // See http://crbug.com/355537.
460 IN_PROC_BROWSER_TEST_F(BrowserTest, ClearPendingOnFailUnlessNTP) {
461 ASSERT_TRUE(test_server()->Start());
462 WebContents* web_contents =
463 browser()->tab_strip_model()->GetActiveWebContents();
464 GURL ntp_url(chrome::GetNewTabPageURL(browser()->profile()));
465 ui_test_utils::NavigateToURL(browser(), ntp_url);
467 // Navigate to a 204 URL (aborts with no content) on the NTP and make sure it
468 // sticks around so that the user can edit it.
469 GURL abort_url(test_server()->GetURL("nocontent"));
471 content::WindowedNotificationObserver stop_observer(
472 content::NOTIFICATION_LOAD_STOP,
473 content::Source<NavigationController>(
474 &web_contents->GetController()));
475 browser()->OpenURL(OpenURLParams(abort_url, Referrer(), CURRENT_TAB,
476 ui::PAGE_TRANSITION_TYPED, false));
477 stop_observer.Wait();
478 EXPECT_TRUE(web_contents->GetController().GetPendingEntry());
479 EXPECT_EQ(abort_url, web_contents->GetVisibleURL());
482 // Navigate to a real URL.
483 GURL real_url(test_server()->GetURL("title1.html"));
484 ui_test_utils::NavigateToURL(browser(), real_url);
485 EXPECT_EQ(real_url, web_contents->GetVisibleURL());
487 // Now navigating to a 204 URL should clear the pending entry.
489 content::WindowedNotificationObserver stop_observer(
490 content::NOTIFICATION_LOAD_STOP,
491 content::Source<NavigationController>(
492 &web_contents->GetController()));
493 browser()->OpenURL(OpenURLParams(abort_url, Referrer(), CURRENT_TAB,
494 ui::PAGE_TRANSITION_TYPED, false));
495 stop_observer.Wait();
496 EXPECT_FALSE(web_contents->GetController().GetPendingEntry());
497 EXPECT_EQ(real_url, web_contents->GetVisibleURL());
501 // Test for crbug.com/297289. Ensure that modal dialogs are closed when a
502 // cross-process navigation is ready to commit.
503 // Flaky test, see https://crbug.com/445155.
504 IN_PROC_BROWSER_TEST_F(BrowserTest, DISABLED_CrossProcessNavCancelsDialogs) {
505 ASSERT_TRUE(test_server()->Start());
506 host_resolver()->AddRule("www.example.com", "127.0.0.1");
507 GURL url(test_server()->GetURL("empty.html"));
508 ui_test_utils::NavigateToURL(browser(), url);
510 // Test this with multiple alert dialogs to ensure that we can navigate away
511 // even if the renderer tries to synchronously create more.
512 // See http://crbug.com/312490.
513 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
514 contents->GetMainFrame()->ExecuteJavaScript(
515 ASCIIToUTF16("alert('one'); alert('two');"));
516 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
517 EXPECT_TRUE(alert->IsValid());
518 AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
519 EXPECT_TRUE(dialog_queue->HasActiveDialog());
521 // A cross-site navigation should force the dialog to close.
522 GURL url2("http://www.example.com/empty.html");
523 ui_test_utils::NavigateToURL(browser(), url2);
524 EXPECT_FALSE(dialog_queue->HasActiveDialog());
526 // Make sure input events still work in the renderer process.
527 EXPECT_FALSE(contents->GetRenderProcessHost()->IgnoreInputEvents());
530 // Make sure that dialogs are closed after a renderer process dies, and that
531 // subsequent navigations work. See http://crbug/com/343265.
532 IN_PROC_BROWSER_TEST_F(BrowserTest, SadTabCancelsDialogs) {
533 ASSERT_TRUE(test_server()->Start());
534 host_resolver()->AddRule("www.example.com", "127.0.0.1");
535 GURL beforeunload_url(test_server()->GetURL("files/beforeunload.html"));
536 ui_test_utils::NavigateToURL(browser(), beforeunload_url);
538 // Start a navigation to trigger the beforeunload dialog.
539 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
540 contents->GetMainFrame()->ExecuteJavaScript(
541 ASCIIToUTF16("window.location.href = 'data:text/html,foo'"));
542 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
543 EXPECT_TRUE(alert->IsValid());
544 AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
545 EXPECT_TRUE(dialog_queue->HasActiveDialog());
547 // Crash the renderer process and ensure the dialog is gone.
548 content::RenderProcessHost* child_process = contents->GetRenderProcessHost();
549 content::RenderProcessHostWatcher crash_observer(
550 child_process,
551 content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
552 child_process->Shutdown(0, false);
553 crash_observer.Wait();
554 EXPECT_FALSE(dialog_queue->HasActiveDialog());
556 // Make sure subsequent navigations work.
557 GURL url2("http://www.example.com/files/empty.html");
558 ui_test_utils::NavigateToURL(browser(), url2);
561 // Make sure that dialogs opened by subframes are closed when the process dies.
562 // See http://crbug.com/366510.
563 IN_PROC_BROWSER_TEST_F(BrowserTest, SadTabCancelsSubframeDialogs) {
564 // Navigate to an iframe that opens an alert dialog.
565 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
566 contents->GetMainFrame()->ExecuteJavaScript(
567 ASCIIToUTF16("window.location.href = 'data:text/html,"
568 "<iframe srcdoc=\"<script>alert(1)</script>\">'"));
569 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
570 EXPECT_TRUE(alert->IsValid());
571 AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
572 EXPECT_TRUE(dialog_queue->HasActiveDialog());
574 // Crash the renderer process and ensure the dialog is gone.
575 content::RenderProcessHost* child_process = contents->GetRenderProcessHost();
576 content::RenderProcessHostWatcher crash_observer(
577 child_process,
578 content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
579 child_process->Shutdown(0, false);
580 crash_observer.Wait();
581 EXPECT_FALSE(dialog_queue->HasActiveDialog());
583 // Make sure subsequent navigations work.
584 GURL url2("data:text/html,foo");
585 ui_test_utils::NavigateToURL(browser(), url2);
588 // Test for crbug.com/22004. Reloading a page with a before unload handler and
589 // then canceling the dialog should not leave the throbber spinning.
590 IN_PROC_BROWSER_TEST_F(BrowserTest, ReloadThenCancelBeforeUnload) {
591 GURL url(std::string("data:text/html,") + kBeforeUnloadHTML);
592 ui_test_utils::NavigateToURL(browser(), url);
594 // Navigate to another page, but click cancel in the dialog. Make sure that
595 // the throbber stops spinning.
596 chrome::Reload(browser(), CURRENT_TAB);
597 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
598 alert->CloseModalDialog();
599 EXPECT_FALSE(
600 browser()->tab_strip_model()->GetActiveWebContents()->IsLoading());
602 // Clear the beforeunload handler so the test can easily exit.
603 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
604 ExecuteJavaScript(ASCIIToUTF16("onbeforeunload=null;"));
607 class RedirectObserver : public content::WebContentsObserver {
608 public:
609 explicit RedirectObserver(content::WebContents* web_contents)
610 : WebContentsObserver(web_contents) {
613 void DidNavigateAnyFrame(
614 content::RenderFrameHost* render_frame_host,
615 const content::LoadCommittedDetails& details,
616 const content::FrameNavigateParams& params) override {
617 params_ = params;
620 void WebContentsDestroyed() override {
621 // Make sure we don't close the tab while the observer is in scope.
622 // See http://crbug.com/314036.
623 FAIL() << "WebContents closed during navigation (http://crbug.com/314036).";
626 const content::FrameNavigateParams& params() const {
627 return params_;
630 private:
631 content::FrameNavigateParams params_;
633 DISALLOW_COPY_AND_ASSIGN(RedirectObserver);
636 // Ensure that a transferred cross-process navigation does not generate
637 // DidStopLoading events until the navigation commits. If it did, then
638 // ui_test_utils::NavigateToURL would proceed before the URL had committed.
639 // http://crbug.com/243957.
640 IN_PROC_BROWSER_TEST_F(BrowserTest, NoStopDuringTransferUntilCommit) {
641 // Create HTTP and HTTPS servers for a cross-site transition.
642 ASSERT_TRUE(test_server()->Start());
643 net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
644 net::SpawnedTestServer::kLocalhost,
645 base::FilePath(kDocRoot));
646 ASSERT_TRUE(https_test_server.Start());
648 // Temporarily replace ContentBrowserClient with one that will cause a
649 // process swap on all redirects to HTTPS URLs.
650 TransferHttpsRedirectsContentBrowserClient new_client;
651 content::ContentBrowserClient* old_client =
652 SetBrowserClientForTesting(&new_client);
654 GURL init_url(test_server()->GetURL("files/title1.html"));
655 ui_test_utils::NavigateToURL(browser(), init_url);
657 // Navigate to a same-site page that redirects, causing a transfer.
658 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
660 // Create a RedirectObserver that goes away before we close the tab.
662 RedirectObserver redirect_observer(contents);
663 GURL dest_url(https_test_server.GetURL("files/title2.html"));
664 GURL redirect_url(test_server()->GetURL("server-redirect?" +
665 dest_url.spec()));
666 ui_test_utils::NavigateToURL(browser(), redirect_url);
668 // We should immediately see the new committed entry.
669 EXPECT_FALSE(contents->GetController().GetPendingEntry());
670 EXPECT_EQ(dest_url,
671 contents->GetController().GetLastCommittedEntry()->GetURL());
673 // We should keep track of the original request URL, redirect chain, and
674 // page transition type during a transfer, since these are necessary for
675 // history autocomplete to work.
676 EXPECT_EQ(redirect_url, contents->GetController().GetLastCommittedEntry()->
677 GetOriginalRequestURL());
678 EXPECT_EQ(2U, redirect_observer.params().redirects.size());
679 EXPECT_EQ(redirect_url, redirect_observer.params().redirects.at(0));
680 EXPECT_EQ(dest_url, redirect_observer.params().redirects.at(1));
681 EXPECT_TRUE(ui::PageTransitionCoreTypeIs(
682 redirect_observer.params().transition, ui::PAGE_TRANSITION_TYPED));
685 // Restore previous browser client.
686 SetBrowserClientForTesting(old_client);
689 // Tests that a cross-process redirect will only cause the beforeunload
690 // handler to run once.
691 IN_PROC_BROWSER_TEST_F(BrowserTest, SingleBeforeUnloadAfterRedirect) {
692 // Create HTTP and HTTPS servers for a cross-site transition.
693 ASSERT_TRUE(test_server()->Start());
694 net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
695 net::SpawnedTestServer::kLocalhost,
696 base::FilePath(kDocRoot));
697 ASSERT_TRUE(https_test_server.Start());
699 // Temporarily replace ContentBrowserClient with one that will cause a
700 // process swap on all redirects to HTTPS URLs.
701 TransferHttpsRedirectsContentBrowserClient new_client;
702 content::ContentBrowserClient* old_client =
703 SetBrowserClientForTesting(&new_client);
705 // Navigate to a page with a beforeunload handler.
706 GURL url(test_server()->GetURL("files/beforeunload.html"));
707 ui_test_utils::NavigateToURL(browser(), url);
709 // Navigate to a URL that redirects to another process and approve the
710 // beforeunload dialog that pops up.
711 content::WindowedNotificationObserver nav_observer(
712 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
713 content::NotificationService::AllSources());
714 GURL https_url(https_test_server.GetURL("files/title1.html"));
715 GURL redirect_url(test_server()->GetURL("server-redirect?" +
716 https_url.spec()));
717 browser()->OpenURL(OpenURLParams(redirect_url, Referrer(), CURRENT_TAB,
718 ui::PAGE_TRANSITION_TYPED, false));
719 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
720 EXPECT_TRUE(
721 static_cast<JavaScriptAppModalDialog*>(alert)->is_before_unload_dialog());
722 alert->native_dialog()->AcceptAppModalDialog();
723 nav_observer.Wait();
725 // Restore previous browser client.
726 SetBrowserClientForTesting(old_client);
729 // Test for crbug.com/80401. Canceling a before unload dialog should reset
730 // the URL to the previous page's URL.
731 IN_PROC_BROWSER_TEST_F(BrowserTest, CancelBeforeUnloadResetsURL) {
732 GURL url(ui_test_utils::GetTestUrl(base::FilePath(
733 base::FilePath::kCurrentDirectory), base::FilePath(kBeforeUnloadFile)));
734 ui_test_utils::NavigateToURL(browser(), url);
736 // Navigate to a page that triggers a cross-site transition.
737 ASSERT_TRUE(test_server()->Start());
738 GURL url2(test_server()->GetURL("files/title1.html"));
739 browser()->OpenURL(OpenURLParams(
740 url2, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
742 content::WindowedNotificationObserver host_destroyed_observer(
743 content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
744 content::NotificationService::AllSources());
746 // Cancel the dialog.
747 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
748 alert->CloseModalDialog();
749 EXPECT_FALSE(
750 browser()->tab_strip_model()->GetActiveWebContents()->IsLoading());
752 // Verify there are no pending history items after the dialog is cancelled.
753 // (see crbug.com/93858)
754 NavigationEntry* entry = browser()->tab_strip_model()->
755 GetActiveWebContents()->GetController().GetPendingEntry();
756 EXPECT_EQ(NULL, entry);
758 // Wait for the ShouldClose_ACK to arrive. We can detect it by waiting for
759 // the pending RVH to be destroyed.
760 host_destroyed_observer.Wait();
761 EXPECT_EQ(url, browser()->toolbar_model()->GetURL());
763 // Clear the beforeunload handler so the test can easily exit.
764 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
765 ExecuteJavaScript(ASCIIToUTF16("onbeforeunload=null;"));
768 // Test for crbug.com/11647. A page closed with window.close() should not have
769 // two beforeunload dialogs shown.
770 // http://crbug.com/410891
771 IN_PROC_BROWSER_TEST_F(BrowserTest,
772 DISABLED_SingleBeforeUnloadAfterWindowClose) {
773 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()->
774 ExecuteJavaScriptForTests(ASCIIToUTF16(kOpenNewBeforeUnloadPage));
776 // Close the new window with JavaScript, which should show a single
777 // beforeunload dialog. Then show another alert, to make it easy to verify
778 // that a second beforeunload dialog isn't shown.
779 browser()->tab_strip_model()->GetWebContentsAt(0)->GetMainFrame()->
780 ExecuteJavaScriptForTests(ASCIIToUTF16("w.close(); alert('bar');"));
781 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
782 alert->native_dialog()->AcceptAppModalDialog();
784 alert = ui_test_utils::WaitForAppModalDialog();
785 EXPECT_FALSE(static_cast<JavaScriptAppModalDialog*>(alert)->
786 is_before_unload_dialog());
787 alert->native_dialog()->AcceptAppModalDialog();
790 // BrowserTest.BeforeUnloadVsBeforeReload times out on Windows.
791 // http://crbug.com/130411
792 #if defined(OS_WIN)
793 #define MAYBE_BeforeUnloadVsBeforeReload DISABLED_BeforeUnloadVsBeforeReload
794 #else
795 #define MAYBE_BeforeUnloadVsBeforeReload BeforeUnloadVsBeforeReload
796 #endif
798 // Test that when a page has an onunload handler, reloading a page shows a
799 // different dialog than navigating to a different page.
800 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_BeforeUnloadVsBeforeReload) {
801 GURL url(std::string("data:text/html,") + kBeforeUnloadHTML);
802 ui_test_utils::NavigateToURL(browser(), url);
804 // Reload the page, and check that we get a "before reload" dialog.
805 chrome::Reload(browser(), CURRENT_TAB);
806 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
807 EXPECT_TRUE(static_cast<JavaScriptAppModalDialog*>(alert)->is_reload());
809 // Cancel the reload.
810 alert->native_dialog()->CancelAppModalDialog();
812 // Navigate to another url, and check that we get a "before unload" dialog.
813 GURL url2(url::kAboutBlankURL);
814 browser()->OpenURL(OpenURLParams(
815 url2, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false));
817 alert = ui_test_utils::WaitForAppModalDialog();
818 EXPECT_FALSE(static_cast<JavaScriptAppModalDialog*>(alert)->is_reload());
820 // Accept the navigation so we end up on a page without a beforeunload hook.
821 alert->native_dialog()->AcceptAppModalDialog();
824 // BeforeUnloadAtQuitWithTwoWindows is a regression test for
825 // http://crbug.com/11842. It opens two windows, one of which has a
826 // beforeunload handler and attempts to exit cleanly.
827 class BeforeUnloadAtQuitWithTwoWindows : public InProcessBrowserTest {
828 public:
829 // This test is for testing a specific shutdown behavior. This mimics what
830 // happens in InProcessBrowserTest::RunTestOnMainThread and QuitBrowsers, but
831 // ensures that it happens through the single IDC_EXIT of the test.
832 void TearDownOnMainThread() override {
833 // Cycle both the MessageLoop and the Cocoa runloop twice to flush out any
834 // Chrome work that generates Cocoa work. Do this twice since there are two
835 // Browsers that must be closed.
836 CycleRunLoops();
837 CycleRunLoops();
839 // Run the application event loop to completion, which will cycle the
840 // native MessagePump on all platforms.
841 base::MessageLoop::current()->PostTask(FROM_HERE,
842 base::MessageLoop::QuitClosure());
843 base::MessageLoop::current()->Run();
845 // Take care of any remaining Cocoa work.
846 CycleRunLoops();
848 // At this point, quit should be for real now.
849 ASSERT_EQ(0u, chrome::GetTotalBrowserCount());
852 // A helper function that cycles the MessageLoop, and on Mac, the Cocoa run
853 // loop. It also drains the NSAutoreleasePool.
854 void CycleRunLoops() {
855 content::RunAllPendingInMessageLoop();
856 #if defined(OS_MACOSX)
857 chrome::testing::NSRunLoopRunAllPending();
858 AutoreleasePool()->Recycle();
859 #endif
863 // Disabled, http://crbug.com/159214 .
864 IN_PROC_BROWSER_TEST_F(BeforeUnloadAtQuitWithTwoWindows,
865 DISABLED_IfThisTestTimesOutItIndicatesFAILURE) {
866 // In the first browser, set up a page that has a beforeunload handler.
867 GURL url(std::string("data:text/html,") + kBeforeUnloadHTML);
868 ui_test_utils::NavigateToURL(browser(), url);
870 // Open a second browser window at about:blank.
871 ui_test_utils::BrowserAddedObserver browser_added_observer;
872 chrome::NewEmptyWindow(browser()->profile(), chrome::GetActiveDesktop());
873 Browser* second_window = browser_added_observer.WaitForSingleNewBrowser();
874 ui_test_utils::NavigateToURL(second_window, GURL(url::kAboutBlankURL));
876 // Tell the application to quit. IDC_EXIT calls AttemptUserExit, which on
877 // everything but ChromeOS allows unload handlers to block exit. On that
878 // platform, though, it exits unconditionally. See the comment and bug ID
879 // in AttemptUserExit() in application_lifetime.cc.
880 #if defined(OS_CHROMEOS)
881 chrome::AttemptExit();
882 #else
883 chrome::ExecuteCommand(second_window, IDC_EXIT);
884 #endif
886 // The beforeunload handler will run at exit, ensure it does, and then accept
887 // it to allow shutdown to proceed.
888 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
889 ASSERT_TRUE(alert);
890 EXPECT_TRUE(
891 static_cast<JavaScriptAppModalDialog*>(alert)->is_before_unload_dialog());
892 alert->native_dialog()->AcceptAppModalDialog();
894 // But wait there's more! If this test times out, it likely means that the
895 // browser has not been able to quit correctly, indicating there's a
896 // regression of the bug noted above.
899 // Test that scripts can fork a new renderer process for a cross-site popup,
900 // based on http://www.google.com/chrome/intl/en/webmasters-faq.html#newtab.
901 // The script must open a new tab, set its window.opener to null, and navigate
902 // it to a cross-site URL. It should also work for meta-refreshes.
903 // See http://crbug.com/93517.
904 IN_PROC_BROWSER_TEST_F(BrowserTest, NullOpenerRedirectForksProcess) {
905 base::CommandLine::ForCurrentProcess()->AppendSwitch(
906 switches::kDisablePopupBlocking);
908 // Create http and https servers for a cross-site transition.
909 ASSERT_TRUE(test_server()->Start());
910 net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
911 net::SpawnedTestServer::kLocalhost,
912 base::FilePath(kDocRoot));
913 ASSERT_TRUE(https_test_server.Start());
914 GURL http_url(test_server()->GetURL("files/title1.html"));
915 GURL https_url(https_test_server.GetURL(std::string()));
917 // Start with an http URL.
918 ui_test_utils::NavigateToURL(browser(), http_url);
919 WebContents* oldtab = browser()->tab_strip_model()->GetActiveWebContents();
920 content::RenderProcessHost* process = oldtab->GetRenderProcessHost();
922 // Now open a tab to a blank page, set its opener to null, and redirect it
923 // cross-site.
924 std::string redirect_popup = "w=window.open();";
925 redirect_popup += "w.opener=null;";
926 redirect_popup += "w.document.location=\"";
927 redirect_popup += https_url.spec();
928 redirect_popup += "\";";
930 content::WindowedNotificationObserver popup_observer(
931 chrome::NOTIFICATION_TAB_ADDED,
932 content::NotificationService::AllSources());
933 content::WindowedNotificationObserver nav_observer(
934 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
935 content::NotificationService::AllSources());
936 oldtab->GetMainFrame()->
937 ExecuteJavaScriptForTests(ASCIIToUTF16(redirect_popup));
939 // Wait for popup window to appear and finish navigating.
940 popup_observer.Wait();
941 ASSERT_EQ(2, browser()->tab_strip_model()->count());
942 WebContents* newtab = browser()->tab_strip_model()->GetActiveWebContents();
943 EXPECT_TRUE(newtab);
944 EXPECT_NE(oldtab, newtab);
945 nav_observer.Wait();
946 ASSERT_TRUE(newtab->GetController().GetLastCommittedEntry());
947 EXPECT_EQ(https_url.spec(),
948 newtab->GetController().GetLastCommittedEntry()->GetURL().spec());
950 // Popup window should not be in the opener's process.
951 content::RenderProcessHost* popup_process =
952 newtab->GetRenderProcessHost();
953 EXPECT_NE(process, popup_process);
955 // Now open a tab to a blank page, set its opener to null, and use a
956 // meta-refresh to navigate it instead.
957 std::string refresh_popup = "w=window.open();";
958 refresh_popup += "w.opener=null;";
959 refresh_popup += "w.document.write(";
960 refresh_popup += "'<META HTTP-EQUIV=\"refresh\" content=\"0; url=";
961 refresh_popup += https_url.spec();
962 refresh_popup += "\">');w.document.close();";
964 content::WindowedNotificationObserver popup_observer2(
965 chrome::NOTIFICATION_TAB_ADDED,
966 content::NotificationService::AllSources());
967 content::WindowedNotificationObserver nav_observer2(
968 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
969 content::NotificationService::AllSources());
970 oldtab->GetMainFrame()->
971 ExecuteJavaScriptForTests(ASCIIToUTF16(refresh_popup));
973 // Wait for popup window to appear and finish navigating.
974 popup_observer2.Wait();
975 ASSERT_EQ(3, browser()->tab_strip_model()->count());
976 WebContents* newtab2 = browser()->tab_strip_model()->GetActiveWebContents();
977 EXPECT_TRUE(newtab2);
978 EXPECT_NE(oldtab, newtab2);
979 nav_observer2.Wait();
980 ASSERT_TRUE(newtab2->GetController().GetLastCommittedEntry());
981 EXPECT_EQ(https_url.spec(),
982 newtab2->GetController().GetLastCommittedEntry()->GetURL().spec());
984 // This popup window should also not be in the opener's process.
985 content::RenderProcessHost* popup_process2 =
986 newtab2->GetRenderProcessHost();
987 EXPECT_NE(process, popup_process2);
990 // Tests that other popup navigations that do not follow the steps at
991 // http://www.google.com/chrome/intl/en/webmasters-faq.html#newtab will not
992 // fork a new renderer process.
993 IN_PROC_BROWSER_TEST_F(BrowserTest, OtherRedirectsDontForkProcess) {
994 base::CommandLine::ForCurrentProcess()->AppendSwitch(
995 switches::kDisablePopupBlocking);
997 // Create http and https servers for a cross-site transition.
998 ASSERT_TRUE(test_server()->Start());
999 net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
1000 net::SpawnedTestServer::kLocalhost,
1001 base::FilePath(kDocRoot));
1002 ASSERT_TRUE(https_test_server.Start());
1003 GURL http_url(test_server()->GetURL("files/title1.html"));
1004 GURL https_url(https_test_server.GetURL(std::string()));
1006 // Start with an http URL.
1007 ui_test_utils::NavigateToURL(browser(), http_url);
1008 WebContents* oldtab = browser()->tab_strip_model()->GetActiveWebContents();
1009 content::RenderProcessHost* process = oldtab->GetRenderProcessHost();
1011 // Now open a tab to a blank page, set its opener to null, and redirect it
1012 // cross-site.
1013 std::string dont_fork_popup = "w=window.open();";
1014 dont_fork_popup += "w.document.location=\"";
1015 dont_fork_popup += https_url.spec();
1016 dont_fork_popup += "\";";
1018 content::WindowedNotificationObserver popup_observer(
1019 chrome::NOTIFICATION_TAB_ADDED,
1020 content::NotificationService::AllSources());
1021 content::WindowedNotificationObserver nav_observer(
1022 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1023 content::NotificationService::AllSources());
1024 oldtab->GetMainFrame()->
1025 ExecuteJavaScriptForTests(ASCIIToUTF16(dont_fork_popup));
1027 // Wait for popup window to appear and finish navigating.
1028 popup_observer.Wait();
1029 ASSERT_EQ(2, browser()->tab_strip_model()->count());
1030 WebContents* newtab = browser()->tab_strip_model()->GetActiveWebContents();
1031 EXPECT_TRUE(newtab);
1032 EXPECT_NE(oldtab, newtab);
1033 nav_observer.Wait();
1034 ASSERT_TRUE(newtab->GetController().GetLastCommittedEntry());
1035 EXPECT_EQ(https_url.spec(),
1036 newtab->GetController().GetLastCommittedEntry()->GetURL().spec());
1038 // Popup window should still be in the opener's process.
1039 content::RenderProcessHost* popup_process =
1040 newtab->GetRenderProcessHost();
1041 EXPECT_EQ(process, popup_process);
1043 // Same thing if the current tab tries to navigate itself.
1044 std::string navigate_str = "document.location=\"";
1045 navigate_str += https_url.spec();
1046 navigate_str += "\";";
1048 content::WindowedNotificationObserver nav_observer2(
1049 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1050 content::NotificationService::AllSources());
1051 oldtab->GetMainFrame()->ExecuteJavaScriptForTests(ASCIIToUTF16(navigate_str));
1052 nav_observer2.Wait();
1053 ASSERT_TRUE(oldtab->GetController().GetLastCommittedEntry());
1054 EXPECT_EQ(https_url.spec(),
1055 oldtab->GetController().GetLastCommittedEntry()->GetURL().spec());
1057 // Original window should still be in the original process.
1058 content::RenderProcessHost* new_process = newtab->GetRenderProcessHost();
1059 EXPECT_EQ(process, new_process);
1062 // Test that get_process_idle_time() returns reasonable values when compared
1063 // with time deltas measured locally.
1064 IN_PROC_BROWSER_TEST_F(BrowserTest, RenderIdleTime) {
1065 base::TimeTicks start = base::TimeTicks::Now();
1066 ui_test_utils::NavigateToURL(
1067 browser(), ui_test_utils::GetTestUrl(
1068 base::FilePath(base::FilePath::kCurrentDirectory),
1069 base::FilePath(kTitle1File)));
1070 content::RenderProcessHost::iterator it(
1071 content::RenderProcessHost::AllHostsIterator());
1072 for (; !it.IsAtEnd(); it.Advance()) {
1073 base::TimeDelta renderer_td =
1074 it.GetCurrentValue()->GetChildProcessIdleTime();
1075 base::TimeDelta browser_td = base::TimeTicks::Now() - start;
1076 EXPECT_TRUE(browser_td >= renderer_td);
1080 // Test IDC_CREATE_SHORTCUTS command is enabled for url scheme file, ftp, http
1081 // and https and disabled for chrome://, about:// etc.
1082 // TODO(pinkerton): Disable app-mode in the model until we implement it
1083 // on the Mac. http://crbug.com/13148
1084 #if !defined(OS_MACOSX)
1085 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutFile) {
1086 CommandUpdater* command_updater =
1087 browser()->command_controller()->command_updater();
1089 static const base::FilePath::CharType* kEmptyFile =
1090 FILE_PATH_LITERAL("empty.html");
1091 GURL file_url(ui_test_utils::GetTestUrl(base::FilePath(
1092 base::FilePath::kCurrentDirectory), base::FilePath(kEmptyFile)));
1093 ASSERT_TRUE(file_url.SchemeIs(url::kFileScheme));
1094 ui_test_utils::NavigateToURL(browser(), file_url);
1095 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1098 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutHttp) {
1099 CommandUpdater* command_updater =
1100 browser()->command_controller()->command_updater();
1102 ASSERT_TRUE(test_server()->Start());
1103 GURL http_url(test_server()->GetURL(std::string()));
1104 ASSERT_TRUE(http_url.SchemeIs(url::kHttpScheme));
1105 ui_test_utils::NavigateToURL(browser(), http_url);
1106 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1109 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutHttps) {
1110 CommandUpdater* command_updater =
1111 browser()->command_controller()->command_updater();
1113 net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_HTTPS,
1114 net::SpawnedTestServer::kLocalhost,
1115 base::FilePath(kDocRoot));
1116 ASSERT_TRUE(test_server.Start());
1117 GURL https_url(test_server.GetURL("/"));
1118 ASSERT_TRUE(https_url.SchemeIs(url::kHttpsScheme));
1119 ui_test_utils::NavigateToURL(browser(), https_url);
1120 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1123 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutFtp) {
1124 CommandUpdater* command_updater =
1125 browser()->command_controller()->command_updater();
1127 net::SpawnedTestServer test_server(net::SpawnedTestServer::TYPE_FTP,
1128 net::SpawnedTestServer::kLocalhost,
1129 base::FilePath(kDocRoot));
1130 ASSERT_TRUE(test_server.Start());
1131 GURL ftp_url(test_server.GetURL(std::string()));
1132 ASSERT_TRUE(ftp_url.SchemeIs(url::kFtpScheme));
1133 ui_test_utils::NavigateToURL(browser(), ftp_url);
1134 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1137 IN_PROC_BROWSER_TEST_F(BrowserTest, CommandCreateAppShortcutInvalid) {
1138 CommandUpdater* command_updater =
1139 browser()->command_controller()->command_updater();
1141 // Urls that should not have shortcuts.
1142 GURL new_tab_url(chrome::kChromeUINewTabURL);
1143 ui_test_utils::NavigateToURL(browser(), new_tab_url);
1144 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1146 GURL history_url(chrome::kChromeUIHistoryURL);
1147 ui_test_utils::NavigateToURL(browser(), history_url);
1148 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1150 GURL downloads_url(chrome::kChromeUIDownloadsURL);
1151 ui_test_utils::NavigateToURL(browser(), downloads_url);
1152 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1154 GURL blank_url(url::kAboutBlankURL);
1155 ui_test_utils::NavigateToURL(browser(), blank_url);
1156 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_CREATE_SHORTCUTS));
1159 // Change a tab into an application window.
1160 // DISABLED: http://crbug.com/72310
1161 IN_PROC_BROWSER_TEST_F(BrowserTest, DISABLED_ConvertTabToAppShortcut) {
1162 ASSERT_TRUE(test_server()->Start());
1163 GURL http_url(test_server()->GetURL(std::string()));
1164 ASSERT_TRUE(http_url.SchemeIs(url::kHttpScheme));
1166 ASSERT_EQ(1, browser()->tab_strip_model()->count());
1167 WebContents* initial_tab = browser()->tab_strip_model()->GetWebContentsAt(0);
1168 WebContents* app_tab = chrome::AddSelectedTabWithURL(
1169 browser(), http_url, ui::PAGE_TRANSITION_TYPED);
1170 ASSERT_EQ(2, browser()->tab_strip_model()->count());
1171 ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile(),
1172 browser()->host_desktop_type()));
1174 // Normal tabs should accept load drops.
1175 EXPECT_TRUE(initial_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1176 EXPECT_TRUE(app_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1178 // Turn |app_tab| into a tab in an app panel.
1179 chrome::ConvertTabToAppWindow(browser(), app_tab);
1181 // The launch should have created a new browser.
1182 ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1183 browser()->host_desktop_type()));
1185 // Find the new browser.
1186 Browser* app_browser = NULL;
1187 for (chrome::BrowserIterator it; !it.done() && !app_browser; it.Next()) {
1188 if (*it != browser())
1189 app_browser = *it;
1191 ASSERT_TRUE(app_browser);
1193 // Check that the tab contents is in the new browser, and not in the old.
1194 ASSERT_EQ(1, browser()->tab_strip_model()->count());
1195 ASSERT_EQ(initial_tab, browser()->tab_strip_model()->GetWebContentsAt(0));
1197 // Check that the appliaction browser has a single tab, and that tab contains
1198 // the content that we app-ified.
1199 ASSERT_EQ(1, app_browser->tab_strip_model()->count());
1200 ASSERT_EQ(app_tab, app_browser->tab_strip_model()->GetWebContentsAt(0));
1202 // Normal tabs should accept load drops.
1203 EXPECT_TRUE(initial_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1205 // The tab in an app window should not.
1206 EXPECT_FALSE(app_tab->GetMutableRendererPrefs()->can_accept_load_drops);
1209 #endif // !defined(OS_MACOSX)
1211 // Test RenderView correctly send back favicon url for web page that redirects
1212 // to an anchor in javascript body.onload handler.
1213 IN_PROC_BROWSER_TEST_F(BrowserTest,
1214 DISABLED_FaviconOfOnloadRedirectToAnchorPage) {
1215 ASSERT_TRUE(test_server()->Start());
1216 GURL url(test_server()->GetURL("files/onload_redirect_to_anchor.html"));
1217 GURL expected_favicon_url(test_server()->GetURL("files/test.png"));
1219 ui_test_utils::NavigateToURL(browser(), url);
1221 NavigationEntry* entry = browser()->tab_strip_model()->
1222 GetActiveWebContents()->GetController().GetLastCommittedEntry();
1223 EXPECT_EQ(expected_favicon_url.spec(), entry->GetFavicon().url.spec());
1226 #if defined(OS_MACOSX) || defined(OS_LINUX) || defined (OS_WIN)
1227 // http://crbug.com/83828. On Mac 10.6, the failure rate is 14%
1228 #define MAYBE_FaviconChange DISABLED_FaviconChange
1229 #else
1230 #define MAYBE_FaviconChange FaviconChange
1231 #endif
1232 // Test that an icon can be changed from JS.
1233 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_FaviconChange) {
1234 static const base::FilePath::CharType* kFile =
1235 FILE_PATH_LITERAL("onload_change_favicon.html");
1236 GURL file_url(ui_test_utils::GetTestUrl(base::FilePath(
1237 base::FilePath::kCurrentDirectory), base::FilePath(kFile)));
1238 ASSERT_TRUE(file_url.SchemeIs(url::kFileScheme));
1239 ui_test_utils::NavigateToURL(browser(), file_url);
1241 NavigationEntry* entry = browser()->tab_strip_model()->
1242 GetActiveWebContents()->GetController().GetLastCommittedEntry();
1243 static const base::FilePath::CharType* kIcon =
1244 FILE_PATH_LITERAL("test1.png");
1245 GURL expected_favicon_url(ui_test_utils::GetTestUrl(base::FilePath(
1246 base::FilePath::kCurrentDirectory), base::FilePath(kIcon)));
1247 EXPECT_EQ(expected_favicon_url.spec(), entry->GetFavicon().url.spec());
1250 // http://crbug.com/172336
1251 #if defined(OS_WIN)
1252 #define MAYBE_TabClosingWhenRemovingExtension \
1253 DISABLED_TabClosingWhenRemovingExtension
1254 #else
1255 #define MAYBE_TabClosingWhenRemovingExtension TabClosingWhenRemovingExtension
1256 #endif
1257 // Makes sure TabClosing is sent when uninstalling an extension that is an app
1258 // tab.
1259 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_TabClosingWhenRemovingExtension) {
1260 ASSERT_TRUE(test_server()->Start());
1261 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1262 GURL url(test_server()->GetURL("empty.html"));
1263 TabStripModel* model = browser()->tab_strip_model();
1265 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1267 const Extension* extension_app = GetExtension();
1269 ui_test_utils::NavigateToURL(browser(), url);
1271 WebContents* app_contents = WebContents::Create(
1272 WebContents::CreateParams(browser()->profile()));
1273 extensions::TabHelper::CreateForWebContents(app_contents);
1274 extensions::TabHelper* extensions_tab_helper =
1275 extensions::TabHelper::FromWebContents(app_contents);
1276 extensions_tab_helper->SetExtensionApp(extension_app);
1278 model->AddWebContents(app_contents, 0, ui::PageTransitionFromInt(0),
1279 TabStripModel::ADD_NONE);
1280 model->SetTabPinned(0, true);
1281 ui_test_utils::NavigateToURL(browser(), url);
1283 MockTabStripModelObserver observer;
1284 model->AddObserver(&observer);
1286 // Uninstall the extension and make sure TabClosing is sent.
1287 ExtensionService* service = extensions::ExtensionSystem::Get(
1288 browser()->profile())->extension_service();
1289 service->UninstallExtension(GetExtension()->id(),
1290 extensions::UNINSTALL_REASON_FOR_TESTING,
1291 base::Bind(&base::DoNothing),
1292 NULL);
1293 EXPECT_EQ(1, observer.closing_count());
1295 model->RemoveObserver(&observer);
1297 // There should only be one tab now.
1298 ASSERT_EQ(1, browser()->tab_strip_model()->count());
1301 #if !defined(OS_MACOSX)
1302 // Open with --app-id=<id>, and see that an application tab opens by default.
1303 IN_PROC_BROWSER_TEST_F(BrowserTest, AppIdSwitch) {
1304 ASSERT_TRUE(test_server()->Start());
1306 // There should be one tab to start with.
1307 ASSERT_EQ(1, browser()->tab_strip_model()->count());
1309 // Load an app.
1310 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1311 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1312 const Extension* extension_app = GetExtension();
1314 base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
1315 command_line.AppendSwitchASCII(switches::kAppId, extension_app->id());
1317 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1318 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1319 StartupBrowserCreatorImpl launch(base::FilePath(), command_line, first_run);
1321 bool new_bookmark_apps_enabled = extensions::util::IsNewBookmarkAppsEnabled();
1323 // If the new bookmark app flow is enabled, the app should open as an tab.
1324 // Otherwise the app should open as an app window.
1325 EXPECT_EQ(!new_bookmark_apps_enabled,
1326 launch.OpenApplicationWindow(browser()->profile(), NULL));
1327 EXPECT_EQ(new_bookmark_apps_enabled,
1328 launch.OpenApplicationTab(browser()->profile()));
1330 // Check that a the number of browsers and tabs is correct.
1331 unsigned int expected_browsers = 1;
1332 int expected_tabs = 1;
1333 new_bookmark_apps_enabled ? expected_tabs++ : expected_browsers++;
1335 EXPECT_EQ(expected_browsers,
1336 chrome::GetBrowserCount(browser()->profile(),
1337 browser()->host_desktop_type()));
1338 EXPECT_EQ(expected_tabs, browser()->tab_strip_model()->count());
1341 // Open an app window and the dev tools window and ensure that the location
1342 // bar settings are correct.
1343 IN_PROC_BROWSER_TEST_F(BrowserTest, ShouldShowLocationBar) {
1344 ASSERT_TRUE(test_server()->Start());
1346 // Load an app.
1347 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1348 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1349 const Extension* extension_app = GetExtension();
1351 // Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.
1352 WebContents* app_window = OpenApplication(AppLaunchParams(
1353 browser()->profile(), extension_app, extensions::LAUNCH_CONTAINER_WINDOW,
1354 NEW_WINDOW, extensions::SOURCE_TEST));
1355 ASSERT_TRUE(app_window);
1357 DevToolsWindow* devtools_window =
1358 DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), false);
1360 // The launch should have created a new app browser and a dev tools browser.
1361 ASSERT_EQ(3u,
1362 chrome::GetBrowserCount(browser()->profile(),
1363 browser()->host_desktop_type()));
1365 // Find the new browsers.
1366 Browser* app_browser = NULL;
1367 Browser* dev_tools_browser = NULL;
1368 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
1369 if (*it == browser()) {
1370 continue;
1371 } else if ((*it)->app_name() == DevToolsWindow::kDevToolsApp) {
1372 dev_tools_browser = *it;
1373 } else {
1374 app_browser = *it;
1377 ASSERT_TRUE(dev_tools_browser);
1378 ASSERT_TRUE(app_browser);
1379 ASSERT_TRUE(app_browser != browser());
1381 EXPECT_FALSE(
1382 dev_tools_browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR));
1383 EXPECT_FALSE(
1384 app_browser->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR));
1386 DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window);
1388 #endif
1390 // Open a normal browser window, a hosted app window, a legacy packaged app
1391 // window and a dev tools window, and check that the web app frame feature is
1392 // supported correctly.
1393 IN_PROC_BROWSER_TEST_F(BrowserTest, ShouldUseWebAppFrame) {
1394 ASSERT_TRUE(test_server()->Start());
1395 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1396 switches::kEnableWebAppFrame);
1398 // Load a hosted app.
1399 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1400 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1401 const Extension* hosted_app = GetExtension();
1403 // Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.
1404 WebContents* hosted_app_window = OpenApplication(AppLaunchParams(
1405 browser()->profile(), hosted_app, extensions::LAUNCH_CONTAINER_WINDOW,
1406 NEW_WINDOW, extensions::SOURCE_UNTRACKED));
1407 ASSERT_TRUE(hosted_app_window);
1409 // Load a packaged app.
1410 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("packaged_app/")));
1411 const Extension* packaged_app = nullptr;
1412 extensions::ExtensionRegistry* registry =
1413 extensions::ExtensionRegistry::Get(browser()->profile());
1414 for (const scoped_refptr<const extensions::Extension>& extension :
1415 registry->enabled_extensions()) {
1416 if (extension->name() == "Packaged App Test")
1417 packaged_app = extension.get();
1419 ASSERT_TRUE(packaged_app);
1421 // Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.
1422 WebContents* packaged_app_window = OpenApplication(AppLaunchParams(
1423 browser()->profile(), packaged_app, extensions::LAUNCH_CONTAINER_WINDOW,
1424 NEW_WINDOW, extensions::SOURCE_UNTRACKED));
1425 ASSERT_TRUE(packaged_app_window);
1427 DevToolsWindow* devtools_window =
1428 DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), false);
1430 // The launch should have created a new app browser and a dev tools browser.
1431 ASSERT_EQ(4u, chrome::GetBrowserCount(browser()->profile(),
1432 browser()->host_desktop_type()));
1434 // Find the new browsers.
1435 Browser* hosted_app_browser = NULL;
1436 Browser* packaged_app_browser = NULL;
1437 Browser* dev_tools_browser = NULL;
1438 for (chrome::BrowserIterator it; !it.done(); it.Next()) {
1439 if (*it == browser()) {
1440 continue;
1441 } else if ((*it)->app_name() == DevToolsWindow::kDevToolsApp) {
1442 dev_tools_browser = *it;
1443 } else if ((*it)->tab_strip_model()->GetActiveWebContents() ==
1444 hosted_app_window) {
1445 hosted_app_browser = *it;
1446 } else {
1447 packaged_app_browser = *it;
1450 ASSERT_TRUE(dev_tools_browser);
1451 ASSERT_TRUE(hosted_app_browser);
1452 ASSERT_TRUE(hosted_app_browser != browser());
1453 ASSERT_TRUE(packaged_app_browser);
1454 ASSERT_TRUE(packaged_app_browser != browser());
1455 ASSERT_TRUE(packaged_app_browser != hosted_app_browser);
1457 EXPECT_FALSE(browser()->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));
1458 EXPECT_FALSE(
1459 dev_tools_browser->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));
1460 EXPECT_EQ(
1461 browser()->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH,
1462 hosted_app_browser->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));
1463 EXPECT_FALSE(packaged_app_browser->SupportsWindowFeature(
1464 Browser::FEATURE_WEBAPPFRAME));
1466 DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window);
1469 // Tests that the CLD (Compact Language Detection) works properly.
1470 IN_PROC_BROWSER_TEST_F(BrowserTest, PageLanguageDetection) {
1471 scoped_ptr<test::CldDataHarness> cld_data_harness =
1472 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
1473 ASSERT_NO_FATAL_FAILURE(cld_data_harness->Init());
1474 ASSERT_TRUE(test_server()->Start());
1476 translate::LanguageDetectionDetails details;
1478 // Open a new tab with a page in English.
1479 AddTabAtIndex(0, GURL(test_server()->GetURL("files/english_page.html")),
1480 ui::PAGE_TRANSITION_TYPED);
1482 WebContents* current_web_contents =
1483 browser()->tab_strip_model()->GetActiveWebContents();
1484 ChromeTranslateClient* chrome_translate_client =
1485 ChromeTranslateClient::FromWebContents(current_web_contents);
1486 content::Source<WebContents> source(current_web_contents);
1488 ui_test_utils::WindowedNotificationObserverWithDetails<
1489 translate::LanguageDetectionDetails>
1490 en_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1491 source);
1492 EXPECT_EQ("",
1493 chrome_translate_client->GetLanguageState().original_language());
1494 en_language_detected_signal.Wait();
1495 EXPECT_TRUE(en_language_detected_signal.GetDetailsFor(
1496 source.map_key(), &details));
1497 EXPECT_EQ("en", details.adopted_language);
1498 EXPECT_EQ("en",
1499 chrome_translate_client->GetLanguageState().original_language());
1501 // Now navigate to a page in French.
1502 ui_test_utils::WindowedNotificationObserverWithDetails<
1503 translate::LanguageDetectionDetails>
1504 fr_language_detected_signal(chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1505 source);
1506 ui_test_utils::NavigateToURL(
1507 browser(), GURL(test_server()->GetURL("files/french_page.html")));
1508 fr_language_detected_signal.Wait();
1509 details.adopted_language.clear();
1510 EXPECT_TRUE(fr_language_detected_signal.GetDetailsFor(
1511 source.map_key(), &details));
1512 EXPECT_EQ("fr", details.adopted_language);
1513 EXPECT_EQ("fr",
1514 chrome_translate_client->GetLanguageState().original_language());
1517 // Chromeos defaults to restoring the last session, so this test isn't
1518 // applicable.
1519 #if !defined(OS_CHROMEOS)
1520 #if defined(OS_MACOSX)
1521 // Crashy, http://crbug.com/38522
1522 #define RestorePinnedTabs DISABLED_RestorePinnedTabs
1523 #endif
1524 // Makes sure pinned tabs are restored correctly on start.
1525 IN_PROC_BROWSER_TEST_F(BrowserTest, RestorePinnedTabs) {
1526 ASSERT_TRUE(test_server()->Start());
1528 // Add an pinned app tab.
1529 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1530 GURL url(test_server()->GetURL("empty.html"));
1531 TabStripModel* model = browser()->tab_strip_model();
1532 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1533 const Extension* extension_app = GetExtension();
1534 ui_test_utils::NavigateToURL(browser(), url);
1535 WebContents* app_contents = WebContents::Create(
1536 WebContents::CreateParams(browser()->profile()));
1537 extensions::TabHelper::CreateForWebContents(app_contents);
1538 extensions::TabHelper* extensions_tab_helper =
1539 extensions::TabHelper::FromWebContents(app_contents);
1540 extensions_tab_helper->SetExtensionApp(extension_app);
1541 model->AddWebContents(app_contents, 0, ui::PageTransitionFromInt(0),
1542 TabStripModel::ADD_NONE);
1543 model->SetTabPinned(0, true);
1544 ui_test_utils::NavigateToURL(browser(), url);
1546 // Add a non pinned tab.
1547 chrome::NewTab(browser());
1549 // Add a pinned non-app tab.
1550 chrome::NewTab(browser());
1551 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1552 model->SetTabPinned(2, true);
1554 // Write out the pinned tabs.
1555 PinnedTabCodec::WritePinnedTabs(browser()->profile());
1557 // Simulate launching again.
1558 base::CommandLine dummy(base::CommandLine::NO_PROGRAM);
1559 chrome::startup::IsFirstRun first_run = first_run::IsChromeFirstRun() ?
1560 chrome::startup::IS_FIRST_RUN : chrome::startup::IS_NOT_FIRST_RUN;
1561 StartupBrowserCreatorImpl launch(base::FilePath(), dummy, first_run);
1562 launch.profile_ = browser()->profile();
1563 launch.ProcessStartupURLs(std::vector<GURL>(),
1564 browser()->host_desktop_type());
1566 // The launch should have created a new browser.
1567 ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1568 browser()->host_desktop_type()));
1570 // Find the new browser.
1571 Browser* new_browser = NULL;
1572 for (chrome::BrowserIterator it; !it.done() && !new_browser; it.Next()) {
1573 if (*it != browser())
1574 new_browser = *it;
1576 ASSERT_TRUE(new_browser);
1577 ASSERT_TRUE(new_browser != browser());
1579 // We should get back an additional tab for the app, and another for the
1580 // default home page.
1581 ASSERT_EQ(3, new_browser->tab_strip_model()->count());
1583 // Make sure the state matches.
1584 TabStripModel* new_model = new_browser->tab_strip_model();
1585 EXPECT_TRUE(new_model->IsAppTab(0));
1586 EXPECT_FALSE(new_model->IsAppTab(1));
1587 EXPECT_FALSE(new_model->IsAppTab(2));
1589 EXPECT_TRUE(new_model->IsTabPinned(0));
1590 EXPECT_TRUE(new_model->IsTabPinned(1));
1591 EXPECT_FALSE(new_model->IsTabPinned(2));
1593 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL),
1594 new_model->GetWebContentsAt(2)->GetURL());
1596 EXPECT_TRUE(
1597 extensions::TabHelper::FromWebContents(
1598 new_model->GetWebContentsAt(0))->extension_app() == extension_app);
1600 #endif // !defined(OS_CHROMEOS)
1602 // This test verifies we don't crash when closing the last window and the app
1603 // menu is showing.
1604 IN_PROC_BROWSER_TEST_F(BrowserTest, CloseWithAppMenuOpen) {
1605 if (browser_defaults::kBrowserAliveWithNoWindows)
1606 return;
1608 // We need a message loop running for menus on windows.
1609 base::MessageLoop::current()->PostTask(
1610 FROM_HERE, base::Bind(&RunCloseWithAppMenuCallback, browser()));
1613 #if !defined(OS_MACOSX)
1614 IN_PROC_BROWSER_TEST_F(BrowserTest, OpenAppWindowLikeNtp) {
1615 ASSERT_TRUE(test_server()->Start());
1617 // Load an app
1618 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1619 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("app/")));
1620 const Extension* extension_app = GetExtension();
1622 // Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.
1623 WebContents* app_window = OpenApplication(AppLaunchParams(
1624 browser()->profile(), extension_app, extensions::LAUNCH_CONTAINER_WINDOW,
1625 NEW_WINDOW, extensions::SOURCE_TEST));
1626 ASSERT_TRUE(app_window);
1628 // Apps launched in a window from the NTP have an extensions tab helper but
1629 // do not have extension_app set in it.
1630 ASSERT_TRUE(extensions::TabHelper::FromWebContents(app_window));
1631 EXPECT_FALSE(
1632 extensions::TabHelper::FromWebContents(app_window)->extension_app());
1633 EXPECT_EQ(extensions::AppLaunchInfo::GetFullLaunchURL(extension_app),
1634 app_window->GetURL());
1636 // The launch should have created a new browser.
1637 ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile(),
1638 browser()->host_desktop_type()));
1640 // Find the new browser.
1641 Browser* new_browser = NULL;
1642 for (chrome::BrowserIterator it; !it.done() && !new_browser; it.Next()) {
1643 if (*it != browser())
1644 new_browser = *it;
1646 ASSERT_TRUE(new_browser);
1647 ASSERT_TRUE(new_browser != browser());
1649 EXPECT_TRUE(new_browser->is_app());
1651 // The browser's app name should include the extension's id.
1652 std::string app_name = new_browser->app_name_;
1653 EXPECT_NE(app_name.find(extension_app->id()), std::string::npos)
1654 << "Name " << app_name << " should contain id "<< extension_app->id();
1656 #endif // !defined(OS_MACOSX)
1658 // Makes sure the browser doesn't crash when
1659 // set_show_state(ui::SHOW_STATE_MAXIMIZED) has been invoked.
1660 IN_PROC_BROWSER_TEST_F(BrowserTest, StartMaximized) {
1661 Browser::Type types[] = { Browser::TYPE_TABBED, Browser::TYPE_POPUP };
1662 for (size_t i = 0; i < arraysize(types); ++i) {
1663 Browser::CreateParams params(types[i], browser()->profile(),
1664 browser()->host_desktop_type());
1665 params.initial_show_state = ui::SHOW_STATE_MAXIMIZED;
1666 AddBlankTabAndShow(new Browser(params));
1670 // Aura doesn't support minimized window. crbug.com/104571.
1671 #if defined(USE_AURA)
1672 #define MAYBE_StartMinimized DISABLED_StartMinimized
1673 #else
1674 #define MAYBE_StartMinimized StartMinimized
1675 #endif
1676 // Makes sure the browser doesn't crash when
1677 // set_show_state(ui::SHOW_STATE_MINIMIZED) has been invoked.
1678 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_StartMinimized) {
1679 Browser::Type types[] = { Browser::TYPE_TABBED, Browser::TYPE_POPUP };
1680 for (size_t i = 0; i < arraysize(types); ++i) {
1681 Browser::CreateParams params(types[i], browser()->profile(),
1682 browser()->host_desktop_type());
1683 params.initial_show_state = ui::SHOW_STATE_MINIMIZED;
1684 AddBlankTabAndShow(new Browser(params));
1688 // Makes sure the forward button is disabled immediately when navigating
1689 // forward to a slow-to-commit page.
1690 IN_PROC_BROWSER_TEST_F(BrowserTest, ForwardDisabledOnForward) {
1691 GURL blank_url(url::kAboutBlankURL);
1692 ui_test_utils::NavigateToURL(browser(), blank_url);
1694 ui_test_utils::NavigateToURL(
1695 browser(), ui_test_utils::GetTestUrl(
1696 base::FilePath(base::FilePath::kCurrentDirectory),
1697 base::FilePath(kTitle1File)));
1699 content::WindowedNotificationObserver back_nav_load_observer(
1700 content::NOTIFICATION_LOAD_STOP,
1701 content::Source<NavigationController>(
1702 &browser()->tab_strip_model()->GetActiveWebContents()->
1703 GetController()));
1704 chrome::GoBack(browser(), CURRENT_TAB);
1705 back_nav_load_observer.Wait();
1706 CommandUpdater* command_updater =
1707 browser()->command_controller()->command_updater();
1708 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_FORWARD));
1710 content::WindowedNotificationObserver forward_nav_load_observer(
1711 content::NOTIFICATION_LOAD_STOP,
1712 content::Source<NavigationController>(
1713 &browser()->tab_strip_model()->GetActiveWebContents()->
1714 GetController()));
1715 chrome::GoForward(browser(), CURRENT_TAB);
1716 // This check will happen before the navigation completes, since the browser
1717 // won't process the renderer's response until the Wait() call below.
1718 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_FORWARD));
1719 forward_nav_load_observer.Wait();
1722 // Makes sure certain commands are disabled when Incognito mode is forced.
1723 IN_PROC_BROWSER_TEST_F(BrowserTest, DisableMenuItemsWhenIncognitoIsForced) {
1724 CommandUpdater* command_updater =
1725 browser()->command_controller()->command_updater();
1726 // At the beginning, all commands are enabled.
1727 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1728 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1729 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1730 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1731 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1732 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1734 // Set Incognito to FORCED.
1735 IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
1736 IncognitoModePrefs::FORCED);
1737 // Bookmarks & Settings commands should get disabled.
1738 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1739 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1740 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1741 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1742 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1743 // New Incognito Window command, however, should be enabled.
1744 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1746 // Create a new browser.
1747 Browser* new_browser =
1748 new Browser(Browser::CreateParams(
1749 browser()->profile()->GetOffTheRecordProfile(),
1750 browser()->host_desktop_type()));
1751 CommandUpdater* new_command_updater =
1752 new_browser->command_controller()->command_updater();
1753 // It should have Bookmarks & Settings commands disabled by default.
1754 EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1755 EXPECT_FALSE(new_command_updater->IsCommandEnabled(
1756 IDC_SHOW_BOOKMARK_MANAGER));
1757 EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1758 EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1759 EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_OPTIONS));
1760 EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1763 // Makes sure New Incognito Window command is disabled when Incognito mode is
1764 // not available.
1765 IN_PROC_BROWSER_TEST_F(BrowserTest,
1766 NoNewIncognitoWindowWhenIncognitoIsDisabled) {
1767 CommandUpdater* command_updater =
1768 browser()->command_controller()->command_updater();
1769 // Set Incognito to DISABLED.
1770 IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
1771 IncognitoModePrefs::DISABLED);
1772 // Make sure New Incognito Window command is disabled. All remaining commands
1773 // should be enabled.
1774 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1775 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1776 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1777 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1778 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1779 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1781 // Create a new browser.
1782 Browser* new_browser =
1783 new Browser(Browser::CreateParams(browser()->profile(),
1784 browser()->host_desktop_type()));
1785 CommandUpdater* new_command_updater =
1786 new_browser->command_controller()->command_updater();
1787 EXPECT_FALSE(new_command_updater->IsCommandEnabled(IDC_NEW_INCOGNITO_WINDOW));
1788 EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1789 EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1790 EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1791 EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1792 EXPECT_TRUE(new_command_updater->IsCommandEnabled(IDC_OPTIONS));
1795 // Makes sure Extensions and Settings commands are disabled in certain
1796 // circumstances even though normally they should stay enabled.
1797 IN_PROC_BROWSER_TEST_F(BrowserTest,
1798 DisableExtensionsAndSettingsWhenIncognitoIsDisabled) {
1799 CommandUpdater* command_updater =
1800 browser()->command_controller()->command_updater();
1801 // Disable extensions. This should disable Extensions menu.
1802 extensions::ExtensionSystem::Get(browser()->profile())->extension_service()->
1803 set_extensions_enabled(false);
1804 // Set Incognito to DISABLED.
1805 IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(),
1806 IncognitoModePrefs::DISABLED);
1807 // Make sure Manage Extensions command is disabled.
1808 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1809 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_NEW_WINDOW));
1810 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SHOW_BOOKMARK_MANAGER));
1811 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1812 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1814 // Create a popup (non-main-UI-type) browser. Settings command as well
1815 // as Extensions should be disabled.
1816 Browser* popup_browser = new Browser(
1817 Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(),
1818 browser()->host_desktop_type()));
1819 CommandUpdater* popup_command_updater =
1820 popup_browser->command_controller()->command_updater();
1821 EXPECT_FALSE(popup_command_updater->IsCommandEnabled(IDC_MANAGE_EXTENSIONS));
1822 EXPECT_FALSE(popup_command_updater->IsCommandEnabled(IDC_OPTIONS));
1823 EXPECT_TRUE(popup_command_updater->IsCommandEnabled(
1824 IDC_SHOW_BOOKMARK_MANAGER));
1825 EXPECT_FALSE(popup_command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1828 // Makes sure Extensions and Settings commands are disabled in certain
1829 // circumstances even though normally they should stay enabled.
1830 IN_PROC_BROWSER_TEST_F(BrowserTest,
1831 DisableOptionsAndImportMenuItemsConsistently) {
1832 // Create a popup browser.
1833 Browser* popup_browser = new Browser(
1834 Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(),
1835 browser()->host_desktop_type()));
1836 CommandUpdater* command_updater =
1837 popup_browser->command_controller()->command_updater();
1838 // OPTIONS and IMPORT_SETTINGS are disabled for a non-normal UI.
1839 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1840 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1842 // Set Incognito to FORCED.
1843 IncognitoModePrefs::SetAvailability(popup_browser->profile()->GetPrefs(),
1844 IncognitoModePrefs::FORCED);
1845 // OPTIONS and IMPORT_SETTINGS are disabled when Incognito is forced.
1846 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1847 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1848 // Set Incognito to AVAILABLE.
1849 IncognitoModePrefs::SetAvailability(popup_browser->profile()->GetPrefs(),
1850 IncognitoModePrefs::ENABLED);
1851 // OPTIONS and IMPORT_SETTINGS are still disabled since it is a non-normal UI.
1852 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_OPTIONS));
1853 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_IMPORT_SETTINGS));
1856 namespace {
1858 void OnZoomLevelChanged(const base::Closure& callback,
1859 const HostZoomMap::ZoomLevelChange& host) {
1860 callback.Run();
1863 } // namespace
1865 #if defined(OS_WIN)
1866 // Flakes regularly on Windows XP
1867 // http://crbug.com/146040
1868 #define MAYBE_PageZoom DISABLED_PageZoom
1869 #else
1870 #define MAYBE_PageZoom PageZoom
1871 #endif
1873 namespace {
1875 int GetZoomPercent(const content::WebContents* contents,
1876 bool* enable_plus,
1877 bool* enable_minus) {
1878 int percent =
1879 ui_zoom::ZoomController::FromWebContents(contents)->GetZoomPercent();
1880 *enable_plus = percent < contents->GetMaximumZoomPercent();
1881 *enable_minus = percent > contents->GetMinimumZoomPercent();
1882 return percent;
1885 } // namespace
1887 IN_PROC_BROWSER_TEST_F(BrowserTest, MAYBE_PageZoom) {
1888 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1889 bool enable_plus, enable_minus;
1892 scoped_refptr<content::MessageLoopRunner> loop_runner(
1893 new content::MessageLoopRunner);
1894 content::HostZoomMap::ZoomLevelChangedCallback callback(
1895 base::Bind(&OnZoomLevelChanged, loop_runner->QuitClosure()));
1896 scoped_ptr<content::HostZoomMap::Subscription> sub =
1897 content::HostZoomMap::GetDefaultForBrowserContext(
1898 browser()->profile())->AddZoomLevelChangedCallback(callback);
1899 chrome::Zoom(browser(), content::PAGE_ZOOM_IN);
1900 loop_runner->Run();
1901 sub.reset();
1902 EXPECT_EQ(GetZoomPercent(contents, &enable_plus, &enable_minus), 110);
1903 EXPECT_TRUE(enable_plus);
1904 EXPECT_TRUE(enable_minus);
1908 scoped_refptr<content::MessageLoopRunner> loop_runner(
1909 new content::MessageLoopRunner);
1910 content::HostZoomMap::ZoomLevelChangedCallback callback(
1911 base::Bind(&OnZoomLevelChanged, loop_runner->QuitClosure()));
1912 scoped_ptr<content::HostZoomMap::Subscription> sub =
1913 content::HostZoomMap::GetDefaultForBrowserContext(
1914 browser()->profile())->AddZoomLevelChangedCallback(callback);
1915 chrome::Zoom(browser(), content::PAGE_ZOOM_RESET);
1916 loop_runner->Run();
1917 sub.reset();
1918 EXPECT_EQ(GetZoomPercent(contents, &enable_plus, &enable_minus), 100);
1919 EXPECT_TRUE(enable_plus);
1920 EXPECT_TRUE(enable_minus);
1924 scoped_refptr<content::MessageLoopRunner> loop_runner(
1925 new content::MessageLoopRunner);
1926 content::HostZoomMap::ZoomLevelChangedCallback callback(
1927 base::Bind(&OnZoomLevelChanged, loop_runner->QuitClosure()));
1928 scoped_ptr<content::HostZoomMap::Subscription> sub =
1929 content::HostZoomMap::GetDefaultForBrowserContext(
1930 browser()->profile())->AddZoomLevelChangedCallback(callback);
1931 chrome::Zoom(browser(), content::PAGE_ZOOM_OUT);
1932 loop_runner->Run();
1933 sub.reset();
1934 EXPECT_EQ(GetZoomPercent(contents, &enable_plus, &enable_minus), 90);
1935 EXPECT_TRUE(enable_plus);
1936 EXPECT_TRUE(enable_minus);
1939 chrome::Zoom(browser(), content::PAGE_ZOOM_RESET);
1942 IN_PROC_BROWSER_TEST_F(BrowserTest, InterstitialCommandDisable) {
1943 ASSERT_TRUE(test_server()->Start());
1944 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1945 GURL url(test_server()->GetURL("empty.html"));
1946 ui_test_utils::NavigateToURL(browser(), url);
1948 CommandUpdater* command_updater =
1949 browser()->command_controller()->command_updater();
1950 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_VIEW_SOURCE));
1951 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_PRINT));
1952 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SAVE_PAGE));
1953 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_ENCODING_MENU));
1955 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1957 TestInterstitialPage* interstitial =
1958 new TestInterstitialPage(contents, false, GURL());
1959 content::WaitForInterstitialAttach(contents);
1961 EXPECT_TRUE(contents->ShowingInterstitialPage());
1963 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_VIEW_SOURCE));
1964 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_PRINT));
1965 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_SAVE_PAGE));
1966 EXPECT_FALSE(command_updater->IsCommandEnabled(IDC_ENCODING_MENU));
1968 // Proceed and wait for interstitial to detach. This doesn't destroy
1969 // |contents|.
1970 interstitial->Proceed();
1971 content::WaitForInterstitialDetach(contents);
1972 // interstitial is deleted now.
1974 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_VIEW_SOURCE));
1975 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_PRINT));
1976 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_SAVE_PAGE));
1977 EXPECT_TRUE(command_updater->IsCommandEnabled(IDC_ENCODING_MENU));
1980 // Ensure that creating an interstitial page closes any JavaScript dialogs
1981 // that were present on the previous page. See http://crbug.com/295695.
1982 IN_PROC_BROWSER_TEST_F(BrowserTest, InterstitialClosesDialogs) {
1983 ASSERT_TRUE(test_server()->Start());
1984 host_resolver()->AddRule("www.example.com", "127.0.0.1");
1985 GURL url(test_server()->GetURL("empty.html"));
1986 ui_test_utils::NavigateToURL(browser(), url);
1988 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1989 contents->GetMainFrame()->ExecuteJavaScript(
1990 ASCIIToUTF16("alert('Dialog showing!');"));
1991 AppModalDialog* alert = ui_test_utils::WaitForAppModalDialog();
1992 EXPECT_TRUE(alert->IsValid());
1993 AppModalDialogQueue* dialog_queue = AppModalDialogQueue::GetInstance();
1994 EXPECT_TRUE(dialog_queue->HasActiveDialog());
1996 TestInterstitialPage* interstitial =
1997 new TestInterstitialPage(contents, false, GURL());
1998 content::WaitForInterstitialAttach(contents);
2000 // The interstitial should have closed the dialog.
2001 EXPECT_TRUE(contents->ShowingInterstitialPage());
2002 EXPECT_FALSE(dialog_queue->HasActiveDialog());
2004 // Don't proceed and wait for interstitial to detach. This doesn't destroy
2005 // |contents|.
2006 interstitial->DontProceed();
2007 content::WaitForInterstitialDetach(contents);
2008 // interstitial is deleted now.
2010 // Make sure input events still work in the renderer process.
2011 EXPECT_FALSE(contents->GetRenderProcessHost()->IgnoreInputEvents());
2015 IN_PROC_BROWSER_TEST_F(BrowserTest, InterstitialCloseTab) {
2016 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
2018 // Interstitial will delete itself when we close the tab.
2019 new TestInterstitialPage(contents, false, GURL());
2020 content::WaitForInterstitialAttach(contents);
2022 EXPECT_TRUE(contents->ShowingInterstitialPage());
2024 // Close the tab and wait for interstitial detach. This destroys |contents|.
2025 content::RunTaskAndWaitForInterstitialDetach(
2026 contents, base::Bind(&chrome::CloseTab, browser()));
2027 // interstitial is deleted now.
2030 class MockWebContentsObserver : public WebContentsObserver {
2031 public:
2032 explicit MockWebContentsObserver(WebContents* web_contents)
2033 : WebContentsObserver(web_contents),
2034 got_user_gesture_(false) {
2037 void DidGetUserGesture() override { got_user_gesture_ = true; }
2039 bool got_user_gesture() const {
2040 return got_user_gesture_;
2043 void set_got_user_gesture(bool got_it) {
2044 got_user_gesture_ = got_it;
2047 private:
2048 bool got_user_gesture_;
2050 DISALLOW_COPY_AND_ASSIGN(MockWebContentsObserver);
2053 IN_PROC_BROWSER_TEST_F(BrowserTest, UserGesturesReported) {
2054 // Regression test for http://crbug.com/110707. Also tests that a user
2055 // gesture is sent when a normal navigation (via e.g. the omnibox) is
2056 // performed.
2057 WebContents* web_contents =
2058 browser()->tab_strip_model()->GetActiveWebContents();
2059 MockWebContentsObserver mock_observer(web_contents);
2061 ASSERT_TRUE(test_server()->Start());
2062 GURL url(test_server()->GetURL("empty.html"));
2064 ui_test_utils::NavigateToURL(browser(), url);
2065 EXPECT_TRUE(mock_observer.got_user_gesture());
2067 mock_observer.set_got_user_gesture(false);
2068 chrome::Reload(browser(), CURRENT_TAB);
2069 EXPECT_TRUE(mock_observer.got_user_gesture());
2072 // TODO(ben): this test was never enabled. It has bit-rotted since being added.
2073 // It originally lived in browser_unittest.cc, but has been moved here to make
2074 // room for real browser unit tests.
2075 #if 0
2076 class BrowserTest2 : public InProcessBrowserTest {
2077 public:
2078 BrowserTest2() {
2079 host_resolver_proc_ = new net::RuleBasedHostResolverProc(NULL);
2080 // Avoid making external DNS lookups. In this test we don't need this
2081 // to succeed.
2082 host_resolver_proc_->AddSimulatedFailure("*.google.com");
2083 scoped_host_resolver_proc_.Init(host_resolver_proc_.get());
2086 private:
2087 scoped_refptr<net::RuleBasedHostResolverProc> host_resolver_proc_;
2088 net::ScopedDefaultHostResolverProc scoped_host_resolver_proc_;
2091 IN_PROC_BROWSER_TEST_F(BrowserTest2, NoTabsInPopups) {
2092 chrome::RegisterAppPrefs(L"Test");
2094 // We start with a normal browser with one tab.
2095 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2097 // Open a popup browser with a single blank foreground tab.
2098 Browser* popup_browser = new Browser(
2099 Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile()));
2100 chrome::AddTabAt(popup_browser, GURL(), -1, true);
2101 EXPECT_EQ(1, popup_browser->tab_strip_model()->count());
2103 // Now try opening another tab in the popup browser.
2104 AddTabWithURLParams params1(url, ui::PAGE_TRANSITION_TYPED);
2105 popup_browser->AddTabWithURL(&params1);
2106 EXPECT_EQ(popup_browser, params1.target);
2108 // The popup should still only have one tab.
2109 EXPECT_EQ(1, popup_browser->tab_strip_model()->count());
2111 // The normal browser should now have two.
2112 EXPECT_EQ(2, browser()->tab_strip_model()->count());
2114 // Open an app frame browser with a single blank foreground tab.
2115 Browser* app_browser = new Browser(Browser::CreateParams::CreateForApp(
2116 L"Test", browser()->profile(), false));
2117 chrome::AddTabAt(app_browser, GURL(), -1, true);
2118 EXPECT_EQ(1, app_browser->tab_strip_model()->count());
2120 // Now try opening another tab in the app browser.
2121 AddTabWithURLParams params2(GURL(url::kAboutBlankURL),
2122 ui::PAGE_TRANSITION_TYPED);
2123 app_browser->AddTabWithURL(&params2);
2124 EXPECT_EQ(app_browser, params2.target);
2126 // The popup should still only have one tab.
2127 EXPECT_EQ(1, app_browser->tab_strip_model()->count());
2129 // The normal browser should now have three.
2130 EXPECT_EQ(3, browser()->tab_strip_model()->count());
2132 // Open an app frame popup browser with a single blank foreground tab.
2133 Browser* app_popup_browser = new Browser(Browser::CreateParams::CreateForApp(
2134 L"Test", browser()->profile(), false));
2135 chrome::AddTabAt(app_popup_browser, GURL(), -1, true);
2136 EXPECT_EQ(1, app_popup_browser->tab_strip_model()->count());
2138 // Now try opening another tab in the app popup browser.
2139 AddTabWithURLParams params3(GURL(url::kAboutBlankURL),
2140 ui::PAGE_TRANSITION_TYPED);
2141 app_popup_browser->AddTabWithURL(&params3);
2142 EXPECT_EQ(app_popup_browser, params3.target);
2144 // The popup should still only have one tab.
2145 EXPECT_EQ(1, app_popup_browser->tab_strip_model()->count());
2147 // The normal browser should now have four.
2148 EXPECT_EQ(4, browser()->tab_strip_model()->count());
2150 // Close the additional browsers.
2151 popup_browser->tab_strip_model()->CloseAllTabs();
2152 app_browser->tab_strip_model()->CloseAllTabs();
2153 app_popup_browser->tab_strip_model()->CloseAllTabs();
2155 #endif
2157 IN_PROC_BROWSER_TEST_F(BrowserTest, WindowOpenClose) {
2158 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2159 switches::kDisablePopupBlocking);
2160 GURL url = ui_test_utils::GetTestUrl(
2161 base::FilePath(), base::FilePath().AppendASCII("window.close.html"));
2163 base::string16 title = ASCIIToUTF16("Title Of Awesomeness");
2164 content::TitleWatcher title_watcher(
2165 browser()->tab_strip_model()->GetActiveWebContents(), title);
2166 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), url, 2);
2167 EXPECT_EQ(title, title_watcher.WaitAndGetTitle());
2170 // TODO(linux_aura) http://crbug.com/163931
2171 // Mac disabled: http://crbug.com/169820
2172 #if !defined(OS_MACOSX) && \
2173 !(defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA))
2174 IN_PROC_BROWSER_TEST_F(BrowserTest, FullscreenBookmarkBar) {
2175 #if defined(OS_WIN) && defined(USE_ASH)
2176 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2177 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2178 switches::kAshBrowserTests))
2179 return;
2180 #endif
2182 chrome::ToggleBookmarkBar(browser());
2183 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
2184 chrome::ToggleFullscreenMode(browser());
2185 EXPECT_TRUE(browser()->window()->IsFullscreen());
2186 #if defined(OS_MACOSX)
2187 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
2188 #elif defined(OS_CHROMEOS)
2189 // TODO(jamescook): If immersive fullscreen is disabled by default, test
2190 // for BookmarkBar::HIDDEN.
2191 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
2192 #else
2193 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2194 #endif
2196 #endif
2198 IN_PROC_BROWSER_TEST_F(BrowserTest, DisallowFileUrlUniversalAccessTest) {
2199 GURL url = ui_test_utils::GetTestUrl(
2200 base::FilePath(),
2201 base::FilePath().AppendASCII("fileurl_universalaccess.html"));
2203 base::string16 expected_title(ASCIIToUTF16("Disallowed"));
2204 content::TitleWatcher title_watcher(
2205 browser()->tab_strip_model()->GetActiveWebContents(), expected_title);
2206 title_watcher.AlsoWaitForTitle(ASCIIToUTF16("Allowed"));
2207 ui_test_utils::NavigateToURL(browser(), url);
2208 ASSERT_EQ(expected_title, title_watcher.WaitAndGetTitle());
2211 class KioskModeTest : public BrowserTest {
2212 public:
2213 KioskModeTest() {}
2215 void SetUpCommandLine(base::CommandLine* command_line) override {
2216 command_line->AppendSwitch(switches::kKioskMode);
2220 #if defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
2221 // Mac: http://crbug.com/103912
2222 // Linux: http://crbug.com/163931
2223 #define MAYBE_EnableKioskModeTest DISABLED_EnableKioskModeTest
2224 #else
2225 #define MAYBE_EnableKioskModeTest EnableKioskModeTest
2226 #endif
2227 IN_PROC_BROWSER_TEST_F(KioskModeTest, MAYBE_EnableKioskModeTest) {
2228 // Check if browser is in fullscreen mode.
2229 ASSERT_TRUE(browser()->window()->IsFullscreen());
2230 ASSERT_FALSE(browser()->window()->IsFullscreenBubbleVisible());
2233 #if defined(OS_WIN)
2234 // This test verifies that Chrome can be launched with a user-data-dir path
2235 // which contains non ASCII characters.
2236 class LaunchBrowserWithNonAsciiUserDatadir : public BrowserTest {
2237 public:
2238 LaunchBrowserWithNonAsciiUserDatadir() {}
2240 virtual void SetUpCommandLine(base::CommandLine* command_line) override {
2241 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
2242 base::FilePath tmp_profile = temp_dir_.path().AppendASCII("tmp_profile");
2243 tmp_profile = tmp_profile.Append(L"Test Chrome G\u00E9raldine");
2245 ASSERT_TRUE(base::CreateDirectory(tmp_profile));
2246 command_line->AppendSwitchPath(switches::kUserDataDir, tmp_profile);
2249 base::ScopedTempDir temp_dir_;
2252 IN_PROC_BROWSER_TEST_F(LaunchBrowserWithNonAsciiUserDatadir,
2253 TestNonAsciiUserDataDir) {
2254 // Verify that the window is present.
2255 ASSERT_TRUE(browser());
2257 #endif // defined(OS_WIN)
2259 // Tests to ensure that the browser continues running in the background after
2260 // the last window closes.
2261 class RunInBackgroundTest : public BrowserTest {
2262 public:
2263 RunInBackgroundTest() {}
2265 void SetUpCommandLine(base::CommandLine* command_line) override {
2266 command_line->AppendSwitch(switches::kKeepAliveForTest);
2270 IN_PROC_BROWSER_TEST_F(RunInBackgroundTest, RunInBackgroundBasicTest) {
2271 // Close the browser window, then open a new one - the browser should keep
2272 // running.
2273 Profile* profile = browser()->profile();
2274 EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
2275 content::WindowedNotificationObserver observer(
2276 chrome::NOTIFICATION_BROWSER_CLOSED,
2277 content::Source<Browser>(browser()));
2278 chrome::CloseWindow(browser());
2279 observer.Wait();
2280 EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
2282 ui_test_utils::BrowserAddedObserver browser_added_observer;
2283 chrome::NewEmptyWindow(profile, chrome::GetActiveDesktop());
2284 browser_added_observer.WaitForSingleNewBrowser();
2286 EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
2289 // Tests to ensure that the browser continues running in the background after
2290 // the last window closes.
2291 class NoStartupWindowTest : public BrowserTest {
2292 public:
2293 NoStartupWindowTest() {}
2295 void SetUpCommandLine(base::CommandLine* command_line) override {
2296 command_line->AppendSwitch(switches::kNoStartupWindow);
2297 command_line->AppendSwitch(switches::kKeepAliveForTest);
2300 // Returns true if any commands were processed.
2301 bool ProcessedAnyCommands(
2302 sessions::BaseSessionService* base_session_service) {
2303 sessions::BaseSessionServiceTestHelper test_helper(base_session_service);
2304 return test_helper.ProcessedAnyCommands();
2308 IN_PROC_BROWSER_TEST_F(NoStartupWindowTest, NoStartupWindowBasicTest) {
2309 #if defined(OS_WIN) && defined(USE_ASH)
2310 // kNoStartupWindow doesn't make sense in Metro+Ash.
2311 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2312 switches::kAshBrowserTests))
2313 return;
2314 #endif
2316 // No browser window should be started by default.
2317 EXPECT_EQ(0u, chrome::GetTotalBrowserCount());
2319 // Starting a browser window should work just fine.
2320 ui_test_utils::BrowserAddedObserver browser_added_observer;
2321 CreateBrowser(ProfileManager::GetActiveUserProfile());
2322 browser_added_observer.WaitForSingleNewBrowser();
2324 EXPECT_EQ(1u, chrome::GetTotalBrowserCount());
2327 // Chromeos needs to track app windows because it considers them to be part of
2328 // session state.
2329 #if !defined(OS_CHROMEOS)
2330 IN_PROC_BROWSER_TEST_F(NoStartupWindowTest, DontInitSessionServiceForApps) {
2331 #if defined(OS_WIN) && defined(USE_ASH)
2332 // kNoStartupWindow doesn't make sense in Metro+Ash.
2333 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2334 switches::kAshBrowserTests))
2335 return;
2336 #endif
2338 Profile* profile = ProfileManager::GetActiveUserProfile();
2340 SessionService* session_service =
2341 SessionServiceFactory::GetForProfile(profile);
2342 sessions::BaseSessionService* base_session_service =
2343 session_service->GetBaseSessionServiceForTest();
2344 ASSERT_FALSE(ProcessedAnyCommands(base_session_service));
2346 ui_test_utils::BrowserAddedObserver browser_added_observer;
2347 CreateBrowserForApp("blah", profile);
2348 browser_added_observer.WaitForSingleNewBrowser();
2350 ASSERT_FALSE(ProcessedAnyCommands(base_session_service));
2352 #endif // !defined(OS_CHROMEOS)
2354 // This test needs to be placed outside the anonymous namespace because we
2355 // need to access private type of Browser.
2356 class AppModeTest : public BrowserTest {
2357 public:
2358 AppModeTest() {}
2360 void SetUpCommandLine(base::CommandLine* command_line) override {
2361 GURL url = ui_test_utils::GetTestUrl(
2362 base::FilePath(), base::FilePath().AppendASCII("title1.html"));
2363 command_line->AppendSwitchASCII(switches::kApp, url.spec());
2367 IN_PROC_BROWSER_TEST_F(AppModeTest, EnableAppModeTest) {
2368 #if defined(OS_WIN) && defined(USE_ASH)
2369 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2370 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2371 switches::kAshBrowserTests))
2372 return;
2373 #endif
2375 // Test that an application browser window loads correctly.
2377 // Verify the browser is in application mode.
2378 EXPECT_TRUE(browser()->is_app());
2381 // Confirm chrome://version contains some expected content.
2382 IN_PROC_BROWSER_TEST_F(BrowserTest, AboutVersion) {
2383 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIVersionURL));
2384 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2385 ASSERT_GT(ui_test_utils::FindInPage(tab, ASCIIToUTF16("WebKit"), true, true,
2386 NULL, NULL),
2388 ASSERT_GT(ui_test_utils::FindInPage(tab, ASCIIToUTF16("OS"), true, true,
2389 NULL, NULL),
2391 ASSERT_GT(ui_test_utils::FindInPage(tab, ASCIIToUTF16("JavaScript"), true,
2392 true, NULL, NULL),
2396 static const base::FilePath::CharType* kTestDir =
2397 FILE_PATH_LITERAL("click_modifier");
2398 static const char kFirstPageTitle[] = "First window";
2399 static const char kSecondPageTitle[] = "New window!";
2401 class ClickModifierTest : public InProcessBrowserTest {
2402 public:
2403 ClickModifierTest() {
2406 // Returns a url that opens a new window or tab when clicked, via javascript.
2407 GURL GetWindowOpenURL() {
2408 return ui_test_utils::GetTestUrl(
2409 base::FilePath(kTestDir),
2410 base::FilePath(FILE_PATH_LITERAL("window_open.html")));
2413 // Returns a url that follows a simple link when clicked, unless affected by
2414 // modifiers.
2415 GURL GetHrefURL() {
2416 return ui_test_utils::GetTestUrl(
2417 base::FilePath(kTestDir),
2418 base::FilePath(FILE_PATH_LITERAL("href.html")));
2421 base::string16 getFirstPageTitle() {
2422 return ASCIIToUTF16(kFirstPageTitle);
2425 base::string16 getSecondPageTitle() {
2426 return ASCIIToUTF16(kSecondPageTitle);
2429 // Loads our test page and simulates a single click using the supplied button
2430 // and modifiers. The click will cause either a navigation or the creation of
2431 // a new window or foreground or background tab. We verify that the expected
2432 // disposition occurs.
2433 void RunTest(Browser* browser,
2434 const GURL& url,
2435 int modifiers,
2436 blink::WebMouseEvent::Button button,
2437 WindowOpenDisposition disposition) {
2438 ui_test_utils::NavigateToURL(browser, url);
2439 EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(),
2440 browser->host_desktop_type()));
2441 EXPECT_EQ(1, browser->tab_strip_model()->count());
2442 content::WebContents* web_contents =
2443 browser->tab_strip_model()->GetActiveWebContents();
2444 EXPECT_EQ(url, web_contents->GetURL());
2446 if (disposition == CURRENT_TAB) {
2447 content::WebContents* web_contents =
2448 browser->tab_strip_model()->GetActiveWebContents();
2449 content::TestNavigationObserver same_tab_observer(web_contents);
2450 SimulateMouseClick(web_contents, modifiers, button);
2451 same_tab_observer.Wait();
2452 EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(),
2453 browser->host_desktop_type()));
2454 EXPECT_EQ(1, browser->tab_strip_model()->count());
2455 EXPECT_EQ(getSecondPageTitle(), web_contents->GetTitle());
2456 return;
2459 content::WindowedNotificationObserver observer(
2460 chrome::NOTIFICATION_TAB_ADDED,
2461 content::NotificationService::AllSources());
2462 SimulateMouseClick(web_contents, modifiers, button);
2463 observer.Wait();
2465 if (disposition == NEW_WINDOW) {
2466 EXPECT_EQ(2u, chrome::GetBrowserCount(browser->profile(),
2467 browser->host_desktop_type()));
2468 return;
2471 EXPECT_EQ(1u, chrome::GetBrowserCount(browser->profile(),
2472 browser->host_desktop_type()));
2473 EXPECT_EQ(2, browser->tab_strip_model()->count());
2474 web_contents = browser->tab_strip_model()->GetActiveWebContents();
2475 WaitForLoadStop(web_contents);
2476 if (disposition == NEW_FOREGROUND_TAB) {
2477 EXPECT_EQ(getSecondPageTitle(), web_contents->GetTitle());
2478 } else {
2479 ASSERT_EQ(NEW_BACKGROUND_TAB, disposition);
2480 EXPECT_EQ(getFirstPageTitle(), web_contents->GetTitle());
2484 private:
2485 DISALLOW_COPY_AND_ASSIGN(ClickModifierTest);
2488 // Tests for clicking on elements with handlers that run window.open.
2490 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenBasicClickTest) {
2491 int modifiers = 0;
2492 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2493 WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2494 RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2497 // TODO(ericu): Alt-click behavior on window.open is platform-dependent and not
2498 // well defined. Should we add tests so we know if it changes?
2500 // Shift-clicks open in a new window.
2501 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenShiftClickTest) {
2502 int modifiers = blink::WebInputEvent::ShiftKey;
2503 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2504 WindowOpenDisposition disposition = NEW_WINDOW;
2505 RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2508 // Control-clicks open in a background tab.
2509 // On OSX meta [the command key] takes the place of control.
2510 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenControlClickTest) {
2511 #if defined(OS_MACOSX)
2512 int modifiers = blink::WebInputEvent::MetaKey;
2513 #else
2514 int modifiers = blink::WebInputEvent::ControlKey;
2515 #endif
2516 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2517 WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2518 RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2521 // Control-shift-clicks open in a foreground tab.
2522 // On OSX meta [the command key] takes the place of control.
2523 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenControlShiftClickTest) {
2524 #if defined(OS_MACOSX)
2525 int modifiers = blink::WebInputEvent::MetaKey;
2526 #else
2527 int modifiers = blink::WebInputEvent::ControlKey;
2528 #endif
2529 modifiers |= blink::WebInputEvent::ShiftKey;
2530 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2531 WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2532 RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2535 // Middle-clicks open in a background tab.
2536 #if defined(OS_LINUX)
2537 // http://crbug.com/396347
2538 #define MAYBE_WindowOpenMiddleClickTest DISABLED_WindowOpenMiddleClickTest
2539 #else
2540 #define MAYBE_WindowOpenMiddleClickTest WindowOpenMiddleClickTest
2541 #endif
2542 IN_PROC_BROWSER_TEST_F(ClickModifierTest, MAYBE_WindowOpenMiddleClickTest) {
2543 int modifiers = 0;
2544 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2545 WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2546 RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2549 // Shift-middle-clicks open in a foreground tab.
2550 IN_PROC_BROWSER_TEST_F(ClickModifierTest, WindowOpenShiftMiddleClickTest) {
2551 int modifiers = blink::WebInputEvent::ShiftKey;
2552 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2553 WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2554 RunTest(browser(), GetWindowOpenURL(), modifiers, button, disposition);
2557 // Tests for clicking on normal links.
2559 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefBasicClickTest) {
2560 int modifiers = 0;
2561 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2562 WindowOpenDisposition disposition = CURRENT_TAB;
2563 RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2566 // TODO(ericu): Alt-click behavior on links is platform-dependent and not well
2567 // defined. Should we add tests so we know if it changes?
2569 // Shift-clicks open in a new window.
2570 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefShiftClickTest) {
2571 int modifiers = blink::WebInputEvent::ShiftKey;
2572 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2573 WindowOpenDisposition disposition = NEW_WINDOW;
2574 RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2577 // Control-clicks open in a background tab.
2578 // On OSX meta [the command key] takes the place of control.
2579 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefControlClickTest) {
2580 #if defined(OS_MACOSX)
2581 int modifiers = blink::WebInputEvent::MetaKey;
2582 #else
2583 int modifiers = blink::WebInputEvent::ControlKey;
2584 #endif
2585 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2586 WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2587 RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2590 // Control-shift-clicks open in a foreground tab.
2591 // On OSX meta [the command key] takes the place of control.
2592 // http://crbug.com/396347
2593 IN_PROC_BROWSER_TEST_F(ClickModifierTest, DISABLED_HrefControlShiftClickTest) {
2594 #if defined(OS_MACOSX)
2595 int modifiers = blink::WebInputEvent::MetaKey;
2596 #else
2597 int modifiers = blink::WebInputEvent::ControlKey;
2598 #endif
2599 modifiers |= blink::WebInputEvent::ShiftKey;
2600 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonLeft;
2601 WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2602 RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2605 // Middle-clicks open in a background tab.
2606 IN_PROC_BROWSER_TEST_F(ClickModifierTest, HrefMiddleClickTest) {
2607 int modifiers = 0;
2608 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2609 WindowOpenDisposition disposition = NEW_BACKGROUND_TAB;
2610 RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2613 // Shift-middle-clicks open in a foreground tab.
2614 // http://crbug.com/396347
2615 IN_PROC_BROWSER_TEST_F(ClickModifierTest, DISABLED_HrefShiftMiddleClickTest) {
2616 int modifiers = blink::WebInputEvent::ShiftKey;
2617 blink::WebMouseEvent::Button button = blink::WebMouseEvent::ButtonMiddle;
2618 WindowOpenDisposition disposition = NEW_FOREGROUND_TAB;
2619 RunTest(browser(), GetHrefURL(), modifiers, button, disposition);
2622 IN_PROC_BROWSER_TEST_F(BrowserTest, GetSizeForNewRenderView) {
2623 // The instant extended NTP has javascript that does not work with
2624 // ui_test_utils::NavigateToURL. The NTP rvh reloads when the browser tries
2625 // to navigate away from the page, which causes the WebContents to end up in
2626 // an inconsistent state. (is_loaded = true, last_commited_url=ntp,
2627 // visible_url=title1.html)
2628 browser()->profile()->GetPrefs()->SetBoolean(prefs::kWebKitJavascriptEnabled,
2629 false);
2630 ASSERT_TRUE(test_server()->Start());
2631 // Create an HTTPS server for cross-site transition.
2632 net::SpawnedTestServer https_test_server(net::SpawnedTestServer::TYPE_HTTPS,
2633 net::SpawnedTestServer::kLocalhost,
2634 base::FilePath(kDocRoot));
2635 ASSERT_TRUE(https_test_server.Start());
2637 // Start with NTP.
2638 ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab"));
2639 ASSERT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
2640 WebContents* web_contents =
2641 browser()->tab_strip_model()->GetActiveWebContents();
2642 content::RenderViewHost* prev_rvh = web_contents->GetRenderViewHost();
2643 const int height_inset =
2644 browser()->window()->GetRenderViewHeightInsetWithDetachedBookmarkBar();
2645 const gfx::Size initial_wcv_size =
2646 web_contents->GetContainerBounds().size();
2647 RenderViewSizeObserver observer(web_contents, browser()->window());
2649 // Navigate to a non-NTP page, without resizing WebContentsView.
2650 ui_test_utils::NavigateToURL(browser(),
2651 test_server()->GetURL("files/title1.html"));
2652 ASSERT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2653 // A new RenderViewHost should be created.
2654 EXPECT_NE(prev_rvh, web_contents->GetRenderViewHost());
2655 prev_rvh = web_contents->GetRenderViewHost();
2656 gfx::Size rwhv_create_size0, rwhv_commit_size0, wcv_commit_size0;
2657 observer.GetSizeForRenderViewHost(web_contents->GetRenderViewHost(),
2658 &rwhv_create_size0,
2659 &rwhv_commit_size0,
2660 &wcv_commit_size0);
2661 // The create height of RenderWidgetHostView should include the height inset.
2662 EXPECT_EQ(gfx::Size(initial_wcv_size.width(),
2663 initial_wcv_size.height() + height_inset),
2664 rwhv_create_size0);
2665 // When a navigation entry is committed, the size of RenderWidgetHostView
2666 // should be the same as when it was first created.
2667 EXPECT_EQ(rwhv_create_size0, rwhv_commit_size0);
2668 // Sizes of the current RenderWidgetHostView and WebContentsView should not
2669 // change before and after WebContentsDelegate::DidNavigateMainFramePostCommit
2670 // (implemented by Browser); we obtain the sizes before PostCommit via
2671 // WebContentsObserver::NavigationEntryCommitted (implemented by
2672 // RenderViewSizeObserver).
2673 EXPECT_EQ(rwhv_commit_size0,
2674 web_contents->GetRenderWidgetHostView()->GetViewBounds().size());
2675 // The behavior differs between OSX and views.
2676 // In OSX, the wcv does not change size until after the commit, when the
2677 // bookmark bar disappears (correct).
2678 // In views, the wcv changes size at commit time.
2679 #if defined(OS_MACOSX)
2680 EXPECT_EQ(gfx::Size(wcv_commit_size0.width(),
2681 wcv_commit_size0.height() + height_inset),
2682 web_contents->GetContainerBounds().size());
2683 #else
2684 EXPECT_EQ(wcv_commit_size0, web_contents->GetContainerBounds().size());
2685 #endif
2687 // Navigate to another non-NTP page, without resizing WebContentsView.
2688 ui_test_utils::NavigateToURL(browser(),
2689 https_test_server.GetURL("files/title2.html"));
2690 ASSERT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2691 // A new RenderVieHost should be created.
2692 EXPECT_NE(prev_rvh, web_contents->GetRenderViewHost());
2693 gfx::Size rwhv_create_size1, rwhv_commit_size1, wcv_commit_size1;
2694 observer.GetSizeForRenderViewHost(web_contents->GetRenderViewHost(),
2695 &rwhv_create_size1,
2696 &rwhv_commit_size1,
2697 &wcv_commit_size1);
2698 EXPECT_EQ(rwhv_create_size1, rwhv_commit_size1);
2699 EXPECT_EQ(rwhv_commit_size1,
2700 web_contents->GetRenderWidgetHostView()->GetViewBounds().size());
2701 EXPECT_EQ(wcv_commit_size1, web_contents->GetContainerBounds().size());
2703 // Navigate from NTP to a non-NTP page, resizing WebContentsView while
2704 // navigation entry is pending.
2705 ui_test_utils::NavigateToURL(browser(), GURL("chrome://newtab"));
2706 gfx::Size wcv_resize_insets(1, 1);
2707 observer.set_wcv_resize_insets(wcv_resize_insets);
2708 ui_test_utils::NavigateToURL(browser(),
2709 test_server()->GetURL("files/title2.html"));
2710 ASSERT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
2711 gfx::Size rwhv_create_size2, rwhv_commit_size2, wcv_commit_size2;
2712 observer.GetSizeForRenderViewHost(web_contents->GetRenderViewHost(),
2713 &rwhv_create_size2,
2714 &rwhv_commit_size2,
2715 &wcv_commit_size2);
2717 // The behavior on OSX and Views is incorrect in this edge case, but they are
2718 // differently incorrect.
2719 // The behavior should be:
2720 // initial wcv size: (100,100) (to choose random numbers)
2721 // initial rwhv size: (100,140)
2722 // commit wcv size: (101, 101)
2723 // commit rwhv size: (101, 141)
2724 // final wcv size: (101, 141)
2725 // final rwhv size: (101, 141)
2727 // On OSX, the commit rwhv size is (101, 101)
2728 // On views, the commit wcv size is (101, 141)
2729 // All other sizes are correct.
2731 // The create height of RenderWidgetHostView should include the height inset.
2732 EXPECT_EQ(gfx::Size(initial_wcv_size.width(),
2733 initial_wcv_size.height() + height_inset),
2734 rwhv_create_size2);
2735 gfx::Size exp_commit_size(initial_wcv_size);
2737 #if defined(OS_MACOSX)
2738 exp_commit_size.Enlarge(wcv_resize_insets.width(),
2739 wcv_resize_insets.height());
2740 #else
2741 exp_commit_size.Enlarge(wcv_resize_insets.width(),
2742 wcv_resize_insets.height() + height_inset);
2743 #endif
2744 EXPECT_EQ(exp_commit_size, rwhv_commit_size2);
2745 EXPECT_EQ(exp_commit_size, wcv_commit_size2);
2746 gfx::Size exp_final_size(initial_wcv_size);
2747 exp_final_size.Enlarge(wcv_resize_insets.width(),
2748 wcv_resize_insets.height() + height_inset);
2749 EXPECT_EQ(exp_final_size,
2750 web_contents->GetRenderWidgetHostView()->GetViewBounds().size());
2751 EXPECT_EQ(exp_final_size, web_contents->GetContainerBounds().size());