instant_extended_interactive_uitest.cc revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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/field_trial.h"
9#include "base/metrics/histogram_base.h"
10#include "base/metrics/histogram_samples.h"
11#include "base/metrics/statistics_recorder.h"
12#include "base/prefs/pref_service.h"
13#include "base/string_util.h"
14#include "base/stringprintf.h"
15#include "base/strings/string_number_conversions.h"
16#include "base/time.h"
17#include "base/utf_string_conversions.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/extensions/extension_browsertest.h"
26#include "chrome/browser/extensions/extension_service.h"
27#include "chrome/browser/favicon/favicon_tab_helper.h"
28#include "chrome/browser/history/history_db_task.h"
29#include "chrome/browser/history/history_service.h"
30#include "chrome/browser/history/history_service_factory.h"
31#include "chrome/browser/history/history_types.h"
32#include "chrome/browser/history/top_sites.h"
33#include "chrome/browser/profiles/profile.h"
34#include "chrome/browser/search/instant_service.h"
35#include "chrome/browser/search/instant_service_factory.h"
36#include "chrome/browser/search/search.h"
37#include "chrome/browser/search_engines/template_url_service.h"
38#include "chrome/browser/search_engines/template_url_service_factory.h"
39#include "chrome/browser/themes/theme_service.h"
40#include "chrome/browser/themes/theme_service_factory.h"
41#include "chrome/browser/ui/browser_list.h"
42#include "chrome/browser/ui/browser_tabstrip.h"
43#include "chrome/browser/ui/omnibox/omnibox_view.h"
44#include "chrome/browser/ui/search/instant_commit_type.h"
45#include "chrome/browser/ui/search/instant_ntp.h"
46#include "chrome/browser/ui/search/instant_overlay.h"
47#include "chrome/browser/ui/search/instant_tab.h"
48#include "chrome/browser/ui/search/instant_test_utils.h"
49#include "chrome/browser/ui/search/search_tab_helper.h"
50#include "chrome/browser/ui/tabs/tab_strip_model.h"
51#include "chrome/browser/ui/webui/theme_source.h"
52#include "chrome/common/chrome_notification_types.h"
53#include "chrome/common/chrome_switches.h"
54#include "chrome/common/instant_types.h"
55#include "chrome/common/pref_names.h"
56#include "chrome/common/thumbnail_score.h"
57#include "chrome/common/url_constants.h"
58#include "chrome/test/base/in_process_browser_test.h"
59#include "chrome/test/base/interactive_test_utils.h"
60#include "chrome/test/base/ui_test_utils.h"
61#include "components/sessions/serialized_navigation_entry.h"
62#include "content/public/browser/navigation_controller.h"
63#include "content/public/browser/navigation_entry.h"
64#include "content/public/browser/notification_service.h"
65#include "content/public/browser/render_process_host.h"
66#include "content/public/browser/render_view_host.h"
67#include "content/public/browser/site_instance.h"
68#include "content/public/browser/url_data_source.h"
69#include "content/public/browser/web_contents.h"
70#include "content/public/browser/web_contents_view.h"
71#include "content/public/common/bindings_policy.h"
72#include "content/public/common/renderer_preferences.h"
73#include "content/public/test/browser_test_utils.h"
74#include "content/public/test/test_utils.h"
75#include "third_party/skia/include/core/SkBitmap.h"
76
77namespace {
78
79// Creates a bitmap of the specified color. Caller takes ownership.
80gfx::Image CreateBitmap(SkColor color) {
81  SkBitmap thumbnail;
82  thumbnail.setConfig(SkBitmap::kARGB_8888_Config, 4, 4);
83  thumbnail.allocPixels();
84  thumbnail.eraseColor(color);
85  return gfx::Image::CreateFrom1xBitmap(thumbnail);  // adds ref.
86}
87
88// Task used to make sure history has finished processing a request. Intended
89// for use with BlockUntilHistoryProcessesPendingRequests.
90class QuittingHistoryDBTask : public history::HistoryDBTask {
91 public:
92  QuittingHistoryDBTask() {}
93
94  virtual bool RunOnDBThread(history::HistoryBackend* backend,
95                             history::HistoryDatabase* db) OVERRIDE {
96    return true;
97  }
98
99  virtual void DoneRunOnMainThread() OVERRIDE {
100    base::MessageLoop::current()->Quit();
101  }
102
103 private:
104  virtual ~QuittingHistoryDBTask() {}
105
106  DISALLOW_COPY_AND_ASSIGN(QuittingHistoryDBTask);
107};
108
109}  // namespace
110
111class InstantExtendedTest : public InProcessBrowserTest,
112                            public InstantTestBase {
113 public:
114  InstantExtendedTest()
115      : on_most_visited_change_calls_(0),
116        most_visited_items_count_(0),
117        first_most_visited_item_id_(0),
118        on_native_suggestions_calls_(0),
119        on_change_calls_(0),
120        submit_count_(0),
121        on_esc_key_press_event_calls_(0) {
122  }
123 protected:
124  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
125    chrome::EnableInstantExtendedAPIForTesting();
126    ASSERT_TRUE(https_test_server().Start());
127    GURL instant_url = https_test_server().GetURL(
128        "files/instant_extended.html?strk=1&");
129    InstantTestBase::Init(instant_url);
130  }
131
132  virtual void SetUpOnMainThread() OVERRIDE {
133    browser()->toolbar_model()->SetSupportsExtractionOfURLLikeSearchTerms(true);
134  }
135
136  int64 GetHistogramCount(const char* name) {
137    base::HistogramBase* histogram =
138        base::StatisticsRecorder::FindHistogram(name);
139    if (!histogram) {
140      // If no histogram is found, it's possible that no values have been
141      // recorded yet. Assume that the value is zero.
142      return 0;
143    }
144    return histogram->SnapshotSamples()->TotalCount();
145  }
146
147  std::string GetOmniboxText() {
148    return UTF16ToUTF8(omnibox()->GetText());
149  }
150
151  void SendDownArrow() {
152    omnibox()->model()->OnUpOrDownKeyPressed(1);
153    // Wait for JavaScript to run the key handler by executing a blank script.
154    EXPECT_TRUE(ExecuteScript(std::string()));
155  }
156
157  void SendUpArrow() {
158    omnibox()->model()->OnUpOrDownKeyPressed(-1);
159    // Wait for JavaScript to run the key handler by executing a blank script.
160    EXPECT_TRUE(ExecuteScript(std::string()));
161  }
162
163  void SendEscape() {
164    omnibox()->model()->OnEscapeKeyPressed();
165    // Wait for JavaScript to run the key handler by executing a blank script.
166    EXPECT_TRUE(ExecuteScript(std::string()));
167  }
168
169  bool UpdateSearchState(content::WebContents* contents) WARN_UNUSED_RESULT {
170    return GetIntFromJS(contents, "onMostVisitedChangedCalls",
171                        &on_most_visited_change_calls_) &&
172           GetIntFromJS(contents, "mostVisitedItemsCount",
173                        &most_visited_items_count_) &&
174           GetIntFromJS(contents, "firstMostVisitedItemId",
175                        &first_most_visited_item_id_) &&
176           GetIntFromJS(contents, "onNativeSuggestionsCalls",
177                        &on_native_suggestions_calls_) &&
178           GetIntFromJS(contents, "onChangeCalls",
179                        &on_change_calls_) &&
180           GetIntFromJS(contents, "submitCount",
181                        &submit_count_) &&
182           GetStringFromJS(contents, "apiHandle.value",
183                           &query_value_) &&
184           GetIntFromJS(contents, "onEscKeyPressedCalls",
185                        &on_esc_key_press_event_calls_);
186  }
187
188  TemplateURL* GetDefaultSearchProviderTemplateURL() {
189    TemplateURLService* template_url_service =
190        TemplateURLServiceFactory::GetForProfile(browser()->profile());
191    if (template_url_service)
192      return template_url_service->GetDefaultSearchProvider();
193    return NULL;
194  }
195
196  bool AddSearchToHistory(string16 term, int visit_count) {
197    TemplateURL* template_url = GetDefaultSearchProviderTemplateURL();
198    if (!template_url)
199      return false;
200
201    HistoryService* history = HistoryServiceFactory::GetForProfile(
202        browser()->profile(), Profile::EXPLICIT_ACCESS);
203    GURL search(template_url->url_ref().ReplaceSearchTerms(
204        TemplateURLRef::SearchTermsArgs(term)));
205    history->AddPageWithDetails(
206        search, string16(), visit_count, visit_count,
207        base::Time::Now(), false, history::SOURCE_BROWSED);
208    history->SetKeywordSearchTermsForURL(
209        search, template_url->id(), term);
210    return true;
211  }
212
213  void BlockUntilHistoryProcessesPendingRequests() {
214    HistoryService* history = HistoryServiceFactory::GetForProfile(
215        browser()->profile(), Profile::EXPLICIT_ACCESS);
216    DCHECK(history);
217    DCHECK(base::MessageLoop::current());
218
219    CancelableRequestConsumer consumer;
220    history->ScheduleDBTask(new QuittingHistoryDBTask(), &consumer);
221    base::MessageLoop::current()->Run();
222  }
223
224  int CountSearchProviderSuggestions() {
225    return omnibox()->model()->autocomplete_controller()->search_provider()->
226        matches().size();
227  }
228
229  int on_most_visited_change_calls_;
230  int most_visited_items_count_;
231  int first_most_visited_item_id_;
232  int on_native_suggestions_calls_;
233  int on_change_calls_;
234  int submit_count_;
235  int on_esc_key_press_event_calls_;
236  std::string query_value_;
237};
238
239// Test class used to verify chrome-search: scheme and access policy from the
240// Instant overlay.  This is a subclass of |ExtensionBrowserTest| because it
241// loads a theme that provides a background image.
242class InstantPolicyTest : public ExtensionBrowserTest, public InstantTestBase {
243 public:
244  InstantPolicyTest() {}
245
246 protected:
247  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
248    chrome::EnableInstantExtendedAPIForTesting();
249    ASSERT_TRUE(https_test_server().Start());
250    GURL instant_url = https_test_server().GetURL(
251        "files/instant_extended.html?strk=1&");
252    InstantTestBase::Init(instant_url);
253  }
254
255  void InstallThemeSource() {
256    ThemeSource* theme = new ThemeSource(profile());
257    content::URLDataSource::Add(profile(), theme);
258  }
259
260  void InstallThemeAndVerify(const std::string& theme_dir,
261                             const std::string& theme_name) {
262    const base::FilePath theme_path = test_data_dir_.AppendASCII(theme_dir);
263    ASSERT_TRUE(InstallExtensionWithUIAutoConfirm(
264        theme_path, 1, ExtensionBrowserTest::browser()));
265    const extensions::Extension* theme =
266        ThemeServiceFactory::GetThemeForProfile(
267            ExtensionBrowserTest::browser()->profile());
268    ASSERT_NE(static_cast<extensions::Extension*>(NULL), theme);
269    ASSERT_EQ(theme->name(), theme_name);
270  }
271
272 private:
273  DISALLOW_COPY_AND_ASSIGN(InstantPolicyTest);
274};
275
276IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ExtendedModeIsOn) {
277  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
278  EXPECT_TRUE(instant()->extended_enabled_);
279}
280
281// Test that Instant is preloaded when the omnibox is focused.
282IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxFocusLoadsInstant) {
283  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
284
285  // Explicitly unfocus the omnibox.
286  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
287  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
288
289  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
290  EXPECT_FALSE(omnibox()->model()->has_focus());
291
292  // Delete any existing overlay.
293  instant()->overlay_.reset();
294  EXPECT_FALSE(instant()->GetOverlayContents());
295
296  // Refocus the omnibox. The InstantController should've preloaded Instant.
297  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
298
299  EXPECT_FALSE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
300  EXPECT_TRUE(omnibox()->model()->has_focus());
301
302  content::WebContents* overlay = instant()->GetOverlayContents();
303  EXPECT_TRUE(overlay);
304
305  // Check that the page supports Instant, but it isn't showing.
306  EXPECT_TRUE(instant()->overlay_->supports_instant());
307  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
308  EXPECT_TRUE(instant()->model()->mode().is_default());
309
310  // Adding a new tab shouldn't delete or recreate the overlay; otherwise,
311  // what's the point of preloading?
312  AddBlankTabAndShow(browser());
313  EXPECT_EQ(overlay, instant()->GetOverlayContents());
314
315  // Unfocusing and refocusing the omnibox should also preserve the overlay.
316  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
317  EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
318
319  FocusOmnibox();
320  EXPECT_FALSE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER));
321  EXPECT_EQ(overlay, instant()->GetOverlayContents());
322}
323
324IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputShowsOverlay) {
325  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
326
327  // Focus omnibox and confirm overlay isn't shown.
328  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
329  content::WebContents* overlay = instant()->GetOverlayContents();
330  EXPECT_TRUE(overlay);
331  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
332  EXPECT_TRUE(instant()->model()->mode().is_default());
333
334  // Typing in the omnibox should show the overlay.
335  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
336  EXPECT_TRUE(instant()->model()->mode().is_search_suggestions());
337  EXPECT_EQ(overlay, instant()->GetOverlayContents());
338}
339
340// Flaky on Linux Tests bot.
341#if defined(OS_LINUX)
342#define MAYBE_UsesOverlayIfTabNotReady DISABLED_UsesOverlayIfTabNotReady
343#else
344#define MAYBE_UsesOverlayIfTabNotReady UsesOverlayIfTabNotReady
345#endif
346
347IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_UsesOverlayIfTabNotReady) {
348  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
349  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
350
351  // Open a new tab and start typing before InstantTab is properly hooked up.
352  // Should use the overlay.
353  ui_test_utils::NavigateToURLWithDisposition(
354      browser(),
355      GURL(chrome::kChromeUINewTabURL),
356      NEW_FOREGROUND_TAB,
357      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
358  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
359
360  // But Instant tab should still exist.
361  ASSERT_NE(static_cast<InstantTab*>(NULL), instant()->instant_tab());
362  EXPECT_FALSE(instant()->UseTabForSuggestions());
363
364  // Wait for Instant Tab support if it still hasn't finished loading.
365  if (!instant()->instant_tab()->supports_instant()) {
366    content::WindowedNotificationObserver instant_tab_observer(
367        chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
368        content::NotificationService::AllSources());
369    instant_tab_observer.Wait();
370  }
371
372  // Hide the overlay. Now, we should be using Instant tab for suggestions.
373  instant()->HideOverlay();
374  EXPECT_TRUE(instant()->UseTabForSuggestions());
375}
376
377// Flaky on Mac Tests bot. crbug.com/242415
378#if defined(OS_MACOSX)
379#define MAYBE_MiddleClickOnSuggestionOpensInNewTab DISABLED_MiddleClickOnSuggestionOpensInNewTab
380#else
381#define MAYBE_MiddleClickOnSuggestionOpensInNewTab MiddleClickOnSuggestionOpensInNewTab
382#endif
383
384// Test that middle clicking on a suggestion opens the result in a new tab.
385IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
386                       MAYBE_MiddleClickOnSuggestionOpensInNewTab) {
387  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
388  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
389  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
390
391  EXPECT_EQ(1, browser()->tab_strip_model()->count());
392
393  // Typing in the omnibox should show the overlay.
394  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://www.example.com/"));
395
396  // Create an event listener that opens the top suggestion in a new tab.
397  EXPECT_TRUE(ExecuteScript(
398      "var rid = getApiHandle().nativeSuggestions[0].rid;"
399      "document.body.addEventListener('click', function() {"
400        "chrome.embeddedSearch.navigateContentWindow(rid, 2);"
401      "});"
402      ));
403
404  content::WindowedNotificationObserver observer(
405        chrome::NOTIFICATION_TAB_ADDED,
406        content::NotificationService::AllSources());
407
408  // Click to trigger the event listener.
409  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
410
411  // Wait for the new tab to be added.
412  observer.Wait();
413
414  // Check that the new tab URL is as expected.
415  content::WebContents* new_tab_contents =
416      browser()->tab_strip_model()->GetWebContentsAt(1);
417  EXPECT_EQ("http://www.example.com/", new_tab_contents->GetURL().spec());
418
419  // Check that there are now two tabs.
420  EXPECT_EQ(2, browser()->tab_strip_model()->count());
421}
422
423IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
424                       UnfocusingOmniboxDoesNotChangeSuggestions) {
425  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
426  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
427  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
428
429  // Get a committed tab to work with.
430  content::WebContents* instant_tab = instant()->GetOverlayContents();
431  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("committed"));
432  browser()->window()->GetLocationBar()->AcceptInput();
433
434  // Put focus back into the omnibox, type, and wait for some gray text.
435  EXPECT_TRUE(content::ExecuteScript(instant_tab,
436                                     "suggestion = 'santa claus';"));
437  SetOmniboxTextAndWaitForSuggestion("santa ");
438  EXPECT_EQ(ASCIIToUTF16("claus"), GetGrayText());
439  EXPECT_TRUE(content::ExecuteScript(instant_tab,
440      "onChangeCalls = onNativeSuggestionsCalls = 0;"));
441
442  // Now unfocus the omnibox.
443  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
444  EXPECT_TRUE(UpdateSearchState(instant_tab));
445  EXPECT_EQ(0, on_change_calls_);
446  EXPECT_EQ(0, on_native_suggestions_calls_);
447}
448
449// Test that omnibox text is correctly set when overlay is committed with Enter.
450IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxTextUponEnterCommit) {
451  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
452  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
453
454  // The page will autocomplete once we set the omnibox value.
455  EXPECT_TRUE(ExecuteScript("suggestion = 'santa claus';"));
456
457  // Set the text, and wait for suggestions to show up.
458  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("santa"));
459  EXPECT_EQ(ASCIIToUTF16("santa"), omnibox()->GetText());
460
461  // Test that the current suggestion is correctly set.
462  EXPECT_EQ(ASCIIToUTF16(" claus"), GetGrayText());
463
464  // Commit the search by pressing Enter.
465  browser()->window()->GetLocationBar()->AcceptInput();
466
467  // 'Enter' commits the query as it was typed.
468  EXPECT_EQ(ASCIIToUTF16("santa"), omnibox()->GetText());
469
470  // Suggestion should be cleared at this point.
471  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
472}
473
474// Test that omnibox text is correctly set when committed with focus lost.
475IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxTextUponFocusLostCommit) {
476  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
477  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
478
479  // Set autocomplete text (grey text).
480  EXPECT_TRUE(ExecuteScript("suggestion = 'johnny depp';"));
481
482  // Set the text, and wait for suggestions to show up.
483  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("johnny"));
484  EXPECT_EQ(ASCIIToUTF16("johnny"), omnibox()->GetText());
485
486  // Test that the current suggestion is correctly set.
487  EXPECT_EQ(ASCIIToUTF16(" depp"), GetGrayText());
488
489  // Commit the overlay by lost focus (e.g. clicking on the page).
490  instant()->CommitIfPossible(INSTANT_COMMIT_FOCUS_LOST);
491
492  // Omnibox text and suggestion should not be changed.
493  EXPECT_EQ(ASCIIToUTF16("johnny"), omnibox()->GetText());
494  EXPECT_EQ(ASCIIToUTF16(" depp"), GetGrayText());
495}
496
497// Test that omnibox text is correctly set when clicking on committed SERP.
498// Disabled on Mac because omnibox focus loss is not working correctly.
499IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
500                       OmniboxTextUponFocusedCommittedSERP) {
501  // Setup Instant.
502  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
503  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
504
505  // Create an observer to wait for the instant tab to support Instant.
506  content::WindowedNotificationObserver observer(
507      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
508      content::NotificationService::AllSources());
509
510  // Do a search and commit it.
511  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello k"));
512  EXPECT_EQ(ASCIIToUTF16("hello k"), omnibox()->GetText());
513  browser()->window()->GetLocationBar()->AcceptInput();
514  observer.Wait();
515
516  // With a committed results page, do a search by unfocusing the omnibox and
517  // focusing the contents.
518  SetOmniboxText("hello");
519  // Calling handleOnChange manually to make sure it is called before the
520  // Focus() call below.
521  EXPECT_TRUE(content::ExecuteScript(instant()->instant_tab()->contents(),
522                                     "suggestion = 'hello kitty';"
523                                     "handleOnChange();"));
524  instant()->instant_tab()->contents()->GetView()->Focus();
525
526  // Omnibox text and suggestion should not be changed.
527  EXPECT_EQ(ASCIIToUTF16("hello"), omnibox()->GetText());
528  EXPECT_EQ(ASCIIToUTF16(" kitty"), GetGrayText());
529}
530
531// Checks that a previous Navigation suggestion is not re-used when a search
532// suggestion comes in.
533IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
534                       NavigationSuggestionIsDiscardedUponSearchSuggestion) {
535  // Setup Instant.
536  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
537  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
538
539  // Tell the page to send a URL suggestion.
540  EXPECT_TRUE(ExecuteScript("suggestion = 'http://www.example.com';"
541                            "behavior = 1;"));
542  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("exa"));
543  EXPECT_EQ(ASCIIToUTF16("example.com"), omnibox()->GetText());
544
545  // Now send a search suggestion and see that Navigation suggestion is no
546  // longer kept.
547  EXPECT_TRUE(ExecuteScript("suggestion = 'exams are great';"
548                            "behavior = 2;"));
549  SetOmniboxText("exam");
550  // Wait for JavaScript to run handleOnChange by executing a blank script.
551  EXPECT_TRUE(ExecuteScript(std::string()));
552
553  instant()->overlay()->contents()->GetView()->Focus();
554  EXPECT_EQ(ASCIIToUTF16("exam"), omnibox()->GetText());
555  EXPECT_EQ(ASCIIToUTF16("s are great"), GetGrayText());
556
557  // TODO(jered): Remove this after fixing OnBlur().
558  omnibox()->RevertAll();
559}
560
561// This test simulates a search provider using the InstantExtended API to
562// navigate through the suggested results and back to the original user query.
563IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NavigateSuggestionsWithArrowKeys) {
564  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
565  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
566
567  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello"));
568  EXPECT_EQ("hello", GetOmniboxText());
569
570  SendDownArrow();
571  EXPECT_EQ("result 1", GetOmniboxText());
572  SendDownArrow();
573  EXPECT_EQ("result 2", GetOmniboxText());
574  SendUpArrow();
575  EXPECT_EQ("result 1", GetOmniboxText());
576  SendUpArrow();
577  EXPECT_EQ("hello", GetOmniboxText());
578
579  // Ensure that the API's value is set correctly.
580  std::string result;
581  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
582                              "window.chrome.searchBox.value",
583                              &result));
584  EXPECT_EQ("hello", result);
585
586  EXPECT_TRUE(HasUserInputInProgress());
587  // TODO(beaudoin): Figure out why this fails.
588  // EXPECT_FALSE(HasTemporaryText());
589
590  // Commit the search by pressing Enter.
591  browser()->window()->GetLocationBar()->AcceptInput();
592  EXPECT_EQ("hello", GetOmniboxText());
593}
594
595// Flaky on Linux Tests bot.  See http://crbug.com/233090.
596#if defined(OS_LINUX)
597#define MAYBE_NavigateToURLSuggestionHitEnterAndLookForSubmit DISABLED_NavigateToURLSuggestionHitEnterAndLookForSubmit
598#else
599#define MAYBE_NavigateToURLSuggestionHitEnterAndLookForSubmit NavigateToURLSuggestionHitEnterAndLookForSubmit
600#endif
601
602// This test simulates a search provider using the InstantExtended API to
603// navigate through the suggested results and back to the original user query.
604// If this test starts to flake, it may be that the second call to AcceptInput
605// below causes instant()->instant_tab() to no longer be valid due to e.g. a
606// navigation. In that case, see https://codereview.chromium.org/12895007/#msg28
607// and onwards for possible alternatives.
608IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
609                       MAYBE_NavigateToURLSuggestionHitEnterAndLookForSubmit) {
610  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
611  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
612
613  // Create an observer to wait for the instant tab to support Instant.
614  content::WindowedNotificationObserver observer(
615      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
616      content::NotificationService::AllSources());
617
618  // Do a search and commit it.
619  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello k"));
620  EXPECT_EQ(ASCIIToUTF16("hello k"), omnibox()->GetText());
621  browser()->window()->GetLocationBar()->AcceptInput();
622  observer.Wait();
623
624  SetOmniboxText("http");
625  EXPECT_EQ("http", GetOmniboxText());
626
627  SendDownArrow();
628  EXPECT_EQ("result 1", GetOmniboxText());
629  SendDownArrow();
630  EXPECT_EQ("result 2", GetOmniboxText());
631
632  // Set the next suggestion to be of type INSTANT_SUGGESTION_URL.
633  EXPECT_TRUE(content::ExecuteScript(instant()->instant_tab()->contents(),
634                                     "suggestionType = 1;"));
635  SendDownArrow();
636  EXPECT_EQ("http://www.google.com", GetOmniboxText());
637
638  EXPECT_TRUE(HasUserInputInProgress());
639
640  EXPECT_TRUE(UpdateSearchState(instant()->instant_tab()->contents()));
641  // Note the commit count is initially 1 due to the AcceptInput() call above.
642  EXPECT_EQ(1, submit_count_);
643
644  std::string old_query_value(query_value_);
645
646  // Commit the search by pressing Enter.
647  browser()->window()->GetLocationBar()->AcceptInput();
648
649  // Make sure a submit message got sent.
650  EXPECT_TRUE(UpdateSearchState(instant()->instant_tab()->contents()));
651  EXPECT_EQ(2, submit_count_);
652  EXPECT_EQ(old_query_value, query_value_);
653}
654
655// This test simulates a search provider using the InstantExtended API to
656// navigate through the suggested results and hitting escape to get back to the
657// original user query.
658IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NavigateSuggestionsAndHitEscape) {
659  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
660  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
661
662  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello"));
663  EXPECT_EQ("hello", GetOmniboxText());
664
665  SendDownArrow();
666  EXPECT_EQ("result 1", GetOmniboxText());
667  SendDownArrow();
668  EXPECT_EQ("result 2", GetOmniboxText());
669  SendEscape();
670  EXPECT_EQ("hello", GetOmniboxText());
671
672  // Ensure that the API's value is set correctly.
673  std::string result;
674  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
675                              "window.chrome.searchBox.value",
676                              &result));
677  EXPECT_EQ("hello", result);
678
679  EXPECT_TRUE(HasUserInputInProgress());
680  EXPECT_FALSE(HasTemporaryText());
681
682  // Commit the search by pressing Enter.
683  browser()->window()->GetLocationBar()->AcceptInput();
684  EXPECT_EQ("hello", GetOmniboxText());
685}
686
687IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PressEscapeWithBlueText) {
688  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
689  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
690
691  // Set blue text completion.
692  EXPECT_TRUE(ExecuteScript("suggestion = 'chimichanga.com';"
693                            "behavior = 1;"));
694
695  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("chimi"));
696
697  EXPECT_EQ(ASCIIToUTF16("chimichanga.com"), omnibox()->GetText());
698  EXPECT_EQ(ASCIIToUTF16("changa.com"), GetBlueText());
699  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
700
701  EXPECT_TRUE(ExecuteScript("onChangeCalls = onNativeSuggestionsCalls = 0;"));
702
703  SendDownArrow();
704
705  EXPECT_EQ(ASCIIToUTF16("result 1"), omnibox()->GetText());
706  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
707  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
708
709  content::WindowedNotificationObserver observer(
710      chrome::NOTIFICATION_INSTANT_SET_SUGGESTION,
711      content::NotificationService::AllSources());
712  SendEscape();
713  observer.Wait();
714
715  EXPECT_EQ(ASCIIToUTF16("chimichanga.com"), omnibox()->GetText());
716  EXPECT_EQ(ASCIIToUTF16("changa.com"), GetBlueText());
717  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
718
719  EXPECT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
720  EXPECT_EQ(0, on_native_suggestions_calls_);
721  EXPECT_EQ(0, on_change_calls_);
722}
723
724IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PressEscapeWithGrayText) {
725  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
726  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
727
728  // Set gray text completion.
729  EXPECT_TRUE(ExecuteScript("suggestion = 'cowabunga';"
730                            "behavior = 2;"));
731
732  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("cowa"));
733
734  EXPECT_EQ(ASCIIToUTF16("cowa"), omnibox()->GetText());
735  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
736  EXPECT_EQ(ASCIIToUTF16("bunga"), GetGrayText());
737
738  EXPECT_TRUE(ExecuteScript("onChangeCalls = onNativeSuggestionsCalls = 0;"));
739
740  SendDownArrow();
741
742  EXPECT_EQ(ASCIIToUTF16("result 1"), omnibox()->GetText());
743  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
744  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
745
746  content::WindowedNotificationObserver observer(
747      chrome::NOTIFICATION_INSTANT_SET_SUGGESTION,
748      content::NotificationService::AllSources());
749  SendEscape();
750  observer.Wait();
751
752  EXPECT_EQ(ASCIIToUTF16("cowa"), omnibox()->GetText());
753  EXPECT_EQ(ASCIIToUTF16(""), GetBlueText());
754  EXPECT_EQ(ASCIIToUTF16("bunga"), GetGrayText());
755
756  EXPECT_TRUE(UpdateSearchState(instant()->GetOverlayContents()));
757  EXPECT_EQ(0, on_native_suggestions_calls_);
758  EXPECT_EQ(0, on_change_calls_);
759}
760
761IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NTPIsPreloaded) {
762  // Setup Instant.
763  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
764  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
765
766  // NTP contents should be preloaded.
767  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
768  content::WebContents* ntp_contents = instant()->ntp_->contents();
769  EXPECT_TRUE(ntp_contents);
770}
771
772// Test that the local NTP is preloaded.
773IN_PROC_BROWSER_TEST_F(InstantExtendedTest, LocalOnlyNTPIsPreloaded) {
774  // Setup Instant.
775  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
776
777  // The second argument says to use only the local overlay and NTP.
778  instant()->SetInstantEnabled(false, true);
779  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
780
781  // NTP contents should be preloaded.
782  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
783  content::WebContents* ntp_contents = instant()->ntp_->contents();
784  EXPECT_NE(static_cast<content::WebContents*>(NULL), ntp_contents);
785  EXPECT_TRUE(instant()->ntp()->IsLocal());
786}
787
788// Test that the local NTP is not preloaded.
789IN_PROC_BROWSER_TEST_F(InstantExtendedTest, LocalOnlyNTPIsNotPreloaded) {
790  // Setup Instant.
791  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
792  ASSERT_TRUE(base::FieldTrialList::CreateTrialsFromString(
793      "InstantExtended/Group1 local_only:1 preload_local_only_ntp:0/"));
794
795  // The second argument says to use only the local overlay and NTP.
796  instant()->SetInstantEnabled(false, true);
797
798  // NTP contents should not be preloaded.
799  EXPECT_EQ(NULL, instant()->ntp());
800}
801
802IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPIsUsedInNewTab) {
803  // Setup Instant.
804  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
805  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
806
807  // NTP contents should be preloaded.
808  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
809  content::WebContents* ntp_contents = instant()->ntp_->contents();
810  EXPECT_TRUE(ntp_contents);
811
812  // Open new tab. Preloaded NTP contents should have been used.
813  ui_test_utils::NavigateToURLWithDisposition(
814      browser(),
815      GURL(chrome::kChromeUINewTabURL),
816      NEW_FOREGROUND_TAB,
817      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
818  content::WebContents* active_tab =
819      browser()->tab_strip_model()->GetActiveWebContents();
820  EXPECT_EQ(ntp_contents, active_tab);
821  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
822}
823
824IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPIsUsedInSameTab) {
825  // Setup Instant.
826  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
827  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
828
829  // NTP contents should be preloaded.
830  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
831  content::WebContents* ntp_contents = instant()->ntp_->contents();
832  EXPECT_TRUE(ntp_contents);
833
834  // Open new tab. Preloaded NTP contents should have been used.
835  ui_test_utils::NavigateToURLWithDisposition(
836      browser(),
837      GURL(chrome::kChromeUINewTabURL),
838      CURRENT_TAB,
839      ui_test_utils::BROWSER_TEST_NONE);
840  content::WebContents* active_tab =
841      browser()->tab_strip_model()->GetActiveWebContents();
842  EXPECT_EQ(ntp_contents, active_tab);
843  EXPECT_TRUE(chrome::IsInstantNTP(active_tab));
844}
845
846IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPForWrongProvider) {
847  // Setup Instant.
848  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
849  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
850
851  // NTP contents should be preloaded.
852  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
853  content::WebContents* ntp_contents = instant()->ntp_->contents();
854  EXPECT_TRUE(ntp_contents);
855  GURL ntp_url = ntp_contents->GetURL();
856
857  // Change providers.
858  SetInstantURL("chrome://blank");
859
860  // Open new tab. Preloaded NTP contents should have not been used.
861  ui_test_utils::NavigateToURLWithDisposition(
862      browser(),
863      GURL(chrome::kChromeUINewTabURL),
864      NEW_FOREGROUND_TAB,
865      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
866  content::WebContents* active_tab =
867      browser()->tab_strip_model()->GetActiveWebContents();
868  EXPECT_NE(ntp_url, active_tab->GetURL());
869}
870
871IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPRenderViewGone) {
872  // Setup Instant.
873  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
874  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
875
876  // NTP contents should be preloaded.
877  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
878  EXPECT_FALSE(instant()->ntp()->IsLocal());
879
880  // NTP not reloaded after being killed.
881  instant()->InstantPageRenderViewGone(instant()->ntp()->contents());
882  EXPECT_EQ(NULL, instant()->ntp());
883
884  // Open new tab. Should use local NTP.
885  ui_test_utils::NavigateToURLWithDisposition(
886      browser(),
887      GURL(chrome::kChromeUINewTabURL),
888      NEW_FOREGROUND_TAB,
889      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
890  content::WebContents* active_tab =
891      browser()->tab_strip_model()->GetActiveWebContents();
892  EXPECT_EQ(instant()->GetLocalInstantURL(), active_tab->GetURL().spec());
893}
894
895IN_PROC_BROWSER_TEST_F(InstantExtendedTest, PreloadedNTPDoesntSupportInstant) {
896  // Setup Instant.
897  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
898  InstantTestBase::Init(instant_url);
899  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
900  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
901
902  // NTP contents should have fallen back to the local page.
903  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
904  EXPECT_TRUE(instant()->ntp()->IsLocal());
905
906  // Open new tab. Should use local NTP.
907  ui_test_utils::NavigateToURLWithDisposition(
908      browser(),
909      GURL(chrome::kChromeUINewTabURL),
910      NEW_FOREGROUND_TAB,
911      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
912  content::WebContents* active_tab =
913      browser()->tab_strip_model()->GetActiveWebContents();
914  EXPECT_EQ(instant()->GetLocalInstantURL(), active_tab->GetURL().spec());
915}
916
917// Flaky, http://crbug.com/240852 .
918IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_OmniboxHasFocusOnNewTab) {
919  // Setup Instant.
920  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
921  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
922
923  // Explicitly unfocus the omnibox.
924  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
925  ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER);
926  EXPECT_FALSE(omnibox()->model()->has_focus());
927
928  // Open new tab. Preloaded NTP contents should have been used.
929  ui_test_utils::NavigateToURLWithDisposition(
930      browser(),
931      GURL(chrome::kChromeUINewTabURL),
932      NEW_FOREGROUND_TAB,
933      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
934
935  // Omnibox should have focus.
936  EXPECT_TRUE(omnibox()->model()->has_focus());
937}
938
939IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OmniboxEmptyOnNewTabPage) {
940  // Setup Instant.
941  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
942  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
943
944  // Open new tab. Preloaded NTP contents should have been used.
945  ui_test_utils::NavigateToURLWithDisposition(
946      browser(),
947      GURL(chrome::kChromeUINewTabURL),
948      NEW_FOREGROUND_TAB,
949      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
950
951  // Omnibox should be empty.
952  EXPECT_TRUE(omnibox()->GetText().empty());
953}
954
955IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoFaviconOnNewTabPage) {
956  // Setup Instant.
957  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
958  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
959
960  // Open new tab. Preloaded NTP contents should have been used.
961  ui_test_utils::NavigateToURLWithDisposition(
962      browser(),
963      GURL(chrome::kChromeUINewTabURL),
964      NEW_FOREGROUND_TAB,
965      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
966
967  // No favicon should be shown.
968  content::WebContents* active_tab =
969      browser()->tab_strip_model()->GetActiveWebContents();
970  FaviconTabHelper* favicon_tab_helper =
971      FaviconTabHelper::FromWebContents(active_tab);
972  EXPECT_FALSE(favicon_tab_helper->ShouldDisplayFavicon());
973
974  // Favicon should be shown off the NTP.
975  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
976  active_tab = browser()->tab_strip_model()->GetActiveWebContents();
977  favicon_tab_helper = FaviconTabHelper::FromWebContents(active_tab);
978  EXPECT_TRUE(favicon_tab_helper->ShouldDisplayFavicon());
979}
980
981IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputOnNTPDoesntShowOverlay) {
982  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
983
984  // Focus omnibox and confirm overlay isn't shown.
985  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
986  content::WebContents* overlay = instant()->GetOverlayContents();
987  EXPECT_TRUE(overlay);
988  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
989  EXPECT_TRUE(instant()->model()->mode().is_default());
990
991  // Navigate to the NTP. Should use preloaded contents.
992  ui_test_utils::NavigateToURLWithDisposition(
993      browser(),
994      GURL(chrome::kChromeUINewTabURL),
995      CURRENT_TAB,
996      ui_test_utils::BROWSER_TEST_NONE);
997
998  // Typing in the omnibox should not show the overlay.
999  SetOmniboxText("query");
1000  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
1001  EXPECT_TRUE(instant()->model()->mode().is_default());
1002}
1003
1004IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ProcessIsolation) {
1005  // Prior to setup, Instant has an overlay with a failed "google.com" load in
1006  // it, which is rendered in the dedicated Instant renderer process.
1007  //
1008  // TODO(sreeram): Fix this up when we stop doing crazy things on init.
1009  InstantService* instant_service =
1010        InstantServiceFactory::GetForProfile(browser()->profile());
1011  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
1012#if !defined(OS_MACOSX)
1013  // The failed "google.com" load is deleted, which sometimes leads to the
1014  // process shutting down on Mac.
1015  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
1016#endif
1017
1018  // Setup Instant.
1019  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1020  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1021
1022  // The registered Instant render process should still exist.
1023  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
1024
1025  // And the Instant overlay and ntp should live inside it.
1026  content::WebContents* overlay = instant()->GetOverlayContents();
1027  EXPECT_TRUE(instant_service->IsInstantProcess(
1028      overlay->GetRenderProcessHost()->GetID()));
1029  content::WebContents* ntp_contents = instant()->ntp_->contents();
1030  EXPECT_TRUE(instant_service->IsInstantProcess(
1031      ntp_contents->GetRenderProcessHost()->GetID()));
1032
1033  // Navigating to the NTP should use the Instant render process.
1034  ui_test_utils::NavigateToURLWithDisposition(
1035      browser(),
1036      GURL(chrome::kChromeUINewTabURL),
1037      CURRENT_TAB,
1038      ui_test_utils::BROWSER_TEST_NONE);
1039  content::WebContents* active_tab =
1040      browser()->tab_strip_model()->GetActiveWebContents();
1041  EXPECT_TRUE(instant_service->IsInstantProcess(
1042      active_tab->GetRenderProcessHost()->GetID()));
1043
1044  // Navigating elsewhere should not use the Instant render process.
1045  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1046  EXPECT_FALSE(instant_service->IsInstantProcess(
1047      active_tab->GetRenderProcessHost()->GetID()));
1048}
1049
1050// Test that a search query will not be displayed for navsuggest queries.
1051IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1052                       SearchQueryNotDisplayedForNavsuggest) {
1053  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1054
1055  // The second argument indicates to use only the local overlay and NTP.
1056  instant()->SetInstantEnabled(true, true);
1057
1058  // Focus omnibox and confirm overlay isn't shown.
1059  FocusOmniboxAndWaitForInstantOverlaySupport();
1060
1061  // Typing in the omnibox should show the overlay.
1062  SetOmniboxText("face");
1063
1064  content::WebContents* overlay = instant()->GetOverlayContents();
1065
1066  // Add a navsuggest suggestion.
1067  instant()->SetSuggestions(
1068      overlay,
1069      std::vector<InstantSuggestion>(
1070          1,
1071          InstantSuggestion(ASCIIToUTF16("http://facemash.com/"),
1072                            INSTANT_COMPLETE_NOW,
1073                            INSTANT_SUGGESTION_URL,
1074                            ASCIIToUTF16("face"),
1075                            kNoMatchIndex)));
1076
1077  while (!omnibox()->model()->autocomplete_controller()->done()) {
1078    content::WindowedNotificationObserver autocomplete_observer(
1079        chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,
1080        content::NotificationService::AllSources());
1081    autocomplete_observer.Wait();
1082  }
1083
1084  EXPECT_TRUE(ExecuteScript(
1085      "var sorted = chrome.embeddedSearch.searchBox.nativeSuggestions.sort("
1086          "function (a,b) {"
1087            "return b.rankingData.relevance - a.rankingData.relevance;"
1088          "});"));
1089
1090  int suggestions_count = -1;
1091  EXPECT_TRUE(GetIntFromJS(
1092      overlay, "sorted.length", &suggestions_count));
1093  ASSERT_GT(suggestions_count, 0);
1094
1095  std::string type;
1096  EXPECT_TRUE(
1097      GetStringFromJS(overlay, "sorted[0].type", &type));
1098  ASSERT_EQ("navsuggest", type);
1099
1100  bool is_search;
1101  EXPECT_TRUE(GetBoolFromJS(
1102      overlay, "!!sorted[0].is_search", &is_search));
1103  EXPECT_FALSE(is_search);
1104}
1105
1106// Verification of fix for BUG=176365.  Ensure that each Instant WebContents in
1107// a tab uses a new BrowsingInstance, to avoid conflicts in the
1108// NavigationController.
1109// Flaky: http://crbug.com/177516
1110IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_UnrelatedSiteInstance) {
1111  // Setup Instant.
1112  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1113  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1114
1115  // Check that the uncommited ntp page and uncommited overlay have unrelated
1116  // site instances.
1117  // TODO(sreeram): |ntp_| is going away, so this check can be removed in the
1118  // future.
1119  content::WebContents* overlay = instant()->GetOverlayContents();
1120  content::WebContents* ntp_contents = instant()->ntp_->contents();
1121  EXPECT_FALSE(overlay->GetSiteInstance()->IsRelatedSiteInstance(
1122      ntp_contents->GetSiteInstance()));
1123
1124  // Type a query and hit enter to get a results page.  The overlay becomes the
1125  // active tab.
1126  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello"));
1127  EXPECT_EQ("hello", GetOmniboxText());
1128  browser()->window()->GetLocationBar()->AcceptInput();
1129  content::WebContents* first_active_tab =
1130      browser()->tab_strip_model()->GetActiveWebContents();
1131  EXPECT_EQ(first_active_tab, overlay);
1132  scoped_refptr<content::SiteInstance> first_site_instance =
1133      first_active_tab->GetSiteInstance();
1134  EXPECT_FALSE(first_site_instance->IsRelatedSiteInstance(
1135      ntp_contents->GetSiteInstance()));
1136
1137  // Navigating elsewhere gets us off of the commited page.  The next
1138  // query will give us a new |overlay| which we will then commit.
1139  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1140
1141  // Show and commit the new overlay.
1142  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("hello again"));
1143  EXPECT_EQ("hello again", GetOmniboxText());
1144  browser()->window()->GetLocationBar()->AcceptInput();
1145  content::WebContents* second_active_tab =
1146      browser()->tab_strip_model()->GetActiveWebContents();
1147  EXPECT_NE(first_active_tab, second_active_tab);
1148  scoped_refptr<content::SiteInstance> second_site_instance =
1149      second_active_tab->GetSiteInstance();
1150  EXPECT_NE(first_site_instance, second_site_instance);
1151  EXPECT_FALSE(first_site_instance->IsRelatedSiteInstance(
1152      second_site_instance));
1153}
1154
1155// Tests that suggestions are sanity checked.
1156IN_PROC_BROWSER_TEST_F(InstantExtendedTest, ValidatesSuggestions) {
1157  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1158  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1159
1160  // Do not set gray text that is not a suffix of the query.
1161  EXPECT_TRUE(ExecuteScript("suggestion = 'potato';"
1162                            "behavior = 2;"));
1163  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
1164  EXPECT_EQ(ASCIIToUTF16("query"), omnibox()->GetText());
1165  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
1166
1167  omnibox()->RevertAll();
1168
1169  // Do not set blue text that is not a valid URL completion.
1170  EXPECT_TRUE(ExecuteScript("suggestion = 'this is not a url!';"
1171                            "behavior = 1;"));
1172  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("this is"));
1173  EXPECT_EQ(ASCIIToUTF16("this is"), omnibox()->GetText());
1174  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
1175
1176  omnibox()->RevertAll();
1177
1178  // Do not set gray text when blue text is already set.
1179  // First set up some blue text completion.
1180  EXPECT_TRUE(ExecuteScript("suggestion = 'www.example.com';"
1181                            "behavior = 1;"));
1182  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://www.ex"));
1183  EXPECT_EQ(ASCIIToUTF16("http://www.example.com"), omnibox()->GetText());
1184  EXPECT_EQ(ASCIIToUTF16("ample.com"), GetBlueText());
1185
1186  // Now try to set gray text for the same query.
1187  EXPECT_TRUE(ExecuteScript("suggestion = 'www.example.com rocks';"
1188                            "behavior = 2;"));
1189  SetOmniboxText("http://www.ex");
1190  EXPECT_EQ(ASCIIToUTF16("http://www.example.com"), omnibox()->GetText());
1191  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
1192
1193  omnibox()->RevertAll();
1194
1195  // Ignore an out-of-date blue text suggestion. (Simulates a laggy
1196  // SetSuggestion IPC by directly calling into InstantController.)
1197  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://www.example.com/"));
1198  instant()->SetSuggestions(
1199      instant()->overlay()->contents(),
1200      std::vector<InstantSuggestion>(
1201          1,
1202          InstantSuggestion(ASCIIToUTF16("www.exa"),
1203                            INSTANT_COMPLETE_NOW,
1204                            INSTANT_SUGGESTION_URL,
1205                            ASCIIToUTF16("www.exa"),
1206                            kNoMatchIndex)));
1207  EXPECT_EQ(
1208      "http://www.example.com/",
1209      omnibox()->model()->result().default_match()->destination_url.spec());
1210
1211  omnibox()->RevertAll();
1212
1213  // TODO(samarth): uncomment after fixing crbug.com/191656.
1214  // Use an out-of-date blue text suggestion, if the text typed by the user is
1215  // contained in the suggestion.
1216  // ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("ex"));
1217  // instant()->SetSuggestions(
1218  //     instant()->overlay()->contents(),
1219  //     std::vector<InstantSuggestion>(
1220  //         1,
1221  //         InstantSuggestion(ASCIIToUTF16("www.example.com"),
1222  //                           INSTANT_COMPLETE_NOW,
1223  //                           INSTANT_SUGGESTION_URL,
1224  //                           ASCIIToUTF16("e"))));
1225  // EXPECT_EQ(
1226  //     "http://www.example.com/",
1227  //     omnibox()->model()->result().default_match()->destination_url.spec());
1228
1229  // omnibox()->RevertAll();
1230
1231  // When asked to suggest blue text in verbatim mode, suggest the exact
1232  // omnibox text rather than using the supplied suggestion text.
1233  EXPECT_TRUE(ExecuteScript("suggestion = 'www.example.com/q';"
1234                            "behavior = 1;"));
1235  SetOmniboxText("www.example.com/q");
1236  omnibox()->OnBeforePossibleChange();
1237  SetOmniboxText("www.example.com/");
1238  omnibox()->OnAfterPossibleChange();
1239  EXPECT_EQ(ASCIIToUTF16("www.example.com/"), omnibox()->GetText());
1240}
1241
1242// Tests that a previous navigation suggestion is not discarded if it's not
1243// stale.
1244IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1245                       NavigationSuggestionIsNotDiscarded) {
1246  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1247  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1248
1249  // Tell the page to send a URL suggestion.
1250  EXPECT_TRUE(ExecuteScript("suggestion = 'http://www.example.com';"
1251                            "behavior = 1;"));
1252  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("exa"));
1253  EXPECT_EQ(ASCIIToUTF16("example.com"), omnibox()->GetText());
1254  SetOmniboxText("exam");
1255  EXPECT_EQ(ASCIIToUTF16("example.com"), omnibox()->GetText());
1256
1257  // TODO(jered): Remove this after fixing OnBlur().
1258  omnibox()->RevertAll();
1259}
1260
1261// TODO(dhollowa): Fix flakes.  http://crbug.com/179930.
1262IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_MostVisited) {
1263  content::WindowedNotificationObserver observer(
1264      chrome::NOTIFICATION_INSTANT_SENT_MOST_VISITED_ITEMS,
1265      content::NotificationService::AllSources());
1266  // Initialize Instant.
1267  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1268  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1269
1270  // Get a handle to the NTP and the current state of the JS.
1271  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
1272  content::WebContents* overlay = instant()->ntp_->contents();
1273  EXPECT_TRUE(overlay);
1274  EXPECT_TRUE(UpdateSearchState(overlay));
1275
1276  // Wait for most visited data to be ready, if necessary.
1277  if (on_most_visited_change_calls_ == 0) {
1278    observer.Wait();
1279    EXPECT_TRUE(UpdateSearchState(overlay));
1280  }
1281
1282  EXPECT_EQ(1, on_most_visited_change_calls_);
1283
1284  // Make sure we have at least two Most Visited Items and save that number.
1285  // TODO(pedrosimonetti): For now, we're relying on the fact that the Top
1286  // Sites will have at lease two items in it. The correct approach would be
1287  // adding those items to the Top Sites manually before starting the test.
1288  EXPECT_GT(most_visited_items_count_, 1);
1289  int old_most_visited_items_count = most_visited_items_count_;
1290
1291  // Delete the fist Most Visited Item.
1292  int rid = first_most_visited_item_id_;
1293  std::ostringstream stream;
1294  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
1295  EXPECT_TRUE(ExecuteScript(stream.str()));
1296  observer.Wait();
1297
1298  // Update Most Visited state.
1299  EXPECT_TRUE(UpdateSearchState(overlay));
1300
1301  // Make sure we have one less item in there.
1302  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count - 1);
1303
1304  // Undo the deletion of the fist Most Visited Item.
1305  stream.str(std::string());
1306  stream << "newTabPageHandle.undoMostVisitedDeletion(" << rid << ");";
1307  EXPECT_TRUE(ExecuteScript(stream.str()));
1308  observer.Wait();
1309
1310  // Update Most Visited state.
1311  EXPECT_TRUE(UpdateSearchState(overlay));
1312
1313  // Make sure we have the same number of items as before.
1314  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count);
1315
1316  // Delete the fist Most Visited Item.
1317  rid = first_most_visited_item_id_;
1318  stream.str(std::string());
1319  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
1320  EXPECT_TRUE(ExecuteScript(stream.str()));
1321  observer.Wait();
1322
1323  // Update Most Visited state.
1324  EXPECT_TRUE(UpdateSearchState(overlay));
1325
1326  // Delete the second Most Visited Item.
1327  rid = first_most_visited_item_id_;
1328  stream.str(std::string());
1329  stream << "newTabPageHandle.deleteMostVisitedItem(" << rid << ");";
1330  EXPECT_TRUE(ExecuteScript(stream.str()));
1331  observer.Wait();
1332
1333  // Update Most Visited state.
1334  EXPECT_TRUE(UpdateSearchState(overlay));
1335
1336  // Make sure we have two less items in there.
1337  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count - 2);
1338
1339  // Delete the second Most Visited Item.
1340  stream.str(std::string());
1341  stream << "newTabPageHandle.undoAllMostVisitedDeletions();";
1342  EXPECT_TRUE(ExecuteScript(stream.str()));
1343  observer.Wait();
1344
1345  // Update Most Visited state.
1346  EXPECT_TRUE(UpdateSearchState(overlay));
1347
1348  // Make sure we have the same number of items as before.
1349  EXPECT_EQ(most_visited_items_count_, old_most_visited_items_count);
1350}
1351
1352IN_PROC_BROWSER_TEST_F(InstantPolicyTest, ThemeBackgroundAccess) {
1353  InstallThemeSource();
1354  ASSERT_NO_FATAL_FAILURE(InstallThemeAndVerify("theme", "camo theme"));
1355  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1356  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1357
1358  // The "Instant" New Tab should have access to chrome-search: scheme but not
1359  // chrome: scheme.
1360  ui_test_utils::NavigateToURLWithDisposition(
1361      browser(),
1362      GURL(chrome::kChromeUINewTabURL),
1363      NEW_FOREGROUND_TAB,
1364      ui_test_utils::BROWSER_TEST_NONE);
1365
1366  content::RenderViewHost* rvh =
1367      browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost();
1368
1369  const std::string chrome_url("chrome://theme/IDR_THEME_NTP_BACKGROUND");
1370  const std::string search_url(
1371      "chrome-search://theme/IDR_THEME_NTP_BACKGROUND");
1372  bool loaded = false;
1373  ASSERT_TRUE(LoadImage(rvh, chrome_url, &loaded));
1374  EXPECT_FALSE(loaded) << chrome_url;
1375  ASSERT_TRUE(LoadImage(rvh, search_url, &loaded));
1376  EXPECT_TRUE(loaded) << search_url;
1377}
1378
1379// TODO(dhollowa): Fix flakes.  http://crbug.com/179930.
1380IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_FaviconAccess) {
1381  // Create a favicon.
1382  history::TopSites* top_sites = browser()->profile()->GetTopSites();
1383  GURL url("http://www.google.com/foo.html");
1384  gfx::Image thumbnail(CreateBitmap(SK_ColorWHITE));
1385  ThumbnailScore high_score(0.0, true, true, base::Time::Now());
1386  EXPECT_TRUE(top_sites->SetPageThumbnail(url, thumbnail, high_score));
1387
1388  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1389  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1390
1391  // The "Instant" New Tab should have access to chrome-search: scheme but not
1392  // chrome: scheme.
1393  ui_test_utils::NavigateToURLWithDisposition(
1394      browser(),
1395      GURL(chrome::kChromeUINewTabURL),
1396      NEW_FOREGROUND_TAB,
1397      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1398
1399  content::RenderViewHost* rvh =
1400      browser()->tab_strip_model()->GetActiveWebContents()->GetRenderViewHost();
1401
1402  // Get the favicons.
1403  const std::string chrome_favicon_url(
1404      "chrome://favicon/largest/http://www.google.com/foo.html");
1405  const std::string search_favicon_url(
1406      "chrome-search://favicon/largest/http://www.google.com/foo.html");
1407  bool loaded = false;
1408  ASSERT_TRUE(LoadImage(rvh, chrome_favicon_url, &loaded));
1409  EXPECT_FALSE(loaded) << chrome_favicon_url;
1410  ASSERT_TRUE(LoadImage(rvh, search_favicon_url, &loaded));
1411  EXPECT_TRUE(loaded) << search_favicon_url;
1412}
1413
1414// WebUIBindings should never be enabled on ANY Instant web contents.
1415IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnNTP) {
1416  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1417  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1418
1419  ui_test_utils::NavigateToURLWithDisposition(
1420      browser(),
1421      GURL(chrome::kChromeUINewTabURL),
1422      NEW_FOREGROUND_TAB,
1423      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1424  const content::WebContents* tab =
1425      browser()->tab_strip_model()->GetActiveWebContents();
1426
1427  // Instant-provided NTP should not have any bindings enabled.
1428  EXPECT_EQ(0, tab->GetRenderViewHost()->GetEnabledBindings());
1429}
1430
1431// WebUIBindings should never be enabled on ANY Instant web contents.
1432IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnPreview) {
1433  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1434  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1435
1436  // Typing in the omnibox shows the overlay.
1437  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
1438  EXPECT_TRUE(instant()->model()->mode().is_search_suggestions());
1439  content::WebContents* preview = instant()->GetOverlayContents();
1440  ASSERT_NE(static_cast<content::WebContents*>(NULL), preview);
1441
1442  // Instant preview should not have any bindings enabled.
1443  EXPECT_EQ(0, preview->GetRenderViewHost()->GetEnabledBindings());
1444}
1445
1446// WebUIBindings should never be enabled on ANY Instant web contents.
1447IN_PROC_BROWSER_TEST_F(InstantExtendedTest, NoWebUIBindingsOnResults) {
1448  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1449  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1450
1451  // Typing in the omnibox shows the overlay.
1452  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
1453  content::WebContents* preview = instant()->GetOverlayContents();
1454  EXPECT_TRUE(instant()->model()->mode().is_search_suggestions());
1455  // Commit the search by pressing Enter.
1456  browser()->window()->GetLocationBar()->AcceptInput();
1457  EXPECT_TRUE(instant()->model()->mode().is_default());
1458  const content::WebContents* tab =
1459      browser()->tab_strip_model()->GetActiveWebContents();
1460  EXPECT_EQ(preview, tab);
1461
1462  // The commited Instant page should not have any bindings enabled.
1463  EXPECT_EQ(0, tab->GetRenderViewHost()->GetEnabledBindings());
1464}
1465
1466// Only implemented in Views and Mac currently: http://crbug.com/164723
1467#if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_MACOSX)
1468#define MAYBE_HomeButtonAffectsMargin HomeButtonAffectsMargin
1469#else
1470#define MAYBE_HomeButtonAffectsMargin DISABLED_HomeButtonAffectsMargin
1471#endif
1472// Check that toggling the state of the home button changes the start-edge
1473// margin and width.
1474IN_PROC_BROWSER_TEST_F(InstantExtendedTest, MAYBE_HomeButtonAffectsMargin) {
1475  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1476  FocusOmniboxAndWaitForInstantOverlaySupport();
1477
1478  // Get the current value of the start-edge margin and width.
1479  int start_margin;
1480  int width;
1481  content::WebContents* overlay = instant()->GetOverlayContents();
1482  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.startMargin",
1483      &start_margin));
1484  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.width", &width));
1485
1486  // Toggle the home button visibility pref.
1487  PrefService* profile_prefs = browser()->profile()->GetPrefs();
1488  bool show_home = profile_prefs->GetBoolean(prefs::kShowHomeButton);
1489  profile_prefs->SetBoolean(prefs::kShowHomeButton, !show_home);
1490
1491  // Make sure the margin and width changed.
1492  int new_start_margin;
1493  int new_width;
1494  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.startMargin",
1495      &new_start_margin));
1496  EXPECT_TRUE(GetIntFromJS(overlay, "chrome.searchBox.width", &new_width));
1497  EXPECT_NE(start_margin, new_start_margin);
1498  EXPECT_NE(width, new_width);
1499  EXPECT_EQ(new_width - width, start_margin - new_start_margin);
1500}
1501
1502// Commit does not happen on Mac: http://crbug.com/178520
1503#if defined(OS_MACOSX)
1504#define MAYBE_CommitWhenFocusLostInFullHeight \
1505        DISABLED_CommitWhenFocusLostInFullHeight
1506#else
1507#define MAYBE_CommitWhenFocusLostInFullHeight CommitWhenFocusLostInFullHeight
1508#endif
1509// Test that the overlay is committed when the omnibox loses focus when it is
1510// shown at 100% height.
1511IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1512                       MAYBE_CommitWhenFocusLostInFullHeight) {
1513  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1514
1515  // Focus omnibox and confirm overlay isn't shown.
1516  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1517  content::WebContents* overlay = instant()->GetOverlayContents();
1518  EXPECT_TRUE(overlay);
1519  EXPECT_TRUE(instant()->model()->mode().is_default());
1520  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
1521
1522  // Typing in the omnibox should show the overlay.
1523  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
1524  EXPECT_TRUE(instant()->IsOverlayingSearchResults());
1525  EXPECT_EQ(overlay, instant()->GetOverlayContents());
1526
1527  // Explicitly unfocus the omnibox without triggering a click. Note that this
1528  // doesn't actually change the focus state of the omnibox, only what the
1529  // Instant controller sees it as.
1530  omnibox()->model()->OnWillKillFocus(NULL);
1531  omnibox()->model()->OnKillFocus();
1532
1533  // Confirm that the overlay has been committed.
1534  content::WebContents* active_tab =
1535      browser()->tab_strip_model()->GetActiveWebContents();
1536  EXPECT_EQ(overlay, active_tab);
1537}
1538
1539#if defined(OS_MACOSX)
1540// http://crbug.com/227076
1541#define MAYBE_CommitWhenShownInFullHeightWithoutFocus \
1542        DISABLED_CommitWhenShownInFullHeightWithoutFocus
1543#else
1544#define MAYBE_CommitWhenShownInFullHeightWithoutFocus \
1545        CommitWhenShownInFullHeightWithoutFocus
1546#endif
1547
1548// Test that the overlay is committed when shown at 100% height without focus
1549// in the omnibox.
1550IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1551                       MAYBE_CommitWhenShownInFullHeightWithoutFocus) {
1552  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1553
1554  // Focus omnibox and confirm overlay isn't shown.
1555  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1556  content::WebContents* overlay = instant()->GetOverlayContents();
1557  EXPECT_TRUE(overlay);
1558  EXPECT_TRUE(instant()->model()->mode().is_default());
1559  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
1560
1561  // Create an observer to wait for the commit.
1562  content::WindowedNotificationObserver commit_observer(
1563      chrome::NOTIFICATION_INSTANT_COMMITTED,
1564      content::NotificationService::AllSources());
1565
1566  // Create an observer to wait for the autocomplete.
1567  content::WindowedNotificationObserver autocomplete_observer(
1568      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
1569      content::NotificationService::AllSources());
1570
1571  // Typing in the omnibox should show the overlay. Don't wait for the overlay
1572  // to show however.
1573  SetOmniboxText("query");
1574
1575  autocomplete_observer.Wait();
1576
1577  // Explicitly unfocus the omnibox without triggering a click. Note that this
1578  // doesn't actually change the focus state of the omnibox, only what the
1579  // Instant controller sees it as.
1580  omnibox()->model()->OnWillKillFocus(NULL);
1581  omnibox()->model()->OnKillFocus();
1582
1583  // Wait for the overlay to show.
1584  commit_observer.Wait();
1585
1586  // Confirm that the overlay has been committed.
1587  content::WebContents* active_tab =
1588      browser()->tab_strip_model()->GetActiveWebContents();
1589  EXPECT_EQ(overlay, active_tab);
1590}
1591
1592// Test that a transient entry is set properly when the overlay is committed
1593// without a navigation.
1594IN_PROC_BROWSER_TEST_F(InstantExtendedTest, TransientEntrySet) {
1595  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1596
1597  // Focus omnibox and confirm overlay isn't shown.
1598  FocusOmniboxAndWaitForInstantOverlaySupport();
1599  content::WebContents* overlay = instant()->GetOverlayContents();
1600  EXPECT_TRUE(overlay);
1601  EXPECT_TRUE(instant()->model()->mode().is_default());
1602  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
1603
1604  // Commit the overlay without triggering a navigation.
1605  content::WindowedNotificationObserver observer(
1606      chrome::NOTIFICATION_INSTANT_COMMITTED,
1607      content::NotificationService::AllSources());
1608  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
1609  browser()->window()->GetLocationBar()->AcceptInput();
1610  observer.Wait();
1611
1612  // Confirm that the overlay has been committed.
1613  content::WebContents* active_tab =
1614      browser()->tab_strip_model()->GetActiveWebContents();
1615  EXPECT_EQ(overlay, active_tab);
1616
1617  // The page hasn't navigated so there should be a transient entry with the
1618  // same URL but different page ID as the last committed entry.
1619  const content::NavigationEntry* transient_entry =
1620      active_tab->GetController().GetTransientEntry();
1621  const content::NavigationEntry* committed_entry =
1622      active_tab->GetController().GetLastCommittedEntry();
1623  EXPECT_EQ(transient_entry->GetURL(), committed_entry->GetURL());
1624  EXPECT_NE(transient_entry->GetPageID(), committed_entry->GetPageID());
1625}
1626
1627// Test that the a transient entry is cleared when the overlay is committed
1628// with a navigation.
1629// TODO(samarth) : this test fails, http://crbug.com/181070.
1630IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_TransientEntryRemoved) {
1631  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1632
1633  // Focus omnibox and confirm overlay isn't shown.
1634  FocusOmniboxAndWaitForInstantOverlaySupport();
1635  content::WebContents* overlay = instant()->GetOverlayContents();
1636  EXPECT_TRUE(overlay);
1637  EXPECT_TRUE(instant()->model()->mode().is_default());
1638  EXPECT_FALSE(instant()->IsOverlayingSearchResults());
1639
1640  // Create an observer to wait for the commit.
1641  content::WindowedNotificationObserver observer(
1642      chrome::NOTIFICATION_INSTANT_COMMITTED,
1643      content::NotificationService::AllSources());
1644
1645  // Trigger a navigation on commit.
1646  EXPECT_TRUE(ExecuteScript(
1647      "getApiHandle().oncancel = function() {"
1648      "  location.replace(location.href + '#q=query');"
1649      "};"
1650      ));
1651
1652  // Commit the overlay.
1653  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("query"));
1654  browser()->window()->GetLocationBar()->AcceptInput();
1655  observer.Wait();
1656
1657  // Confirm that the overlay has been committed.
1658  content::WebContents* active_tab =
1659      browser()->tab_strip_model()->GetActiveWebContents();
1660  EXPECT_EQ(overlay, active_tab);
1661
1662  // The page has navigated so there should be no transient entry.
1663  const content::NavigationEntry* transient_entry =
1664      active_tab->GetController().GetTransientEntry();
1665  EXPECT_EQ(NULL, transient_entry);
1666
1667  // The last committed entry should be the URL the page navigated to.
1668  const content::NavigationEntry* committed_entry =
1669      active_tab->GetController().GetLastCommittedEntry();
1670  EXPECT_TRUE(EndsWith(committed_entry->GetURL().spec(), "#q=query", true));
1671}
1672
1673IN_PROC_BROWSER_TEST_F(InstantExtendedTest, RestrictedURLReading) {
1674  std::string search_query;
1675  bool is_undefined;
1676  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1677  FocusOmniboxAndWaitForInstantOverlaySupport();
1678
1679  // Verify we can read out something ok.
1680  const char kOKQuery[] = "santa";
1681  SetOmniboxText(kOKQuery);
1682  EXPECT_EQ(ASCIIToUTF16(kOKQuery), omnibox()->GetText());
1683  // Must always assert the value is defined before trying to read it, as trying
1684  // to read undefined values causes the test to hang.
1685  EXPECT_TRUE(GetBoolFromJS(instant()->GetOverlayContents(),
1686                            "apiHandle.value === undefined",
1687                            &is_undefined));
1688  ASSERT_FALSE(is_undefined);
1689  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
1690                              "apiHandle.value",
1691                              &search_query));
1692  EXPECT_EQ(kOKQuery, search_query);
1693
1694  // Verify we can't read out something that should be restricted, like a https
1695  // url with a path.
1696  const char kHTTPSUrlWithPath[] = "https://www.example.com/foobar";
1697  SetOmniboxText(kHTTPSUrlWithPath);
1698  EXPECT_EQ(ASCIIToUTF16(kHTTPSUrlWithPath), omnibox()->GetText());
1699  EXPECT_TRUE(GetBoolFromJS(instant()->GetOverlayContents(),
1700                            "apiHandle.value === undefined",
1701                            &is_undefined));
1702  EXPECT_TRUE(is_undefined);
1703}
1704
1705IN_PROC_BROWSER_TEST_F(InstantExtendedTest, RestrictedItemReadback) {
1706  // Initialize Instant.
1707  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1708  FocusOmniboxAndWaitForInstantOverlaySupport();
1709
1710  // Get a handle to the NTP and the current state of the JS.
1711  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
1712  content::WebContents* preview_tab = instant()->ntp()->contents();
1713  EXPECT_TRUE(preview_tab);
1714
1715  // Manufacture a few autocomplete results and get them down to the page.
1716  std::vector<InstantAutocompleteResult> autocomplete_results;
1717  for (int i = 0; i < 3; ++i) {
1718    std::string description(base::StringPrintf("Test Description %d", i));
1719    std::string url(base::StringPrintf("http://www.testurl%d.com", i));
1720
1721    InstantAutocompleteResult res;
1722    res.provider = ASCIIToUTF16(AutocompleteProvider::TypeToString(
1723        AutocompleteProvider::TYPE_BUILTIN));
1724    res.type = AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED,
1725    res.description = ASCIIToUTF16(description);
1726    res.destination_url = ASCIIToUTF16(url);
1727    res.transition = content::PAGE_TRANSITION_TYPED;
1728    res.relevance = 42 + i;
1729
1730    autocomplete_results.push_back(res);
1731  }
1732  instant()->overlay()->SendAutocompleteResults(autocomplete_results);
1733
1734  // Apparently, one needs to access nativeSuggestions before
1735  // apiHandle.setRestrictedValue can work.
1736  EXPECT_TRUE(ExecuteScript("var foo = apiHandle.nativeSuggestions;"));
1737
1738  const char kQueryString[] = "Hippos go berzerk!";
1739
1740  // First set the query text to a non restricted value and ensure it can be
1741  // read back.
1742  std::ostringstream stream;
1743  stream << "apiHandle.setValue('" << kQueryString << "');";
1744  EXPECT_TRUE(ExecuteScript(stream.str()));
1745
1746  std::string query_string;
1747  bool is_undefined;
1748  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
1749                              "apiHandle.value",
1750                              &query_string));
1751  EXPECT_EQ(kQueryString, query_string);
1752
1753  // Set the query text to the first restricted autocomplete item.
1754  int rid = 1;
1755  stream.str(std::string());
1756  stream << "apiHandle.setRestrictedValue(" << rid << ");";
1757  EXPECT_TRUE(ExecuteScript(stream.str()));
1758
1759  // Expect that we now receive undefined when reading the value back.
1760  EXPECT_TRUE(GetBoolFromJS(
1761      instant()->GetOverlayContents(),
1762      "apiHandle.value === undefined",
1763      &is_undefined));
1764  EXPECT_TRUE(is_undefined);
1765
1766  // Now set the query text to a non restricted value and ensure that the
1767  // visibility has been reset and the string can again be read back.
1768  stream.str(std::string());
1769  stream << "apiHandle.setValue('" << kQueryString << "');";
1770  EXPECT_TRUE(ExecuteScript(stream.str()));
1771
1772  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
1773                              "apiHandle.value",
1774                              &query_string));
1775  EXPECT_EQ(kQueryString, query_string);
1776}
1777
1778// Test that autocomplete results are sent to the page only when all the
1779// providers are done.
1780IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AutocompleteProvidersDone) {
1781  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1782  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1783
1784  content::WebContents* overlay = instant()->GetOverlayContents();
1785  EXPECT_TRUE(UpdateSearchState(overlay));
1786  EXPECT_EQ(0, on_native_suggestions_calls_);
1787
1788  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("railroad"));
1789
1790  EXPECT_EQ(overlay, instant()->GetOverlayContents());
1791  EXPECT_TRUE(UpdateSearchState(overlay));
1792  EXPECT_EQ(1, on_native_suggestions_calls_);
1793}
1794
1795// Test that the Bookmark provider is enabled, and returns results.
1796// TODO(sreeram): Convert this to a unit test.
1797IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DISABLED_HasBookmarkProvider) {
1798  // No need to setup Instant.
1799  set_browser(browser());
1800
1801  BookmarkModel* bookmark_model =
1802      BookmarkModelFactory::GetForProfile(browser()->profile());
1803  ASSERT_TRUE(bookmark_model);
1804  ui_test_utils::WaitForBookmarkModelToLoad(bookmark_model);
1805  bookmark_utils::AddIfNotBookmarked(bookmark_model, GURL("http://angeline/"),
1806                                     ASCIIToUTF16("angeline"));
1807
1808  SetOmniboxText("angeline");
1809
1810  bool found_bookmark_match = false;
1811
1812  const AutocompleteResult& result = omnibox()->model()->result();
1813  for (AutocompleteResult::const_iterator iter = result.begin();
1814       !found_bookmark_match && iter != result.end(); ++iter) {
1815    found_bookmark_match = iter->type == AutocompleteMatchType::BOOKMARK_TITLE;
1816  }
1817
1818  EXPECT_TRUE(found_bookmark_match);
1819}
1820
1821// Test that the omnibox's temporary text is reset when the popup is closed.
1822IN_PROC_BROWSER_TEST_F(InstantExtendedTest, TemporaryTextResetWhenPopupClosed) {
1823  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1824  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1825  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
1826
1827  // Show the overlay and arrow-down to a suggestion (this sets temporary text).
1828  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("juju"));
1829  SendDownArrow();
1830
1831  EXPECT_TRUE(HasTemporaryText());
1832  EXPECT_EQ("result 1", GetOmniboxText());
1833
1834  // Click outside the omnibox (but not on the overlay), to make the omnibox
1835  // lose focus. Close the popup explicitly, to workaround test/toolkit issues.
1836  ui_test_utils::ClickOnView(browser(), VIEW_ID_TOOLBAR);
1837  omnibox()->CloseOmniboxPopup();
1838
1839  // The temporary text should've been accepted as the user text.
1840  EXPECT_FALSE(HasTemporaryText());
1841  EXPECT_EQ("result 1", GetOmniboxText());
1842
1843  // Now refocus the omnibox and hit Escape. This shouldn't crash.
1844  FocusOmnibox();
1845  SendEscape();
1846
1847  // The omnibox should've reverted to the underlying permanent URL.
1848  EXPECT_FALSE(HasTemporaryText());
1849  EXPECT_EQ(std::string(content::kAboutBlankURL), GetOmniboxText());
1850}
1851
1852// Test that autocomplete results aren't sent when the popup is closed.
1853IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
1854                       NoAutocompleteResultsWhenPopupClosed) {
1855  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1856  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1857  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
1858
1859  // Show the overlay and arrow-down to a suggestion (this sets temporary text).
1860  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("thangam"));
1861  SendDownArrow();
1862  EXPECT_TRUE(HasTemporaryText());
1863
1864  EXPECT_TRUE(ExecuteScript("onChangeCalls = onNativeSuggestionsCalls = 0;"));
1865
1866  content::WebContents* overlay = instant()->GetOverlayContents();
1867  EXPECT_TRUE(UpdateSearchState(overlay));
1868  EXPECT_EQ(0, on_change_calls_);
1869  EXPECT_EQ(0, on_native_suggestions_calls_);
1870
1871  // Click outside the omnibox (but not on the overlay), to make the omnibox
1872  // lose focus. Close the popup explicitly, to workaround test/toolkit issues.
1873  ui_test_utils::ClickOnView(browser(), VIEW_ID_TOOLBAR);
1874  omnibox()->CloseOmniboxPopup();
1875  EXPECT_FALSE(HasTemporaryText());
1876
1877  EXPECT_EQ(overlay, instant()->GetOverlayContents());
1878  EXPECT_TRUE(UpdateSearchState(overlay));
1879  EXPECT_EQ(0, on_change_calls_);
1880  EXPECT_EQ(0, on_native_suggestions_calls_);
1881}
1882
1883// Test that suggestions are not accepted when unexpected.
1884IN_PROC_BROWSER_TEST_F(InstantExtendedTest, DeniesUnexpectedSuggestions) {
1885  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1886  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1887  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("chip"));
1888  SendDownArrow();
1889
1890  EXPECT_EQ("result 1", GetOmniboxText());
1891  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
1892
1893  // Make the page send an unexpected suggestion.
1894  EXPECT_TRUE(ExecuteScript("suggestion = 'chippies';"
1895                            "handleOnChange();"));
1896
1897  // Verify that the suggestion is ignored.
1898  EXPECT_EQ("result 1", GetOmniboxText());
1899  EXPECT_EQ(ASCIIToUTF16(""), GetGrayText());
1900}
1901
1902// Test that autocomplete results are cleared when the query is cleared.
1903IN_PROC_BROWSER_TEST_F(InstantExtendedTest, EmptyAutocompleteResults) {
1904  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1905  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1906
1907  // Type a URL, so that there's at least one autocomplete result (a "URL what
1908  // you typed" match).
1909  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("http://upsamina/"));
1910
1911  content::WebContents* overlay = instant()->GetOverlayContents();
1912
1913  int num_autocomplete_results = 0;
1914  EXPECT_TRUE(GetIntFromJS(
1915      overlay,
1916      "chrome.embeddedSearch.searchBox.nativeSuggestions.length",
1917      &num_autocomplete_results));
1918  EXPECT_LT(0, num_autocomplete_results);
1919
1920  // Erase the query in the omnibox.
1921  SetOmniboxText("");
1922
1923  EXPECT_TRUE(GetIntFromJS(
1924      overlay,
1925      "chrome.embeddedSearch.searchBox.nativeSuggestions.length",
1926      &num_autocomplete_results));
1927  EXPECT_EQ(0, num_autocomplete_results);
1928}
1929
1930// Test that hitting Esc to clear the omnibox works. http://crbug.com/231744.
1931IN_PROC_BROWSER_TEST_F(InstantExtendedTest, EscapeClearsOmnibox) {
1932  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1933  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1934
1935  // Navigate to the Instant NTP, and wait for it to be recognized.
1936  content::WindowedNotificationObserver instant_tab_observer(
1937      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
1938      content::NotificationService::AllSources());
1939  ui_test_utils::NavigateToURLWithDisposition(
1940      browser(),
1941      GURL(chrome::kChromeUINewTabURL),
1942      NEW_FOREGROUND_TAB,
1943      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1944  instant_tab_observer.Wait();
1945
1946  content::WebContents* contents =
1947      browser()->tab_strip_model()->GetActiveWebContents();
1948
1949  // Type a query. Verify that the query is seen by the page.
1950  SetOmniboxText("mojo");
1951  std::string query;
1952  EXPECT_TRUE(GetStringFromJS(contents, "chrome.embeddedSearch.searchBox.value",
1953                              &query));
1954  EXPECT_EQ("mojo", query);
1955
1956  EXPECT_TRUE(content::ExecuteScript(contents,
1957                                     "onChangeCalls = submitCount = 0;"));
1958
1959  // Hit Escape, and verify that the page sees that the query is cleared.
1960  SendEscape();
1961  EXPECT_TRUE(GetStringFromJS(contents, "chrome.embeddedSearch.searchBox.value",
1962                              &query));
1963  EXPECT_EQ("", query);
1964  EXPECT_EQ("", GetOmniboxText());
1965
1966  EXPECT_TRUE(UpdateSearchState(contents));
1967  EXPECT_LT(0, on_change_calls_);
1968  EXPECT_EQ(0, submit_count_);
1969  EXPECT_LT(0, on_esc_key_press_event_calls_);
1970}
1971
1972IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OnDefaultSearchProviderChanged) {
1973  InstantService* instant_service =
1974      InstantServiceFactory::GetForProfile(browser()->profile());
1975  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
1976
1977  // Setup Instant.
1978  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
1979  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
1980  EXPECT_EQ(1, instant_service->GetInstantProcessCount());
1981
1982  // Navigating to the NTP should use the Instant render process.
1983  ui_test_utils::NavigateToURLWithDisposition(
1984      browser(),
1985      GURL(chrome::kChromeUINewTabURL),
1986      CURRENT_TAB,
1987      ui_test_utils::BROWSER_TEST_NONE);
1988  content::WebContents* ntp_contents =
1989      browser()->tab_strip_model()->GetActiveWebContents();
1990  EXPECT_TRUE(chrome::IsInstantNTP(ntp_contents));
1991  EXPECT_TRUE(instant_service->IsInstantProcess(
1992      ntp_contents->GetRenderProcessHost()->GetID()));
1993  GURL ntp_url = ntp_contents->GetURL();
1994
1995  AddBlankTabAndShow(browser());
1996  content::WebContents* active_tab =
1997      browser()->tab_strip_model()->GetActiveWebContents();
1998  EXPECT_FALSE(chrome::IsInstantNTP(active_tab));
1999  EXPECT_FALSE(instant_service->IsInstantProcess(
2000      active_tab->GetRenderProcessHost()->GetID()));
2001
2002  TemplateURLData data;
2003  data.short_name = ASCIIToUTF16("t");
2004  data.SetURL("http://defaultturl/q={searchTerms}");
2005  data.suggestions_url = "http://defaultturl2/q={searchTerms}";
2006  data.instant_url = "http://does/not/exist";
2007  data.alternate_urls.push_back(data.instant_url + "#q={searchTerms}");
2008  data.search_terms_replacement_key = "strk";
2009
2010  TemplateURL* template_url = new TemplateURL(browser()->profile(), data);
2011  TemplateURLService* service =
2012      TemplateURLServiceFactory::GetForProfile(browser()->profile());
2013  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
2014  service->Add(template_url);  // Takes ownership of |template_url|.
2015
2016  // Change the default search provider.
2017  content::WindowedNotificationObserver observer(
2018      content::NOTIFICATION_LOAD_STOP,
2019      content::Source<content::NavigationController>(
2020          &ntp_contents->GetController()));
2021  service->SetDefaultSearchProvider(template_url);
2022  observer.Wait();
2023
2024  // |ntp_contents| should not use the Instant render process.
2025  EXPECT_FALSE(chrome::IsInstantNTP(ntp_contents));
2026  EXPECT_FALSE(instant_service->IsInstantProcess(
2027      ntp_contents->GetRenderProcessHost()->GetID()));
2028  // Make sure the URL remains the same.
2029  EXPECT_EQ(ntp_url, ntp_contents->GetURL());
2030}
2031
2032IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OverlayRenderViewGone) {
2033  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2034  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2035  EXPECT_NE(static_cast<content::WebContents*>(NULL),
2036            instant()->GetOverlayContents());
2037
2038  // Overlay is not reloaded after being killed.
2039  EXPECT_FALSE(instant()->overlay()->IsLocal());
2040  instant()->InstantPageRenderViewGone(instant()->GetOverlayContents());
2041  EXPECT_EQ(NULL, instant()->GetOverlayContents());
2042
2043  // The local overlay is used on the next Update().
2044  SetOmniboxText("query");
2045  EXPECT_TRUE(instant()->overlay()->IsLocal());
2046
2047  // Switched back to the remote overlay when omnibox loses and regains focus.
2048  instant()->HideOverlay();
2049  browser()->tab_strip_model()->GetActiveWebContents()->GetView()->Focus();
2050  FocusOmnibox();
2051  EXPECT_FALSE(instant()->overlay()->IsLocal());
2052}
2053
2054IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OverlayDoesntSupportInstant) {
2055  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
2056  InstantTestBase::Init(instant_url);
2057  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2058
2059  // Focus the omnibox. When the support determination response comes back,
2060  // Instant will destroy the non-Instant page and fall back to the local page.
2061  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2062  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
2063  EXPECT_TRUE(instant()->overlay()->IsLocal());
2064
2065  // The local overlay is used on the next Update().
2066  SetOmniboxText("query");
2067  EXPECT_TRUE(instant()->overlay()->IsLocal());
2068
2069  // Switched back to the remote overlay when omnibox loses and regains focus.
2070  instant()->HideOverlay();
2071  browser()->tab_strip_model()->GetActiveWebContents()->GetView()->Focus();
2072  FocusOmnibox();
2073  EXPECT_FALSE(instant()->overlay()->IsLocal());
2074
2075  // Overlay falls back to local again after determining support.
2076  FocusOmniboxAndWaitForInstantOverlaySupport();
2077  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
2078  EXPECT_TRUE(instant()->overlay()->IsLocal());
2079}
2080
2081// Test that if Instant alters the input from URL to search, it's respected.
2082IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputChangedFromURLToSearch) {
2083  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2084  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2085
2086  content::WebContents* overlay = instant()->GetOverlayContents();
2087  EXPECT_TRUE(ExecuteScript("suggestions = ['mcqueen.com'];"));
2088
2089  SetOmniboxTextAndWaitForOverlayToShow("lightning");
2090  EXPECT_EQ("lightning", GetOmniboxText());
2091
2092  SendDownArrow();
2093  EXPECT_EQ("mcqueen.com", GetOmniboxText());
2094
2095  // Press Enter.
2096  browser()->window()->GetLocationBar()->AcceptInput();
2097
2098  // Confirm that the Instant overlay was committed.
2099  EXPECT_EQ(overlay, browser()->tab_strip_model()->GetActiveWebContents());
2100}
2101
2102// Test that if Instant alters the input from search to URL, it's respected.
2103IN_PROC_BROWSER_TEST_F(InstantExtendedTest, InputChangedFromSearchToURL) {
2104  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2105  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2106
2107  content::WebContents* overlay = instant()->GetOverlayContents();
2108  EXPECT_TRUE(ExecuteScript("suggestionType = 1;"));  // INSTANT_SUGGESTION_URL
2109
2110  SetOmniboxTextAndWaitForOverlayToShow("mack.com");
2111  EXPECT_EQ("mack.com", GetOmniboxText());
2112
2113  SendDownArrow();
2114  EXPECT_EQ("result 1", GetOmniboxText());
2115
2116  // Press Enter.
2117  browser()->window()->GetLocationBar()->AcceptInput();
2118
2119  // Confirm that the Instant overlay was NOT committed.
2120  EXPECT_NE(overlay, browser()->tab_strip_model()->GetActiveWebContents());
2121}
2122
2123// Test that renderer initiated navigations to an instant URL from a non
2124// Instant page do not end up in an Instant process if they are bounced to the
2125// browser.
2126IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
2127                       RendererInitiatedNavigationNotInInstantProcess) {
2128  InstantService* instant_service =
2129      InstantServiceFactory::GetForProfile(browser()->profile());
2130  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
2131
2132  // Setup Instant.
2133  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2134  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2135
2136  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
2137  EXPECT_EQ(1, browser()->tab_strip_model()->count());
2138
2139  // Don't use https server for the non instant URL so that the browser uses
2140  // different RenderViews.
2141  GURL non_instant_url = test_server()->GetURL("files/simple.html");
2142  ui_test_utils::NavigateToURLWithDisposition(
2143      browser(),
2144      non_instant_url,
2145      CURRENT_TAB,
2146      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
2147  content::WebContents* contents =
2148      browser()->tab_strip_model()->GetActiveWebContents();
2149  EXPECT_FALSE(instant_service->IsInstantProcess(
2150      contents->GetRenderProcessHost()->GetID()));
2151  EXPECT_EQ(non_instant_url, contents->GetURL());
2152
2153  int old_render_view_id = contents->GetRenderViewHost()->GetRoutingID();
2154  int old_render_process_id = contents->GetRenderProcessHost()->GetID();
2155
2156  std::string instant_url_with_query = instant_url().spec() + "q=3";
2157  std::string add_link_script = base::StringPrintf(
2158      "var a = document.createElement('a');"
2159      "a.id = 'toClick';"
2160      "a.href = '%s';"
2161      "document.body.appendChild(a);",
2162      instant_url_with_query.c_str());
2163  EXPECT_TRUE(content::ExecuteScript(contents, add_link_script));
2164
2165  // Ensure that navigations are bounced to the browser.
2166  contents->GetMutableRendererPrefs()->browser_handles_all_top_level_requests =
2167      true;
2168  contents->GetRenderViewHost()->SyncRendererPrefs();
2169
2170  content::WindowedNotificationObserver observer(
2171        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2172        content::NotificationService::AllSources());
2173  EXPECT_TRUE(content::ExecuteScript(
2174      contents, "document.getElementById('toClick').click();"));
2175  observer.Wait();
2176
2177  EXPECT_EQ(1, browser()->tab_strip_model()->count());
2178  contents = browser()->tab_strip_model()->GetActiveWebContents();
2179  EXPECT_FALSE(instant_service->IsInstantProcess(
2180      contents->GetRenderProcessHost()->GetID()));
2181  EXPECT_EQ(GURL(instant_url_with_query), contents->GetURL());
2182  int new_render_view_id = contents->GetRenderViewHost()->GetRoutingID();
2183  int new_render_process_id = contents->GetRenderProcessHost()->GetID();
2184
2185  EXPECT_TRUE(old_render_process_id != new_render_process_id ||
2186              old_render_view_id != new_render_view_id);
2187}
2188
2189// Test that renderer initiated navigations to an Instant URL from an
2190// Instant process end up in an Instant process.
2191IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
2192                       RendererInitiatedNavigationInInstantProcess) {
2193  InstantService* instant_service =
2194      InstantServiceFactory::GetForProfile(browser()->profile());
2195  ASSERT_NE(static_cast<InstantService*>(NULL), instant_service);
2196
2197  // Setup Instant.
2198  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2199  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2200
2201  EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
2202  EXPECT_EQ(1, browser()->tab_strip_model()->count());
2203
2204  ui_test_utils::NavigateToURLWithDisposition(
2205      browser(),
2206      instant_url(),
2207      CURRENT_TAB,
2208      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
2209  content::WebContents* contents =
2210      browser()->tab_strip_model()->GetActiveWebContents();
2211  EXPECT_TRUE(instant_service->IsInstantProcess(
2212      contents->GetRenderProcessHost()->GetID()));
2213
2214  std::string instant_url_with_query = instant_url().spec() + "q=3";
2215  std::string add_link_script = base::StringPrintf(
2216      "var a = document.createElement('a');"
2217      "a.id = 'toClick';"
2218      "a.href = '%s';"
2219      "document.body.appendChild(a);",
2220      instant_url_with_query.c_str());
2221  EXPECT_TRUE(content::ExecuteScript(contents, add_link_script));
2222
2223  content::WindowedNotificationObserver observer(
2224        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2225        content::NotificationService::AllSources());
2226  EXPECT_TRUE(content::ExecuteScript(
2227      contents, "document.getElementById('toClick').click();"));
2228  observer.Wait();
2229
2230  EXPECT_EQ(1, browser()->tab_strip_model()->count());
2231  contents = browser()->tab_strip_model()->GetActiveWebContents();
2232  EXPECT_TRUE(instant_service->IsInstantProcess(
2233      contents->GetRenderProcessHost()->GetID()));
2234  EXPECT_EQ(GURL(instant_url_with_query), contents->GetURL());
2235}
2236
2237IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderDoesntRun) {
2238  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2239  FocusOmniboxAndWaitForInstantOverlaySupport();
2240
2241  // Add "query" to history.
2242  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("query"), 10000));
2243  BlockUntilHistoryProcessesPendingRequests();
2244
2245  SetOmniboxText("quer");
2246
2247  // Should get only SWYT from SearchProvider.
2248  EXPECT_EQ(1, CountSearchProviderSuggestions());
2249}
2250
2251IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderRunsForLocalOnly) {
2252  // Force local-only Instant.
2253  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2254  instant()->SetInstantEnabled(true, true);
2255  FocusOmniboxAndWaitForInstantOverlaySupport();
2256
2257  // Add "query" to history.
2258  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("query"), 10000));
2259  BlockUntilHistoryProcessesPendingRequests();
2260
2261  SetOmniboxText("quer");
2262
2263  // Should get 2 suggestions from SearchProvider:
2264  //   - SWYT for "quer"
2265  //   - Search history suggestion for "query"
2266  EXPECT_EQ(2, CountSearchProviderSuggestions());
2267}
2268
2269IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderRunsForFallback) {
2270  // Use an Instant URL that won't support Instant.
2271  GURL instant_url = test_server()->GetURL("files/empty.html?strk=1");
2272  InstantTestBase::Init(instant_url);
2273  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2274  FocusOmniboxAndWaitForInstantOverlaySupport();
2275  // Should fallback to the local overlay.
2276  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
2277  EXPECT_TRUE(instant()->overlay()->IsLocal());
2278
2279  // Add "query" to history and wait for Instant support.
2280  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("query"), 10000));
2281  BlockUntilHistoryProcessesPendingRequests();
2282
2283  SetOmniboxText("quer");
2284
2285  // Should get 2 suggestions from SearchProvider:
2286  //   - SWYT for "quer"
2287  //   - Search history suggestion for "query"
2288  EXPECT_EQ(2, CountSearchProviderSuggestions());
2289}
2290
2291IN_PROC_BROWSER_TEST_F(InstantExtendedTest, SearchProviderForLocalNTP) {
2292  // Force local-only Instant.
2293  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2294  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2295  instant()->SetInstantEnabled(true, true);
2296
2297  // Add "google" to history.
2298  ASSERT_TRUE(AddSearchToHistory(ASCIIToUTF16("google"), 10000));
2299  BlockUntilHistoryProcessesPendingRequests();
2300
2301  // Create an observer to wait for the autocomplete.
2302  content::WindowedNotificationObserver autocomplete_observer(
2303      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
2304      content::NotificationService::AllSources());
2305
2306  SetOmniboxText("http://www.example.com");
2307
2308  autocomplete_observer.Wait();
2309  ASSERT_TRUE(omnibox()->model()->autocomplete_controller()->
2310              search_provider()->IsNonInstantSearchDone());
2311}
2312
2313IN_PROC_BROWSER_TEST_F(InstantExtendedTest, OverlaySendsSearchWhatYouTyped) {
2314  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2315  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2316
2317  // This input could be interpreted either as an URL or a query based on the
2318  // relative ranking of search-what-you-typed or url-what-you-typed.
2319  content::WindowedNotificationObserver autocomplete_observer(
2320      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
2321      content::NotificationService::AllSources());
2322  SetOmniboxText("define:foo");
2323  autocomplete_observer.Wait();
2324
2325  // In this case, we should treat [define:foo] as a query, so
2326  // search-what-you-typed should be the top suggestion.
2327  EXPECT_TRUE(ExecuteScript(
2328      "var sorted = chrome.embeddedSearch.searchBox.nativeSuggestions.sort("
2329          "function (a,b) {"
2330            "return b.rankingData.relevance - a.rankingData.relevance;"
2331          "});"));
2332  std::string type;
2333  EXPECT_TRUE(GetStringFromJS(instant()->GetOverlayContents(),
2334                              "sorted[0].type", &type));
2335  ASSERT_EQ("search-what-you-typed", type);
2336}
2337
2338IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
2339                       OverlayDoesNotEchoSearchProviderNAVSUGGEST) {
2340  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2341  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2342
2343  // Show the overlay so suggestions are allowed.
2344  SetOmniboxTextAndWaitForOverlayToShow("www.");
2345  content::WebContents* overlay = instant()->GetOverlayContents();
2346
2347  // Set a URL suggestion and wait for SearchProvider to echo it.
2348  content::WindowedNotificationObserver autocomplete_observer(
2349      chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
2350      content::NotificationService::AllSources());
2351  instant()->SetSuggestions(
2352      overlay,
2353      std::vector<InstantSuggestion>(
2354          1,
2355          InstantSuggestion(ASCIIToUTF16("http://www.example.com/"),
2356                            INSTANT_COMPLETE_NOW,
2357                            INSTANT_SUGGESTION_URL,
2358                            ASCIIToUTF16("www."),
2359                            kNoMatchIndex)));
2360  autocomplete_observer.Wait();
2361
2362  // Check that SearchProvider set a NAVSUGGEST match.
2363  bool have_navsuggest_match = false;
2364  SearchProvider* search_provider =
2365      omnibox()->model()->autocomplete_controller()->search_provider();
2366  for (ACMatches::const_iterator match = search_provider->matches().begin();
2367       match != search_provider->matches().end(); ++match) {
2368    if (match->type == AutocompleteMatchType::NAVSUGGEST) {
2369      have_navsuggest_match = true;
2370      break;
2371    }
2372  }
2373  ASSERT_TRUE(have_navsuggest_match);
2374
2375  // Check that InstantController did not send the NAVSUGGEST match.
2376  bool sent_navsuggest_match = true;
2377  EXPECT_TRUE(GetBoolFromJS(overlay,
2378      "chrome.embeddedSearch.searchBox.nativeSuggestions.some("
2379          "function (s) {"
2380            "return s.type == 'navsuggest';"
2381          "})", &sent_navsuggest_match));
2382  EXPECT_FALSE(sent_navsuggest_match);
2383}
2384
2385IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AcceptingURLSearchDoesNotNavigate) {
2386  // Get a committed Instant tab, which will be in the Instant process and thus
2387  // support chrome::GetSearchTerms().
2388  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2389  FocusOmniboxAndWaitForInstantOverlaySupport();
2390
2391  // Create an observer to wait for the instant tab to support Instant.
2392  content::WindowedNotificationObserver observer(
2393      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
2394      content::NotificationService::AllSources());
2395
2396  // Do a search and commit it.
2397  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("foo"));
2398  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
2399  browser()->window()->GetLocationBar()->AcceptInput();
2400  observer.Wait();
2401
2402  // Set URL-like search terms for the instant tab.
2403  content::WebContents* instant_tab = instant()->instant_tab()->contents();
2404  content::NavigationEntry* visible_entry =
2405      instant_tab->GetController().GetVisibleEntry();
2406  visible_entry->SetExtraData(sessions::kSearchTermsKey,
2407                              ASCIIToUTF16("http://example.com"));
2408  SetOmniboxText("http://example.com");
2409  omnibox()->model()->SetInputInProgress(false);
2410  omnibox()->CloseOmniboxPopup();
2411
2412  // Accept the omnibox input.
2413  EXPECT_FALSE(omnibox()->model()->user_input_in_progress());
2414  EXPECT_EQ(ToolbarModel::URL_LIKE_SEARCH_TERMS,
2415            browser()->toolbar_model()->GetSearchTermsType());
2416  GURL instant_tab_url = instant_tab->GetURL();
2417  browser()->window()->GetLocationBar()->AcceptInput();
2418  EXPECT_EQ(instant_tab_url, instant_tab->GetURL());
2419}
2420
2421IN_PROC_BROWSER_TEST_F(InstantExtendedTest, AcceptingJSSearchDoesNotRunJS) {
2422  // Get a committed Instant tab, which will be in the Instant process and thus
2423  // support chrome::GetSearchTerms().
2424  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2425  FocusOmniboxAndWaitForInstantOverlaySupport();
2426
2427  // Create an observer to wait for the instant tab to support Instant.
2428  content::WindowedNotificationObserver observer(
2429      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
2430      content::NotificationService::AllSources());
2431
2432  // Do a search and commit it.
2433  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("foo"));
2434  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
2435  browser()->window()->GetLocationBar()->AcceptInput();
2436  observer.Wait();
2437
2438  // Set URL-like search terms for the instant tab.
2439  content::WebContents* instant_tab = instant()->instant_tab()->contents();
2440  content::NavigationEntry* visible_entry =
2441      instant_tab->GetController().GetVisibleEntry();
2442  const char kEvilJS[] = "javascript:document.title='evil';1;";
2443  visible_entry->SetExtraData(sessions::kSearchTermsKey, ASCIIToUTF16(kEvilJS));
2444  SetOmniboxText(kEvilJS);
2445  omnibox()->model()->SetInputInProgress(false);
2446  omnibox()->CloseOmniboxPopup();
2447
2448  // Accept the omnibox input.
2449  EXPECT_FALSE(omnibox()->model()->user_input_in_progress());
2450  EXPECT_EQ(ToolbarModel::URL_LIKE_SEARCH_TERMS,
2451            browser()->toolbar_model()->GetSearchTermsType());
2452  browser()->window()->GetLocationBar()->AcceptInput();
2453  // Force some Javascript to run in the renderer so the inline javascript:
2454  // would be forced to run if it's going to.
2455  EXPECT_TRUE(content::ExecuteScript(instant_tab, "1;"));
2456  EXPECT_NE(ASCIIToUTF16("evil"), instant_tab->GetTitle());
2457}
2458
2459// Flaky on mac: http://crbug.com/242164
2460#if defined(OS_MACOSX)
2461#define MAYBE_ReloadSearchAfterBackReloadsCorrectQuery DISABLED_ReloadSearchAfterBackReloadsCorrectQuery
2462#else
2463#define MAYBE_ReloadSearchAfterBackReloadsCorrectQuery ReloadSearchAfterBackReloadsCorrectQuery
2464#endif
2465
2466IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
2467                       MAYBE_ReloadSearchAfterBackReloadsCorrectQuery) {
2468  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2469  FocusOmniboxAndWaitForInstantOverlaySupport();
2470
2471  // Create an observer to wait for the instant tab to support Instant.
2472  content::WindowedNotificationObserver observer(
2473      chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
2474      content::NotificationService::AllSources());
2475
2476  // Search for [foo].
2477  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("foo"));
2478  EXPECT_EQ(ASCIIToUTF16("foo"), omnibox()->GetText());
2479  browser()->window()->GetLocationBar()->AcceptInput();
2480  observer.Wait();
2481
2482  // Search again for [bar].
2483  content::WebContents* instant_tab = instant()->instant_tab()->contents();
2484  EXPECT_TRUE(content::ExecuteScript(instant_tab,
2485                                     "suggestion = 'bart';"));
2486  SetOmniboxTextAndWaitForSuggestion("bar");
2487  EXPECT_EQ(ASCIIToUTF16("t"), GetGrayText());
2488
2489  // Accept the new query and wait for the page to navigate.
2490  content::WindowedNotificationObserver nav_observer(
2491        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2492        content::NotificationService::AllSources());
2493  browser()->window()->GetLocationBar()->AcceptInput();
2494  nav_observer.Wait();
2495
2496  // Press back button and reload.
2497  content::WindowedNotificationObserver back_observer(
2498        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2499        content::NotificationService::AllSources());
2500  instant_tab->GetController().GoBack();
2501  back_observer.Wait();
2502  EXPECT_EQ("foo", GetOmniboxText());
2503  FocusOmnibox();
2504  content::WindowedNotificationObserver reload_observer(
2505        content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2506        content::NotificationService::AllSources());
2507  browser()->window()->GetLocationBar()->AcceptInput();
2508  reload_observer.Wait();
2509
2510  EXPECT_EQ("foo", GetOmniboxText());
2511}
2512
2513class InstantExtendedFirstTabTest : public InProcessBrowserTest,
2514                                    public InstantTestBase {
2515 public:
2516  InstantExtendedFirstTabTest() {}
2517 protected:
2518  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2519    command_line->AppendSwitch(switches::kEnableInstantExtendedAPI);
2520    command_line->AppendSwitch(switches::kDisableLocalFirstLoadNTP);
2521  }
2522};
2523
2524// Flaky: http://crbug.com/238863
2525IN_PROC_BROWSER_TEST_F(
2526    InstantExtendedFirstTabTest, DISABLED_RedirectToLocalOnLoadFailure) {
2527  // Create a new window to test the first NTP load.
2528  ui_test_utils::NavigateToURLWithDisposition(
2529      browser(),
2530      GURL(chrome::kChromeUINewTabURL),
2531      NEW_WINDOW,
2532      ui_test_utils::BROWSER_TEST_WAIT_FOR_BROWSER);
2533
2534  const BrowserList* native_browser_list = BrowserList::GetInstance(
2535      chrome::HOST_DESKTOP_TYPE_NATIVE);
2536  ASSERT_EQ(2u, native_browser_list->size());
2537  set_browser(native_browser_list->get(1));
2538
2539  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2540
2541  // Also make sure our instant_tab_ is loaded.
2542  if (!instant()->instant_tab_) {
2543    content::WindowedNotificationObserver instant_tab_observer(
2544        chrome::NOTIFICATION_INSTANT_TAB_SUPPORT_DETERMINED,
2545        content::NotificationService::AllSources());
2546    instant_tab_observer.Wait();
2547  }
2548
2549  // NTP contents should be preloaded.
2550  ASSERT_NE(static_cast<InstantNTP*>(NULL), instant()->ntp());
2551  EXPECT_TRUE(instant()->ntp()->IsLocal());
2552
2553  // Overlay contents should be preloaded.
2554  ASSERT_NE(static_cast<InstantOverlay*>(NULL), instant()->overlay());
2555  EXPECT_TRUE(instant()->overlay()->IsLocal());
2556
2557  // Instant tab contents should be preloaded.
2558  ASSERT_NE(static_cast<InstantTab*>(NULL), instant()->instant_tab());
2559  EXPECT_TRUE(instant()->instant_tab()->IsLocal());
2560}
2561
2562IN_PROC_BROWSER_TEST_F(InstantExtendedTest,
2563                       PageVisibilityEventOnCommit) {
2564  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2565  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2566
2567  // Set the text, and wait for suggestions to show up.
2568  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("search"));
2569
2570  content::WebContents* overlay = instant()->GetOverlayContents();
2571
2572  // Before commiting, verify visibility calls.
2573  int on_visibility_calls = -1;
2574  EXPECT_TRUE(GetIntFromJS(overlay, "onvisibilitycalls", &on_visibility_calls));
2575  EXPECT_EQ(1, on_visibility_calls);
2576
2577  // Commit the search by pressing Enter.
2578  browser()->window()->GetLocationBar()->AcceptInput();
2579
2580  // After commiting, verify visibility calls.
2581  on_visibility_calls = -1;
2582  EXPECT_TRUE(GetIntFromJS(overlay, "onvisibilitycalls", &on_visibility_calls));
2583  EXPECT_EQ(1, on_visibility_calls);
2584}
2585
2586// Test that if the LogDropdownShown() call records a histogram value.
2587IN_PROC_BROWSER_TEST_F(InstantExtendedTest, LogDropdownShown) {
2588  ASSERT_NO_FATAL_FAILURE(SetupInstant(browser()));
2589  FocusOmniboxAndWaitForInstantOverlayAndNTPSupport();
2590  int64 histogramValue = GetHistogramCount("Instant.TimeToFirstShowFromWeb");
2591  ASSERT_TRUE(SetOmniboxTextAndWaitForOverlayToShow("a"));
2592  EXPECT_EQ(histogramValue + 1,
2593            GetHistogramCount("Instant.TimeToFirstShowFromWeb"));
2594}
2595