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