- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / autocomplete / history_quick_provider_unittest.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/autocomplete/history_quick_provider.h"
6
7 #include <algorithm>
8 #include <functional>
9 #include <set>
10 #include <string>
11 #include <vector>
12
13 #include "base/format_macros.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
20 #include "chrome/browser/autocomplete/autocomplete_result.h"
21 #include "chrome/browser/autocomplete/history_url_provider.h"
22 #include "chrome/browser/bookmarks/bookmark_test_helpers.h"
23 #include "chrome/browser/history/history_backend.h"
24 #include "chrome/browser/history/history_database.h"
25 #include "chrome/browser/history/history_service.h"
26 #include "chrome/browser/history/history_service_factory.h"
27 #include "chrome/browser/history/in_memory_url_index.h"
28 #include "chrome/browser/history/url_database.h"
29 #include "chrome/browser/history/url_index_private_data.h"
30 #include "chrome/browser/search_engines/template_url.h"
31 #include "chrome/browser/search_engines/template_url_service.h"
32 #include "chrome/browser/search_engines/template_url_service_factory.h"
33 #include "chrome/common/pref_names.h"
34 #include "chrome/test/base/testing_browser_process.h"
35 #include "chrome/test/base/testing_profile.h"
36 #include "content/public/test/test_browser_thread.h"
37 #include "sql/transaction.h"
38 #include "testing/gtest/include/gtest/gtest.h"
39
40 using base::Time;
41 using base::TimeDelta;
42
43 using content::BrowserThread;
44
45 struct TestURLInfo {
46   std::string url;
47   std::string title;
48   int visit_count;
49   int typed_count;
50   int days_from_now;
51 } quick_test_db[] = {
52   {"http://www.google.com/", "Google", 3, 3, 0},
53   {"http://slashdot.org/favorite_page.html", "Favorite page", 200, 100, 0},
54   {"http://kerneltrap.org/not_very_popular.html", "Less popular", 4, 0, 0},
55   {"http://freshmeat.net/unpopular.html", "Unpopular", 1, 1, 0},
56   {"http://news.google.com/?ned=us&topic=n", "Google News - U.S.", 2, 2, 0},
57   {"http://news.google.com/", "Google News", 1, 1, 0},
58   {"http://foo.com/", "Dir", 200, 100, 0},
59   {"http://foo.com/dir/", "Dir", 2, 1, 10},
60   {"http://foo.com/dir/another/", "Dir", 10, 5, 0},
61   {"http://foo.com/dir/another/again/", "Dir", 5, 1, 0},
62   {"http://foo.com/dir/another/again/myfile.html", "File", 3, 1, 0},
63   {"http://visitedest.com/y/a", "VA", 10, 1, 20},
64   {"http://visitedest.com/y/b", "VB", 9, 1, 20},
65   {"http://visitedest.com/x/c", "VC", 8, 1, 20},
66   {"http://visitedest.com/x/d", "VD", 7, 1, 20},
67   {"http://visitedest.com/y/e", "VE", 6, 1, 20},
68   {"http://typeredest.com/y/a", "TA", 5, 5, 0},
69   {"http://typeredest.com/y/b", "TB", 5, 4, 0},
70   {"http://typeredest.com/x/c", "TC", 5, 3, 0},
71   {"http://typeredest.com/x/d", "TD", 5, 2, 0},
72   {"http://typeredest.com/y/e", "TE", 5, 1, 0},
73   {"http://daysagoest.com/y/a", "DA", 1, 1, 0},
74   {"http://daysagoest.com/y/b", "DB", 1, 1, 1},
75   {"http://daysagoest.com/x/c", "DC", 1, 1, 2},
76   {"http://daysagoest.com/x/d", "DD", 1, 1, 3},
77   {"http://daysagoest.com/y/e", "DE", 1, 1, 4},
78   {"http://abcdefghixyzjklmnopqrstuvw.com/a", "", 3, 1, 0},
79   {"http://spaces.com/path%20with%20spaces/foo.html", "Spaces", 2, 2, 0},
80   {"http://abcdefghijklxyzmnopqrstuvw.com/a", "", 3, 1, 0},
81   {"http://abcdefxyzghijklmnopqrstuvw.com/a", "", 3, 1, 0},
82   {"http://abcxyzdefghijklmnopqrstuvw.com/a", "", 3, 1, 0},
83   {"http://xyzabcdefghijklmnopqrstuvw.com/a", "", 3, 1, 0},
84   {"http://cda.com/Dogs%20Cats%20Gorillas%20Sea%20Slugs%20and%20Mice",
85    "Dogs & Cats & Mice & Other Animals", 1, 1, 0},
86   {"https://monkeytrap.org/", "", 3, 1, 0},
87   {"http://popularsitewithpathonly.com/moo",
88    "popularsitewithpathonly.com/moo", 50, 50, 0},
89   {"http://popularsitewithroot.com/", "popularsitewithroot.com", 50, 50, 0},
90   {"http://testsearch.com/?q=thequery", "Test Search Engine", 10, 10, 0},
91   {"http://testsearch.com/", "Test Search Engine", 9, 9, 0},
92   {"http://anotherengine.com/?q=thequery", "Another Search Engine", 8, 8, 0}
93 };
94
95 class HistoryQuickProviderTest : public testing::Test,
96                                  public AutocompleteProviderListener {
97  public:
98   HistoryQuickProviderTest()
99       : ui_thread_(BrowserThread::UI, &message_loop_),
100         file_thread_(BrowserThread::FILE, &message_loop_) {}
101
102   // AutocompleteProviderListener:
103   virtual void OnProviderUpdate(bool updated_matches) OVERRIDE {}
104
105  protected:
106   class SetShouldContain : public std::unary_function<const std::string&,
107                                                       std::set<std::string> > {
108    public:
109     explicit SetShouldContain(const ACMatches& matched_urls);
110
111     void operator()(const std::string& expected);
112
113     std::set<std::string> LeftOvers() const { return matches_; }
114
115    private:
116     std::set<std::string> matches_;
117   };
118
119   static BrowserContextKeyedService* CreateTemplateURLService(
120       content::BrowserContext* profile) {
121     return new TemplateURLService(static_cast<Profile*>(profile));
122   }
123
124   virtual void SetUp();
125   virtual void TearDown();
126
127   virtual void GetTestData(size_t* data_count, TestURLInfo** test_data);
128
129   // Fills test data into the history system.
130   void FillData();
131
132   // Runs an autocomplete query on |text| and checks to see that the returned
133   // results' destination URLs match those provided. |expected_urls| does not
134   // need to be in sorted order.
135   void RunTest(const string16 text,
136                std::vector<std::string> expected_urls,
137                bool can_inline_top_result,
138                string16 expected_fill_into_edit);
139
140   base::MessageLoopForUI message_loop_;
141   content::TestBrowserThread ui_thread_;
142   content::TestBrowserThread file_thread_;
143
144   scoped_ptr<TestingProfile> profile_;
145   HistoryService* history_service_;
146
147   ACMatches ac_matches_;  // The resulting matches after running RunTest.
148
149   scoped_refptr<HistoryQuickProvider> provider_;
150 };
151
152 void HistoryQuickProviderTest::SetUp() {
153   profile_.reset(new TestingProfile());
154   ASSERT_TRUE(profile_->CreateHistoryService(true, false));
155   profile_->CreateBookmarkModel(true);
156   test::WaitForBookmarkModelToLoad(profile_.get());
157   profile_->BlockUntilHistoryIndexIsRefreshed();
158   history_service_ =
159       HistoryServiceFactory::GetForProfile(profile_.get(),
160                                            Profile::EXPLICIT_ACCESS);
161   EXPECT_TRUE(history_service_);
162   provider_ = new HistoryQuickProvider(this, profile_.get());
163   TemplateURLServiceFactory::GetInstance()->SetTestingFactoryAndUse(
164       profile_.get(), &HistoryQuickProviderTest::CreateTemplateURLService);
165   FillData();
166   provider_->GetIndex()->RebuildFromHistory(
167       history_service_->history_backend_->db());
168 }
169
170 void HistoryQuickProviderTest::TearDown() {
171   provider_ = NULL;
172 }
173
174 void HistoryQuickProviderTest::GetTestData(size_t* data_count,
175                                            TestURLInfo** test_data) {
176   DCHECK(data_count);
177   DCHECK(test_data);
178   *data_count = arraysize(quick_test_db);
179   *test_data = &quick_test_db[0];
180 }
181
182 void HistoryQuickProviderTest::FillData() {
183   sql::Connection& db(history_service_->history_backend_->db()->GetDB());
184   ASSERT_TRUE(db.is_open());
185
186   size_t data_count = 0;
187   TestURLInfo* test_data = NULL;
188   GetTestData(&data_count, &test_data);
189   size_t visit_id = 1;
190   for (size_t i = 0; i < data_count; ++i) {
191     const TestURLInfo& cur(test_data[i]);
192     Time visit_time = Time::Now() - TimeDelta::FromDays(cur.days_from_now);
193     sql::Transaction transaction(&db);
194
195     // Add URL.
196     transaction.Begin();
197     std::string sql_cmd_line = base::StringPrintf(
198         "INSERT INTO \"urls\" VALUES(%" PRIuS ", \'%s\', \'%s\', %d, %d, %"
199         PRId64 ", 0, 0)",
200         i + 1, cur.url.c_str(), cur.title.c_str(), cur.visit_count,
201         cur.typed_count, visit_time.ToInternalValue());
202     sql::Statement sql_stmt(db.GetUniqueStatement(sql_cmd_line.c_str()));
203     EXPECT_TRUE(sql_stmt.Run());
204     transaction.Commit();
205
206     // Add visits.
207     for (int j = 0; j < cur.visit_count; ++j) {
208       // Assume earlier visits are at one-day intervals.
209       visit_time -= TimeDelta::FromDays(1);
210       transaction.Begin();
211       // Mark the most recent |cur.typed_count| visits as typed.
212       std::string sql_cmd_line = base::StringPrintf(
213           "INSERT INTO \"visits\" VALUES(%" PRIuS ", %" PRIuS ", %" PRId64
214           ", 0, %d, 0, 1)",
215           visit_id++, i + 1, visit_time.ToInternalValue(),
216           (j < cur.typed_count) ? content::PAGE_TRANSITION_TYPED :
217                                   content::PAGE_TRANSITION_LINK);
218
219       sql::Statement sql_stmt(db.GetUniqueStatement(sql_cmd_line.c_str()));
220       EXPECT_TRUE(sql_stmt.Run());
221       transaction.Commit();
222     }
223   }
224 }
225
226 HistoryQuickProviderTest::SetShouldContain::SetShouldContain(
227     const ACMatches& matched_urls) {
228   for (ACMatches::const_iterator iter = matched_urls.begin();
229        iter != matched_urls.end(); ++iter)
230     matches_.insert(iter->destination_url.spec());
231 }
232
233 void HistoryQuickProviderTest::SetShouldContain::operator()(
234     const std::string& expected) {
235   EXPECT_EQ(1U, matches_.erase(expected))
236       << "Results did not contain '" << expected << "' but should have.";
237 }
238
239
240 void HistoryQuickProviderTest::RunTest(const string16 text,
241                                        std::vector<std::string> expected_urls,
242                                        bool can_inline_top_result,
243                                        string16 expected_fill_into_edit) {
244   SCOPED_TRACE(text);  // Minimal hint to query being run.
245   base::MessageLoop::current()->RunUntilIdle();
246   AutocompleteInput input(text, string16::npos, string16(), GURL(),
247                           AutocompleteInput::INVALID_SPEC, false, false, true,
248                           AutocompleteInput::ALL_MATCHES);
249   provider_->Start(input, false);
250   EXPECT_TRUE(provider_->done());
251
252   ac_matches_ = provider_->matches();
253
254   // We should have gotten back at most AutocompleteProvider::kMaxMatches.
255   EXPECT_LE(ac_matches_.size(), AutocompleteProvider::kMaxMatches);
256
257   // If the number of expected and actual matches aren't equal then we need
258   // test no further, but let's do anyway so that we know which URLs failed.
259   EXPECT_EQ(expected_urls.size(), ac_matches_.size());
260
261   // Verify that all expected URLs were found and that all found URLs
262   // were expected.
263   std::set<std::string> leftovers =
264       for_each(expected_urls.begin(), expected_urls.end(),
265                SetShouldContain(ac_matches_)).LeftOvers();
266   EXPECT_EQ(0U, leftovers.size()) << "There were " << leftovers.size()
267       << " unexpected results, one of which was: '"
268       << *(leftovers.begin()) << "'.";
269
270   if (expected_urls.empty())
271     return;
272
273   // Verify that we got the results in the order expected.
274   int best_score = ac_matches_.begin()->relevance + 1;
275   int i = 0;
276   std::vector<std::string>::const_iterator expected = expected_urls.begin();
277   for (ACMatches::const_iterator actual = ac_matches_.begin();
278        actual != ac_matches_.end() && expected != expected_urls.end();
279        ++actual, ++expected, ++i) {
280     EXPECT_EQ(*expected, actual->destination_url.spec())
281         << "For result #" << i << " we got '" << actual->destination_url.spec()
282         << "' but expected '" << *expected << "'.";
283     EXPECT_LT(actual->relevance, best_score)
284       << "At result #" << i << " (url=" << actual->destination_url.spec()
285       << "), we noticed scores are not monotonically decreasing.";
286     best_score = actual->relevance;
287   }
288
289   EXPECT_EQ(can_inline_top_result, ac_matches_[0].allowed_to_be_default_match);
290   if (can_inline_top_result) {
291     // When the top scorer is inline-able make sure we get the expected
292     // fill_into_edit and autocomplete offset.
293     EXPECT_EQ(expected_fill_into_edit, ac_matches_[0].fill_into_edit)
294         << "fill_into_edit was: '" << ac_matches_[0].fill_into_edit
295         << "' but we expected '" << expected_fill_into_edit << "'.";
296     size_t text_pos = expected_fill_into_edit.find(text);
297     ASSERT_NE(string16::npos, text_pos);
298     EXPECT_EQ(ac_matches_[0].fill_into_edit.substr(text_pos + text.size()),
299               ac_matches_[0].inline_autocompletion);
300   } else {
301     // When the top scorer is not inline-able autocomplete offset must be npos.
302     EXPECT_TRUE(ac_matches_[0].inline_autocompletion.empty());
303     // Also, the score must be too low to be inlineable.
304     // TODO(mpearson): when the controller reorders for inlining, there's no
305     // longer any connection between scores and what's inlineable / allowed
306     // to be the default match.  Remove this test.
307     EXPECT_LT(ac_matches_[0].relevance,
308               AutocompleteResult::kLowestDefaultScore);
309   }
310 }
311
312 TEST_F(HistoryQuickProviderTest, SimpleSingleMatch) {
313   std::vector<std::string> expected_urls;
314   expected_urls.push_back("http://slashdot.org/favorite_page.html");
315   RunTest(ASCIIToUTF16("slashdot"), expected_urls, true,
316           ASCIIToUTF16("slashdot.org/favorite_page.html"));
317 }
318
319 TEST_F(HistoryQuickProviderTest, MultiTermTitleMatch) {
320   std::vector<std::string> expected_urls;
321   expected_urls.push_back(
322       "http://cda.com/Dogs%20Cats%20Gorillas%20Sea%20Slugs%20and%20Mice");
323   RunTest(ASCIIToUTF16("mice other animals"), expected_urls, false,
324           ASCIIToUTF16("cda.com/Dogs Cats Gorillas Sea Slugs and Mice"));
325 }
326
327 TEST_F(HistoryQuickProviderTest, NonWordLastCharacterMatch) {
328   std::string expected_url("http://slashdot.org/favorite_page.html");
329   std::vector<std::string> expected_urls;
330   expected_urls.push_back(expected_url);
331   RunTest(ASCIIToUTF16("slashdot.org/"), expected_urls, true,
332           ASCIIToUTF16("slashdot.org/favorite_page.html"));
333 }
334
335 TEST_F(HistoryQuickProviderTest, MultiMatch) {
336   std::vector<std::string> expected_urls;
337   // Scores high because of typed_count.
338   expected_urls.push_back("http://foo.com/");
339   // Scores high because of visit count.
340   expected_urls.push_back("http://foo.com/dir/another/");
341   // Scores high because of high visit count.
342   expected_urls.push_back("http://foo.com/dir/another/again/");
343   RunTest(ASCIIToUTF16("foo"), expected_urls, true, ASCIIToUTF16("foo.com"));
344 }
345
346 TEST_F(HistoryQuickProviderTest, StartRelativeMatch) {
347   std::vector<std::string> expected_urls;
348   expected_urls.push_back("http://xyzabcdefghijklmnopqrstuvw.com/a");
349   RunTest(ASCIIToUTF16("xyza"), expected_urls, true,
350           ASCIIToUTF16("xyzabcdefghijklmnopqrstuvw.com/a"));
351 }
352
353 TEST_F(HistoryQuickProviderTest, EncodingMatch) {
354   std::vector<std::string> expected_urls;
355   expected_urls.push_back("http://spaces.com/path%20with%20spaces/foo.html");
356   RunTest(ASCIIToUTF16("path with spaces"), expected_urls, false,
357           ASCIIToUTF16("CANNOT AUTOCOMPLETE"));
358 }
359
360 TEST_F(HistoryQuickProviderTest, VisitCountMatches) {
361   std::vector<std::string> expected_urls;
362   expected_urls.push_back("http://visitedest.com/y/a");
363   expected_urls.push_back("http://visitedest.com/y/b");
364   expected_urls.push_back("http://visitedest.com/x/c");
365   RunTest(ASCIIToUTF16("visitedest"), expected_urls, true,
366           ASCIIToUTF16("visitedest.com/y/a"));
367 }
368
369 TEST_F(HistoryQuickProviderTest, TypedCountMatches) {
370   std::vector<std::string> expected_urls;
371   expected_urls.push_back("http://typeredest.com/y/a");
372   expected_urls.push_back("http://typeredest.com/y/b");
373   expected_urls.push_back("http://typeredest.com/x/c");
374   RunTest(ASCIIToUTF16("typeredest"), expected_urls, true,
375           ASCIIToUTF16("typeredest.com/y/a"));
376 }
377
378 TEST_F(HistoryQuickProviderTest, DaysAgoMatches) {
379   std::vector<std::string> expected_urls;
380   expected_urls.push_back("http://daysagoest.com/y/a");
381   expected_urls.push_back("http://daysagoest.com/y/b");
382   expected_urls.push_back("http://daysagoest.com/x/c");
383   RunTest(ASCIIToUTF16("daysagoest"), expected_urls, true,
384           ASCIIToUTF16("daysagoest.com/y/a"));
385 }
386
387 TEST_F(HistoryQuickProviderTest, EncodingLimitMatch) {
388   std::vector<std::string> expected_urls;
389   std::string url(
390       "http://cda.com/Dogs%20Cats%20Gorillas%20Sea%20Slugs%20and%20Mice");
391   // First check that a mid-word match yield no results.
392   RunTest(ASCIIToUTF16("ice"), expected_urls, false,
393           ASCIIToUTF16("cda.com/Dogs Cats Gorillas Sea Slugs and Mice"));
394   // Then check that we get results when the match is at a word start
395   // that is present because of an encoded separate (%20 = space).
396   expected_urls.push_back(url);
397   RunTest(ASCIIToUTF16("Mice"), expected_urls, false,
398           ASCIIToUTF16("cda.com/Dogs Cats Gorillas Sea Slugs and Mice"));
399   // Verify that the matches' ACMatchClassifications offsets are in range.
400   ACMatchClassifications content(ac_matches_[0].contents_class);
401   // The max offset accounts for 6 occurrences of '%20' plus the 'http://'.
402   const size_t max_offset = url.length() - ((6 * 2) + 7);
403   for (ACMatchClassifications::const_iterator citer = content.begin();
404        citer != content.end(); ++citer)
405     EXPECT_LT(citer->offset, max_offset);
406   ACMatchClassifications description(ac_matches_[0].description_class);
407   std::string page_title("Dogs & Cats & Mice & Other Animals");
408   for (ACMatchClassifications::const_iterator diter = description.begin();
409        diter != description.end(); ++diter)
410     EXPECT_LT(diter->offset, page_title.length());
411 }
412
413 TEST_F(HistoryQuickProviderTest, Spans) {
414   // Test SpansFromTermMatch
415   history::TermMatches matches_a;
416   // Simulates matches: '.xx.xxx..xx...xxxxx..' which will test no match at
417   // either beginning or end as well as adjacent matches.
418   matches_a.push_back(history::TermMatch(1, 1, 2));
419   matches_a.push_back(history::TermMatch(2, 4, 3));
420   matches_a.push_back(history::TermMatch(3, 9, 1));
421   matches_a.push_back(history::TermMatch(3, 10, 1));
422   matches_a.push_back(history::TermMatch(4, 14, 5));
423   ACMatchClassifications spans_a =
424       HistoryQuickProvider::SpansFromTermMatch(matches_a, 20, false);
425   // ACMatch spans should be: 'NM-NM---N-M-N--M----N-'
426   ASSERT_EQ(9U, spans_a.size());
427   EXPECT_EQ(0U, spans_a[0].offset);
428   EXPECT_EQ(ACMatchClassification::NONE, spans_a[0].style);
429   EXPECT_EQ(1U, spans_a[1].offset);
430   EXPECT_EQ(ACMatchClassification::MATCH, spans_a[1].style);
431   EXPECT_EQ(3U, spans_a[2].offset);
432   EXPECT_EQ(ACMatchClassification::NONE, spans_a[2].style);
433   EXPECT_EQ(4U, spans_a[3].offset);
434   EXPECT_EQ(ACMatchClassification::MATCH, spans_a[3].style);
435   EXPECT_EQ(7U, spans_a[4].offset);
436   EXPECT_EQ(ACMatchClassification::NONE, spans_a[4].style);
437   EXPECT_EQ(9U, spans_a[5].offset);
438   EXPECT_EQ(ACMatchClassification::MATCH, spans_a[5].style);
439   EXPECT_EQ(11U, spans_a[6].offset);
440   EXPECT_EQ(ACMatchClassification::NONE, spans_a[6].style);
441   EXPECT_EQ(14U, spans_a[7].offset);
442   EXPECT_EQ(ACMatchClassification::MATCH, spans_a[7].style);
443   EXPECT_EQ(19U, spans_a[8].offset);
444   EXPECT_EQ(ACMatchClassification::NONE, spans_a[8].style);
445   // Simulates matches: 'xx.xx' which will test matches at both beginning and
446   // end.
447   history::TermMatches matches_b;
448   matches_b.push_back(history::TermMatch(1, 0, 2));
449   matches_b.push_back(history::TermMatch(2, 3, 2));
450   ACMatchClassifications spans_b =
451       HistoryQuickProvider::SpansFromTermMatch(matches_b, 5, true);
452   // ACMatch spans should be: 'M-NM-'
453   ASSERT_EQ(3U, spans_b.size());
454   EXPECT_EQ(0U, spans_b[0].offset);
455   EXPECT_EQ(ACMatchClassification::MATCH | ACMatchClassification::URL,
456             spans_b[0].style);
457   EXPECT_EQ(2U, spans_b[1].offset);
458   EXPECT_EQ(ACMatchClassification::URL, spans_b[1].style);
459   EXPECT_EQ(3U, spans_b[2].offset);
460   EXPECT_EQ(ACMatchClassification::MATCH | ACMatchClassification::URL,
461             spans_b[2].style);
462 }
463
464 TEST_F(HistoryQuickProviderTest, DeleteMatch) {
465   std::vector<std::string> expected_urls;
466   expected_urls.push_back("http://slashdot.org/favorite_page.html");
467   // Fill up ac_matches_; we don't really care about the test yet.
468   RunTest(ASCIIToUTF16("slashdot"), expected_urls, true,
469           ASCIIToUTF16("slashdot.org/favorite_page.html"));
470   EXPECT_EQ(1U, ac_matches_.size());
471   provider_->DeleteMatch(ac_matches_[0]);
472   // Verify it's no longer an indexed visit.
473   expected_urls.clear();
474   RunTest(ASCIIToUTF16("slashdot"), expected_urls, true,
475           ASCIIToUTF16("NONE EXPECTED"));
476 }
477
478 TEST_F(HistoryQuickProviderTest, PreventBeatingURLWhatYouTypedMatch) {
479   std::vector<std::string> expected_urls;
480
481   expected_urls.clear();
482   expected_urls.push_back("http://popularsitewithroot.com/");
483   // If the user enters a hostname (no path) that he/she has visited
484   // before, we should make sure that all HistoryQuickProvider results
485   // have scores less than what HistoryURLProvider will assign the
486   // URL-what-you-typed match.
487   RunTest(ASCIIToUTF16("popularsitewithroot.com"), expected_urls, true,
488           ASCIIToUTF16("popularsitewithroot.com"));
489   EXPECT_LT(ac_matches_[0].relevance,
490             HistoryURLProvider::kScoreForBestInlineableResult);
491
492   // Check that if the user didn't quite enter the full hostname, this
493   // hostname would've normally scored above the URL-what-you-typed match.
494   RunTest(ASCIIToUTF16("popularsitewithroot.c"), expected_urls, true,
495           ASCIIToUTF16("popularsitewithroot.com"));
496   EXPECT_GE(ac_matches_[0].relevance,
497             HistoryURLProvider::kScoreForWhatYouTypedResult);
498
499   expected_urls.clear();
500   expected_urls.push_back("http://popularsitewithpathonly.com/moo");
501   // If the user enters a hostname of a host that he/she has visited
502   // but never visited the root page of, we should make sure that all
503   // HistoryQuickProvider results have scores less than what the
504   // HistoryURLProvider will assign the URL-what-you-typed match.
505   RunTest(ASCIIToUTF16("popularsitewithpathonly.com"), expected_urls, true,
506           ASCIIToUTF16("popularsitewithpathonly.com/moo"));
507   EXPECT_LT(ac_matches_[0].relevance,
508             HistoryURLProvider::kScoreForUnvisitedIntranetResult);
509
510   // Verify the same thing happens if the user adds a / to end of the
511   // hostname.
512   RunTest(ASCIIToUTF16("popularsitewithpathonly.com/"), expected_urls, true,
513           ASCIIToUTF16("popularsitewithpathonly.com/moo"));
514   EXPECT_LT(ac_matches_[0].relevance,
515             HistoryURLProvider::kScoreForUnvisitedIntranetResult);
516
517   // Check that if the user didn't quite enter the full hostname, this
518   // page would've normally scored above the URL-what-you-typed match.
519   RunTest(ASCIIToUTF16("popularsitewithpathonly.co"), expected_urls, true,
520           ASCIIToUTF16("popularsitewithpathonly.com/moo"));
521   EXPECT_GE(ac_matches_[0].relevance,
522             HistoryURLProvider::kScoreForWhatYouTypedResult);
523
524   // If the user enters a hostname + path that he/she has not visited
525   // before (but visited other things on the host), we can allow
526   // inline autocompletions.
527   RunTest(ASCIIToUTF16("popularsitewithpathonly.com/mo"), expected_urls, true,
528           ASCIIToUTF16("popularsitewithpathonly.com/moo"));
529   EXPECT_GE(ac_matches_[0].relevance,
530             HistoryURLProvider::kScoreForWhatYouTypedResult);
531
532   // If the user enters a hostname + path that he/she has visited
533   // before, we should make sure that all HistoryQuickProvider results
534   // have scores less than what the HistoryURLProvider will assign
535   // the URL-what-you-typed match.
536   RunTest(ASCIIToUTF16("popularsitewithpathonly.com/moo"),
537           expected_urls, true,
538           ASCIIToUTF16("popularsitewithpathonly.com/moo"));
539   EXPECT_LT(ac_matches_[0].relevance,
540             HistoryURLProvider::kScoreForBestInlineableResult);
541 }
542
543 TEST_F(HistoryQuickProviderTest, CullSearchResults) {
544   // Set up a default search engine.
545   TemplateURLData data;
546   data.SetKeyword(ASCIIToUTF16("TestEngine"));
547   data.SetURL("http://testsearch.com/?q={searchTerms}");
548   TemplateURLService* template_url_service =
549       TemplateURLServiceFactory::GetForProfile(profile_.get());
550   TemplateURL* template_url = new TemplateURL(profile_.get(), data);
551   template_url_service->Add(template_url);
552   template_url_service->SetDefaultSearchProvider(template_url);
553   template_url_service->Load();
554
555   // A search results page should not be returned when typing a query.
556   std::vector<std::string> expected_urls;
557   expected_urls.push_back("http://anotherengine.com/?q=thequery");
558   RunTest(ASCIIToUTF16("thequery"), expected_urls, false, string16());
559
560   // A search results page should not be returned when typing the engine URL.
561   expected_urls.clear();
562   expected_urls.push_back("http://testsearch.com/");
563   RunTest(ASCIIToUTF16("testsearch"), expected_urls, true,
564           ASCIIToUTF16("testsearch.com"));
565 }
566
567 // HQPOrderingTest -------------------------------------------------------------
568
569 TestURLInfo ordering_test_db[] = {
570   {"http://www.teamliquid.net/tlpd/korean/games/21648_bisu_vs_iris", "", 6, 3,
571       256},
572   {"http://www.amazon.com/", "amazon.com: online shopping for electronics, "
573       "apparel, computers, books, dvds & more", 20, 20, 10},
574   {"http://www.teamliquid.net/forum/viewmessage.php?topic_id=52045&"
575       "currentpage=83", "google images", 6, 6, 0},
576   {"http://www.tempurpedic.com/", "tempur-pedic", 7, 7, 0},
577   {"http://www.teamfortress.com/", "", 5, 5, 6},
578   {"http://www.rottentomatoes.com/", "", 3, 3, 7},
579   {"http://music.google.com/music/listen?u=0#start_pl", "", 3, 3, 9},
580   {"https://www.emigrantdirect.com/", "high interest savings account, high "
581       "yield savings - emigrantdirect", 5, 5, 3},
582   {"http://store.steampowered.com/", "", 6, 6, 1},
583   {"http://techmeme.com/", "techmeme", 111, 110, 4},
584   {"http://www.teamliquid.net/tlpd", "team liquid progaming database", 15, 15,
585       2},
586   {"http://store.steampowered.com/", "the steam summer camp sale", 6, 6, 1},
587   {"http://www.teamliquid.net/tlpd/korean/players", "tlpd - bw korean - player "
588       "index", 25, 7, 219},
589   {"http://slashdot.org/", "slashdot: news for nerds, stuff that matters", 3, 3,
590       6},
591   {"http://translate.google.com/", "google translate", 3, 3, 0},
592   {"http://arstechnica.com/", "ars technica", 3, 3, 3},
593   {"http://www.rottentomatoes.com/", "movies | movie trailers | reviews - "
594       "rotten tomatoes", 3, 3, 7},
595   {"http://www.teamliquid.net/", "team liquid - starcraft 2 and brood war pro "
596       "gaming news", 26, 25, 3},
597   {"http://metaleater.com/", "metaleater", 4, 3, 8},
598   {"http://half.com/", "half.com: textbooks , books , music , movies , games , "
599       "video games", 4, 4, 6},
600   {"http://teamliquid.net/", "team liquid - starcraft 2 and brood war pro "
601       "gaming news", 8, 5, 9},
602 };
603
604 class HQPOrderingTest : public HistoryQuickProviderTest {
605  protected:
606   virtual void GetTestData(size_t* data_count,
607                            TestURLInfo** test_data) OVERRIDE;
608 };
609
610 void HQPOrderingTest::GetTestData(size_t* data_count, TestURLInfo** test_data) {
611   DCHECK(data_count);
612   DCHECK(test_data);
613   *data_count = arraysize(ordering_test_db);
614   *test_data = &ordering_test_db[0];
615 }
616
617 TEST_F(HQPOrderingTest, TEMatch) {
618   std::vector<std::string> expected_urls;
619   expected_urls.push_back("http://techmeme.com/");
620   expected_urls.push_back("http://www.teamliquid.net/");
621   expected_urls.push_back("http://www.teamliquid.net/tlpd");
622   RunTest(ASCIIToUTF16("te"), expected_urls, true,
623           ASCIIToUTF16("techmeme.com"));
624 }
625
626 TEST_F(HQPOrderingTest, TEAMatch) {
627   std::vector<std::string> expected_urls;
628   expected_urls.push_back("http://www.teamliquid.net/");
629   expected_urls.push_back("http://www.teamliquid.net/tlpd");
630   expected_urls.push_back("http://www.teamliquid.net/tlpd/korean/players");
631   RunTest(ASCIIToUTF16("tea"), expected_urls, true,
632           ASCIIToUTF16("www.teamliquid.net"));
633 }