Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / search / search_unittest.cc
1 // Copyright (c) 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 "base/command_line.h"
6 #include "base/metrics/field_trial.h"
7 #include "base/metrics/histogram_base.h"
8 #include "base/metrics/histogram_samples.h"
9 #include "base/metrics/statistics_recorder.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/browser/managed_mode/managed_mode_url_filter.h"
13 #include "chrome/browser/managed_mode/managed_user_service.h"
14 #include "chrome/browser/managed_mode/managed_user_service_factory.h"
15 #include "chrome/browser/search/instant_service.h"
16 #include "chrome/browser/search/instant_service_factory.h"
17 #include "chrome/browser/search/search.h"
18 #include "chrome/browser/search_engines/search_terms_data.h"
19 #include "chrome/browser/search_engines/template_url_service.h"
20 #include "chrome/browser/search_engines/template_url_service_factory.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/common/pref_names.h"
24 #include "chrome/common/url_constants.h"
25 #include "chrome/test/base/browser_with_test_window_test.h"
26 #include "chrome/test/base/ui_test_utils.h"
27 #include "components/variations/entropy_provider.h"
28 #include "content/public/browser/render_process_host.h"
29 #include "content/public/browser/render_view_host.h"
30 #include "content/public/browser/site_instance.h"
31 #include "content/public/browser/web_contents.h"
32 #include "content/public/common/renderer_preferences.h"
33 #include "url/gurl.h"
34
35 namespace chrome {
36
37 class EmbeddedSearchFieldTrialTest : public testing::Test {
38  protected:
39   virtual void SetUp() {
40     field_trial_list_.reset(new base::FieldTrialList(
41         new metrics::SHA1EntropyProvider("42")));
42     base::StatisticsRecorder::Initialize();
43   }
44
45  private:
46   scoped_ptr<base::FieldTrialList> field_trial_list_;
47 };
48
49 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoEmptyAndValid) {
50   FieldTrialFlags flags;
51
52   EXPECT_TRUE(GetFieldTrialInfo(&flags));
53   EXPECT_EQ(0ul, flags.size());
54
55   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
56                                                      "Group77"));
57   EXPECT_TRUE(GetFieldTrialInfo(&flags));
58   EXPECT_EQ(0ul, flags.size());
59 }
60
61 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoInvalidNumber) {
62   FieldTrialFlags flags;
63
64   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
65                                                      "Group77.2"));
66   EXPECT_TRUE(GetFieldTrialInfo(&flags));
67   EXPECT_EQ(0ul, flags.size());
68 }
69
70 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoInvalidName) {
71   FieldTrialFlags flags;
72
73   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
74                                                      "Invalid77"));
75   EXPECT_TRUE(GetFieldTrialInfo(&flags));
76   EXPECT_EQ(0ul, flags.size());
77 }
78
79 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoValidGroup) {
80   FieldTrialFlags flags;
81
82   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
83                                                      "Group77"));
84   EXPECT_TRUE(GetFieldTrialInfo(&flags));
85   EXPECT_EQ(0ul, flags.size());
86 }
87
88 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoValidFlag) {
89   FieldTrialFlags flags;
90
91   EXPECT_EQ(9999ul, GetUInt64ValueForFlagWithDefault("foo", 9999, flags));
92   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
93                                                      "Group77 foo:6"));
94   EXPECT_TRUE(GetFieldTrialInfo(&flags));
95   EXPECT_EQ(1ul, flags.size());
96   EXPECT_EQ(6ul, GetUInt64ValueForFlagWithDefault("foo", 9999, flags));
97 }
98
99 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoNewName) {
100   FieldTrialFlags flags;
101
102   EXPECT_EQ(9999ul, GetUInt64ValueForFlagWithDefault("foo", 9999, flags));
103   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
104                                                      "Group77 foo:6"));
105   EXPECT_TRUE(GetFieldTrialInfo(&flags));
106   EXPECT_EQ(1ul, flags.size());
107   EXPECT_EQ(6ul, GetUInt64ValueForFlagWithDefault("foo", 9999, flags));
108 }
109
110 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoNewNameOverridesOld) {
111   FieldTrialFlags flags;
112
113   EXPECT_EQ(9999ul, GetUInt64ValueForFlagWithDefault("foo", 9999, flags));
114   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
115                                                      "Group77 foo:6"));
116   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("InstantExtended",
117                                                      "Group78 foo:5"));
118   EXPECT_TRUE(GetFieldTrialInfo(&flags));
119   EXPECT_EQ(1ul, flags.size());
120   EXPECT_EQ(6ul, GetUInt64ValueForFlagWithDefault("foo", 9999, flags));
121 }
122
123 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoLotsOfFlags) {
124   FieldTrialFlags flags;
125
126   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
127       "EmbeddedSearch", "Group77 bar:1 baz:7 cat:dogs"));
128   EXPECT_TRUE(GetFieldTrialInfo(&flags));
129   EXPECT_EQ(3ul, flags.size());
130   EXPECT_EQ(true, GetBoolValueForFlagWithDefault("bar", false, flags));
131   EXPECT_EQ(7ul, GetUInt64ValueForFlagWithDefault("baz", 0, flags));
132   EXPECT_EQ("dogs",
133             GetStringValueForFlagWithDefault("cat", std::string(), flags));
134   EXPECT_EQ("default",
135             GetStringValueForFlagWithDefault("moose", "default", flags));
136 }
137
138 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoDisabled) {
139   FieldTrialFlags flags;
140
141   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
142       "EmbeddedSearch", "Group77 bar:1 baz:7 cat:dogs DISABLED"));
143   EXPECT_FALSE(GetFieldTrialInfo(&flags));
144   EXPECT_EQ(0ul, flags.size());
145 }
146
147 TEST_F(EmbeddedSearchFieldTrialTest, GetFieldTrialInfoControlFlags) {
148   FieldTrialFlags flags;
149
150   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
151       "EmbeddedSearch", "Control77 bar:1 baz:7 cat:dogs"));
152   EXPECT_TRUE(GetFieldTrialInfo(&flags));
153   EXPECT_EQ(3ul, flags.size());
154 }
155
156 class SearchTest : public BrowserWithTestWindowTest {
157  protected:
158   virtual void SetUp() OVERRIDE {
159     BrowserWithTestWindowTest::SetUp();
160     field_trial_list_.reset(new base::FieldTrialList(
161         new metrics::SHA1EntropyProvider("42")));
162     TemplateURLServiceFactory::GetInstance()->SetTestingFactoryAndUse(
163         profile(), &TemplateURLServiceFactory::BuildInstanceFor);
164     TemplateURLService* template_url_service =
165         TemplateURLServiceFactory::GetForProfile(profile());
166     ui_test_utils::WaitForTemplateURLServiceToLoad(template_url_service);
167     SetSearchProvider(true, false);
168   }
169
170   virtual void SetSearchProvider(bool set_ntp_url, bool insecure_ntp_url) {
171     TemplateURLService* template_url_service =
172         TemplateURLServiceFactory::GetForProfile(profile());
173     TemplateURLData data;
174     data.SetURL("http://foo.com/url?bar={searchTerms}");
175     data.instant_url = "http://foo.com/instant?"
176         "{google:omniboxStartMarginParameter}{google:forceInstantResults}"
177         "foo=foo#foo=foo&strk";
178     if (set_ntp_url) {
179       data.new_tab_url = (insecure_ntp_url ? "http" : "https") +
180           std::string("://foo.com/newtab?strk");
181     }
182     data.alternate_urls.push_back("http://foo.com/alt#quux={searchTerms}");
183     data.search_terms_replacement_key = "strk";
184
185     TemplateURL* template_url = new TemplateURL(profile(), data);
186     // Takes ownership of |template_url|.
187     template_url_service->Add(template_url);
188     template_url_service->SetDefaultSearchProvider(template_url);
189   }
190
191   // Build an Instant URL with or without a valid search terms replacement key
192   // as per |has_search_term_replacement_key|. Set that URL as the instant URL
193   // for the default search provider.
194   void SetDefaultInstantTemplateUrl(bool has_search_term_replacement_key) {
195     TemplateURLService* template_url_service =
196         TemplateURLServiceFactory::GetForProfile(profile());
197
198     static const char kInstantURLWithStrk[] =
199         "http://foo.com/instant?foo=foo#foo=foo&strk";
200     static const char kInstantURLNoStrk[] =
201         "http://foo.com/instant?foo=foo#foo=foo";
202
203     TemplateURLData data;
204     data.SetURL("http://foo.com/url?bar={searchTerms}");
205     data.instant_url = (has_search_term_replacement_key ?
206         kInstantURLWithStrk : kInstantURLNoStrk);
207     data.search_terms_replacement_key = "strk";
208
209     TemplateURL* template_url = new TemplateURL(profile(), data);
210     // Takes ownership of |template_url|.
211     template_url_service->Add(template_url);
212     template_url_service->SetDefaultSearchProvider(template_url);
213   }
214
215   bool InInstantProcess(const content::WebContents* contents) {
216     InstantService* instant_service =
217         InstantServiceFactory::GetForProfile(profile());
218     return instant_service->IsInstantProcess(
219         contents->GetRenderProcessHost()->GetID());
220   }
221
222   scoped_ptr<base::FieldTrialList> field_trial_list_;
223 };
224
225 struct SearchTestCase {
226   const char* url;
227   bool expected_result;
228   const char* comment;
229 };
230
231 TEST_F(SearchTest, ShouldAssignURLToInstantRendererExtendedEnabled) {
232   EnableQueryExtractionForTesting();
233
234   const SearchTestCase kTestCases[] = {
235     {chrome::kChromeSearchLocalNtpUrl, true,  ""},
236     {"https://foo.com/instant?strk",   true,  ""},
237     {"https://foo.com/instant#strk",   true,  ""},
238     {"https://foo.com/instant?strk=0", true,  ""},
239     {"https://foo.com/url?strk",       true,  ""},
240     {"https://foo.com/alt?strk",       true,  ""},
241     {"http://foo.com/instant",         false, "Non-HTTPS"},
242     {"http://foo.com/instant?strk",    false, "Non-HTTPS"},
243     {"http://foo.com/instant?strk=1",  false, "Non-HTTPS"},
244     {"https://foo.com/instant",        false, "No search terms replacement"},
245     {"https://foo.com/?strk",          false, "Non-exact path"},
246   };
247
248   for (size_t i = 0; i < arraysize(kTestCases); ++i) {
249     const SearchTestCase& test = kTestCases[i];
250     EXPECT_EQ(test.expected_result,
251               ShouldAssignURLToInstantRenderer(GURL(test.url), profile()))
252         << test.url << " " << test.comment;
253   }
254 }
255
256 TEST_F(SearchTest, ShouldAssignURLToInstantRendererExtendedEnabledNotOnSRP) {
257   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
258       "EmbeddedSearch", "Group1 espv:2 suppress_on_srp:1"));
259
260   const SearchTestCase kTestCases[] = {
261     {chrome::kChromeSearchLocalNtpUrl, true,  ""},
262     {"https://foo.com/instant?strk",   true,  ""},
263     {"https://foo.com/instant#strk",   true,  ""},
264     {"https://foo.com/instant?strk=0", true,  ""},
265     {"https://foo.com/url?strk",       false, "Disabled on SRP"},
266     {"https://foo.com/alt?strk",       false, "Disabled ON SRP"},
267     {"http://foo.com/instant",         false, "Non-HTTPS"},
268     {"http://foo.com/instant?strk",    false, "Non-HTTPS"},
269     {"http://foo.com/instant?strk=1",  false, "Non-HTTPS"},
270     {"https://foo.com/instant",        false, "No search terms replacement"},
271     {"https://foo.com/?strk",          false, "Non-exact path"},
272   };
273
274   for (size_t i = 0; i < arraysize(kTestCases); ++i) {
275     const SearchTestCase& test = kTestCases[i];
276     EXPECT_EQ(test.expected_result,
277               ShouldAssignURLToInstantRenderer(GURL(test.url), profile()))
278         << test.url << " " << test.comment;
279   }
280 }
281
282 TEST_F(SearchTest, ShouldUseProcessPerSiteForInstantURL) {
283   EnableQueryExtractionForTesting();
284
285   const SearchTestCase kTestCases[] = {
286     {"chrome-search://local-ntp",      true,  "Local NTP"},
287     {"chrome-search://remote-ntp",     true,  "Remote NTP"},
288     {"invalid-scheme://local-ntp",     false, "Invalid Local NTP URL"},
289     {"invalid-scheme://online-ntp",    false, "Invalid Online NTP URL"},
290     {"chrome-search://foo.com",        false, "Search result page"},
291     {"https://foo.com/instant?strk",   false,  ""},
292     {"https://foo.com/instant#strk",   false,  ""},
293     {"https://foo.com/instant?strk=0", false,  ""},
294     {"https://foo.com/url?strk",       false,  ""},
295     {"https://foo.com/alt?strk",       false,  ""},
296     {"http://foo.com/instant",         false,  "Non-HTTPS"},
297     {"http://foo.com/instant?strk",    false,  "Non-HTTPS"},
298     {"http://foo.com/instant?strk=1",  false,  "Non-HTTPS"},
299     {"https://foo.com/instant",        false,  "No search terms replacement"},
300     {"https://foo.com/?strk",          false,  "Non-exact path"},
301   };
302
303   for (size_t i = 0; i < arraysize(kTestCases); ++i) {
304     const SearchTestCase& test = kTestCases[i];
305     EXPECT_EQ(test.expected_result,
306               ShouldUseProcessPerSiteForInstantURL(GURL(test.url), profile()))
307         << test.url << " " << test.comment;
308   }
309 }
310
311 // Each test case represents a navigation to |start_url| followed by a
312 // navigation to |end_url|. We will check whether each navigation lands in an
313 // Instant process, and also whether the navigation from start to end re-uses
314 // the same SiteInstance (and hence the same RenderViewHost, etc.).
315 const struct ProcessIsolationTestCase {
316   const char* description;
317   const char* start_url;
318   bool start_in_instant_process;
319   const char* end_url;
320   bool end_in_instant_process;
321   bool same_site_instance;
322 } kProcessIsolationTestCases[] = {
323   {"Local NTP -> SRP",
324    "chrome-search://local-ntp",       true,
325    "https://foo.com/url?strk",        true,   false },
326   {"Local NTP -> Regular",
327    "chrome-search://local-ntp",       true,
328    "https://foo.com/other",           false,  false },
329   {"Remote NTP -> SRP",
330    "https://foo.com/newtab?strk",     true,
331    "https://foo.com/url?strk",        true,   false },
332   {"Remote NTP -> Regular",
333    "https://foo.com/newtab?strk",     true,
334    "https://foo.com/other",           false,  false },
335   {"SRP -> SRP",
336    "https://foo.com/url?strk",        true,
337    "https://foo.com/url?strk",        true,   true  },
338   {"SRP -> Regular",
339    "https://foo.com/url?strk",        true,
340    "https://foo.com/other",           false,  false },
341   {"Regular -> SRP",
342    "https://foo.com/other",           false,
343    "https://foo.com/url?strk",        true,   false },
344 };
345
346 TEST_F(SearchTest, ProcessIsolation) {
347   EnableQueryExtractionForTesting();
348
349   for (size_t i = 0; i < arraysize(kProcessIsolationTestCases); ++i) {
350     const ProcessIsolationTestCase& test = kProcessIsolationTestCases[i];
351     AddTab(browser(), GURL("chrome://blank"));
352     const content::WebContents* contents =
353         browser()->tab_strip_model()->GetActiveWebContents();
354
355     // Navigate to start URL.
356     NavigateAndCommitActiveTab(GURL(test.start_url));
357     EXPECT_EQ(test.start_in_instant_process, InInstantProcess(contents))
358         << test.description;
359
360     // Save state.
361     const scoped_refptr<content::SiteInstance> start_site_instance =
362         contents->GetSiteInstance();
363     const content::RenderProcessHost* start_rph =
364         contents->GetRenderProcessHost();
365     const content::RenderViewHost* start_rvh =
366         contents->GetRenderViewHost();
367
368     // Navigate to end URL.
369     NavigateAndCommitActiveTab(GURL(test.end_url));
370     EXPECT_EQ(test.end_in_instant_process, InInstantProcess(contents))
371         << test.description;
372
373     EXPECT_EQ(test.same_site_instance,
374               start_site_instance == contents->GetSiteInstance())
375         << test.description;
376     EXPECT_EQ(test.same_site_instance,
377               start_rvh == contents->GetRenderViewHost())
378         << test.description;
379     EXPECT_EQ(test.same_site_instance,
380               start_rph == contents->GetRenderProcessHost())
381         << test.description;
382   }
383 }
384
385 TEST_F(SearchTest, ProcessIsolation_RendererInitiated) {
386   EnableQueryExtractionForTesting();
387
388   for (size_t i = 0; i < arraysize(kProcessIsolationTestCases); ++i) {
389     const ProcessIsolationTestCase& test = kProcessIsolationTestCases[i];
390     AddTab(browser(), GURL("chrome://blank"));
391     content::WebContents* contents =
392         browser()->tab_strip_model()->GetActiveWebContents();
393
394     // Navigate to start URL.
395     NavigateAndCommitActiveTab(GURL(test.start_url));
396     EXPECT_EQ(test.start_in_instant_process, InInstantProcess(contents))
397         << test.description;
398
399     // Save state.
400     const scoped_refptr<content::SiteInstance> start_site_instance =
401         contents->GetSiteInstance();
402     const content::RenderProcessHost* start_rph =
403         contents->GetRenderProcessHost();
404     const content::RenderViewHost* start_rvh =
405         contents->GetRenderViewHost();
406
407     // Navigate to end URL via a renderer-initiated navigation.
408     content::NavigationController* controller = &contents->GetController();
409     content::NavigationController::LoadURLParams load_params(
410         GURL(test.end_url));
411     load_params.is_renderer_initiated = true;
412     load_params.transition_type = content::PAGE_TRANSITION_LINK;
413
414     controller->LoadURLWithParams(load_params);
415     CommitPendingLoad(controller);
416     EXPECT_EQ(test.end_in_instant_process, InInstantProcess(contents))
417         << test.description;
418
419     EXPECT_EQ(test.same_site_instance,
420               start_site_instance == contents->GetSiteInstance())
421         << test.description;
422     EXPECT_EQ(test.same_site_instance,
423               start_rvh == contents->GetRenderViewHost())
424         << test.description;
425     EXPECT_EQ(test.same_site_instance,
426               start_rph == contents->GetRenderProcessHost())
427         << test.description;
428   }
429 }
430
431 const SearchTestCase kInstantNTPTestCases[] = {
432   {"https://foo.com/instant?strk",         false, "Valid Instant URL"},
433   {"https://foo.com/instant#strk",         false, "Valid Instant URL"},
434   {"https://foo.com/url?strk",             false, "Valid search URL"},
435   {"https://foo.com/url#strk",             false, "Valid search URL"},
436   {"https://foo.com/alt?strk",             false, "Valid alternative URL"},
437   {"https://foo.com/alt#strk",             false, "Valid alternative URL"},
438   {"https://foo.com/url?strk&bar=",        false, "No query terms"},
439   {"https://foo.com/url?strk&q=abc",       false, "No query terms key"},
440   {"https://foo.com/url?strk#bar=abc",     false, "Query terms key in ref"},
441   {"https://foo.com/url?strk&bar=abc",     false, "Has query terms"},
442   {"http://foo.com/instant?strk=1",        false, "Insecure URL"},
443   {"https://foo.com/instant",              false, "No search term replacement"},
444   {"chrome://blank/",                      false, "Chrome scheme"},
445   {"chrome-search://foo",                  false, "Chrome-search scheme"},
446   {"https://bar.com/instant?strk=1",       false, "Random non-search page"},
447   {chrome::kChromeSearchLocalNtpUrl,       true,  "Local new tab page"},
448   {"https://foo.com/newtab?strk",          true,  "New tab URL"},
449   {"http://foo.com/newtab?strk",           false, "Insecure New tab URL"},
450 };
451
452 TEST_F(SearchTest, InstantNTPExtendedEnabled) {
453   EnableQueryExtractionForTesting();
454   AddTab(browser(), GURL("chrome://blank"));
455   for (size_t i = 0; i < arraysize(kInstantNTPTestCases); ++i) {
456     const SearchTestCase& test = kInstantNTPTestCases[i];
457     NavigateAndCommitActiveTab(GURL(test.url));
458     const content::WebContents* contents =
459         browser()->tab_strip_model()->GetWebContentsAt(0);
460     EXPECT_EQ(test.expected_result, IsInstantNTP(contents))
461         << test.url << " " << test.comment;
462   }
463 }
464
465 TEST_F(SearchTest, InstantNTPCustomNavigationEntry) {
466   EnableQueryExtractionForTesting();
467   AddTab(browser(), GURL("chrome://blank"));
468   for (size_t i = 0; i < arraysize(kInstantNTPTestCases); ++i) {
469     const SearchTestCase& test = kInstantNTPTestCases[i];
470     NavigateAndCommitActiveTab(GURL(test.url));
471     content::WebContents* contents =
472         browser()->tab_strip_model()->GetWebContentsAt(0);
473     content::NavigationController& controller = contents->GetController();
474     controller.SetTransientEntry(
475         controller.CreateNavigationEntry(GURL("chrome://blank"),
476                                          content::Referrer(),
477                                          content::PAGE_TRANSITION_LINK,
478                                          false,
479                                          std::string(),
480                                          contents->GetBrowserContext()));
481     // The active entry is chrome://blank and not an NTP.
482     EXPECT_FALSE(IsInstantNTP(contents));
483     EXPECT_EQ(test.expected_result,
484               NavEntryIsInstantNTP(contents,
485                                    controller.GetLastCommittedEntry()))
486         << test.url << " " << test.comment;
487   }
488 }
489
490 TEST_F(SearchTest, InstantCacheableNTPNavigationEntry) {
491   AddTab(browser(), GURL("chrome://blank"));
492   content::WebContents* contents =
493         browser()->tab_strip_model()->GetWebContentsAt(0);
494   content::NavigationController& controller = contents->GetController();
495   // Local NTP.
496   NavigateAndCommitActiveTab(GURL(chrome::kChromeSearchLocalNtpUrl));
497   EXPECT_TRUE(NavEntryIsInstantNTP(contents,
498                                    controller.GetLastCommittedEntry()));
499   // Instant page is not cacheable NTP.
500   NavigateAndCommitActiveTab(GetInstantURL(profile(), kDisableStartMargin,
501                                            false));
502   EXPECT_FALSE(NavEntryIsInstantNTP(contents,
503                                     controller.GetLastCommittedEntry()));
504   // Test Cacheable NTP
505   NavigateAndCommitActiveTab(chrome::GetNewTabPageURL(profile()));
506   EXPECT_TRUE(NavEntryIsInstantNTP(contents,
507                                    controller.GetLastCommittedEntry()));
508 }
509
510 TEST_F(SearchTest, InstantCacheableNTPNavigationEntryNewProfile) {
511   SetSearchProvider(false, false);
512   AddTab(browser(), GURL(chrome::kChromeUINewTabURL));
513   content::WebContents* contents =
514         browser()->tab_strip_model()->GetWebContentsAt(0);
515   content::NavigationController& controller = contents->GetController();
516   // Test virtual url chrome://newtab  for first NTP of a new profile
517   EXPECT_TRUE(NavEntryIsInstantNTP(contents,
518                                    controller.GetLastCommittedEntry()));
519   // The new_tab_url gets set after the first NTP is visible.
520   SetSearchProvider(true, false);
521   EXPECT_TRUE(NavEntryIsInstantNTP(contents,
522                                    controller.GetLastCommittedEntry()));
523 }
524
525 TEST_F(SearchTest, NoRewriteInIncognito) {
526   profile()->ForceIncognito(true);
527   EXPECT_EQ(GURL(), chrome::GetNewTabPageURL(profile()));
528   GURL new_tab_url(chrome::kChromeUINewTabURL);
529   EXPECT_FALSE(HandleNewTabURLRewrite(&new_tab_url, profile()));
530   EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), new_tab_url);
531 }
532
533 TEST_F(SearchTest, UseLocalNTPIfNTPURLIsInsecure) {
534   // Set an insecure new tab page URL and verify that it's ignored.
535   SetSearchProvider(true, true);
536   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl),
537             chrome::GetNewTabPageURL(profile()));
538   GURL new_tab_url(chrome::kChromeUINewTabURL);
539   EXPECT_TRUE(HandleNewTabURLRewrite(&new_tab_url, profile()));
540   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), new_tab_url);
541 }
542
543 TEST_F(SearchTest, UseLocalNTPIfNTPURLIsNotSet) {
544   // Set an insecure new tab page URL and verify that it's ignored.
545   SetSearchProvider(false, true);
546   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl),
547             chrome::GetNewTabPageURL(profile()));
548   GURL new_tab_url(chrome::kChromeUINewTabURL);
549   EXPECT_TRUE(HandleNewTabURLRewrite(&new_tab_url, profile()));
550   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), new_tab_url);
551 }
552
553 TEST_F(SearchTest, UseLocalNTPIfNTPURLIsBlockedForSupervisedUser) {
554   // Block access to foo.com in the URL filter.
555   ManagedUserService* managed_user_service =
556       ManagedUserServiceFactory::GetForProfile(profile());
557   ManagedModeURLFilter* url_filter =
558       managed_user_service->GetURLFilterForUIThread();
559   std::map<std::string, bool> hosts;
560   hosts["foo.com"] = false;
561   url_filter->SetManualHosts(&hosts);
562
563   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl),
564             chrome::GetNewTabPageURL(profile()));
565   GURL new_tab_url(chrome::kChromeUINewTabURL);
566   EXPECT_TRUE(HandleNewTabURLRewrite(&new_tab_url, profile()));
567   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), new_tab_url);
568   EXPECT_EQ(GURL(), GetInstantURL(profile(), kDisableStartMargin, false));
569 }
570
571 TEST_F(SearchTest, GetInstantURL) {
572   // No Instant URL because "strk" is missing.
573   SetDefaultInstantTemplateUrl(false);
574   EXPECT_EQ(GURL(), GetInstantURL(profile(), kDisableStartMargin, false));
575
576   // Set an Instant URL with a valid search terms replacement key.
577   SetDefaultInstantTemplateUrl(true);
578
579   // Now there should be a valid Instant URL. Note the HTTPS "upgrade".
580   EXPECT_EQ(GURL("https://foo.com/instant?foo=foo#foo=foo&strk"),
581             GetInstantURL(profile(), kDisableStartMargin, false));
582
583   // Enable suggest. No difference.
584   profile()->GetPrefs()->SetBoolean(prefs::kSearchSuggestEnabled, true);
585   EXPECT_EQ(GURL("https://foo.com/instant?foo=foo#foo=foo&strk"),
586             GetInstantURL(profile(), kDisableStartMargin, false));
587
588   // Disable suggest. No Instant URL.
589   profile()->GetPrefs()->SetBoolean(prefs::kSearchSuggestEnabled, false);
590   EXPECT_EQ(GURL(), GetInstantURL(profile(), kDisableStartMargin, false));
591 }
592
593 TEST_F(SearchTest, StartMarginCGI) {
594   // No margin.
595   profile()->GetPrefs()->SetBoolean(prefs::kSearchSuggestEnabled, true);
596
597   EXPECT_EQ(GURL("https://foo.com/instant?foo=foo#foo=foo&strk"),
598             GetInstantURL(profile(), kDisableStartMargin, false));
599
600   // With start margin.
601   EXPECT_EQ(GURL("https://foo.com/instant?es_sm=10&foo=foo#foo=foo&strk"),
602             GetInstantURL(profile(), 10, false));
603 }
604
605 TEST_F(SearchTest, InstantSearchEnabledCGI) {
606   // Disable Instant Search.
607   // Make sure {google:forceInstantResults} is not set in the Instant URL.
608   EXPECT_EQ(GURL("https://foo.com/instant?foo=foo#foo=foo&strk"),
609             GetInstantURL(profile(), kDisableStartMargin, false));
610
611   // Enable Instant Search.
612   // Make sure {google:forceInstantResults} is set in the Instant URL.
613   EXPECT_EQ(GURL("https://foo.com/instant?ion=1&foo=foo#foo=foo&strk"),
614             GetInstantURL(profile(), kDisableStartMargin, true));
615 }
616
617 TEST_F(SearchTest, CommandLineOverrides) {
618   GURL local_instant_url(GetLocalInstantURL(profile()));
619   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), local_instant_url);
620
621   TemplateURLService* template_url_service =
622       TemplateURLServiceFactory::GetForProfile(profile());
623   TemplateURLData data;
624   data.SetURL("{google:baseURL}search?q={searchTerms}");
625   data.instant_url = "{google:baseURL}webhp?strk";
626   data.search_terms_replacement_key = "strk";
627   TemplateURL* template_url = new TemplateURL(profile(), data);
628   // Takes ownership of |template_url|.
629   template_url_service->Add(template_url);
630   template_url_service->SetDefaultSearchProvider(template_url);
631
632   // By default, Instant Extended forces the instant URL to be HTTPS, so even if
633   // we set a Google base URL that is HTTP, we should get an HTTPS URL.
634   UIThreadSearchTermsData::SetGoogleBaseURL("http://www.foo.com/");
635   GURL instant_url(GetInstantURL(profile(), kDisableStartMargin, false));
636   ASSERT_TRUE(instant_url.is_valid());
637   EXPECT_EQ("https://www.foo.com/webhp?strk", instant_url.spec());
638
639   // However, if the Google base URL is specified on the command line, the
640   // instant URL should just use it, even if it's HTTP.
641   UIThreadSearchTermsData::SetGoogleBaseURL(std::string());
642   CommandLine::ForCurrentProcess()->AppendSwitchASCII(switches::kGoogleBaseURL,
643                                                       "http://www.bar.com/");
644   instant_url = GetInstantURL(profile(), kDisableStartMargin, false);
645   ASSERT_TRUE(instant_url.is_valid());
646   EXPECT_EQ("http://www.bar.com/webhp?strk", instant_url.spec());
647
648   // Similarly, setting a Google base URL on the command line should allow you
649   // to get the Google version of the local NTP, even though search provider's
650   // URL doesn't contain "google".
651   local_instant_url = GetLocalInstantURL(profile());
652   EXPECT_EQ(GURL(chrome::kChromeSearchLocalNtpUrl), local_instant_url);
653
654   // If we specify extra search query params, they should be inserted into the
655   // query portion of the instant URL.
656   CommandLine::ForCurrentProcess()->AppendSwitchASCII(
657       switches::kExtraSearchQueryParams, "a=b");
658   instant_url = GetInstantURL(profile(), kDisableStartMargin, false);
659   ASSERT_TRUE(instant_url.is_valid());
660   EXPECT_EQ("http://www.bar.com/webhp?a=b&strk", instant_url.spec());
661 }
662
663 TEST_F(SearchTest, ShouldPrefetchSearchResults_InstantExtendedAPIEnabled) {
664   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
665       "EmbeddedSearch",
666       "Group1 espv:2 prefetch_results:1"));
667   EXPECT_TRUE(ShouldPrefetchSearchResults());
668 #if defined(OS_IOS) || defined(OS_ANDROID)
669   EXPECT_EQ(1ul, EmbeddedSearchPageVersion());
670 #else
671   EXPECT_EQ(2ul, EmbeddedSearchPageVersion());
672 #endif
673 }
674
675 TEST_F(SearchTest, ShouldPrefetchSearchResults_DisabledViaFieldTrial) {
676   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
677       "EmbeddedSearch",
678       "Group1 espv:89 prefetch_results:0"));
679   EXPECT_FALSE(ShouldPrefetchSearchResults());
680   EXPECT_EQ(89ul, EmbeddedSearchPageVersion());
681 }
682
683 TEST_F(SearchTest, ShouldPrefetchSearchResults_EnabledViaFieldTrial) {
684   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
685       "EmbeddedSearch",
686       "Group1 espv:80 prefetch_results:1"));
687   EXPECT_TRUE(ShouldPrefetchSearchResults());
688   EXPECT_EQ(80ul, EmbeddedSearchPageVersion());
689 }
690
691 TEST_F(SearchTest, ShouldPrefetchSearchResults_EnabledViaCommandLine) {
692   CommandLine::ForCurrentProcess()->AppendSwitch(
693       switches::kPrefetchSearchResults);
694   // Command-line enable should override Finch.
695   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
696       "EmbeddedSearch",
697       "Group1 espv:80 prefetch_results:0"));
698   EXPECT_TRUE(ShouldPrefetchSearchResults());
699   EXPECT_EQ(80ul, EmbeddedSearchPageVersion());
700 }
701
702 TEST_F(SearchTest,
703        ShouldReuseInstantSearchBasePage_PrefetchResultsFlagDisabled) {
704   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
705       "EmbeddedSearch",
706       "Group1 espv:89 prefetch_results:0 reuse_instant_search_base_page:1"));
707   EXPECT_FALSE(ShouldPrefetchSearchResults());
708   EXPECT_FALSE(ShouldReuseInstantSearchBasePage());
709   EXPECT_EQ(89ul, EmbeddedSearchPageVersion());
710 }
711
712 TEST_F(SearchTest, ShouldReuseInstantSearchBasePage_EnabledViaFieldTrial) {
713   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
714       "EmbeddedSearch",
715       "Group1 espv:89 prefetch_results:1 reuse_instant_search_base_page:1"));
716   EXPECT_TRUE(ShouldReuseInstantSearchBasePage());
717   EXPECT_EQ(89ul, EmbeddedSearchPageVersion());
718 }
719
720 TEST_F(SearchTest, ShouldReuseInstantSearchBasePage_DisabledViaFieldTrial) {
721   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
722       "EmbeddedSearch",
723       "Group1 espv:89 prefetch_results:1 reuse_instant_search_base_page:0"));
724   EXPECT_FALSE(ShouldReuseInstantSearchBasePage());
725   EXPECT_EQ(89ul, EmbeddedSearchPageVersion());
726 }
727
728 TEST_F(SearchTest, ShouldShowGoogleLocalNTP_Default) {
729   EXPECT_TRUE(ShouldShowGoogleLocalNTP());
730 }
731
732 TEST_F(SearchTest, ShouldShowGoogleLocalNTP_EnabledViaFinch) {
733   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
734       "EmbeddedSearch", "Group1 espv:2 google_local_ntp:1"));
735   EXPECT_TRUE(ShouldShowGoogleLocalNTP());
736 }
737
738 TEST_F(SearchTest, ShouldShowGoogleLocalNTP_DisabledViaFinch) {
739   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
740       "EmbeddedSearch", "Group1 espv:2 google_local_ntp:0"));
741   EXPECT_FALSE(ShouldShowGoogleLocalNTP());
742 }
743
744 TEST_F(SearchTest, ShouldReuseInstantSearchBasePage_EnabledViaCommandLine) {
745   CommandLine::ForCurrentProcess()->AppendSwitch(
746       switches::kPrefetchSearchResults);
747   // Command-line enable should override Finch.
748   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
749       "EmbeddedSearch",
750       "Group1 espv:89 prefetch_results:0 reuse_instant_search_base_page:0"));
751   EXPECT_TRUE(ShouldPrefetchSearchResults());
752   EXPECT_TRUE(ShouldReuseInstantSearchBasePage());
753   EXPECT_EQ(89ul, EmbeddedSearchPageVersion());
754 }
755
756 TEST_F(SearchTest, IsNTPURL) {
757   GURL invalid_url;
758   GURL ntp_url(chrome::kChromeUINewTabURL);
759   GURL local_ntp_url(GetLocalInstantURL(profile()));
760
761   EXPECT_FALSE(chrome::IsNTPURL(invalid_url, profile()));
762   // No margin.
763   EnableQueryExtractionForTesting();
764   profile()->GetPrefs()->SetBoolean(prefs::kSearchSuggestEnabled, true);
765   GURL remote_ntp_url(GetInstantURL(profile(), kDisableStartMargin, false));
766   GURL search_url_with_search_terms("https://foo.com/url?strk&bar=abc");
767   GURL search_url_without_search_terms("https://foo.com/url?strk&bar");
768
769   EXPECT_FALSE(chrome::IsNTPURL(ntp_url, profile()));
770   EXPECT_TRUE(chrome::IsNTPURL(local_ntp_url, profile()));
771   EXPECT_TRUE(chrome::IsNTPURL(remote_ntp_url, profile()));
772   EXPECT_FALSE(chrome::IsNTPURL(search_url_with_search_terms, profile()));
773   EXPECT_TRUE(chrome::IsNTPURL(search_url_without_search_terms, profile()));
774
775   EXPECT_FALSE(chrome::IsNTPURL(ntp_url, NULL));
776   EXPECT_FALSE(chrome::IsNTPURL(local_ntp_url, NULL));
777   EXPECT_FALSE(chrome::IsNTPURL(remote_ntp_url, NULL));
778   EXPECT_FALSE(chrome::IsNTPURL(search_url_with_search_terms, NULL));
779   EXPECT_FALSE(chrome::IsNTPURL(search_url_without_search_terms, NULL));
780 }
781
782 TEST_F(SearchTest, GetSearchURLs) {
783   std::vector<GURL> search_urls = GetSearchURLs(profile());
784   EXPECT_EQ(2U, search_urls.size());
785   EXPECT_EQ("http://foo.com/alt#quux=", search_urls[0].spec());
786   EXPECT_EQ("http://foo.com/url?bar=", search_urls[1].spec());
787 }
788
789 TEST_F(SearchTest, GetSearchResultPrefetchBaseURL) {
790   // "prefetch_results" flag is disabled.
791   EXPECT_EQ(GURL(), GetSearchResultPrefetchBaseURL(profile()));
792
793   // "prefetch_results" flag is enabled via field trials.
794   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
795       "EmbeddedSearch",
796       "Group1 espv:80 prefetch_results:1"));
797   EXPECT_TRUE(ShouldPrefetchSearchResults());
798
799   EXPECT_EQ(GURL("https://foo.com/instant?ion=1&foo=foo#foo=foo&strk"),
800             GetSearchResultPrefetchBaseURL(profile()));
801 }
802
803 TEST_F(SearchTest, ForceInstantResultsParam) {
804   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
805                                                      "Group1 espv:2"));
806   EXPECT_TRUE(IsInstantExtendedAPIEnabled());
807   EXPECT_EQ("ion=1&", ForceInstantResultsParam(true));
808   EXPECT_EQ(std::string(), ForceInstantResultsParam(false));
809 }
810
811 struct ExtractSearchTermsTestCase {
812   const char* url;
813   const char* expected_result;
814   const char* comment;
815 };
816
817 TEST_F(SearchTest, ExtractSearchTermsFromURL) {
818   const ExtractSearchTermsTestCase kTestCases[] = {
819     {chrome::kChromeSearchLocalNtpUrl,           "",    "NTP url"},
820     {"https://foo.com/instant?strk",             "",    "Invalid search url"},
821     {"https://foo.com/instant#strk",             "",    "Invalid search url"},
822     {"https://foo.com/alt#quux=foo",             "foo", "Valid search url"},
823     {"https://foo.com/alt#quux=foo&strk",        "foo", "Valid search url"}
824   };
825
826   for (size_t i = 0; i < arraysize(kTestCases); ++i) {
827     const ExtractSearchTermsTestCase& test = kTestCases[i];
828     EXPECT_EQ(
829         test.expected_result,
830         UTF16ToASCII(chrome::ExtractSearchTermsFromURL(profile(),
831                                                        GURL(test.url))))
832             << test.url << " " << test.comment;
833   }
834 }
835
836 struct QueryExtractionAllowedTestCase {
837   const char* url;
838   bool expected_result;
839   const char* comment;
840 };
841
842 TEST_F(SearchTest, IsQueryExtractionAllowedForURL) {
843   const QueryExtractionAllowedTestCase kTestCases[] = {
844     {"http://foo.com/instant?strk",       false, "HTTP URL"},
845     {"https://foo.com/instant?strk",      true,  "Valid URL"},
846     {"https://foo.com/instant?",          false,
847      "No search terms replacement key"},
848     {"https://foo.com/alt#quux=foo",      false,
849      "No search terms replacement key"},
850     {"https://foo.com/alt#quux=foo&strk", true,  "Valid search url"}
851   };
852
853   for (size_t i = 0; i < arraysize(kTestCases); ++i) {
854     const QueryExtractionAllowedTestCase& test = kTestCases[i];
855     EXPECT_EQ(test.expected_result,
856               chrome::IsQueryExtractionAllowedForURL(profile(), GURL(test.url)))
857         << test.url << " " << test.comment;
858   }
859 }
860
861 class SearchURLTest : public SearchTest {
862  protected:
863   virtual void SetSearchProvider(bool set_ntp_url, bool insecure_ntp_url)
864       OVERRIDE {
865     TemplateURLService* template_url_service =
866         TemplateURLServiceFactory::GetForProfile(profile());
867     TemplateURLData data;
868     data.SetURL("{google:baseURL}search?"
869                 "{google:instantExtendedEnabledParameter}q={searchTerms}");
870     data.search_terms_replacement_key = "espv";
871     template_url_ = new TemplateURL(profile(), data);
872     // |template_url_service| takes ownership of |template_url_|.
873     template_url_service->Add(template_url_);
874     template_url_service->SetDefaultSearchProvider(template_url_);
875   }
876
877   TemplateURL* template_url_;
878 };
879
880 TEST_F(SearchURLTest, QueryExtractionEnabled) {
881   EnableQueryExtractionForTesting();
882   EXPECT_TRUE(IsQueryExtractionEnabled());
883   TemplateURLRef::SearchTermsArgs search_terms_args(base::ASCIIToUTF16("foo"));
884   GURL result(template_url_->url_ref().ReplaceSearchTerms(search_terms_args));
885   ASSERT_TRUE(result.is_valid());
886   // Query extraction is enabled. Make sure
887   // {google:instantExtendedEnabledParameter} is set in the search URL.
888   EXPECT_EQ("http://www.google.com/search?espv=2&q=foo", result.spec());
889 }
890
891 TEST_F(SearchURLTest, QueryExtractionDisabled) {
892   EXPECT_FALSE(IsQueryExtractionEnabled());
893   TemplateURLRef::SearchTermsArgs search_terms_args(base::ASCIIToUTF16("foo"));
894   GURL result(template_url_->url_ref().ReplaceSearchTerms(search_terms_args));
895   ASSERT_TRUE(result.is_valid());
896   // Query extraction is disabled. Make sure
897   // {google:instantExtendedEnabledParameter} is not set in the search URL.
898   EXPECT_EQ("http://www.google.com/search?q=foo", result.spec());
899 }
900
901 typedef SearchTest InstantExtendedEnabledParamTest;
902
903 TEST_F(InstantExtendedEnabledParamTest, QueryExtractionDisabled) {
904   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
905                                                      "Group1 espv:12"));
906   // Make sure InstantExtendedEnabledParam() returns an empty string for search
907   // requests.
908 #if defined(OS_IOS) || defined(OS_ANDROID)
909   // Query extraction is always enabled on mobile.
910   EXPECT_TRUE(IsQueryExtractionEnabled());
911   EXPECT_EQ("espv=12&", InstantExtendedEnabledParam(true));
912 #else
913   EXPECT_FALSE(IsQueryExtractionEnabled());
914   EXPECT_EQ("", InstantExtendedEnabledParam(true));
915 #endif
916   EXPECT_EQ("espv=12&", InstantExtendedEnabledParam(false));
917 }
918
919 TEST_F(InstantExtendedEnabledParamTest, QueryExtractionEnabled) {
920   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
921       "EmbeddedSearch", "Group1 espv:10 query_extraction:1"));
922   EXPECT_TRUE(IsQueryExtractionEnabled());
923   // Make sure InstantExtendedEnabledParam() returns a non-empty param string
924   // for search requests.
925   EXPECT_EQ("espv=10&", InstantExtendedEnabledParam(true));
926   EXPECT_EQ("espv=10&", InstantExtendedEnabledParam(false));
927 }
928
929 TEST_F(InstantExtendedEnabledParamTest, UseDefaultEmbeddedSearchPageVersion) {
930   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
931       "EmbeddedSearch", "Group1 espv:-1 query_extraction:1"));
932   EXPECT_TRUE(IsQueryExtractionEnabled());
933 #if defined(OS_IOS) || defined(OS_ANDROID)
934   EXPECT_EQ("espv=1&", InstantExtendedEnabledParam(true));
935   EXPECT_EQ("espv=1&", InstantExtendedEnabledParam(false));
936 #else
937   EXPECT_EQ("espv=2&", InstantExtendedEnabledParam(true));
938   EXPECT_EQ("espv=2&", InstantExtendedEnabledParam(false));
939 #endif
940 }
941
942 typedef SearchTest IsQueryExtractionEnabledTest;
943
944 TEST_F(IsQueryExtractionEnabledTest, NotSet) {
945   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
946       "EmbeddedSearch", "Group1 espv:2"));
947   EXPECT_TRUE(IsInstantExtendedAPIEnabled());
948   EXPECT_FALSE(IsQueryExtractionEnabled());
949   EXPECT_EQ(2ul, EmbeddedSearchPageVersion());
950 }
951
952 TEST_F(IsQueryExtractionEnabledTest, EnabledViaFieldTrial) {
953   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
954       "EmbeddedSearch", "Group1 espv:2 query_extraction:1"));
955   EXPECT_TRUE(IsInstantExtendedAPIEnabled());
956   EXPECT_TRUE(IsQueryExtractionEnabled());
957   EXPECT_EQ(2ul, EmbeddedSearchPageVersion());
958 }
959
960 TEST_F(IsQueryExtractionEnabledTest, DisabledViaFieldTrial) {
961   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
962       "EmbeddedSearch", "Group1 espv:2 query_extraction:0"));
963   EXPECT_TRUE(IsInstantExtendedAPIEnabled());
964   EXPECT_FALSE(IsQueryExtractionEnabled());
965   EXPECT_EQ(2ul, EmbeddedSearchPageVersion());
966 }
967
968 TEST_F(IsQueryExtractionEnabledTest, EnabledViaCommandLine) {
969   EnableQueryExtractionForTesting();
970   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
971       "EmbeddedSearch", "Group1 espv:2 query_extraction:0"));
972   EXPECT_TRUE(IsInstantExtendedAPIEnabled());
973   EXPECT_TRUE(IsQueryExtractionEnabled());
974   EXPECT_EQ(2ul, EmbeddedSearchPageVersion());
975 }
976
977 typedef SearchTest ShouldHideTopVerbatimTest;
978
979 TEST_F(ShouldHideTopVerbatimTest, DoNotHideByDefault) {
980   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
981                                                      "Control"));
982   EXPECT_FALSE(ShouldHideTopVerbatimMatch());
983 }
984
985 TEST_F(ShouldHideTopVerbatimTest, DoNotHideInInstantExtended) {
986   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
987                                                      "Group1"));
988   EXPECT_FALSE(ShouldHideTopVerbatimMatch());
989 }
990
991 TEST_F(ShouldHideTopVerbatimTest, EnableByFlagInInstantExtended) {
992   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
993                                                      "Group1 hide_verbatim:1"));
994   EXPECT_TRUE(ShouldHideTopVerbatimMatch());
995 }
996
997 TEST_F(ShouldHideTopVerbatimTest, EnableByFlagOutsideInstantExtended) {
998   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
999       "EmbeddedSearch", "Controll1 hide_verbatim:1"));
1000   EXPECT_TRUE(ShouldHideTopVerbatimMatch());
1001 }
1002
1003 TEST_F(ShouldHideTopVerbatimTest, DisableByFlag) {
1004   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("EmbeddedSearch",
1005                                                      "Group1 hide_verbatim:0"));
1006   EXPECT_FALSE(ShouldHideTopVerbatimMatch());
1007 }
1008
1009 typedef SearchTest DisplaySearchButtonTest;
1010
1011 TEST_F(DisplaySearchButtonTest, NotSet) {
1012   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1013       "EmbeddedSearch", "Group1 espv:2"));
1014   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_NEVER, GetDisplaySearchButtonConditions());
1015 }
1016
1017 TEST_F(DisplaySearchButtonTest, Never) {
1018   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1019       "EmbeddedSearch", "Group1 espv:2 display_search_button:0"));
1020   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_NEVER, GetDisplaySearchButtonConditions());
1021 }
1022
1023 TEST_F(DisplaySearchButtonTest, CommandLineNever) {
1024   CommandLine::ForCurrentProcess()->AppendSwitch(
1025       switches::kDisableSearchButtonInOmnibox);
1026   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_NEVER, GetDisplaySearchButtonConditions());
1027
1028   // Command-line disable should override the field trial.
1029   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1030       "EmbeddedSearch", "Group1 espv:2 display_search_button:1"));
1031   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_NEVER, GetDisplaySearchButtonConditions());
1032 }
1033
1034 TEST_F(DisplaySearchButtonTest, ForSearchTermReplacement) {
1035   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1036       "EmbeddedSearch", "Group1 espv:2 display_search_button:1"));
1037   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_FOR_STR, GetDisplaySearchButtonConditions());
1038 }
1039
1040 TEST_F(DisplaySearchButtonTest, CommandLineForSearchTermReplacement) {
1041   CommandLine::ForCurrentProcess()->AppendSwitch(
1042       switches::kEnableSearchButtonInOmniboxForStr);
1043   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_FOR_STR, GetDisplaySearchButtonConditions());
1044 }
1045
1046 TEST_F(DisplaySearchButtonTest, ForSearchTermReplacementOrInputInProgress) {
1047   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1048       "EmbeddedSearch", "Group1 espv:2 display_search_button:2"));
1049   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_FOR_STR_OR_IIP,
1050             GetDisplaySearchButtonConditions());
1051 }
1052
1053 TEST_F(DisplaySearchButtonTest,
1054        CommandLineForSearchTermReplacementOrInputInProgress) {
1055   CommandLine::ForCurrentProcess()->AppendSwitch(
1056       switches::kEnableSearchButtonInOmniboxForStrOrIip);
1057   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_FOR_STR_OR_IIP,
1058             GetDisplaySearchButtonConditions());
1059 }
1060
1061 TEST_F(DisplaySearchButtonTest, Always) {
1062   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1063       "EmbeddedSearch", "Group1 espv:2 display_search_button:3"));
1064   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_ALWAYS, GetDisplaySearchButtonConditions());
1065 }
1066
1067 TEST_F(DisplaySearchButtonTest, CommandLineAlways) {
1068   CommandLine::ForCurrentProcess()->AppendSwitch(
1069       switches::kEnableSearchButtonInOmniboxAlways);
1070   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_ALWAYS, GetDisplaySearchButtonConditions());
1071 }
1072
1073 TEST_F(DisplaySearchButtonTest, InvalidValue) {
1074   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1075       "EmbeddedSearch", "Group1 espv:2 display_search_button:4"));
1076   EXPECT_EQ(DISPLAY_SEARCH_BUTTON_NEVER, GetDisplaySearchButtonConditions());
1077 }
1078
1079 typedef SearchTest OriginChipTest;
1080
1081 TEST_F(OriginChipTest, NotSet) {
1082   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1083       "EmbeddedSearch", "Group1 espv:2"));
1084   EXPECT_FALSE(ShouldDisplayOriginChip());
1085   EXPECT_EQ(ORIGIN_CHIP_DISABLED, GetOriginChipPosition());
1086 }
1087
1088 TEST_F(OriginChipTest, Disabled) {
1089   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1090       "EmbeddedSearch", "Group1 espv:2 origin_chip:0"));
1091   EXPECT_FALSE(ShouldDisplayOriginChip());
1092   EXPECT_EQ(ORIGIN_CHIP_DISABLED, GetOriginChipPosition());
1093 }
1094
1095 TEST_F(OriginChipTest, OriginChipLeadingLocationBar) {
1096   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1097       "EmbeddedSearch", "Group1 espv:2 origin_chip:1"));
1098   EXPECT_TRUE(ShouldDisplayOriginChip());
1099   EXPECT_EQ(ORIGIN_CHIP_LEADING_LOCATION_BAR, GetOriginChipPosition());
1100 }
1101
1102 TEST_F(OriginChipTest, OriginChipTrailingLocationBar) {
1103   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1104       "EmbeddedSearch", "Group1 espv:2 origin_chip:2"));
1105   EXPECT_TRUE(ShouldDisplayOriginChip());
1106   EXPECT_EQ(ORIGIN_CHIP_TRAILING_LOCATION_BAR, GetOriginChipPosition());
1107 }
1108
1109 TEST_F(OriginChipTest, OriginChipLeadingMenuButton) {
1110   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1111       "EmbeddedSearch", "Group1 espv:2 origin_chip:3"));
1112   EXPECT_TRUE(ShouldDisplayOriginChip());
1113   EXPECT_EQ(ORIGIN_CHIP_LEADING_MENU_BUTTON, GetOriginChipPosition());
1114 }
1115
1116 TEST_F(OriginChipTest, OriginChipInvalidValue) {
1117   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1118       "EmbeddedSearch", "Group1 espv:2 origin_chip:4"));
1119   EXPECT_FALSE(ShouldDisplayOriginChip());
1120   EXPECT_EQ(ORIGIN_CHIP_DISABLED, GetOriginChipPosition());
1121 }
1122
1123 TEST_F(OriginChipTest, CommandLineDisabled) {
1124   CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableOriginChip);
1125   EXPECT_FALSE(ShouldDisplayOriginChip());
1126   EXPECT_EQ(ORIGIN_CHIP_DISABLED, GetOriginChipPosition());
1127
1128   // Command-line disable should override the field trial.
1129   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1130       "EmbeddedSearch", "Group1 espv:2 origin_chip:1"));
1131   EXPECT_FALSE(ShouldDisplayOriginChip());
1132   EXPECT_EQ(ORIGIN_CHIP_DISABLED, GetOriginChipPosition());
1133 }
1134
1135 TEST_F(OriginChipTest, CommandLineOriginChip) {
1136   CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnableOriginChip);
1137   EXPECT_TRUE(ShouldDisplayOriginChip());
1138   EXPECT_EQ(ORIGIN_CHIP_TRAILING_LOCATION_BAR, GetOriginChipPosition());
1139
1140   // Command-line enable should override the field trial.
1141   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1142       "EmbeddedSearch", "Group1 espv:2 origin_chip:0"));
1143   EXPECT_TRUE(ShouldDisplayOriginChip());
1144   EXPECT_EQ(ORIGIN_CHIP_TRAILING_LOCATION_BAR, GetOriginChipPosition());
1145 }
1146
1147 TEST_F(OriginChipTest, CommandLineOriginChipLeadingLocationBar) {
1148   CommandLine::ForCurrentProcess()->AppendSwitch(
1149       switches::kEnableOriginChipLeadingLocationBar);
1150   EXPECT_TRUE(ShouldDisplayOriginChip());
1151   EXPECT_EQ(ORIGIN_CHIP_LEADING_LOCATION_BAR, GetOriginChipPosition());
1152 }
1153
1154 TEST_F(OriginChipTest, CommandLineOriginChipTrailingLocationBar) {
1155   CommandLine::ForCurrentProcess()->AppendSwitch(
1156       switches::kEnableOriginChipTrailingLocationBar);
1157   EXPECT_TRUE(ShouldDisplayOriginChip());
1158   EXPECT_EQ(ORIGIN_CHIP_TRAILING_LOCATION_BAR, GetOriginChipPosition());
1159 }
1160
1161 TEST_F(OriginChipTest, CommandLineOriginChipLeadingMenuButton) {
1162   CommandLine::ForCurrentProcess()->AppendSwitch(
1163       switches::kEnableOriginChipLeadingMenuButton);
1164   EXPECT_TRUE(ShouldDisplayOriginChip());
1165   EXPECT_EQ(ORIGIN_CHIP_LEADING_MENU_BUTTON, GetOriginChipPosition());
1166 }
1167
1168 typedef SearchTest OriginChipV2Test;
1169
1170 TEST_F(OriginChipV2Test, NotSet) {
1171   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1172       "EmbeddedSearch", "Group1 espv:2"));
1173   EXPECT_FALSE(ShouldDisplayOriginChipV2());
1174   EXPECT_EQ(ORIGIN_CHIP_V2_DISABLED, GetOriginChipV2HideTrigger());
1175 }
1176
1177 TEST_F(OriginChipV2Test, Disabled) {
1178   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1179       "EmbeddedSearch", "Group1 espv:2 origin_chip_v2:0"));
1180   EXPECT_FALSE(ShouldDisplayOriginChipV2());
1181   EXPECT_EQ(ORIGIN_CHIP_V2_DISABLED, GetOriginChipV2HideTrigger());
1182 }
1183
1184 TEST_F(OriginChipV2Test, HideOnMouseRelease) {
1185   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1186       "EmbeddedSearch", "Group1 espv:2 origin_chip_v2:1"));
1187   EXPECT_TRUE(ShouldDisplayOriginChipV2());
1188   EXPECT_EQ(ORIGIN_CHIP_V2_HIDE_ON_MOUSE_RELEASE, GetOriginChipV2HideTrigger());
1189 }
1190
1191 TEST_F(OriginChipV2Test, HideOnUserInput) {
1192   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1193       "EmbeddedSearch", "Group1 espv:2 origin_chip_v2:2"));
1194   EXPECT_TRUE(ShouldDisplayOriginChipV2());
1195   EXPECT_EQ(ORIGIN_CHIP_V2_HIDE_ON_USER_INPUT, GetOriginChipV2HideTrigger());
1196 }
1197
1198 TEST_F(OriginChipV2Test, InvalidValue) {
1199   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1200       "EmbeddedSearch", "Group1 espv:2 origin_chip_v2:3"));
1201   EXPECT_FALSE(ShouldDisplayOriginChipV2());
1202   EXPECT_EQ(ORIGIN_CHIP_V2_DISABLED, GetOriginChipV2HideTrigger());
1203 }
1204
1205 TEST_F(OriginChipV2Test, BothVersions) {
1206   // With both the original and v2 origin chip experiments enabled, v2 should
1207   // disable the original.
1208   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1209       "EmbeddedSearch", "Group1 espv:2 origin_chip:1 origin_chip_v2:1"));
1210   EXPECT_FALSE(ShouldDisplayOriginChip());
1211   EXPECT_EQ(ORIGIN_CHIP_DISABLED, GetOriginChipPosition());
1212   EXPECT_TRUE(ShouldDisplayOriginChipV2());
1213   EXPECT_EQ(ORIGIN_CHIP_V2_HIDE_ON_MOUSE_RELEASE, GetOriginChipV2HideTrigger());
1214 }
1215
1216 TEST_F(OriginChipV2Test, CommandLineDisabled) {
1217   CommandLine::ForCurrentProcess()->AppendSwitch(
1218       switches::kDisableOriginChipV2);
1219   EXPECT_FALSE(ShouldDisplayOriginChipV2());
1220   EXPECT_EQ(ORIGIN_CHIP_V2_DISABLED, GetOriginChipV2HideTrigger());
1221
1222   // Command-line disable should override the field trial.
1223   ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
1224       "EmbeddedSearch", "Group1 espv:2 origin_chip_v2:1"));
1225   EXPECT_FALSE(ShouldDisplayOriginChipV2());
1226   EXPECT_EQ(ORIGIN_CHIP_V2_DISABLED, GetOriginChipV2HideTrigger());
1227 }
1228
1229 TEST_F(OriginChipV2Test, CommandLineHideOnMouseRelease) {
1230   CommandLine::ForCurrentProcess()->AppendSwitch(
1231       switches::kEnableOriginChipV2HideOnMouseRelease);
1232   EXPECT_TRUE(ShouldDisplayOriginChipV2());
1233   EXPECT_EQ(ORIGIN_CHIP_V2_HIDE_ON_MOUSE_RELEASE, GetOriginChipV2HideTrigger());
1234 }
1235
1236 TEST_F(OriginChipV2Test, CommandLineHideOnUserInput) {
1237   CommandLine::ForCurrentProcess()->AppendSwitch(
1238       switches::kEnableOriginChipV2HideOnUserInput);
1239   EXPECT_TRUE(ShouldDisplayOriginChipV2());
1240   EXPECT_EQ(ORIGIN_CHIP_V2_HIDE_ON_USER_INPUT, GetOriginChipV2HideTrigger());
1241 }
1242
1243 }  // namespace chrome