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