instant_extended_interactive_uitest.cc revision ca12bfac764ba476d6cd062bf1dde12cc64c3f40
1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <sstream>
6
7#include "base/command_line.h"
8#include "base/metrics/histogram_base.h"
9#include "base/metrics/histogram_samples.h"
10#include "base/metrics/statistics_recorder.h"
11#include "base/prefs/pref_service.h"
12#include "base/run_loop.h"
13#include "base/strings/string_number_conversions.h"
14#include "base/strings/string_util.h"
15#include "base/strings/stringprintf.h"
16#include "base/strings/utf_string_conversions.h"
17#include "base/time/time.h"
18#include "chrome/browser/autocomplete/autocomplete_controller.h"
19#include "chrome/browser/autocomplete/autocomplete_match.h"
20#include "chrome/browser/autocomplete/autocomplete_provider.h"
21#include "chrome/browser/autocomplete/autocomplete_result.h"
22#include "chrome/browser/autocomplete/search_provider.h"
23#include "chrome/browser/bookmarks/bookmark_model_factory.h"
24#include "chrome/browser/bookmarks/bookmark_utils.h"
25#include "chrome/browser/chrome_notification_types.h"
26#include "chrome/browser/extensions/extension_browsertest.h"
27#include "chrome/browser/extensions/extension_service.h"
28#include "chrome/browser/favicon/favicon_tab_helper.h"
29#include "chrome/browser/history/history_db_task.h"
30#include "chrome/browser/history/history_service.h"
31#include "chrome/browser/history/history_service_factory.h"
32#include "chrome/browser/history/history_types.h"
33#include "chrome/browser/history/top_sites.h"
34#include "chrome/browser/profiles/profile.h"
35#include "chrome/browser/search/instant_service.h"
36#include "chrome/browser/search/instant_service_factory.h"
37#include "chrome/browser/search/search.h"
38#include "chrome/browser/search_engines/template_url_service.h"
39#include "chrome/browser/search_engines/template_url_service_factory.h"
40#include "chrome/browser/task_manager/task_manager.h"
41#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
42#include "chrome/browser/themes/theme_service.h"
43#include "chrome/browser/themes/theme_service_factory.h"
44#include "chrome/browser/ui/browser_list.h"
45#include "chrome/browser/ui/browser_tabstrip.h"
46#include "chrome/browser/ui/omnibox/omnibox_view.h"
47#include "chrome/browser/ui/search/instant_ntp.h"
48#include "chrome/browser/ui/search/instant_ntp_prerenderer.h"
49#include "chrome/browser/ui/search/instant_tab.h"
50#include "chrome/browser/ui/search/instant_test_utils.h"
51#include "chrome/browser/ui/search/search_tab_helper.h"
52#include "chrome/browser/ui/tabs/tab_strip_model.h"
53#include "chrome/browser/ui/webui/theme_source.h"
54#include "chrome/common/chrome_switches.h"
55#include "chrome/common/instant_types.h"
56#include "chrome/common/pref_names.h"
57#include "chrome/common/thumbnail_score.h"
58#include "chrome/common/url_constants.h"
59#include "chrome/test/base/in_process_browser_test.h"
60#include "chrome/test/base/interactive_test_utils.h"
61#include "chrome/test/base/ui_test_utils.h"
62#include "components/sessions/serialized_navigation_entry.h"
63#include "content/public/browser/navigation_controller.h"
64#include "content/public/browser/navigation_entry.h"
65#include "content/public/browser/notification_service.h"
66#include "content/public/browser/render_process_host.h"
67#include "content/public/browser/render_view_host.h"
68#include "content/public/browser/site_instance.h"
69#include "content/public/browser/url_data_source.h"
70#include "content/public/browser/web_contents.h"
71#include "content/public/browser/web_contents_view.h"
72#include "content/public/common/bindings_policy.h"
73#include "content/public/common/renderer_preferences.h"
74#include "content/public/test/browser_test_utils.h"
75#include "content/public/test/test_utils.h"
76#include "grit/generated_resources.h"
77#include "net/base/network_change_notifier.h"
78#include "testing/gmock/include/gmock/gmock.h"
79#include "third_party/skia/include/core/SkBitmap.h"
80#include "ui/base/l10n/l10n_util.h"
81
82using testing::HasSubstr;
83
84namespace {
85
86// Creates a bitmap of the specified color. Caller takes ownership.
87gfx::Image CreateBitmap(SkColor color) {
88  SkBitmap thumbnail;
89  thumbnail.setConfig(SkBitmap::kARGB_8888_Config, 4, 4);
90  thumbnail.allocPixels();
91  thumbnail.eraseColor(color);
92  return gfx::Image::CreateFrom1xBitmap(thumbnail);  // adds ref.
93}
94
95// Task used to make sure history has finished processing a request. Intended
96// for use with BlockUntilHistoryProcessesPendingRequests.
97class QuittingHistoryDBTask : public history::HistoryDBTask {
98 public:
99  QuittingHistoryDBTask() {}
100
101  virtual bool RunOnDBThread(history::HistoryBackend* backend,
102                             history::HistoryDatabase* db) OVERRIDE {
103    return true;
104  }
105
106  virtual void DoneRunOnMainThread() OVERRIDE {
107    base::MessageLoop::current()->Quit();
108  }
109
110 private:
111  virtual ~QuittingHistoryDBTask() {}
112
113  DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
114};
115
116class FakeNetworkChangeNotifier : public net::NetworkChangeNotifier {
117 public:
118  FakeNetworkChangeNotifier() : connection_type_(CONNECTION_NONE) {}
119
120  virtual ConnectionType GetCurrentConnectionType() const OVERRIDE {
121    return connection_type_;
122  }
123
124  void SetConnectionType(ConnectionType type) {
125    connection_type_ = type;
126    NotifyObserversOfNetworkChange(type);
127    base::RunLoop().RunUntilIdle();
128  }
129
130  virtual ~FakeNetworkChangeNotifier() {}
131
132 private:
133  ConnectionType connection_type_;
134  DISALLOW_COPY_AND_ASSIGN(FakeNetworkChangeNotifier);
135};
136}  // namespace
137
138class InstantExtendedTest : public InProcessBrowserTest,
139                            public InstantTestBase {
140 public:
141  InstantExtendedTest()
142      : on_most_visited_change_calls_(0),
143        most_visited_items_count_(0),
144        first_most_visited_item_id_(0),
145        on_native_suggestions_calls_(0),
146        on_change_calls_(0),
147        submit_count_(0),
148        on_esc_key_press_event_calls_(0),
149        on_focus_changed_calls_(0),
150        is_focused_(false),
151        on_toggle_voice_search_calls_(0) {
152  }
153 protected:
154  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
155    chrome::EnableInstantExtendedAPIForTesting();
156    ASSERT_TRUE(https_test_server().Start());
157    GURL instant_url = https_test_server().GetURL(
158        "files/instant_extended.html?strk=1&");
159    InstantTestBase::Init(instant_url);
160  }
161
162  int64 GetHistogramCount(const char* name) {
163    base::HistogramBase* histogram =
164        base::StatisticsRecorder::FindHistogram(name);
165    if (!histogram) {
166      // If no histogram is found, it's possible that no values have been
167      // recorded yet. Assume that the value is zero.
168      return 0;
169    }
170    return histogram->SnapshotSamples()->TotalCount();
171  }
172
173  void SendDownArrow() {
174    omnibox()->model()->OnUpOrDownKeyPressed(1);
175    // Wait for JavaScript to run the key handler by executing a blank script.
176    EXPECT_TRUE(ExecuteScript(std::string()));
177  }
178
179  void SendUpArrow() {
180    omnibox()->model()->OnUpOrDownKeyPressed(-1);
181    // Wait for JavaScript to run the key handler by executing a blank script.
182    EXPECT_TRUE(ExecuteScript(std::string()));
183  }
184
185  void SendEscape() {
186    omnibox()->model()->OnEscapeKeyPressed();
187    // Wait for JavaScript to run the key handler by executing a blank script.
188    EXPECT_TRUE(ExecuteScript(std::string()));
189  }
190
191  bool UpdateSearchState(content::WebContents* contents) WARN_UNUSED_RESULT {
192    return GetIntFromJS(contents, "onMostVisitedChangedCalls",
193                        &on_most_visited_change_calls_) &&
194           GetIntFromJS(contents, "mostVisitedItemsCount",
195                        &most_visited_items_count_) &&
196           GetIntFromJS(contents, "firstMostVisitedItemId",
197                        &first_most_visited_item_id_) &&
198           GetIntFromJS(contents, "onNativeSuggestionsCalls",
199                        &on_native_suggestions_calls_) &&
200           GetIntFromJS(contents, "onChangeCalls",
201                        &on_change_calls_) &&
202           GetIntFromJS(contents, "submitCount",
203                        &submit_count_) &&
204           GetStringFromJS(contents, "apiHandle.value",
205                           &query_value_) &&
206           GetIntFromJS(contents, "onEscKeyPressedCalls",
207                        &on_esc_key_press_event_calls_) &&
208           GetIntFromJS(contents, "onFocusChangedCalls",
209                       &on_focus_changed_calls_) &&
210           GetBoolFromJS(contents, "isFocused",
211                         &is_focused_) &&
212           GetIntFromJS(contents, "onToggleVoiceSearchCalls",
213                        &on_toggle_voice_search_calls_);
214  }
215
216  TemplateURL* GetDefaultSearchProviderTemplateURL() {
217    TemplateURLService* template_url_service =
218        TemplateURLServiceFactory::GetForProfile(browser()->profile());
219    if (template_url_service)
220      return template_url_service->GetDefaultSearchProvider();
221    return NULL;
222  }
223
224  bool AddSearchToHistory(string16 term, int visit_count) {
225    TemplateURL* template_url = GetDefaultSearchProviderTemplateURL();
226    if (!template_url)
227      return false;
228
229    HistoryService* history = HistoryServiceFactory::GetForProfile(
230        browser()->profile(), Profile::EXPLICIT_ACCESS);
231    GURL search(template_url->url_ref().ReplaceSearchTerms(
232        TemplateURLRef::SearchTermsArgs(term)));
233    history->AddPageWithDetails(
234        search, string16(), visit_count, visit_count,
235        base::Time::Now(), false, history::SOURCE_BROWSED);
236    history->SetKeywordSearchTermsForURL(
237        search, template_url->id(), term);
238    return true;
239  }
240
241  void BlockUntilHistoryProcessesPendingRequests() {
242    HistoryService* history = HistoryServiceFactory::GetForProfile(
243        browser()->profile(), Profile::EXPLICIT_ACCESS);
244    DCHECK(history);
245    DCHECK(base::MessageLoop::current());
246
247    CancelableRequestConsumer consumer;
248    history->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
249    base::MessageLoop::current()->Run();
250  }
251
252  int CountSearchProviderSuggestions() {
253    return omnibox()->model()->autocomplete_controller()->search_provider()->
254        matches().size();
255  }
256
257  int on_most_visited_change_calls_;
258  int most_visited_items_count_;
259  int first_most_visited_item_id_;
260  int on_native_suggestions_calls_;
261  int on_change_calls_;
262  int submit_count_;
263  int on_esc_key_press_event_calls_;
264  std::string query_value_;
265  int on_focus_changed_calls_;
266  bool is_focused_;
267  int on_toggle_voice_search_calls_;
268};
269
270class InstantExtendedNetworkTest : public InstantExtendedTest {
271 protected:
272  virtual void SetUpOnMainThread() OVERRIDE {
273    disable_for_test_.reset(new net::NetworkChangeNotifier::DisableForTest);
274    fake_network_change_notifier_.reset(new FakeNetworkChangeNotifier);
275    InstantExtendedTest::SetUpOnMainThread();
276  }
277
278  virtual void CleanUpOnMainThread() OVERRIDE {
279    InstantExtendedTest::CleanUpOnMainThread();
280    fake_network_change_notifier_.reset();
281    disable_for_test_.reset();
282  }
283
284  void SetConnectionType(net::NetworkChangeNotifier::ConnectionType type) {
285    fake_network_change_notifier_->SetConnectionType(type);
286  }
287
288 private:
289  scoped_ptr<net::NetworkChangeNotifier::DisableForTest> disable_for_test_;
290  scoped_ptr<FakeNetworkChangeNotifier> fake_network_change_notifier_;
291};
292
293// Test class used to verify chrome-search: scheme and access policy from the
294// Instant overlay.  This is a subclass of |ExtensionBrowserTest| because it
295// loads a theme that provides a background image.
296class InstantPolicyTest : public ExtensionBrowserTest, public InstantTestBase {
297 public:
298  InstantPolicyTest() {}
299
300 protected:
301  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
302    chrome::EnableInstantExtendedAPIForTesting();
303    ASSERT_TRUE(https_test_server().Start());
304    GURL instant_url = https_test_server().GetURL(
305        "files/instant_extended.html?strk=1&");
306    InstantTestBase::Init(instant_url);
307  }
308
309  void InstallThemeSource() {
310    ThemeSource* theme = new ThemeSource(profile());
311    content::URLDataSource::Add(profile(), theme);
312  }
313
314  void InstallThemeAndVerify(const std::string& theme_dir,
315                             const std::string& theme_name) {
316    const base::FilePath theme_path = test_data_dir_.AppendASCII(theme_dir);
317    ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(
318        theme_path, 1, ExtensionBrowserTest::browser()));
319    const extensions::Extension* theme =
320        ThemeServiceFactory::GetThemeForProfile(
321            ExtensionBrowserTest::browser()->profile());
322    ASSERT_NE(static_cast<extensions::Extension*>(NULL), theme);
323    ASSERT_EQ(theme->name(), theme_name);
324  }
325
326 private:
327  DISALLOW_COPY_AND_ASSIGN(InstantPolicyTest);
328};
329
330#if defined(HTML_INSTANT_EXTENDED_POPUP)
331
332IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ExtendedModeIsOn) {
333  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
334  EXPECT_TRUE(instant()->extended_enabled_);
335}
336
337IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NTPIsPreloaded) {
338  // Setup Instant.
339  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
340  FocusOmniboxAndWaitForInstantNTPSupport();
341
342  // NTP contents should be preloaded.
343  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
344  content::WebContents* ntp_contents = instant()->ntp_->contents();
345  EXPECT_TRUE(ntp_contents);
346}
347#endif  // HTML_INSTANT_EXTENDED_POPUP
348
349IN_PROC_BROWSER_TEST_F(InstantExtendedNetworkTest, NTPReactsToNetworkChanges) {
350  // Setup Instant.
351  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
352  FocusOmniboxAndWaitForInstantNTPSupport();
353
354  InstantService* instant_service =
355      InstantServiceFactory::GetForProfile(browser()->profile());
356  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
357
358  // The setup first initializes the platform specific NetworkChangeNotifier.
359  // The InstantExtendedNetworkTest replaces it with a fake, but by the time,
360  // InstantNTPPrerenderer has already registered itself. So the
361  // InstantNTPPrerenderer needs to register itself as NetworkChangeObserver
362  // again.
363  net::NetworkChangeNotifier::AddNetworkChangeObserver(
364      instant_service->ntp_prerenderer());
365
366  // The fake network change notifier will provide the network state to be
367  // offline, so the ntp will be local.
368  ASSERT_NE(static_cast<InstantNTP*>(NULL),
369            instant_service->ntp_prerenderer()->ntp());
370  EXPECT_TRUE(instant_service->ntp_prerenderer()->ntp()->IsLocal());
371
372  // Change the connect state, and wait for the notifications to be run, and NTP
373  // support to be determined.
374  SetConnectionType(net::NetworkChangeNotifier::CONNECTION_ETHERNET);
375  FocusOmniboxAndWaitForInstantNTPSupport();
376
377  // Verify the network state is fine, and InstantNTPPrerenderer doesn't want
378  // to switch to local NTP anymore.
379  EXPECT_FALSE(net::NetworkChangeNotifier::IsOffline());
380  EXPECT_FALSE(instant_service->ntp_prerenderer()->ShouldSwitchToLocalNTP());
381
382  // Open new tab.
383  ui_test_utils::NavigateToURLWithDisposition(
384      browser(),
385      GURL(chrome::kChromeUINewTabURL),
386      NEW_FOREGROUND_TAB,
387      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
388  content::WebContents* active_tab =
389      browser()->tab_strip_model()->GetActiveWebContents();
390
391  // Verify new NTP is not local.
392  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
393  EXPECT_NE(instant_service->ntp_prerenderer()->GetLocalInstantURL(),
394            active_tab->GetURL().spec());
395  ASSERT_NE(static_cast<InstantNTP*>(NULL),
396            instant_service->ntp_prerenderer()->ntp());
397  EXPECT_FALSE(instant_service->ntp_prerenderer()->ntp()->IsLocal());
398
399  SetConnectionType(net::NetworkChangeNotifier::CONNECTION_NONE);
400  FocusOmniboxAndWaitForInstantNTPSupport();
401
402  // Verify the network state is fine, and InstantNTPPrerenderer doesn't want
403  // to switch to local NTP anymore.
404  EXPECT_TRUE(net::NetworkChangeNotifier::IsOffline());
405  EXPECT_TRUE(instant_service->ntp_prerenderer()->ShouldSwitchToLocalNTP());
406
407  // Open new tab. Preloaded NTP contents should have been used.
408  ui_test_utils::NavigateToURLWithDisposition(
409      browser(),
410      GURL(chrome::kChromeUINewTabURL),
411      NEW_FOREGROUND_TAB,
412      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
413  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
414
415  // Verify new NTP is not local.
416  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
417  EXPECT_EQ(instant_service->ntp_prerenderer()->GetLocalInstantURL(),
418            active_tab->GetURL().spec());
419  ASSERT_NE(static_cast<InstantNTP*>(NULL),
420            instant_service->ntp_prerenderer()->ntp());
421  EXPECT_TRUE(instant_service->ntp_prerenderer()->ntp()->IsLocal());
422}
423
424#if defined(HTML_INSTANT_EXTENDED_POPUP)
425IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPIsUsedInSameTab) {
426  // Setup Instant.
427  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
428  FocusOmniboxAndWaitForInstantNTPSupport();
429
430  // NTP contents should be preloaded.
431  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
432  content::WebContents* ntp_contents = instant()->ntp_->contents();
433  EXPECT_TRUE(ntp_contents);
434
435  // Open new tab. Preloaded NTP contents should have been used.
436  ui_test_utils::NavigateToURLWithDisposition(
437      browser(),
438      GURL(chrome::kChromeUINewTabURL),
439      CURRENT_TAB,
440      ui_test_utils::BROWSER_TEST_NONE);
441  content::WebContents* active_tab =
442      browser()->tab_strip_model()->GetActiveWebContents();
443  EXPECT_EQ(ntp_contents, active_tab);
444  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
445}
446
447IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPForWrongProvider) {
448  // Setup Instant.
449  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
450  FocusOmniboxAndWaitForInstantNTPSupport();
451
452  // NTP contents should be preloaded.
453  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
454  content::WebContents* ntp_contents = instant()->ntp_->contents();
455  EXPECT_TRUE(ntp_contents);
456  GURL ntp_url = ntp_contents->GetURL();
457
458  // Change providers.
459  SetInstantURL("chrome://blank");
460
461  // Open new tab. Preloaded NTP contents should have not been used.
462  ui_test_utils::NavigateToURLWithDisposition(
463      browser(),
464      GURL(chrome::kChromeUINewTabURL),
465      NEW_FOREGROUND_TAB,
466      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
467  content::WebContents* active_tab =
468      browser()->tab_strip_model()->GetActiveWebContents();
469  EXPECT_NE(ntp_url, active_tab->GetURL());
470}
471
472IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPRenderProcessGone) {
473  // Setup Instant.
474  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
475  FocusOmniboxAndWaitForInstantNTPSupport();
476
477  // NTP contents should be preloaded.
478  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
479  EXPECT_FALSE(instant()->ntp()->IsLocal());
480
481  // NTP not reloaded after being killed.
482  instant()->InstantPageRenderProcessGone(instant()->ntp()->contents());
483  EXPECT_EQ(NULL, instant()->ntp());
484
485  // Open new tab. Should use local NTP.
486  ui_test_utils::NavigateToURLWithDisposition(
487      browser(),
488      GURL(chrome::kChromeUINewTabURL),
489      NEW_FOREGROUND_TAB,
490      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
491  content::WebContents* active_tab =
492      browser()->tab_strip_model()->GetActiveWebContents();
493  EXPECT_EQ(instant()->GetLocalInstantURL(), active_tab->GetURL().spec());
494}
495
496IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPDoesntSupportInstant) {
497  // Setup Instant.
498  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
499  InstantTestBase::Init(instant_url);
500  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
501  FocusOmniboxAndWaitForInstantNTPSupport();
502
503  // NTP contents should have fallen back to the local page.
504  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
505  EXPECT_TRUE(instant()->ntp()->IsLocal());
506
507  // Open new tab. Should use local NTP.
508  ui_test_utils::NavigateToURLWithDisposition(
509      browser(),
510      GURL(chrome::kChromeUINewTabURL),
511      NEW_FOREGROUND_TAB,
512      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
513  content::WebContents* active_tab =
514      browser()->tab_strip_model()->GetActiveWebContents();
515  EXPECT_EQ(instant()->GetLocalInstantURL(), active_tab->GetURL().spec());
516}
517
518// Flaky, http://crbug.com/240852 .
519IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_OmniboxHasFocusOnNewTab) {
520  // Setup Instant.
521  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
522  FocusOmniboxAndWaitForInstantNTPSupport();
523
524  // Explicitly unfocus the omnibox.
525  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
526  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
527  EXPECT_FALSE(omnibox()->model()->has_focus());
528
529  // Open new tab. Preloaded NTP contents should have been used.
530  ui_test_utils::NavigateToURLWithDisposition(
531      browser(),
532      GURL(chrome::kChromeUINewTabURL),
533      NEW_FOREGROUND_TAB,
534      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
535
536  // Omnibox should have focus.
537  EXPECT_TRUE(omnibox()->model()->has_focus());
538}
539
540IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxEmptyOnNewTabPage) {
541  // Setup Instant.
542  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
543  FocusOmniboxAndWaitForInstantNTPSupport();
544
545  // Open new tab. Preloaded NTP contents should have been used.
546  ui_test_utils::NavigateToURLWithDisposition(
547      browser(),
548      GURL(chrome::kChromeUINewTabURL),
549      NEW_FOREGROUND_TAB,
550      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
551
552  // Omnibox should be empty.
553  EXPECT_TRUE(omnibox()->GetText().empty());
554}
555
556IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoFaviconOnNewTabPage) {
557  // Setup Instant.
558  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
559  FocusOmniboxAndWaitForInstantNTPSupport();
560
561  // Open new tab. Preloaded NTP contents should have been used.
562  ui_test_utils::NavigateToURLWithDisposition(
563      browser(),
564      GURL(chrome::kChromeUINewTabURL),
565      NEW_FOREGROUND_TAB,
566      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
567
568  // No favicon should be shown.
569  content::WebContents* active_tab =
570      browser()->tab_strip_model()->GetActiveWebContents();
571  FaviconTabHelper* favicon_tab_helper =
572      FaviconTabHelper::FromWebContents(active_tab);
573  EXPECT_FALSE(favicon_tab_helper->ShouldDisplayFavicon());
574
575  // Favicon should be shown off the NTP.
576  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
577  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
578  favicon_tab_helper = FaviconTabHelper::FromWebContents(active_tab);
579  EXPECT_TRUE(favicon_tab_helper->ShouldDisplayFavicon());
580}
581
582IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ProcessIsolation) {
583  // Prior to setup, Instant has an ntp with a failed "google.com" load in
584  // it, which is rendered in the dedicated Instant renderer process.
585  //
586  // TODO(sreeram): Fix this up when we stop doing crazy things on init.
587  InstantService* instant_service =
588        InstantServiceFactory::GetForProfile(browser()->profile());
589  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
590#if !defined(OS_MACOSX)
591  // The failed "google.com" load is deleted, which sometimes leads to the
592  // process shutting down on Mac.
593  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
594#endif
595
596  // Setup Instant.
597  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
598  FocusOmniboxAndWaitForInstantNTPSupport();
599
600  // The registered Instant render process should still exist.
601  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
602  // And the Instant ntp should live inside it.
603  content::WebContents* ntp_contents = instant()->ntp_->contents();
604  EXPECT_TRUE(instant_service->IsInstantProcess(
605      ntp_contents->GetRenderProcessHost()->GetID()));
606
607  // Navigating to the NTP should use the Instant render process.
608  ui_test_utils::NavigateToURLWithDisposition(
609      browser(),
610      GURL(chrome::kChromeUINewTabURL),
611      CURRENT_TAB,
612      ui_test_utils::BROWSER_TEST_NONE);
613  content::WebContents* active_tab =
614      browser()->tab_strip_model()->GetActiveWebContents();
615  EXPECT_TRUE(instant_service->IsInstantProcess(
616      active_tab->GetRenderProcessHost()->GetID()));
617
618  // Navigating elsewhere should not use the Instant render process.
619  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
620  EXPECT_FALSE(instant_service->IsInstantProcess(
621      active_tab->GetRenderProcessHost()->GetID()));
622}
623
624IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_MostVisited) {
625  content::WindowedNotificationObserver observer(
626      chrome::NOTIFICATION_INSTANT_SENT_MOST_VISITED_ITEMS,
627      content::NotificationService::AllSources());
628  // Initialize Instant.
629  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
630  FocusOmniboxAndWaitForInstantNTPSupport();
631
632  // Get a handle to the NTP and the current state of the JS.
633  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
634  content::WebContents* ntp = instant()->ntp_->contents();
635  EXPECT_TRUE(ntp);
636  EXPECT_TRUE(UpdateSearchState(ntp));
637
638  // Wait for most visited data to be ready, if necessary.
639  if (on_most_visited_change_calls_ == 0) {
640    observer.Wait();
641    EXPECT_TRUE(UpdateSearchState(ntp));
642  }
643
644  EXPECT_EQ(1, on_most_visited_change_calls_);
645
646  // Make sure we have at least two Most Visited Items and save that number.
647  // TODO(pedrosimonetti): For now, we're relying on the fact that the Top
648  // Sites will have at lease two items in it. The correct approach would be
649  // adding those items to the Top Sites manually before starting the test.
650  EXPECT_GT(most_visited_items_count_, 1);
651  int old_most_visited_items_count = most_visited_items_count_;
652
653  // Delete the fist Most Visited Item.
654  int rid = first_most_visited_item_id_;
655  std::ostringstream stream;
656  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
657  EXPECT_TRUE(content::ExecuteScript(ntp, stream.str()));
658  observer.Wait();
659
660  // Update Most Visited state.
661  EXPECT_TRUE(UpdateSearchState(ntp));
662
663  // Make sure we have one less item in there.
664  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count - 1);
665
666  // Undo the deletion of the fist Most Visited Item.
667  stream.str(std::string());
668  stream << "newTabPageHandle.undoMostVisitedDeletion(" << rid << ");";
669  EXPECT_TRUE(content::ExecuteScript(ntp, stream.str()));
670  observer.Wait();
671
672  // Update Most Visited state.
673  EXPECT_TRUE(UpdateSearchState(ntp));
674
675  // Make sure we have the same number of items as before.
676  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count);
677
678  // Delete the fist Most Visited Item.
679  rid = first_most_visited_item_id_;
680  stream.str(std::string());
681  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
682  EXPECT_TRUE(content::ExecuteScript(ntp, stream.str()));
683  observer.Wait();
684
685  // Update Most Visited state.
686  EXPECT_TRUE(UpdateSearchState(ntp));
687
688  // Delete the second Most Visited Item.
689  rid = first_most_visited_item_id_;
690  stream.str(std::string());
691  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
692  EXPECT_TRUE(content::ExecuteScript(ntp, stream.str()));
693  observer.Wait();
694
695  // Update Most Visited state.
696  EXPECT_TRUE(UpdateSearchState(ntp));
697
698  // Make sure we have two less items in there.
699  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count - 2);
700
701  // Delete the second Most Visited Item.
702  stream.str(std::string());
703  stream << "newTabPageHandle.undoAllMostVisitedDeletions();";
704  EXPECT_TRUE(content::ExecuteScript(ntp, stream.str()));
705  observer.Wait();
706
707  // Update Most Visited state.
708  EXPECT_TRUE(UpdateSearchState(ntp));
709
710  // Make sure we have the same number of items as before.
711  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count);
712}
713
714// TODO(dhollowa): Fix flakes.  http://crbug.com/179930.
715IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_FaviconAccess) {
716  // Create a favicon.
717  history::TopSites* top_sites = browser()->profile()->GetTopSites();
718  GURL url("http://www.google.com/foo.html");
719  gfx::Image thumbnail(CreateBitmap(SK_ColorWHITE));
720  ThumbnailScore high_score(0.0, true, true, base::Time::Now());
721  EXPECT_TRUE(top_sites->SetPageThumbnail(url, thumbnail, high_score));
722
723  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
724  FocusOmniboxAndWaitForInstantNTPSupport();
725
726  // The "Instant" New Tab should have access to chrome-search: scheme but not
727  // chrome: scheme.
728  ui_test_utils::NavigateToURLWithDisposition(
729      browser(),
730      GURL(chrome::kChromeUINewTabURL),
731      NEW_FOREGROUND_TAB,
732      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
733
734  content::RenderViewHost* rvh =
735      browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost();
736
737  // Get the favicons.
738  const std::string chrome_favicon_url(
739      "chrome://favicon/largest/http://www.google.com/foo.html");
740  const std::string search_favicon_url(
741      "chrome-search://favicon/largest/http://www.google.com/foo.html");
742  bool loaded = false;
743  ASSERT_TRUE(LoadImage(rvh, chrome_favicon_url, &loaded));
744  EXPECT_FALSE(loaded) << chrome_favicon_url;
745  ASSERT_TRUE(LoadImage(rvh, search_favicon_url, &loaded));
746  EXPECT_TRUE(loaded) << search_favicon_url;
747}
748
749// Only implemented in Views and Mac currently: http://crbug.com/164723
750#if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_MACOSX)
751#define MAYBE_HomeButtonAffectsMargin HomeButtonAffectsMargin
752#else
753#define MAYBE_HomeButtonAffectsMargin DISABLED_HomeButtonAffectsMargin
754#endif
755
756// Check that toggling the state of the home button changes the start-edge
757// margin and width.
758IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_HomeButtonAffectsMargin) {
759  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
760  FocusOmniboxAndWaitForInstantNTPSupport();
761
762  // Get the current value of the start-edge margin and width.
763  int start_margin;
764  int width;
765  content::WebContents* ntp = instant()->ntp_->contents();
766  EXPECT_TRUE(GetIntFromJS(ntp, "chrome.searchBox.startMargin", &start_margin));
767  EXPECT_TRUE(GetIntFromJS(ntp, "chrome.searchBox.width", &width));
768
769  // Toggle the home button visibility pref.
770  PrefService* profile_prefs = browser()->profile()->GetPrefs();
771  bool show_home = profile_prefs->GetBoolean(prefs::kShowHomeButton);
772  profile_prefs->SetBoolean(prefs::kShowHomeButton, !show_home);
773
774  // Make sure the margin and width changed.
775  int new_start_margin;
776  int new_width;
777  EXPECT_TRUE(GetIntFromJS(ntp, "chrome.searchBox.startMargin",
778      &new_start_margin));
779  EXPECT_TRUE(GetIntFromJS(ntp, "chrome.searchBox.width", &new_width));
780  EXPECT_NE(start_margin, new_start_margin);
781  EXPECT_NE(width, new_width);
782  EXPECT_EQ(new_width - width, start_margin - new_start_margin);
783}
784
785// WebUIBindings should never be enabled on ANY Instant web contents.
786IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnNTP) {
787  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
788  FocusOmniboxAndWaitForInstantNTPSupport();
789
790  ui_test_utils::NavigateToURLWithDisposition(
791      browser(),
792      GURL(chrome::kChromeUINewTabURL),
793      NEW_FOREGROUND_TAB,
794      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
795  const content::WebContents* tab =
796      browser()->tab_strip_model()->GetActiveWebContents();
797
798  // Instant-provided NTP should not have any bindings enabled.
799  EXPECT_EQ(0, tab->GetRenderViewHost()->GetEnabledBindings());
800}
801
802// WebUIBindings should never be enabled on ANY Instant web contents.
803IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnResults) {
804  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
805  FocusOmniboxAndWaitForInstantNTPSupport();
806
807  // Type a query and press enter to get results.
808  SetOmniboxText("query");
809  // Commit the search by pressing Enter.
810  browser()->window()->GetLocationBar()->AcceptInput();
811  EXPECT_TRUE(instant()->model()->mode().is_default());
812  const content::WebContents* tab =
813      browser()->tab_strip_model()->GetActiveWebContents();
814
815  // The commited Instant page should not have any bindings enabled.
816  EXPECT_EQ(0, tab->GetRenderViewHost()->GetEnabledBindings());
817}
818
819// Test that the Bookmark provider is enabled, and returns results.
820// TODO(sreeram): Convert this to a unit test.
821IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_HasBookmarkProvider) {
822  // No need to setup Instant.
823  set_browser(browser());
824
825  BookmarkModel* bookmark_model =
826      BookmarkModelFactory::GetForProfile(browser()->profile());
827  ASSERT_TRUE(bookmark_model);
828  ui_test_utils::WaitForBookmarkModelToLoad(bookmark_model);
829  bookmark_utils::AddIfNotBookmarked(bookmark_model, GURL("http://angeline/"),
830                                     ASCIIToUTF16("angeline"));
831
832  SetOmniboxText("angeline");
833
834  bool found_bookmark_match = false;
835
836  const AutocompleteResult& result = omnibox()->model()->result();
837  for (AutocompleteResult::const_iterator iter = result.begin();
838       !found_bookmark_match && iter != result.end(); ++iter) {
839    found_bookmark_match = iter->type == AutocompleteMatchType::BOOKMARK_TITLE;
840  }
841
842  EXPECT_TRUE(found_bookmark_match);
843}
844
845// Test that hitting Esc to clear the omnibox works. http://crbug.com/231744.
846IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_EscapeClearsOmnibox) {
847  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
848  FocusOmniboxAndWaitForInstantNTPSupport();
849
850  // Navigate to the Instant NTP, and wait for it to be recognized.
851  content::WindowedNotificationObserver instant_tab_observer(
852      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
853      content::NotificationService::AllSources());
854  ui_test_utils::NavigateToURLWithDisposition(
855      browser(),
856      GURL(chrome::kChromeUINewTabURL),
857      NEW_FOREGROUND_TAB,
858      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
859  instant_tab_observer.Wait();
860
861  content::WebContents* contents =
862      browser()->tab_strip_model()->GetActiveWebContents();
863
864  // Type a query. Verify that the query is seen by the page.
865  SetOmniboxText("mojo");
866  std::string query;
867  EXPECT_TRUE(GetStringFromJS(contents, "chrome.embeddedSearch.searchBox.value",
868                              &query));
869  EXPECT_EQ("mojo", query);
870
871  EXPECT_TRUE(content::ExecuteScript(contents,
872                                     "onChangeCalls = submitCount = 0;"));
873
874  // Hit Escape, and verify that the page sees that the query is cleared.
875  SendEscape();
876  EXPECT_TRUE(GetStringFromJS(contents, "chrome.embeddedSearch.searchBox.value",
877                              &query));
878  EXPECT_EQ("", query);
879  EXPECT_EQ("", GetOmniboxText());
880
881  EXPECT_TRUE(UpdateSearchState(contents));
882  EXPECT_LT(0, on_change_calls_);
883  EXPECT_EQ(0, submit_count_);
884  EXPECT_LT(0, on_esc_key_press_event_calls_);
885}
886
887// Test that renderer initiated navigations to an instant URL from a non
888// Instant page do not end up in an Instant process if they are bounced to the
889// browser.
890IN_PROC_BROWSER_TEST_F(
891    InstantExtendedTest,
892    DISABLED_RendererInitiatedNavigationNotInInstantProcess) {
893  InstantService* instant_service =
894      InstantServiceFactory::GetForProfile(browser()->profile());
895  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
896
897  // Setup Instant.
898  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
899  FocusOmniboxAndWaitForInstantNTPSupport();
900
901  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
902  EXPECT_EQ(1, browser()->tab_strip_model()->count());
903
904  // Don't use https server for the non instant URL so that the browser uses
905  // different RenderViews.
906  GURL non_instant_url = test_server()->GetURL("files/simple.html");
907  ui_test_utils::NavigateToURLWithDisposition(
908      browser(),
909      non_instant_url,
910      CURRENT_TAB,
911      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
912  content::WebContents* contents =
913      browser()->tab_strip_model()->GetActiveWebContents();
914  EXPECT_FALSE(instant_service->IsInstantProcess(
915      contents->GetRenderProcessHost()->GetID()));
916  EXPECT_EQ(non_instant_url, contents->GetURL());
917
918  int old_render_view_id = contents->GetRenderViewHost()->GetRoutingID();
919  int old_render_process_id = contents->GetRenderProcessHost()->GetID();
920
921  std::string instant_url_with_query = instant_url().spec() + "q=3";
922  std::string add_link_script = base::StringPrintf(
923      "var a = document.createElement('a');"
924      "a.id = 'toClick';"
925      "a.href = '%s';"
926      "document.body.appendChild(a);",
927      instant_url_with_query.c_str());
928  EXPECT_TRUE(content::ExecuteScript(contents, add_link_script));
929
930  // Ensure that navigations are bounced to the browser.
931  contents->GetMutableRendererPrefs()->browser_handles_all_top_level_requests =
932      true;
933  contents->GetRenderViewHost()->SyncRendererPrefs();
934
935  content::WindowedNotificationObserver observer(
936        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
937        content::NotificationService::AllSources());
938  EXPECT_TRUE(content::ExecuteScript(
939      contents, "document.getElementById('toClick').click();"));
940  observer.Wait();
941
942  EXPECT_EQ(1, browser()->tab_strip_model()->count());
943  contents = browser()->tab_strip_model()->GetActiveWebContents();
944  EXPECT_FALSE(instant_service->IsInstantProcess(
945      contents->GetRenderProcessHost()->GetID()));
946  EXPECT_EQ(GURL(instant_url_with_query), contents->GetURL());
947  int new_render_view_id = contents->GetRenderViewHost()->GetRoutingID();
948  int new_render_process_id = contents->GetRenderProcessHost()->GetID();
949
950  EXPECT_TRUE(old_render_process_id != new_render_process_id ||
951              old_render_view_id != new_render_view_id);
952}
953
954// Test that renderer initiated navigations to an Instant URL from an
955// Instant process end up in an Instant process.
956IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
957                       RendererInitiatedNavigationInInstantProcess) {
958  InstantService* instant_service =
959      InstantServiceFactory::GetForProfile(browser()->profile());
960  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
961
962  // Setup Instant.
963  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
964  FocusOmniboxAndWaitForInstantNTPSupport();
965
966  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
967  EXPECT_EQ(1, browser()->tab_strip_model()->count());
968
969  ui_test_utils::NavigateToURLWithDisposition(
970      browser(),
971      instant_url(),
972      CURRENT_TAB,
973      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
974  content::WebContents* contents =
975      browser()->tab_strip_model()->GetActiveWebContents();
976  EXPECT_TRUE(instant_service->IsInstantProcess(
977      contents->GetRenderProcessHost()->GetID()));
978
979  std::string instant_url_with_query = instant_url().spec() + "q=3";
980  std::string add_link_script = base::StringPrintf(
981      "var a = document.createElement('a');"
982      "a.id = 'toClick';"
983      "a.href = '%s';"
984      "document.body.appendChild(a);",
985      instant_url_with_query.c_str());
986  EXPECT_TRUE(content::ExecuteScript(contents, add_link_script));
987
988  content::WindowedNotificationObserver observer(
989        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
990        content::NotificationService::AllSources());
991  EXPECT_TRUE(content::ExecuteScript(
992      contents, "document.getElementById('toClick').click();"));
993  observer.Wait();
994
995  EXPECT_EQ(1, browser()->tab_strip_model()->count());
996  contents = browser()->tab_strip_model()->GetActiveWebContents();
997  EXPECT_TRUE(instant_service->IsInstantProcess(
998      contents->GetRenderProcessHost()->GetID()));
999  EXPECT_EQ(GURL(instant_url_with_query), contents->GetURL());
1000}
1001
1002IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AcceptingURLSearchDoesNotNavigate) {
1003  // Get a committed Instant tab, which will be in the Instant process and thus
1004  // support chrome::GetSearchTerms().
1005  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1006  FocusOmnibox();
1007
1008  // Create an observer to wait for the instant tab to support Instant.
1009  content::WindowedNotificationObserver observer(
1010      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1011      content::NotificationService::AllSources());
1012
1013  // Do a search and commit it.
1014  SetOmniboxText("foo");
1015  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
1016  browser()->window()->GetLocationBar()->AcceptInput();
1017  observer.Wait();
1018
1019  // Set URL-like search terms for the instant tab.
1020  content::WebContents* instant_tab = instant()->instant_tab()->contents();
1021  content::NavigationEntry* visible_entry =
1022      instant_tab->GetController().GetVisibleEntry();
1023  visible_entry->SetExtraData(sessions::kSearchTermsKey,
1024                              ASCIIToUTF16("http://example.com"));
1025  SetOmniboxText("http://example.com");
1026  omnibox()->model()->SetInputInProgress(false);
1027  omnibox()->CloseOmniboxPopup();
1028
1029  // Accept the omnibox input.
1030  EXPECT_FALSE(omnibox()->model()->user_input_in_progress());
1031  EXPECT_TRUE(
1032      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms());
1033  GURL instant_tab_url = instant_tab->GetURL();
1034  browser()->window()->GetLocationBar()->AcceptInput();
1035  EXPECT_EQ(instant_tab_url, instant_tab->GetURL());
1036}
1037
1038// TODO(jered): Figure out why this test flakes and fix it.
1039IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1040                       DISABLED_AcceptingJSSearchDoesNotRunJS) {
1041  // Get a committed Instant tab, which will be in the Instant process and thus
1042  // support chrome::GetSearchTerms().
1043  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1044  FocusOmnibox();
1045
1046  // Create an observer to wait for the instant tab to support Instant.
1047  content::WindowedNotificationObserver observer(
1048      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1049      content::NotificationService::AllSources());
1050
1051  // Do a search and commit it.
1052  SetOmniboxText("foo");
1053  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
1054  browser()->window()->GetLocationBar()->AcceptInput();
1055  observer.Wait();
1056
1057  // Set URL-like search terms for the instant tab.
1058  content::WebContents* instant_tab = instant()->instant_tab()->contents();
1059  content::NavigationEntry* visible_entry =
1060      instant_tab->GetController().GetVisibleEntry();
1061  const char kEvilJS[] = "javascript:document.title='evil';1;";
1062  visible_entry->SetExtraData(sessions::kSearchTermsKey, ASCIIToUTF16(kEvilJS));
1063  SetOmniboxText(kEvilJS);
1064  omnibox()->model()->SetInputInProgress(false);
1065  omnibox()->CloseOmniboxPopup();
1066
1067  // Accept the omnibox input.
1068  EXPECT_FALSE(omnibox()->model()->user_input_in_progress());
1069  EXPECT_TRUE(
1070      browser()->toolbar_model()->WouldReplaceSearchURLWithSearchTerms());
1071  browser()->window()->GetLocationBar()->AcceptInput();
1072  // Force some Javascript to run in the renderer so the inline javascript:
1073  // would be forced to run if it's going to.
1074  EXPECT_TRUE(content::ExecuteScript(instant_tab, "1;"));
1075  EXPECT_NE(ASCIIToUTF16("evil"), instant_tab->GetTitle());
1076}
1077
1078IN_PROC_BROWSER_TEST_F(
1079    InstantExtendedTest,
1080    DISABLED_ReloadSearchAfterBackReloadsCorrectQuery) {
1081  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1082  FocusOmnibox();
1083
1084  // Create an observer to wait for the instant tab to support Instant.
1085  content::WindowedNotificationObserver observer(
1086      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1087      content::NotificationService::AllSources());
1088
1089  // Search for [foo].
1090  SetOmniboxText("foo");
1091  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
1092  browser()->window()->GetLocationBar()->AcceptInput();
1093  observer.Wait();
1094
1095  // Search again for [bar].
1096  content::WebContents* instant_tab = instant()->instant_tab()->contents();
1097  EXPECT_TRUE(content::ExecuteScript(instant_tab,
1098                                     "suggestion = 'bart';"));
1099  SetOmniboxTextAndWaitForSuggestion("bar");
1100
1101  // Accept the new query and wait for the page to navigate.
1102  content::WindowedNotificationObserver nav_observer(
1103        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1104        content::NotificationService::AllSources());
1105  browser()->window()->GetLocationBar()->AcceptInput();
1106  nav_observer.Wait();
1107
1108  // Press back button and reload.
1109  content::WindowedNotificationObserver back_observer(
1110        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1111        content::NotificationService::AllSources());
1112  instant_tab->GetController().GoBack();
1113  back_observer.Wait();
1114  EXPECT_EQ("foo", GetOmniboxText());
1115  FocusOmnibox();
1116  content::WindowedNotificationObserver reload_observer(
1117        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1118        content::NotificationService::AllSources());
1119  browser()->window()->GetLocationBar()->AcceptInput();
1120  reload_observer.Wait();
1121
1122  EXPECT_EQ("foo", GetOmniboxText());
1123}
1124
1125class InstantExtendedFirstTabTest : public InProcessBrowserTest,
1126                                    public InstantTestBase {
1127 public:
1128  InstantExtendedFirstTabTest() {}
1129 protected:
1130  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
1131    command_line->AppendSwitch(switches::kEnableInstantExtendedAPI);
1132    command_line->AppendSwitch(switches::kDisableLocalFirstLoadNTP);
1133  }
1134};
1135
1136// Flaky: http://crbug.com/238863
1137IN_PROC_BROWSER_TEST_F(
1138    InstantExtendedFirstTabTest, DISABLED_RedirectToLocalOnLoadFailure) {
1139  // Create a new window to test the first NTP load.
1140  ui_test_utils::NavigateToURLWithDisposition(
1141      browser(),
1142      GURL(chrome::kChromeUINewTabURL),
1143      NEW_WINDOW,
1144      ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER);
1145
1146  const BrowserList* browser_list = BrowserList::GetInstance(
1147      chrome::GetActiveDesktop());
1148  ASSERT_EQ(2u, browser_list->size());
1149  set_browser(browser_list->get(1));
1150
1151  FocusOmniboxAndWaitForInstantNTPSupport();
1152
1153  // Also make sure our instant_tab_ is loaded.
1154  if (!instant()->instant_tab_) {
1155    content::WindowedNotificationObserver instant_tab_observer(
1156        chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1157        content::NotificationService::AllSources());
1158    instant_tab_observer.Wait();
1159  }
1160
1161  // NTP contents should be preloaded.
1162  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
1163  EXPECT_TRUE(instant()->ntp()->IsLocal());
1164
1165  // Instant tab contents should be preloaded.
1166  ASSERT_NE(static_cast<InstantTab*>(NULL), instant()->instant_tab());
1167  EXPECT_TRUE(instant()->instant_tab()->IsLocal());
1168}
1169
1170// Broken on mac: http://crbug.com/247448
1171#if defined(OS_MACOSX)
1172#define MAYBE_KeyboardTogglesVoiceSearch DISABLED_KeyboardTogglesVoiceSearch
1173#else
1174#define MAYBE_KeyboardTogglesVoiceSearch KeyboardTogglesVoiceSearch
1175#endif
1176IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_KeyboardTogglesVoiceSearch) {
1177  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1178  FocusOmniboxAndWaitForInstantNTPSupport();
1179
1180  // Open new tab and test that toggle is fired.
1181  ui_test_utils::NavigateToURLWithDisposition(
1182      browser(),
1183      GURL(chrome::kChromeUINewTabURL),
1184      CURRENT_TAB,
1185      ui_test_utils::BROWSER_TEST_NONE);
1186  content::WebContents* active_tab =
1187      browser()->tab_strip_model()->GetActiveWebContents();
1188  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_OEM_PERIOD,
1189                                              true, true, false, false));
1190  EXPECT_TRUE(UpdateSearchState(active_tab));
1191  EXPECT_EQ(1, on_toggle_voice_search_calls_);
1192}
1193
1194// Test to verify that the omnibox search query is updated on browser
1195// back/forward button press events.
1196IN_PROC_BROWSER_TEST_F(InstantExtendedTest, UpdateSearchQueryOnNavigation) {
1197  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1198
1199  // Focus omnibox.
1200  FocusOmniboxAndWaitForInstantNTPSupport();
1201  SetOmniboxText("flowers");
1202
1203  // Commit the search by pressing 'Enter'.
1204  PressEnterAndWaitForNavigation();
1205  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1206
1207  // Typing in the new search query in omnibox.
1208  SetOmniboxText("cattles");
1209  // Commit the search by pressing 'Enter'.
1210  PressEnterAndWaitForNavigation();
1211  // 'Enter' commits the query as it was typed. This creates a navigation entry
1212  // in the history.
1213  EXPECT_EQ(ASCIIToUTF16("cattles"), omnibox()->GetText());
1214
1215  content::WebContents* active_tab =
1216      browser()->tab_strip_model()->GetActiveWebContents();
1217  EXPECT_TRUE(active_tab->GetController().CanGoBack());
1218  content::WindowedNotificationObserver load_stop_observer(
1219      content::NOTIFICATION_LOAD_STOP,
1220      content::Source<content::NavigationController>(
1221          &active_tab->GetController()));
1222  active_tab->GetController().GoBack();
1223  load_stop_observer.Wait();
1224
1225  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1226  // Commit the search by pressing 'Enter'.
1227  FocusOmnibox();
1228  PressEnterAndWaitForNavigation();
1229  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1230}
1231
1232#endif  // HTML_INSTANT_EXTENDED_POPUP
1233
1234#if !defined(HTML_INSTANT_EXTENDED_POPUP)
1235IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchReusesInstantTab) {
1236  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1237  FocusOmniboxAndWaitForInstantNTPSupport();
1238
1239  content::WindowedNotificationObserver observer(
1240      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1241      content::NotificationService::AllSources());
1242  SetOmniboxText("flowers");
1243  PressEnterAndWaitForNavigation();
1244  observer.Wait();
1245
1246  // Just did a regular search.
1247  content::WebContents* active_tab =
1248      browser()->tab_strip_model()->GetActiveWebContents();
1249  ASSERT_THAT(active_tab->GetURL().spec(), HasSubstr("q=flowers"));
1250  ASSERT_TRUE(UpdateSearchState(active_tab));
1251  ASSERT_EQ(0, submit_count_);
1252
1253  SetOmniboxText("puppies");
1254  PressEnterAndWaitForNavigation();
1255
1256  // Should have reused the tab and sent an onsubmit message.
1257  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1258  ASSERT_THAT(active_tab->GetURL().spec(), HasSubstr("q=puppies"));
1259  ASSERT_TRUE(UpdateSearchState(active_tab));
1260  EXPECT_EQ(1, submit_count_);
1261}
1262
1263IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1264                       SearchDoesntReuseInstantTabWithoutSupport) {
1265  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1266  FocusOmniboxAndWaitForInstantNTPSupport();
1267
1268  // Don't wait for the navigation to complete.
1269  SetOmniboxText("flowers");
1270  browser()->window()->GetLocationBar()->AcceptInput();
1271
1272  SetOmniboxText("puppies");
1273  browser()->window()->GetLocationBar()->AcceptInput();
1274
1275  // Should not have reused the tab.
1276  ASSERT_THAT(
1277      browser()->tab_strip_model()->GetActiveWebContents()->GetURL().spec(),
1278      HasSubstr("q=puppies"));
1279}
1280
1281IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1282                       TypedSearchURLDoesntReuseInstantTab) {
1283  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1284  FocusOmniboxAndWaitForInstantNTPSupport();
1285
1286  // Create an observer to wait for the instant tab to support Instant.
1287  content::WindowedNotificationObserver observer_1(
1288      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1289      content::NotificationService::AllSources());
1290  SetOmniboxText("flowers");
1291  PressEnterAndWaitForNavigation();
1292  observer_1.Wait();
1293
1294  // Just did a regular search.
1295  content::WebContents* active_tab =
1296      browser()->tab_strip_model()->GetActiveWebContents();
1297  ASSERT_THAT(active_tab->GetURL().spec(), HasSubstr("q=flowers"));
1298  ASSERT_TRUE(UpdateSearchState(active_tab));
1299  ASSERT_EQ(0, submit_count_);
1300
1301  // Typed in a search URL "by hand".
1302  content::WindowedNotificationObserver observer_2(
1303      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1304      content::NotificationService::AllSources());
1305  SetOmniboxText(instant_url().spec() + "#q=puppies");
1306  PressEnterAndWaitForNavigation();
1307  observer_2.Wait();
1308
1309  // Should not have reused the tab.
1310  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1311  ASSERT_THAT(active_tab->GetURL().spec(), HasSubstr("q=puppies"));
1312}
1313
1314IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxMarginSetForSearchURLs) {
1315  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1316  FocusOmniboxAndWaitForInstantNTPSupport();
1317
1318  // Create an observer to wait for the instant tab to support Instant.
1319  content::WindowedNotificationObserver observer(
1320      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1321      content::NotificationService::AllSources());
1322
1323  SetOmniboxText("flowers");
1324  browser()->window()->GetLocationBar()->AcceptInput();
1325  observer.Wait();
1326
1327  const std::string& url =
1328      browser()->tab_strip_model()->GetActiveWebContents()->GetURL().spec();
1329  // Make sure we actually used search_url, not instant_url.
1330  ASSERT_THAT(url, HasSubstr("&is_search"));
1331  EXPECT_THAT(url, HasSubstr("&es_sm="));
1332}
1333
1334#endif  // if !defined(HTML_INSTANT_EXTENDED_POPUP)
1335
1336// Test to verify that switching tabs should not dispatch onmostvisitedchanged
1337// events.
1338IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoMostVisitedChangedOnTabSwitch) {
1339  // Initialize Instant.
1340  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1341  FocusOmniboxAndWaitForInstantNTPSupport();
1342
1343  // Open new tab. Preloaded NTP contents should have been used.
1344  ui_test_utils::NavigateToURLWithDisposition(
1345      browser(),
1346      GURL(chrome::kChromeUINewTabURL),
1347      NEW_FOREGROUND_TAB,
1348      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1349  EXPECT_EQ(2, browser()->tab_strip_model()->count());
1350
1351  // Make sure new tab received the onmostvisitedchanged event once.
1352  content::WebContents* active_tab =
1353      browser()->tab_strip_model()->GetActiveWebContents();
1354  EXPECT_TRUE(UpdateSearchState(active_tab));
1355  EXPECT_EQ(1, on_most_visited_change_calls_);
1356
1357  // Activate the previous tab.
1358  browser()->tab_strip_model()->ActivateTabAt(0, false);
1359
1360  // Switch back to new tab.
1361  browser()->tab_strip_model()->ActivateTabAt(1, false);
1362
1363  // Confirm that new tab got no onmostvisitedchanged event.
1364  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1365  EXPECT_TRUE(UpdateSearchState(active_tab));
1366  EXPECT_EQ(1, on_most_visited_change_calls_);
1367}
1368
1369IN_PROC_BROWSER_TEST_F(InstantPolicyTest, ThemeBackgroundAccess) {
1370  InstallThemeSource();
1371  ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
1372  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1373  FocusOmniboxAndWaitForInstantNTPSupport();
1374
1375  // The "Instant" New Tab should have access to chrome-search: scheme but not
1376  // chrome: scheme.
1377  ui_test_utils::NavigateToURLWithDisposition(
1378      browser(),
1379      GURL(chrome::kChromeUINewTabURL),
1380      NEW_FOREGROUND_TAB,
1381      ui_test_utils::BROWSER_TEST_NONE);
1382
1383  content::RenderViewHost* rvh =
1384      browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost();
1385
1386  const std::string chrome_url("chrome://theme/IDR_THEME_NTP_BACKGROUND");
1387  const std::string search_url(
1388      "chrome-search://theme/IDR_THEME_NTP_BACKGROUND");
1389  bool loaded = false;
1390  ASSERT_TRUE(LoadImage(rvh, chrome_url, &loaded));
1391  EXPECT_FALSE(loaded) << chrome_url;
1392  ASSERT_TRUE(LoadImage(rvh, search_url, &loaded));
1393  EXPECT_TRUE(loaded) << search_url;
1394}
1395
1396IN_PROC_BROWSER_TEST_F(InstantPolicyTest,
1397                       NoThemeBackgroundChangeEventOnTabSwitch) {
1398  InstallThemeSource();
1399  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1400  FocusOmniboxAndWaitForInstantNTPSupport();
1401
1402  // Install a theme.
1403  ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
1404  EXPECT_EQ(1, browser()->tab_strip_model()->count());
1405
1406  // Open new tab. Preloaded NTP contents should have been used.
1407  ui_test_utils::NavigateToURLWithDisposition(
1408      browser(),
1409      GURL(chrome::kChromeUINewTabURL),
1410      NEW_FOREGROUND_TAB,
1411      ui_test_utils::BROWSER_TEST_NONE);
1412  EXPECT_EQ(2, browser()->tab_strip_model()->count());
1413
1414  content::WebContents* active_tab =
1415      browser()->tab_strip_model()->GetActiveWebContents();
1416  ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
1417  int on_theme_changed_calls = 0;
1418  EXPECT_TRUE(GetIntFromJS(active_tab, "onThemeChangedCalls",
1419                           &on_theme_changed_calls));
1420  EXPECT_EQ(1, on_theme_changed_calls);
1421
1422  // Activate the previous tab.
1423  browser()->tab_strip_model()->ActivateTabAt(0, false);
1424  ASSERT_EQ(0, browser()->tab_strip_model()->active_index());
1425
1426  // Switch back to new tab.
1427  browser()->tab_strip_model()->ActivateTabAt(1, false);
1428  ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
1429
1430  // Confirm that new tab got no onthemechanged event while switching tabs.
1431  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1432  on_theme_changed_calls = 0;
1433  EXPECT_TRUE(GetIntFromJS(active_tab, "onThemeChangedCalls",
1434                           &on_theme_changed_calls));
1435  EXPECT_EQ(1, on_theme_changed_calls);
1436}
1437
1438IN_PROC_BROWSER_TEST_F(InstantPolicyTest,
1439                       SendThemeBackgroundChangedEvent) {
1440  InstallThemeSource();
1441  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1442  FocusOmniboxAndWaitForInstantNTPSupport();
1443
1444  // Install a theme.
1445  ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
1446
1447  // Open new tab. Preloaded NTP contents should have been used.
1448  ui_test_utils::NavigateToURLWithDisposition(
1449      browser(),
1450      GURL(chrome::kChromeUINewTabURL),
1451      NEW_FOREGROUND_TAB,
1452      ui_test_utils::BROWSER_TEST_NONE);
1453  EXPECT_EQ(2, browser()->tab_strip_model()->count());
1454
1455  // Make sure new tab received an onthemechanged event.
1456  content::WebContents* active_tab =
1457      browser()->tab_strip_model()->GetActiveWebContents();
1458  ASSERT_EQ(1, browser()->tab_strip_model()->active_index());
1459  int on_theme_changed_calls = 0;
1460  EXPECT_TRUE(GetIntFromJS(active_tab, "onThemeChangedCalls",
1461                           &on_theme_changed_calls));
1462  EXPECT_EQ(1, on_theme_changed_calls);
1463
1464  // Install a new theme.
1465  ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme2", "snowflake theme"));
1466
1467  // Confirm that new tab is notified about the theme changed event.
1468  on_theme_changed_calls = 0;
1469  EXPECT_TRUE(GetIntFromJS(active_tab, "onThemeChangedCalls",
1470                           &on_theme_changed_calls));
1471  EXPECT_EQ(2, on_theme_changed_calls);
1472}
1473
1474// Flaky on Mac and Linux Tests bots.
1475#if defined(OS_MACOSX) || defined(OS_LINUX)
1476#define MAYBE_UpdateSearchQueryOnBackNavigation DISABLED_UpdateSearchQueryOnBackNavigation
1477#else
1478#define MAYBE_UpdateSearchQueryOnBackNavigation UpdateSearchQueryOnBackNavigation
1479#endif
1480// Test to verify that the omnibox search query is updated on browser
1481// back button press event.
1482IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1483                       MAYBE_UpdateSearchQueryOnBackNavigation) {
1484  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1485
1486  // Focus omnibox and confirm overlay isn't shown.
1487  FocusOmniboxAndWaitForInstantNTPSupport();
1488
1489  // Create an observer to wait for the instant tab to support Instant.
1490  content::WindowedNotificationObserver observer(
1491      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1492      content::NotificationService::AllSources());
1493
1494  SetOmniboxText("flowers");
1495  // Commit the search by pressing 'Enter'.
1496  PressEnterAndWaitForNavigation();
1497  observer.Wait();
1498
1499  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1500
1501  // Typing in the new search query in omnibox.
1502  SetOmniboxText("cattles");
1503  // Commit the search by pressing 'Enter'.
1504  PressEnterAndWaitForNavigation();
1505  // 'Enter' commits the query as it was typed. This creates a navigation entry
1506  // in the history.
1507  EXPECT_EQ(ASCIIToUTF16("cattles"), omnibox()->GetText());
1508
1509  content::WebContents* active_tab =
1510      browser()->tab_strip_model()->GetActiveWebContents();
1511  EXPECT_TRUE(active_tab->GetController().CanGoBack());
1512  content::WindowedNotificationObserver load_stop_observer(
1513      content::NOTIFICATION_LOAD_STOP,
1514      content::Source<content::NavigationController>(
1515          &active_tab->GetController()));
1516  active_tab->GetController().GoBack();
1517  load_stop_observer.Wait();
1518
1519  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1520  // Commit the search by pressing 'Enter'.
1521  FocusOmnibox();
1522  PressEnterAndWaitForNavigation();
1523  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1524}
1525
1526// Flaky on Mac and Linux Tests bots.
1527#if defined(OS_MACOSX) || defined(OS_LINUX)
1528#define MAYBE_UpdateSearchQueryOnForwardNavigation DISABLED_UpdateSearchQueryOnForwardNavigation
1529#else
1530#define MAYBE_UpdateSearchQueryOnForwardNavigation UpdateSearchQueryOnForwardNavigation
1531#endif
1532// Test to verify that the omnibox search query is updated on browser
1533// forward button press events.
1534IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1535                       MAYBE_UpdateSearchQueryOnForwardNavigation) {
1536  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1537
1538  // Focus omnibox and confirm overlay isn't shown.
1539  FocusOmniboxAndWaitForInstantNTPSupport();
1540
1541  // Create an observer to wait for the instant tab to support Instant.
1542  content::WindowedNotificationObserver observer(
1543      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1544      content::NotificationService::AllSources());
1545
1546  SetOmniboxText("flowers");
1547  // Commit the search by pressing 'Enter'.
1548  PressEnterAndWaitForNavigation();
1549  observer.Wait();
1550
1551  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1552
1553  // Typing in the new search query in omnibox.
1554  SetOmniboxText("cattles");
1555  // Commit the search by pressing 'Enter'.
1556  PressEnterAndWaitForNavigation();
1557  // 'Enter' commits the query as it was typed. This creates a navigation entry
1558  // in the history.
1559  EXPECT_EQ(ASCIIToUTF16("cattles"), omnibox()->GetText());
1560
1561  content::WebContents* active_tab =
1562      browser()->tab_strip_model()->GetActiveWebContents();
1563  EXPECT_TRUE(active_tab->GetController().CanGoBack());
1564  content::WindowedNotificationObserver load_stop_observer(
1565      content::NOTIFICATION_LOAD_STOP,
1566      content::Source<content::NavigationController>(
1567          &active_tab->GetController()));
1568  active_tab->GetController().GoBack();
1569  load_stop_observer.Wait();
1570
1571  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1572
1573  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1574  EXPECT_TRUE(active_tab->GetController().CanGoForward());
1575  content::WindowedNotificationObserver load_stop_observer_2(
1576      content::NOTIFICATION_LOAD_STOP,
1577      content::Source<content::NavigationController>(
1578          &active_tab->GetController()));
1579  active_tab->GetController().GoForward();
1580  load_stop_observer_2.Wait();
1581
1582  // Commit the search by pressing 'Enter'.
1583  FocusOmnibox();
1584  EXPECT_EQ(ASCIIToUTF16("cattles"), omnibox()->GetText());
1585  PressEnterAndWaitForNavigation();
1586  EXPECT_EQ(ASCIIToUTF16("cattles"), omnibox()->GetText());
1587}
1588
1589// Flaky on all bots since re-enabled in r208032, crbug.com/253092
1590IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_NavigateBackToNTP) {
1591  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1592  FocusOmniboxAndWaitForInstantNTPSupport();
1593
1594  // Open a new tab page.
1595  ui_test_utils::NavigateToURLWithDisposition(
1596      browser(),
1597      GURL(chrome::kChromeUINewTabURL),
1598      NEW_FOREGROUND_TAB,
1599      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1600  EXPECT_EQ(2, browser()->tab_strip_model()->count());
1601
1602  content::WindowedNotificationObserver observer(
1603      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1604      content::NotificationService::AllSources());
1605  SetOmniboxText("flowers");
1606  PressEnterAndWaitForNavigation();
1607  observer.Wait();
1608
1609  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1610
1611  // Typing in the new search query in omnibox.
1612  // Commit the search by pressing 'Enter'.
1613  SetOmniboxText("cattles");
1614  PressEnterAndWaitForNavigation();
1615
1616  // 'Enter' commits the query as it was typed. This creates a navigation entry
1617  // in the history.
1618  EXPECT_EQ(ASCIIToUTF16("cattles"), omnibox()->GetText());
1619
1620  // Navigate back to "flowers" search result page.
1621  content::WebContents* active_tab =
1622      browser()->tab_strip_model()->GetActiveWebContents();
1623  EXPECT_TRUE(active_tab->GetController().CanGoBack());
1624  content::WindowedNotificationObserver load_stop_observer(
1625      content::NOTIFICATION_LOAD_STOP,
1626      content::Source<content::NavigationController>(
1627          &active_tab->GetController()));
1628  active_tab->GetController().GoBack();
1629  load_stop_observer.Wait();
1630
1631  EXPECT_EQ(ASCIIToUTF16("flowers"), omnibox()->GetText());
1632
1633  // Navigate back to NTP.
1634  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1635  EXPECT_TRUE(active_tab->GetController().CanGoBack());
1636  content::WindowedNotificationObserver load_stop_observer_2(
1637      content::NOTIFICATION_LOAD_STOP,
1638      content::Source<content::NavigationController>(
1639          &active_tab->GetController()));
1640  active_tab->GetController().GoBack();
1641  load_stop_observer_2.Wait();
1642
1643  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1644  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
1645}
1646
1647// Flaky on Windows and Mac try bots.
1648#if defined(OS_CHROMEOS)
1649#define MAYBE_DispatchMVChangeEventWhileNavigatingBackToNTP DispatchMVChangeEventWhileNavigatingBackToNTP
1650#else
1651#define MAYBE_DispatchMVChangeEventWhileNavigatingBackToNTP DISABLED_DispatchMVChangeEventWhileNavigatingBackToNTP
1652#endif
1653IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1654                       MAYBE_DispatchMVChangeEventWhileNavigatingBackToNTP) {
1655  // Setup Instant.
1656  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1657  FocusOmniboxAndWaitForInstantNTPSupport();
1658
1659  // Open new tab. Preloaded NTP contents should have been used.
1660  ui_test_utils::NavigateToURLWithDisposition(
1661      browser(),
1662      GURL(chrome::kChromeUINewTabURL),
1663      NEW_FOREGROUND_TAB,
1664      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1665
1666  content::WebContents* active_tab =
1667      browser()->tab_strip_model()->GetActiveWebContents();
1668  EXPECT_TRUE(UpdateSearchState(active_tab));
1669  EXPECT_EQ(1, on_most_visited_change_calls_);
1670
1671  content::WindowedNotificationObserver observer(
1672      content::NOTIFICATION_LOAD_STOP,
1673      content::NotificationService::AllSources());
1674  // Set the text and press enter to navigate from NTP.
1675  SetOmniboxText("Pen");
1676  PressEnterAndWaitForNavigation();
1677  EXPECT_EQ(ASCIIToUTF16("Pen"), omnibox()->GetText());
1678  observer.Wait();
1679
1680  // Navigate back to NTP.
1681  content::WindowedNotificationObserver back_observer(
1682      content::NOTIFICATION_LOAD_STOP,
1683      content::NotificationService::AllSources());
1684  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1685  EXPECT_TRUE(active_tab->GetController().CanGoBack());
1686  active_tab->GetController().GoBack();
1687  back_observer.Wait();
1688
1689  // Verify that onmostvisitedchange event is dispatched when we navigate from
1690  // SRP to NTP.
1691  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
1692  EXPECT_TRUE(UpdateSearchState(active_tab));
1693  EXPECT_EQ(1, on_most_visited_change_calls_);
1694}
1695
1696IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OnDefaultSearchProviderChanged) {
1697  InstantService* instant_service =
1698      InstantServiceFactory::GetForProfile(browser()->profile());
1699  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
1700
1701  // Setup Instant.
1702  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1703  FocusOmniboxAndWaitForInstantNTPSupport();
1704  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
1705
1706  // Navigating to the NTP should use the Instant render process.
1707  content::WindowedNotificationObserver new_tab_observer(
1708      content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1709      content::NotificationService::AllSources());
1710  ui_test_utils::NavigateToURLWithDisposition(
1711      browser(),
1712      GURL(chrome::kChromeUINewTabURL),
1713      CURRENT_TAB,
1714      ui_test_utils::BROWSER_TEST_NONE);
1715  new_tab_observer.Wait();
1716
1717  content::WebContents* ntp_contents =
1718      browser()->tab_strip_model()->GetActiveWebContents();
1719  EXPECT_TRUE(chrome::IsInstantNTP(ntp_contents));
1720  EXPECT_TRUE(instant_service->IsInstantProcess(
1721      ntp_contents->GetRenderProcessHost()->GetID()));
1722  GURL ntp_url = ntp_contents->GetURL();
1723
1724  AddBlankTabAndShow(browser());
1725  content::WebContents* active_tab =
1726      browser()->tab_strip_model()->GetActiveWebContents();
1727  EXPECT_FALSE(chrome::IsInstantNTP(active_tab));
1728  EXPECT_FALSE(instant_service->IsInstantProcess(
1729      active_tab->GetRenderProcessHost()->GetID()));
1730
1731  TemplateURLData data;
1732  data.short_name = ASCIIToUTF16("t");
1733  data.SetURL("http://defaultturl/q={searchTerms}");
1734  data.suggestions_url = "http://defaultturl2/q={searchTerms}";
1735  data.instant_url = "http://does/not/exist";
1736  data.alternate_urls.push_back(data.instant_url + "#q={searchTerms}");
1737  data.search_terms_replacement_key = "strk";
1738
1739  TemplateURL* template_url = new TemplateURL(browser()->profile(), data);
1740  TemplateURLService* service =
1741      TemplateURLServiceFactory::GetForProfile(browser()->profile());
1742  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1743  service->Add(template_url);  // Takes ownership of |template_url|.
1744
1745  // Change the default search provider.
1746  content::WindowedNotificationObserver observer(
1747      content::NOTIFICATION_LOAD_STOP,
1748      content::Source<content::NavigationController>(
1749          &ntp_contents->GetController()));
1750  service->SetDefaultSearchProvider(template_url);
1751  observer.Wait();
1752
1753  // |ntp_contents| should not use the Instant render process.
1754  EXPECT_FALSE(chrome::IsInstantNTP(ntp_contents));
1755  EXPECT_FALSE(instant_service->IsInstantProcess(
1756      ntp_contents->GetRenderProcessHost()->GetID()));
1757  // Make sure the URL remains the same.
1758  EXPECT_EQ(ntp_url, ntp_contents->GetURL());
1759}
1760
1761IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1762                       ReloadLocalNTPOnSearchProviderChange) {
1763  // Setup Instant.
1764  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1765  FocusOmniboxAndWaitForInstantNTPSupport();
1766
1767  // Navigate to Local NTP.
1768  content::WindowedNotificationObserver new_tab_observer(
1769      content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1770      content::NotificationService::AllSources());
1771  ui_test_utils::NavigateToURLWithDisposition(
1772      browser(),
1773      GURL(chrome::kChromeSearchLocalNtpUrl),
1774      CURRENT_TAB,
1775      ui_test_utils::BROWSER_TEST_NONE);
1776  new_tab_observer.Wait();
1777
1778  content::WebContents* ntp_contents =
1779      browser()->tab_strip_model()->GetActiveWebContents();
1780  GURL ntp_url = ntp_contents->GetURL();
1781
1782  TemplateURLData data;
1783  data.short_name = ASCIIToUTF16("t");
1784  data.SetURL("http://defaultturl/q={searchTerms}");
1785  data.suggestions_url = "http://defaultturl2/q={searchTerms}";
1786  data.instant_url = "http://does/not/exist";
1787  data.alternate_urls.push_back(data.instant_url + "#q={searchTerms}");
1788  data.search_terms_replacement_key = "strk";
1789
1790  TemplateURL* template_url = new TemplateURL(browser()->profile(), data);
1791  TemplateURLService* service =
1792      TemplateURLServiceFactory::GetForProfile(browser()->profile());
1793  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1794  service->Add(template_url);  // Takes ownership of |template_url|.
1795
1796  // Change the default search provider. This will reload the local NTP and the
1797  // page URL will remain the same.
1798  content::WindowedNotificationObserver observer(
1799      content::NOTIFICATION_LOAD_STOP,
1800      content::Source<content::NavigationController>(
1801          &ntp_contents->GetController()));
1802  service->SetDefaultSearchProvider(template_url);
1803  observer.Wait();
1804
1805  // Make sure the URL remains the same.
1806  EXPECT_EQ(ntp_url, ntp_contents->GetURL());
1807}
1808