1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "components/autofill/core/browser/webdata/autofill_table.h"
6 
7 #include <map>
8 #include <set>
9 #include <tuple>
10 #include <utility>
11 
12 #include "base/command_line.h"
13 #include "base/files/file_util.h"
14 #include "base/files/scoped_temp_dir.h"
15 #include "base/guid.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/test/scoped_feature_list.h"
22 #include "base/time/time.h"
23 #include "build/build_config.h"
24 #include "components/autofill/core/browser/autofill_test_utils.h"
25 #include "components/autofill/core/browser/autofill_type.h"
26 #include "components/autofill/core/browser/data_model/autofill_metadata.h"
27 #include "components/autofill/core/browser/data_model/autofill_profile.h"
28 #include "components/autofill/core/browser/data_model/credit_card.h"
29 #include "components/autofill/core/browser/data_model/credit_card_cloud_token_data.h"
30 #include "components/autofill/core/browser/payments/payments_customer_data.h"
31 #include "components/autofill/core/browser/webdata/autofill_change.h"
32 #include "components/autofill/core/browser/webdata/autofill_entry.h"
33 #include "components/autofill/core/common/autofill_clock.h"
34 #include "components/autofill/core/common/autofill_constants.h"
35 #include "components/autofill/core/common/autofill_features.h"
36 #include "components/autofill/core/common/autofill_switches.h"
37 #include "components/autofill/core/common/autofill_util.h"
38 #include "components/autofill/core/common/form_field_data.h"
39 #include "components/os_crypt/os_crypt_mocker.h"
40 #include "components/sync/protocol/entity_metadata.pb.h"
41 #include "components/sync/protocol/model_type_state.pb.h"
42 #include "components/webdata/common/web_database.h"
43 #include "sql/statement.h"
44 #include "testing/gmock/include/gmock/gmock.h"
45 #include "testing/gtest/include/gtest/gtest.h"
46 
47 using base::ASCIIToUTF16;
48 using base::Time;
49 using base::TimeDelta;
50 using sync_pb::EntityMetadata;
51 using sync_pb::ModelTypeState;
52 using syncer::EntityMetadataMap;
53 using syncer::MetadataBatch;
54 using testing::ElementsAre;
55 using testing::UnorderedElementsAre;
56 
57 namespace autofill {
58 
59 // So we can compare AutofillKeys with EXPECT_EQ().
operator <<(std::ostream & os,const AutofillKey & key)60 std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
61   return os << base::UTF16ToASCII(key.name()) << ", "
62             << base::UTF16ToASCII(key.value());
63 }
64 
65 // So we can compare AutofillChanges with EXPECT_EQ().
operator <<(std::ostream & os,const AutofillChange & change)66 std::ostream& operator<<(std::ostream& os, const AutofillChange& change) {
67   switch (change.type()) {
68     case AutofillChange::ADD: {
69       os << "ADD";
70       break;
71     }
72     case AutofillChange::UPDATE: {
73       os << "UPDATE";
74       break;
75     }
76     case AutofillChange::REMOVE: {
77       os << "REMOVE";
78       break;
79     }
80     case AutofillChange::EXPIRE: {
81       os << "EXPIRED";
82       break;
83     }
84   }
85   return os << " " << change.key();
86 }
87 
88 namespace {
89 
90 typedef std::set<AutofillEntry,
91                  bool (*)(const AutofillEntry&, const AutofillEntry&)>
92     AutofillEntrySet;
93 typedef AutofillEntrySet::iterator AutofillEntrySetIterator;
94 
CompareAutofillEntries(const AutofillEntry & a,const AutofillEntry & b)95 bool CompareAutofillEntries(const AutofillEntry& a, const AutofillEntry& b) {
96   return std::tie(a.key().name(), a.key().value(), a.date_created(),
97                   a.date_last_used()) <
98          std::tie(b.key().name(), b.key().value(), b.date_created(),
99                   b.date_last_used());
100 }
101 
MakeAutofillEntry(const std::string & name,const std::string & value,time_t date_created,time_t date_last_used)102 AutofillEntry MakeAutofillEntry(const std::string& name,
103                                 const std::string& value,
104                                 time_t date_created,
105                                 time_t date_last_used) {
106   if (date_last_used < 0)
107     date_last_used = date_created;
108   return AutofillEntry(AutofillKey(ASCIIToUTF16(name), ASCIIToUTF16(value)),
109                        Time::FromTimeT(date_created),
110                        Time::FromTimeT(date_last_used));
111 }
112 
113 // Checks |actual| and |expected| contain the same elements.
CompareAutofillEntrySets(const AutofillEntrySet & actual,const AutofillEntrySet & expected)114 void CompareAutofillEntrySets(const AutofillEntrySet& actual,
115                               const AutofillEntrySet& expected) {
116   ASSERT_EQ(expected.size(), actual.size());
117   size_t count = 0;
118   for (auto it = actual.begin(); it != actual.end(); ++it) {
119     count += expected.count(*it);
120   }
121   EXPECT_EQ(actual.size(), count);
122 }
123 
GetAutofillEntryCount(const base::string16 & name,const base::string16 & value,WebDatabase * db)124 int GetAutofillEntryCount(const base::string16& name,
125                           const base::string16& value,
126                           WebDatabase* db) {
127   sql::Statement s(db->GetSQLConnection()->GetUniqueStatement(
128       "SELECT count FROM autofill WHERE name = ? AND value = ?"));
129   s.BindString16(0, name);
130   s.BindString16(1, value);
131   s.Step();
132   return s.ColumnInt(0);
133 }
134 
135 }  // namespace
136 
137 class AutofillTableTest : public testing::Test {
138  public:
AutofillTableTest()139   AutofillTableTest() {}
~AutofillTableTest()140   ~AutofillTableTest() override {}
141 
142  protected:
SetUp()143   void SetUp() override {
144     OSCryptMocker::SetUp();
145     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
146     file_ = temp_dir_.GetPath().AppendASCII("TestWebDatabase");
147 
148     table_.reset(new AutofillTable);
149     db_.reset(new WebDatabase);
150     db_->AddTable(table_.get());
151     ASSERT_EQ(sql::INIT_OK, db_->Init(file_));
152   }
153 
TearDown()154   void TearDown() override { OSCryptMocker::TearDown(); }
155 
156   base::FilePath file_;
157   base::ScopedTempDir temp_dir_;
158   std::unique_ptr<AutofillTable> table_;
159   std::unique_ptr<WebDatabase> db_;
160   base::test::ScopedFeatureList scoped_feature_list_;
161 
162  private:
163   DISALLOW_COPY_AND_ASSIGN(AutofillTableTest);
164 };
165 
TEST_F(AutofillTableTest,Autofill)166 TEST_F(AutofillTableTest, Autofill) {
167   Time t1 = AutofillClock::Now();
168 
169   // Simulate the submission of a handful of entries in a field called "Name",
170   // some more often than others.
171   AutofillChangeList changes;
172   FormFieldData field;
173   field.name = ASCIIToUTF16("Name");
174   field.value = ASCIIToUTF16("Superman");
175   base::Time now = AutofillClock::Now();
176   base::TimeDelta two_seconds = base::TimeDelta::FromSeconds(2);
177   EXPECT_TRUE(table_->AddFormFieldValue(field, &changes));
178   std::vector<AutofillEntry> v;
179   for (int i = 0; i < 5; ++i) {
180     field.value = ASCIIToUTF16("Clark Kent");
181     EXPECT_TRUE(
182         table_->AddFormFieldValueTime(field, &changes, now + i * two_seconds));
183   }
184   for (int i = 0; i < 3; ++i) {
185     field.value = ASCIIToUTF16("Clark Sutter");
186     EXPECT_TRUE(
187         table_->AddFormFieldValueTime(field, &changes, now + i * two_seconds));
188   }
189   for (int i = 0; i < 2; ++i) {
190     field.name = ASCIIToUTF16("Favorite Color");
191     field.value = ASCIIToUTF16("Green");
192     EXPECT_TRUE(
193         table_->AddFormFieldValueTime(field, &changes, now + i * two_seconds));
194   }
195 
196   // We have added the name Clark Kent 5 times, so count should be 5.
197   EXPECT_EQ(5, GetAutofillEntryCount(ASCIIToUTF16("Name"),
198                                      ASCIIToUTF16("Clark Kent"), db_.get()));
199 
200   // Storing in the data base should be case sensitive, so there should be no
201   // database entry for clark kent lowercase.
202   EXPECT_EQ(0, GetAutofillEntryCount(ASCIIToUTF16("Name"),
203                                      ASCIIToUTF16("clark kent"), db_.get()));
204 
205   EXPECT_EQ(2, GetAutofillEntryCount(ASCIIToUTF16("Favorite Color"),
206                                      ASCIIToUTF16("Green"), db_.get()));
207 
208   // This is meant to get a list of suggestions for Name.  The empty prefix
209   // in the second argument means it should return all suggestions for a name
210   // no matter what they start with.  The order that the names occur in the list
211   // should be decreasing order by count.
212   EXPECT_TRUE(table_->GetFormValuesForElementName(ASCIIToUTF16("Name"),
213                                                   base::string16(), &v, 6));
214   EXPECT_EQ(3U, v.size());
215   if (v.size() == 3) {
216     EXPECT_EQ(ASCIIToUTF16("Clark Kent"), v[0].key().value());
217     EXPECT_EQ(ASCIIToUTF16("Clark Sutter"), v[1].key().value());
218     EXPECT_EQ(ASCIIToUTF16("Superman"), v[2].key().value());
219   }
220 
221   // If we query again limiting the list size to 1, we should only get the most
222   // frequent entry.
223   EXPECT_TRUE(table_->GetFormValuesForElementName(ASCIIToUTF16("Name"),
224                                                   base::string16(), &v, 1));
225   EXPECT_EQ(1U, v.size());
226   if (v.size() == 1) {
227     EXPECT_EQ(ASCIIToUTF16("Clark Kent"), v[0].key().value());
228   }
229 
230   // Querying for suggestions given a prefix is case-insensitive, so the prefix
231   // "cLa" shoud get suggestions for both Clarks.
232   EXPECT_TRUE(table_->GetFormValuesForElementName(ASCIIToUTF16("Name"),
233                                                   ASCIIToUTF16("cLa"), &v, 6));
234   EXPECT_EQ(2U, v.size());
235   if (v.size() == 2) {
236     EXPECT_EQ(ASCIIToUTF16("Clark Kent"), v[0].key().value());
237     EXPECT_EQ(ASCIIToUTF16("Clark Sutter"), v[1].key().value());
238   }
239 
240   // Removing all elements since the beginning of this function should remove
241   // everything from the database.
242   changes.clear();
243   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(t1, Time(), &changes));
244 
245   const AutofillChange kExpectedChanges[] = {
246       AutofillChange(
247           AutofillChange::REMOVE,
248           AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"))),
249       AutofillChange(
250           AutofillChange::REMOVE,
251           AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Clark Kent"))),
252       AutofillChange(
253           AutofillChange::REMOVE,
254           AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Clark Sutter"))),
255       AutofillChange(
256           AutofillChange::REMOVE,
257           AutofillKey(ASCIIToUTF16("Favorite Color"), ASCIIToUTF16("Green"))),
258   };
259   EXPECT_EQ(base::size(kExpectedChanges), changes.size());
260   for (size_t i = 0; i < base::size(kExpectedChanges); ++i) {
261     EXPECT_EQ(kExpectedChanges[i], changes[i]);
262   }
263 
264   EXPECT_EQ(0, GetAutofillEntryCount(ASCIIToUTF16("Name"),
265                                      ASCIIToUTF16("Clark Kent"), db_.get()));
266 
267   EXPECT_TRUE(table_->GetFormValuesForElementName(ASCIIToUTF16("Name"),
268                                                   base::string16(), &v, 6));
269   EXPECT_EQ(0U, v.size());
270 
271   // Now add some values with empty strings.
272   const base::string16 kValue = ASCIIToUTF16("  toto   ");
273   field.name = ASCIIToUTF16("blank");
274   field.value = base::string16();
275   EXPECT_TRUE(table_->AddFormFieldValue(field, &changes));
276   field.name = ASCIIToUTF16("blank");
277   field.value = ASCIIToUTF16(" ");
278   EXPECT_TRUE(table_->AddFormFieldValue(field, &changes));
279   field.name = ASCIIToUTF16("blank");
280   field.value = ASCIIToUTF16("      ");
281   EXPECT_TRUE(table_->AddFormFieldValue(field, &changes));
282   field.name = ASCIIToUTF16("blank");
283   field.value = kValue;
284   EXPECT_TRUE(table_->AddFormFieldValue(field, &changes));
285 
286   // They should be stored normally as the DB layer does not check for empty
287   // values.
288   v.clear();
289   EXPECT_TRUE(table_->GetFormValuesForElementName(ASCIIToUTF16("blank"),
290                                                   base::string16(), &v, 10));
291   EXPECT_EQ(4U, v.size());
292 }
293 
TEST_F(AutofillTableTest,Autofill_GetEntry_Populated)294 TEST_F(AutofillTableTest, Autofill_GetEntry_Populated) {
295   AutofillChangeList changes;
296   FormFieldData field;
297   field.name = ASCIIToUTF16("Name");
298   field.value = ASCIIToUTF16("Superman");
299   base::Time now = base::Time::FromDoubleT(1546889367);
300 
301   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, now));
302 
303   std::vector<AutofillEntry> prefix_v;
304   EXPECT_TRUE(table_->GetFormValuesForElementName(
305       field.name, ASCIIToUTF16("Super"), &prefix_v, 10));
306 
307   std::vector<AutofillEntry> no_prefix_v;
308   EXPECT_TRUE(table_->GetFormValuesForElementName(field.name, ASCIIToUTF16(""),
309                                                   &no_prefix_v, 10));
310 
311   AutofillEntry expected_entry(AutofillKey(field.name, field.value), now, now);
312 
313   EXPECT_THAT(prefix_v, ElementsAre(expected_entry));
314   EXPECT_THAT(no_prefix_v, ElementsAre(expected_entry));
315 
316   // Update date_last_used.
317   base::Time new_time = now + base::TimeDelta::FromSeconds(1000);
318   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, new_time));
319   EXPECT_TRUE(table_->GetFormValuesForElementName(
320       field.name, ASCIIToUTF16("Super"), &prefix_v, 10));
321   EXPECT_TRUE(table_->GetFormValuesForElementName(field.name, ASCIIToUTF16(""),
322                                                   &no_prefix_v, 10));
323 
324   expected_entry =
325       AutofillEntry(AutofillKey(field.name, field.value), now, new_time);
326 
327   EXPECT_THAT(prefix_v, ElementsAre(expected_entry));
328   EXPECT_THAT(no_prefix_v, ElementsAre(expected_entry));
329 }
330 
TEST_F(AutofillTableTest,Autofill_GetCountOfValuesContainedBetween)331 TEST_F(AutofillTableTest, Autofill_GetCountOfValuesContainedBetween) {
332   AutofillChangeList changes;
333   // This test makes time comparisons that are precise to a microsecond, but the
334   // database uses the time_t format which is only precise to a second.
335   // Make sure we use timestamps rounded to a second.
336   Time begin = Time::FromTimeT(AutofillClock::Now().ToTimeT());
337   Time now = begin;
338   TimeDelta second = TimeDelta::FromSeconds(1);
339 
340   struct Entry {
341     const char* name;
342     const char* value;
343   } entries[] = {{"Alter ego", "Superman"}, {"Name", "Superman"},
344                  {"Name", "Clark Kent"},    {"Name", "Superman"},
345                  {"Name", "Clark Sutter"},  {"Nomen", "Clark Kent"}};
346 
347   for (Entry entry : entries) {
348     FormFieldData field;
349     field.name = ASCIIToUTF16(entry.name);
350     field.value = ASCIIToUTF16(entry.value);
351     ASSERT_TRUE(table_->AddFormFieldValueTime(field, &changes, now));
352     now += second;
353   }
354 
355   // While the entry "Alter ego" : "Superman" is entirely contained within
356   // the first second, the value "Superman" itself appears in another entry,
357   // so it is not contained.
358   EXPECT_EQ(0, table_->GetCountOfValuesContainedBetween(begin, begin + second));
359 
360   // No values are entirely contained within the first three seconds either
361   // (note that the second time constraint is exclusive).
362   EXPECT_EQ(
363       0, table_->GetCountOfValuesContainedBetween(begin, begin + 3 * second));
364 
365   // Only "Superman" is entirely contained within the first four seconds.
366   EXPECT_EQ(
367       1, table_->GetCountOfValuesContainedBetween(begin, begin + 4 * second));
368 
369   // "Clark Kent" and "Clark Sutter" are contained between the first
370   // and seventh second.
371   EXPECT_EQ(2, table_->GetCountOfValuesContainedBetween(begin + second,
372                                                         begin + 7 * second));
373 
374   // Beginning from the third second, "Clark Kent" is not contained.
375   EXPECT_EQ(1, table_->GetCountOfValuesContainedBetween(begin + 3 * second,
376                                                         begin + 7 * second));
377 
378   // We have three distinct values total.
379   EXPECT_EQ(
380       3, table_->GetCountOfValuesContainedBetween(begin, begin + 7 * second));
381 
382   // And we should get the same result for unlimited time interval.
383   EXPECT_EQ(3, table_->GetCountOfValuesContainedBetween(Time(), Time::Max()));
384 
385   // The null time interval is also interpreted as unlimited.
386   EXPECT_EQ(3, table_->GetCountOfValuesContainedBetween(Time(), Time()));
387 
388   // An interval that does not fully contain any entries returns zero.
389   EXPECT_EQ(0, table_->GetCountOfValuesContainedBetween(begin + second,
390                                                         begin + 2 * second));
391 
392   // So does an interval which has no intersection with any entry.
393   EXPECT_EQ(0, table_->GetCountOfValuesContainedBetween(Time(), begin));
394 }
395 
TEST_F(AutofillTableTest,Autofill_RemoveBetweenChanges)396 TEST_F(AutofillTableTest, Autofill_RemoveBetweenChanges) {
397   TimeDelta one_day(TimeDelta::FromDays(1));
398   Time t1 = AutofillClock::Now();
399   Time t2 = t1 + one_day;
400 
401   AutofillChangeList changes;
402   FormFieldData field;
403   field.name = ASCIIToUTF16("Name");
404   field.value = ASCIIToUTF16("Superman");
405   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, t1));
406   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, t2));
407 
408   changes.clear();
409   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(t1, t2, &changes));
410   ASSERT_EQ(1U, changes.size());
411   EXPECT_EQ(AutofillChange(
412                 AutofillChange::UPDATE,
413                 AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"))),
414             changes[0]);
415   changes.clear();
416 
417   EXPECT_TRUE(
418       table_->RemoveFormElementsAddedBetween(t2, t2 + one_day, &changes));
419   ASSERT_EQ(1U, changes.size());
420   EXPECT_EQ(AutofillChange(
421                 AutofillChange::REMOVE,
422                 AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"))),
423             changes[0]);
424 }
425 
TEST_F(AutofillTableTest,Autofill_AddChanges)426 TEST_F(AutofillTableTest, Autofill_AddChanges) {
427   TimeDelta one_day(TimeDelta::FromDays(1));
428   Time t1 = AutofillClock::Now();
429   Time t2 = t1 + one_day;
430 
431   AutofillChangeList changes;
432   FormFieldData field;
433   field.name = ASCIIToUTF16("Name");
434   field.value = ASCIIToUTF16("Superman");
435   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, t1));
436   ASSERT_EQ(1U, changes.size());
437   EXPECT_EQ(AutofillChange(
438                 AutofillChange::ADD,
439                 AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"))),
440             changes[0]);
441 
442   changes.clear();
443   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, t2));
444   ASSERT_EQ(1U, changes.size());
445   EXPECT_EQ(AutofillChange(
446                 AutofillChange::UPDATE,
447                 AutofillKey(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"))),
448             changes[0]);
449 }
450 
TEST_F(AutofillTableTest,Autofill_UpdateOneWithOneTimestamp)451 TEST_F(AutofillTableTest, Autofill_UpdateOneWithOneTimestamp) {
452   AutofillEntry entry(MakeAutofillEntry("foo", "bar", 1, -1));
453   std::vector<AutofillEntry> entries;
454   entries.push_back(entry);
455   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
456 
457   EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16("foo"), ASCIIToUTF16("bar"),
458                                      db_.get()));
459 
460   std::vector<AutofillEntry> all_entries;
461   ASSERT_TRUE(table_->GetAllAutofillEntries(&all_entries));
462   ASSERT_EQ(1U, all_entries.size());
463   EXPECT_EQ(entry, all_entries[0]);
464 }
465 
TEST_F(AutofillTableTest,Autofill_UpdateOneWithTwoTimestamps)466 TEST_F(AutofillTableTest, Autofill_UpdateOneWithTwoTimestamps) {
467   AutofillEntry entry(MakeAutofillEntry("foo", "bar", 1, 2));
468   std::vector<AutofillEntry> entries;
469   entries.push_back(entry);
470   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
471 
472   EXPECT_EQ(2, GetAutofillEntryCount(ASCIIToUTF16("foo"), ASCIIToUTF16("bar"),
473                                      db_.get()));
474 
475   std::vector<AutofillEntry> all_entries;
476   ASSERT_TRUE(table_->GetAllAutofillEntries(&all_entries));
477   ASSERT_EQ(1U, all_entries.size());
478   EXPECT_EQ(entry, all_entries[0]);
479 }
480 
TEST_F(AutofillTableTest,Autofill_GetAutofillTimestamps)481 TEST_F(AutofillTableTest, Autofill_GetAutofillTimestamps) {
482   AutofillEntry entry(MakeAutofillEntry("foo", "bar", 1, 2));
483   std::vector<AutofillEntry> entries;
484   entries.push_back(entry);
485   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
486 
487   Time date_created, date_last_used;
488   ASSERT_TRUE(table_->GetAutofillTimestamps(ASCIIToUTF16("foo"),
489                                             ASCIIToUTF16("bar"), &date_created,
490                                             &date_last_used));
491   EXPECT_EQ(Time::FromTimeT(1), date_created);
492   EXPECT_EQ(Time::FromTimeT(2), date_last_used);
493 }
494 
TEST_F(AutofillTableTest,Autofill_UpdateTwo)495 TEST_F(AutofillTableTest, Autofill_UpdateTwo) {
496   AutofillEntry entry0(MakeAutofillEntry("foo", "bar0", 1, -1));
497   AutofillEntry entry1(MakeAutofillEntry("foo", "bar1", 2, 3));
498   std::vector<AutofillEntry> entries;
499   entries.push_back(entry0);
500   entries.push_back(entry1);
501   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
502 
503   EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16("foo"), ASCIIToUTF16("bar0"),
504                                      db_.get()));
505   EXPECT_EQ(2, GetAutofillEntryCount(ASCIIToUTF16("foo"), ASCIIToUTF16("bar1"),
506                                      db_.get()));
507 }
508 
TEST_F(AutofillTableTest,Autofill_UpdateNullTerminated)509 TEST_F(AutofillTableTest, Autofill_UpdateNullTerminated) {
510   const char kName[] = "foo";
511   const char kValue[] = "bar";
512   // A value which contains terminating character.
513   std::string value(kValue, base::size(kValue));
514 
515   AutofillEntry entry0(MakeAutofillEntry(kName, kValue, 1, -1));
516   AutofillEntry entry1(MakeAutofillEntry(kName, value, 2, 3));
517   std::vector<AutofillEntry> entries;
518   entries.push_back(entry0);
519   entries.push_back(entry1);
520   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
521 
522   EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16(kName), ASCIIToUTF16(kValue),
523                                      db_.get()));
524   EXPECT_EQ(2, GetAutofillEntryCount(ASCIIToUTF16(kName), ASCIIToUTF16(value),
525                                      db_.get()));
526 
527   std::vector<AutofillEntry> all_entries;
528   ASSERT_TRUE(table_->GetAllAutofillEntries(&all_entries));
529   ASSERT_EQ(2U, all_entries.size());
530   EXPECT_EQ(entry0, all_entries[0]);
531   EXPECT_EQ(entry1, all_entries[1]);
532 }
533 
TEST_F(AutofillTableTest,Autofill_UpdateReplace)534 TEST_F(AutofillTableTest, Autofill_UpdateReplace) {
535   AutofillChangeList changes;
536   // Add a form field.  This will be replaced.
537   FormFieldData field;
538   field.name = ASCIIToUTF16("Name");
539   field.value = ASCIIToUTF16("Superman");
540   EXPECT_TRUE(table_->AddFormFieldValue(field, &changes));
541 
542   AutofillEntry entry(MakeAutofillEntry("Name", "Superman", 1, 2));
543   std::vector<AutofillEntry> entries;
544   entries.push_back(entry);
545   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
546 
547   std::vector<AutofillEntry> all_entries;
548   ASSERT_TRUE(table_->GetAllAutofillEntries(&all_entries));
549   ASSERT_EQ(1U, all_entries.size());
550   EXPECT_EQ(entry, all_entries[0]);
551 }
552 
TEST_F(AutofillTableTest,Autofill_UpdateDontReplace)553 TEST_F(AutofillTableTest, Autofill_UpdateDontReplace) {
554   Time t = AutofillClock::Now();
555   AutofillEntry existing(
556       MakeAutofillEntry("Name", "Superman", t.ToTimeT(), -1));
557 
558   AutofillChangeList changes;
559   // Add a form field.  This will NOT be replaced.
560   FormFieldData field;
561   field.name = existing.key().name();
562   field.value = existing.key().value();
563   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, t));
564   AutofillEntry entry(MakeAutofillEntry("Name", "Clark Kent", 1, 2));
565   std::vector<AutofillEntry> entries;
566   entries.push_back(entry);
567   ASSERT_TRUE(table_->UpdateAutofillEntries(entries));
568 
569   std::vector<AutofillEntry> all_entries;
570   ASSERT_TRUE(table_->GetAllAutofillEntries(&all_entries));
571   ASSERT_EQ(2U, all_entries.size());
572   AutofillEntrySet expected_entries(all_entries.begin(), all_entries.end(),
573                                     CompareAutofillEntries);
574   EXPECT_EQ(1U, expected_entries.count(existing));
575   EXPECT_EQ(1U, expected_entries.count(entry));
576 }
577 
TEST_F(AutofillTableTest,Autofill_AddFormFieldValues)578 TEST_F(AutofillTableTest, Autofill_AddFormFieldValues) {
579   Time t = AutofillClock::Now();
580 
581   // Add multiple values for "firstname" and "lastname" names.  Test that only
582   // first value of each gets added. Related to security issue:
583   // http://crbug.com/51727.
584   std::vector<FormFieldData> elements;
585   FormFieldData field;
586   field.name = ASCIIToUTF16("firstname");
587   field.value = ASCIIToUTF16("Joe");
588   elements.push_back(field);
589 
590   field.name = ASCIIToUTF16("firstname");
591   field.value = ASCIIToUTF16("Jane");
592   elements.push_back(field);
593 
594   field.name = ASCIIToUTF16("lastname");
595   field.value = ASCIIToUTF16("Smith");
596   elements.push_back(field);
597 
598   field.name = ASCIIToUTF16("lastname");
599   field.value = ASCIIToUTF16("Jones");
600   elements.push_back(field);
601 
602   std::vector<AutofillChange> changes;
603   table_->AddFormFieldValuesTime(elements, &changes, t);
604 
605   ASSERT_EQ(2U, changes.size());
606   EXPECT_EQ(changes[0], AutofillChange(AutofillChange::ADD,
607                                        AutofillKey(ASCIIToUTF16("firstname"),
608                                                    ASCIIToUTF16("Joe"))));
609   EXPECT_EQ(changes[1], AutofillChange(AutofillChange::ADD,
610                                        AutofillKey(ASCIIToUTF16("lastname"),
611                                                    ASCIIToUTF16("Smith"))));
612 
613   std::vector<AutofillEntry> all_entries;
614   ASSERT_TRUE(table_->GetAllAutofillEntries(&all_entries));
615   ASSERT_EQ(2U, all_entries.size());
616 }
617 
TEST_F(AutofillTableTest,Autofill_RemoveFormElementsAddedBetween_UsedOnlyBefore)618 TEST_F(AutofillTableTest,
619        Autofill_RemoveFormElementsAddedBetween_UsedOnlyBefore) {
620   // Add an entry used only before the targetted range.
621   AutofillChangeList changes;
622   FormFieldData field;
623   field.name = ASCIIToUTF16("Name");
624   field.value = ASCIIToUTF16("Superman");
625   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
626                                             base::Time::FromTimeT(10)));
627   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
628                                             base::Time::FromTimeT(20)));
629   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
630                                             base::Time::FromTimeT(30)));
631   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
632                                             base::Time::FromTimeT(40)));
633   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
634                                             base::Time::FromTimeT(50)));
635 
636   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
637 
638   changes.clear();
639   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(
640       base::Time::FromTimeT(51), base::Time::FromTimeT(60), &changes));
641   EXPECT_TRUE(changes.empty());
642   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
643 }
644 
TEST_F(AutofillTableTest,Autofill_RemoveFormElementsAddedBetween_UsedOnlyAfter)645 TEST_F(AutofillTableTest,
646        Autofill_RemoveFormElementsAddedBetween_UsedOnlyAfter) {
647   // Add an entry used only after the targetted range.
648   AutofillChangeList changes;
649   FormFieldData field;
650   field.name = ASCIIToUTF16("Name");
651   field.value = ASCIIToUTF16("Superman");
652   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
653                                             base::Time::FromTimeT(50)));
654   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
655                                             base::Time::FromTimeT(60)));
656   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
657                                             base::Time::FromTimeT(70)));
658   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
659                                             base::Time::FromTimeT(80)));
660   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
661                                             base::Time::FromTimeT(90)));
662 
663   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
664 
665   changes.clear();
666   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(
667       base::Time::FromTimeT(40), base::Time::FromTimeT(50), &changes));
668   EXPECT_TRUE(changes.empty());
669   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
670 }
671 
TEST_F(AutofillTableTest,Autofill_RemoveFormElementsAddedBetween_UsedOnlyDuring)672 TEST_F(AutofillTableTest,
673        Autofill_RemoveFormElementsAddedBetween_UsedOnlyDuring) {
674   // Add an entry used entirely during the targetted range.
675   AutofillChangeList changes;
676   FormFieldData field;
677   field.name = ASCIIToUTF16("Name");
678   field.value = ASCIIToUTF16("Superman");
679   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
680                                             base::Time::FromTimeT(10)));
681   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
682                                             base::Time::FromTimeT(20)));
683   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
684                                             base::Time::FromTimeT(30)));
685   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
686                                             base::Time::FromTimeT(40)));
687   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
688                                             base::Time::FromTimeT(50)));
689 
690   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
691 
692   changes.clear();
693   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(
694       base::Time::FromTimeT(10), base::Time::FromTimeT(51), &changes));
695   ASSERT_EQ(1U, changes.size());
696   EXPECT_EQ(AutofillChange(AutofillChange::REMOVE,
697                            AutofillKey(field.name, field.value)),
698             changes[0]);
699   EXPECT_EQ(0, GetAutofillEntryCount(field.name, field.value, db_.get()));
700 }
701 
TEST_F(AutofillTableTest,Autofill_RemoveFormElementsAddedBetween_UsedBeforeAndDuring)702 TEST_F(AutofillTableTest,
703        Autofill_RemoveFormElementsAddedBetween_UsedBeforeAndDuring) {
704   // Add an entry used both before and during the targetted range.
705   AutofillChangeList changes;
706   FormFieldData field;
707   field.name = ASCIIToUTF16("Name");
708   field.value = ASCIIToUTF16("Superman");
709   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
710                                             base::Time::FromTimeT(10)));
711   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
712                                             base::Time::FromTimeT(20)));
713   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
714                                             base::Time::FromTimeT(30)));
715   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
716                                             base::Time::FromTimeT(40)));
717   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
718                                             base::Time::FromTimeT(50)));
719 
720   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
721 
722   changes.clear();
723   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(
724       base::Time::FromTimeT(40), base::Time::FromTimeT(60), &changes));
725   ASSERT_EQ(1U, changes.size());
726   EXPECT_EQ(AutofillChange(AutofillChange::UPDATE,
727                            AutofillKey(field.name, field.value)),
728             changes[0]);
729   EXPECT_EQ(4, GetAutofillEntryCount(field.name, field.value, db_.get()));
730   base::Time date_created, date_last_used;
731   EXPECT_TRUE(table_->GetAutofillTimestamps(field.name, field.value,
732                                             &date_created, &date_last_used));
733   EXPECT_EQ(base::Time::FromTimeT(10), date_created);
734   EXPECT_EQ(base::Time::FromTimeT(39), date_last_used);
735 }
736 
TEST_F(AutofillTableTest,Autofill_RemoveFormElementsAddedBetween_UsedDuringAndAfter)737 TEST_F(AutofillTableTest,
738        Autofill_RemoveFormElementsAddedBetween_UsedDuringAndAfter) {
739   // Add an entry used both during and after the targetted range.
740   AutofillChangeList changes;
741   FormFieldData field;
742   field.name = ASCIIToUTF16("Name");
743   field.value = ASCIIToUTF16("Superman");
744   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
745                                             base::Time::FromTimeT(50)));
746   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
747                                             base::Time::FromTimeT(60)));
748   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
749                                             base::Time::FromTimeT(70)));
750   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
751                                             base::Time::FromTimeT(80)));
752   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes,
753                                             base::Time::FromTimeT(90)));
754 
755   EXPECT_EQ(5, GetAutofillEntryCount(field.name, field.value, db_.get()));
756 
757   changes.clear();
758   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(
759       base::Time::FromTimeT(40), base::Time::FromTimeT(80), &changes));
760   ASSERT_EQ(1U, changes.size());
761   EXPECT_EQ(AutofillChange(AutofillChange::UPDATE,
762                            AutofillKey(field.name, field.value)),
763             changes[0]);
764   EXPECT_EQ(2, GetAutofillEntryCount(field.name, field.value, db_.get()));
765   base::Time date_created, date_last_used;
766   EXPECT_TRUE(table_->GetAutofillTimestamps(field.name, field.value,
767                                             &date_created, &date_last_used));
768   EXPECT_EQ(base::Time::FromTimeT(80), date_created);
769   EXPECT_EQ(base::Time::FromTimeT(90), date_last_used);
770 }
771 
TEST_F(AutofillTableTest,Autofill_RemoveFormElementsAddedBetween_OlderThan30Days)772 TEST_F(AutofillTableTest,
773        Autofill_RemoveFormElementsAddedBetween_OlderThan30Days) {
774   const base::Time kNow = AutofillClock::Now();
775   const base::Time k29DaysOld = kNow - base::TimeDelta::FromDays(29);
776   const base::Time k30DaysOld = kNow - base::TimeDelta::FromDays(30);
777   const base::Time k31DaysOld = kNow - base::TimeDelta::FromDays(31);
778 
779   // Add some form field entries.
780   AutofillChangeList changes;
781   FormFieldData field;
782   field.name = ASCIIToUTF16("Name");
783   field.value = ASCIIToUTF16("Superman");
784   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, kNow));
785   field.value = ASCIIToUTF16("Clark Kent");
786   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, k29DaysOld));
787   field.value = ASCIIToUTF16("Clark Sutter");
788   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, k31DaysOld));
789   EXPECT_EQ(3U, changes.size());
790 
791   // Removing all elements added before 30days from the database.
792   changes.clear();
793   EXPECT_TRUE(table_->RemoveFormElementsAddedBetween(base::Time(), k30DaysOld,
794                                                      &changes));
795   ASSERT_EQ(1U, changes.size());
796   EXPECT_EQ(AutofillChange(AutofillChange::REMOVE,
797                            AutofillKey(ASCIIToUTF16("Name"),
798                                        ASCIIToUTF16("Clark Sutter"))),
799             changes[0]);
800   EXPECT_EQ(0, GetAutofillEntryCount(ASCIIToUTF16("Name"),
801                                      ASCIIToUTF16("Clark Sutter"), db_.get()));
802   EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16("Name"),
803                                      ASCIIToUTF16("Superman"), db_.get()));
804   EXPECT_EQ(1, GetAutofillEntryCount(ASCIIToUTF16("Name"),
805                                      ASCIIToUTF16("Clark Kent"), db_.get()));
806   changes.clear();
807 }
808 
809 // Tests that we set the change type to EXPIRE for expired elements and we
810 // delete an old entry.
TEST_F(AutofillTableTest,RemoveExpiredFormElements_Expires_DeleteEntry)811 TEST_F(AutofillTableTest, RemoveExpiredFormElements_Expires_DeleteEntry) {
812   auto kNow = AutofillClock::Now();
813   auto k2YearsOld = kNow - base::TimeDelta::FromDays(
814                                2 * kAutocompleteRetentionPolicyPeriodInDays);
815 
816   AutofillChangeList changes;
817   FormFieldData field;
818   field.name = ASCIIToUTF16("Name");
819   field.value = ASCIIToUTF16("Superman");
820   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, k2YearsOld));
821   changes.clear();
822 
823   EXPECT_TRUE(table_->RemoveExpiredFormElements(&changes));
824 
825   EXPECT_EQ(AutofillChange(AutofillChange::EXPIRE,
826                            AutofillKey(field.name, field.value)),
827             changes[0]);
828 }
829 
830 // Tests that we don't
831 // delete non-expired entries' data from the SQLite table.
TEST_F(AutofillTableTest,RemoveExpiredFormElements_NotOldEnough)832 TEST_F(AutofillTableTest, RemoveExpiredFormElements_NotOldEnough) {
833   auto kNow = AutofillClock::Now();
834   auto k2DaysOld = kNow - base::TimeDelta::FromDays(2);
835 
836   AutofillChangeList changes;
837   FormFieldData field;
838   field.name = ASCIIToUTF16("Name");
839   field.value = ASCIIToUTF16("Superman");
840   EXPECT_TRUE(table_->AddFormFieldValueTime(field, &changes, k2DaysOld));
841   changes.clear();
842 
843   EXPECT_TRUE(table_->RemoveExpiredFormElements(&changes));
844   EXPECT_TRUE(changes.empty());
845 }
846 
TEST_F(AutofillTableTest,AutofillProfile)847 TEST_F(AutofillTableTest, AutofillProfile) {
848   // Add a 'Home' profile with non-default data. The specific values are not
849   // important.
850   AutofillProfile home_profile;
851   home_profile.set_origin(std::string());
852   home_profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John"));
853   home_profile.SetRawInfo(NAME_MIDDLE, ASCIIToUTF16("Q."));
854   home_profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
855   home_profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("js@smith.xyz"));
856   home_profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Google"));
857   home_profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 Apple Way"));
858   home_profile.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("unit 5"));
859   home_profile.SetRawInfo(ADDRESS_HOME_DEPENDENT_LOCALITY,
860                           ASCIIToUTF16("Beverly Hills"));
861   home_profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Los Angeles"));
862   home_profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
863   home_profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("90025"));
864   home_profile.SetRawInfo(ADDRESS_HOME_SORTING_CODE, ASCIIToUTF16("MAGIC ###"));
865   home_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
866   home_profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("18181234567"));
867   home_profile.set_language_code("en");
868   home_profile.SetClientValidityFromBitfieldValue(6);
869   home_profile.set_is_client_validity_states_updated(true);
870 
871   Time pre_creation_time = AutofillClock::Now();
872   EXPECT_TRUE(table_->AddAutofillProfile(home_profile));
873   Time post_creation_time = AutofillClock::Now();
874 
875   // Get the 'Home' profile.
876   std::unique_ptr<AutofillProfile> db_profile =
877       table_->GetAutofillProfile(home_profile.guid());
878   ASSERT_TRUE(db_profile);
879   EXPECT_EQ(home_profile, *db_profile);
880   sql::Statement s_home(db_->GetSQLConnection()->GetUniqueStatement(
881       "SELECT date_modified "
882       "FROM autofill_profiles WHERE guid=?"));
883   s_home.BindString(0, home_profile.guid());
884   ASSERT_TRUE(s_home.is_valid());
885   ASSERT_TRUE(s_home.Step());
886   EXPECT_GE(s_home.ColumnInt64(0), pre_creation_time.ToTimeT());
887   EXPECT_LE(s_home.ColumnInt64(0), post_creation_time.ToTimeT());
888   EXPECT_FALSE(s_home.Step());
889 
890   // Add a 'Billing' profile.
891   AutofillProfile billing_profile = home_profile;
892   billing_profile.set_guid(base::GenerateGUID());
893   billing_profile.set_origin("https://www.example.com/");
894   billing_profile.SetRawInfo(ADDRESS_HOME_LINE1,
895                              ASCIIToUTF16("5678 Bottom Street"));
896   billing_profile.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("suite 3"));
897 
898   pre_creation_time = AutofillClock::Now();
899   EXPECT_TRUE(table_->AddAutofillProfile(billing_profile));
900   post_creation_time = AutofillClock::Now();
901 
902   // Get the 'Billing' profile.
903   db_profile = table_->GetAutofillProfile(billing_profile.guid());
904   ASSERT_TRUE(db_profile);
905   EXPECT_EQ(billing_profile, *db_profile);
906   sql::Statement s_billing(db_->GetSQLConnection()->GetUniqueStatement(
907       "SELECT date_modified FROM autofill_profiles WHERE guid=?"));
908   s_billing.BindString(0, billing_profile.guid());
909   ASSERT_TRUE(s_billing.is_valid());
910   ASSERT_TRUE(s_billing.Step());
911   EXPECT_GE(s_billing.ColumnInt64(0), pre_creation_time.ToTimeT());
912   EXPECT_LE(s_billing.ColumnInt64(0), post_creation_time.ToTimeT());
913   EXPECT_FALSE(s_billing.Step());
914 
915   // Update the 'Billing' profile, name only.
916   billing_profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Jane"));
917   Time pre_modification_time = AutofillClock::Now();
918   EXPECT_TRUE(table_->UpdateAutofillProfile(billing_profile));
919   Time post_modification_time = AutofillClock::Now();
920   db_profile = table_->GetAutofillProfile(billing_profile.guid());
921   ASSERT_TRUE(db_profile);
922   EXPECT_EQ(billing_profile, *db_profile);
923   sql::Statement s_billing_updated(db_->GetSQLConnection()->GetUniqueStatement(
924       "SELECT date_modified FROM autofill_profiles WHERE guid=?"));
925   s_billing_updated.BindString(0, billing_profile.guid());
926   ASSERT_TRUE(s_billing_updated.is_valid());
927   ASSERT_TRUE(s_billing_updated.Step());
928   EXPECT_GE(s_billing_updated.ColumnInt64(0), pre_modification_time.ToTimeT());
929   EXPECT_LE(s_billing_updated.ColumnInt64(0), post_modification_time.ToTimeT());
930   EXPECT_FALSE(s_billing_updated.Step());
931 
932   // Update the 'Billing' profile with non-default data. The specific values are
933   // not important.
934   billing_profile.set_origin(kSettingsOrigin);
935   billing_profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Janice"));
936   billing_profile.SetRawInfo(NAME_MIDDLE, ASCIIToUTF16("C."));
937   billing_profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Joplin"));
938   billing_profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("jane@singer.com"));
939   billing_profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Indy"));
940   billing_profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("Open Road"));
941   billing_profile.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("Route 66"));
942   billing_profile.SetRawInfo(ADDRESS_HOME_DEPENDENT_LOCALITY,
943                              ASCIIToUTF16("District 9"));
944   billing_profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("NFA"));
945   billing_profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("NY"));
946   billing_profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("10011"));
947   billing_profile.SetRawInfo(ADDRESS_HOME_SORTING_CODE, ASCIIToUTF16("123456"));
948   billing_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
949   billing_profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
950                              ASCIIToUTF16("18181230000"));
951   billing_profile.SetClientValidityFromBitfieldValue(54);
952   billing_profile.set_is_client_validity_states_updated(true);
953 
954   Time pre_modification_time_2 = AutofillClock::Now();
955   EXPECT_TRUE(table_->UpdateAutofillProfile(billing_profile));
956   Time post_modification_time_2 = AutofillClock::Now();
957   db_profile = table_->GetAutofillProfile(billing_profile.guid());
958   ASSERT_TRUE(db_profile);
959   EXPECT_EQ(billing_profile, *db_profile);
960   sql::Statement s_billing_updated_2(
961       db_->GetSQLConnection()->GetUniqueStatement(
962           "SELECT date_modified FROM autofill_profiles WHERE guid=?"));
963   s_billing_updated_2.BindString(0, billing_profile.guid());
964   ASSERT_TRUE(s_billing_updated_2.is_valid());
965   ASSERT_TRUE(s_billing_updated_2.Step());
966   EXPECT_GE(s_billing_updated_2.ColumnInt64(0),
967             pre_modification_time_2.ToTimeT());
968   EXPECT_LE(s_billing_updated_2.ColumnInt64(0),
969             post_modification_time_2.ToTimeT());
970   EXPECT_FALSE(s_billing_updated_2.Step());
971 
972   // Remove the 'Billing' profile.
973   EXPECT_TRUE(table_->RemoveAutofillProfile(billing_profile.guid()));
974   db_profile = table_->GetAutofillProfile(billing_profile.guid());
975   EXPECT_FALSE(db_profile);
976 }
977 
TEST_F(AutofillTableTest,CreditCard)978 TEST_F(AutofillTableTest, CreditCard) {
979   // Add a 'Work' credit card.
980   CreditCard work_creditcard;
981   work_creditcard.set_origin("https://www.example.com/");
982   work_creditcard.SetRawInfo(CREDIT_CARD_NAME_FULL,
983                              ASCIIToUTF16("Jack Torrance"));
984   work_creditcard.SetRawInfo(CREDIT_CARD_NUMBER,
985                              ASCIIToUTF16("1234567890123456"));
986   work_creditcard.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("04"));
987   work_creditcard.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR,
988                              ASCIIToUTF16("2013"));
989 
990   Time pre_creation_time = AutofillClock::Now();
991   EXPECT_TRUE(table_->AddCreditCard(work_creditcard));
992   Time post_creation_time = AutofillClock::Now();
993 
994   // Get the 'Work' credit card.
995   std::unique_ptr<CreditCard> db_creditcard =
996       table_->GetCreditCard(work_creditcard.guid());
997   ASSERT_TRUE(db_creditcard);
998   EXPECT_EQ(work_creditcard, *db_creditcard);
999   sql::Statement s_work(db_->GetSQLConnection()->GetUniqueStatement(
1000       "SELECT guid, name_on_card, expiration_month, expiration_year, "
1001       "card_number_encrypted, date_modified "
1002       "FROM credit_cards WHERE guid=?"));
1003   s_work.BindString(0, work_creditcard.guid());
1004   ASSERT_TRUE(s_work.is_valid());
1005   ASSERT_TRUE(s_work.Step());
1006   EXPECT_GE(s_work.ColumnInt64(5), pre_creation_time.ToTimeT());
1007   EXPECT_LE(s_work.ColumnInt64(5), post_creation_time.ToTimeT());
1008   EXPECT_FALSE(s_work.Step());
1009 
1010   // Add a 'Target' credit card.
1011   CreditCard target_creditcard;
1012   target_creditcard.set_origin(std::string());
1013   target_creditcard.SetRawInfo(CREDIT_CARD_NAME_FULL,
1014                                ASCIIToUTF16("Jack Torrance"));
1015   target_creditcard.SetRawInfo(CREDIT_CARD_NUMBER,
1016                                ASCIIToUTF16("1111222233334444"));
1017   target_creditcard.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("06"));
1018   target_creditcard.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR,
1019                                ASCIIToUTF16("2012"));
1020 
1021   pre_creation_time = AutofillClock::Now();
1022   EXPECT_TRUE(table_->AddCreditCard(target_creditcard));
1023   post_creation_time = AutofillClock::Now();
1024   db_creditcard = table_->GetCreditCard(target_creditcard.guid());
1025   ASSERT_TRUE(db_creditcard);
1026   EXPECT_EQ(target_creditcard, *db_creditcard);
1027   sql::Statement s_target(db_->GetSQLConnection()->GetUniqueStatement(
1028       "SELECT guid, name_on_card, expiration_month, expiration_year, "
1029       "card_number_encrypted, date_modified "
1030       "FROM credit_cards WHERE guid=?"));
1031   s_target.BindString(0, target_creditcard.guid());
1032   ASSERT_TRUE(s_target.is_valid());
1033   ASSERT_TRUE(s_target.Step());
1034   EXPECT_GE(s_target.ColumnInt64(5), pre_creation_time.ToTimeT());
1035   EXPECT_LE(s_target.ColumnInt64(5), post_creation_time.ToTimeT());
1036   EXPECT_FALSE(s_target.Step());
1037 
1038   // Update the 'Target' credit card.
1039   target_creditcard.set_origin("Interactive Autofill dialog");
1040   target_creditcard.SetRawInfo(CREDIT_CARD_NAME_FULL,
1041                                ASCIIToUTF16("Charles Grady"));
1042   Time pre_modification_time = AutofillClock::Now();
1043   EXPECT_TRUE(table_->UpdateCreditCard(target_creditcard));
1044   Time post_modification_time = AutofillClock::Now();
1045   db_creditcard = table_->GetCreditCard(target_creditcard.guid());
1046   ASSERT_TRUE(db_creditcard);
1047   EXPECT_EQ(target_creditcard, *db_creditcard);
1048   sql::Statement s_target_updated(db_->GetSQLConnection()->GetUniqueStatement(
1049       "SELECT guid, name_on_card, expiration_month, expiration_year, "
1050       "card_number_encrypted, date_modified "
1051       "FROM credit_cards WHERE guid=?"));
1052   s_target_updated.BindString(0, target_creditcard.guid());
1053   ASSERT_TRUE(s_target_updated.is_valid());
1054   ASSERT_TRUE(s_target_updated.Step());
1055   EXPECT_GE(s_target_updated.ColumnInt64(5), pre_modification_time.ToTimeT());
1056   EXPECT_LE(s_target_updated.ColumnInt64(5), post_modification_time.ToTimeT());
1057   EXPECT_FALSE(s_target_updated.Step());
1058 
1059   // Remove the 'Target' credit card.
1060   EXPECT_TRUE(table_->RemoveCreditCard(target_creditcard.guid()));
1061   db_creditcard = table_->GetCreditCard(target_creditcard.guid());
1062   EXPECT_FALSE(db_creditcard);
1063 }
1064 
TEST_F(AutofillTableTest,AddFullServerCreditCard)1065 TEST_F(AutofillTableTest, AddFullServerCreditCard) {
1066   CreditCard credit_card;
1067   credit_card.set_record_type(CreditCard::FULL_SERVER_CARD);
1068   credit_card.set_server_id("server_id");
1069   credit_card.set_origin("https://www.example.com/");
1070   credit_card.SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Jack Torrance"));
1071   credit_card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1234567890123456"));
1072   credit_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("04"));
1073   credit_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2013"));
1074 
1075   EXPECT_TRUE(table_->AddFullServerCreditCard(credit_card));
1076 
1077   std::vector<std::unique_ptr<CreditCard>> outputs;
1078   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
1079   ASSERT_EQ(1U, outputs.size());
1080   EXPECT_EQ(0, credit_card.Compare(*outputs[0]));
1081 }
1082 
TEST_F(AutofillTableTest,UpdateAutofillProfile)1083 TEST_F(AutofillTableTest, UpdateAutofillProfile) {
1084   // Add a profile to the db.
1085   AutofillProfile profile;
1086   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John"));
1087   profile.SetRawInfo(NAME_MIDDLE, ASCIIToUTF16("Q."));
1088   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1089   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("js@example.com"));
1090   profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Google"));
1091   profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 Apple Way"));
1092   profile.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("unit 5"));
1093   profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Los Angeles"));
1094   profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1095   profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("90025"));
1096   profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
1097   profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("18181234567"));
1098   profile.set_language_code("en");
1099   table_->AddAutofillProfile(profile);
1100 
1101   // Set a mocked value for the profile's creation time.
1102   const time_t kMockCreationDate = AutofillClock::Now().ToTimeT() - 13;
1103   sql::Statement s_mock_creation_date(
1104       db_->GetSQLConnection()->GetUniqueStatement(
1105           "UPDATE autofill_profiles SET date_modified = ?"));
1106   ASSERT_TRUE(s_mock_creation_date.is_valid());
1107   s_mock_creation_date.BindInt64(0, kMockCreationDate);
1108   ASSERT_TRUE(s_mock_creation_date.Run());
1109 
1110   // Get the profile.
1111   std::unique_ptr<AutofillProfile> db_profile =
1112       table_->GetAutofillProfile(profile.guid());
1113   ASSERT_TRUE(db_profile);
1114   EXPECT_EQ(profile, *db_profile);
1115   sql::Statement s_original(db_->GetSQLConnection()->GetUniqueStatement(
1116       "SELECT date_modified FROM autofill_profiles"));
1117   ASSERT_TRUE(s_original.is_valid());
1118   ASSERT_TRUE(s_original.Step());
1119   EXPECT_EQ(kMockCreationDate, s_original.ColumnInt64(0));
1120   EXPECT_FALSE(s_original.Step());
1121 
1122   // Now, update the profile and save the update to the database.
1123   // The modification date should change to reflect the update.
1124   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("js@smith.xyz"));
1125   table_->UpdateAutofillProfile(profile);
1126 
1127   // Get the profile.
1128   db_profile = table_->GetAutofillProfile(profile.guid());
1129   ASSERT_TRUE(db_profile);
1130   EXPECT_EQ(profile, *db_profile);
1131   sql::Statement s_updated(db_->GetSQLConnection()->GetUniqueStatement(
1132       "SELECT date_modified FROM autofill_profiles"));
1133   ASSERT_TRUE(s_updated.is_valid());
1134   ASSERT_TRUE(s_updated.Step());
1135   EXPECT_LT(kMockCreationDate, s_updated.ColumnInt64(0));
1136   EXPECT_FALSE(s_updated.Step());
1137 
1138   // Set a mocked value for the profile's modification time.
1139   const time_t mock_modification_date = AutofillClock::Now().ToTimeT() - 7;
1140   sql::Statement s_mock_modification_date(
1141       db_->GetSQLConnection()->GetUniqueStatement(
1142           "UPDATE autofill_profiles SET date_modified = ?"));
1143   ASSERT_TRUE(s_mock_modification_date.is_valid());
1144   s_mock_modification_date.BindInt64(0, mock_modification_date);
1145   ASSERT_TRUE(s_mock_modification_date.Run());
1146 
1147   // Finally, call into |UpdateAutofillProfile()| without changing the
1148   // profile.  The modification date should not change.
1149   table_->UpdateAutofillProfile(profile);
1150 
1151   // Get the profile.
1152   db_profile = table_->GetAutofillProfile(profile.guid());
1153   ASSERT_TRUE(db_profile);
1154   EXPECT_EQ(profile, *db_profile);
1155   sql::Statement s_unchanged(db_->GetSQLConnection()->GetUniqueStatement(
1156       "SELECT date_modified FROM autofill_profiles"));
1157   ASSERT_TRUE(s_unchanged.is_valid());
1158   ASSERT_TRUE(s_unchanged.Step());
1159   EXPECT_EQ(mock_modification_date, s_unchanged.ColumnInt64(0));
1160   EXPECT_FALSE(s_unchanged.Step());
1161 }
1162 
TEST_F(AutofillTableTest,UpdateCreditCard)1163 TEST_F(AutofillTableTest, UpdateCreditCard) {
1164   // Add a credit card to the db.
1165   CreditCard credit_card;
1166   credit_card.SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Jack Torrance"));
1167   credit_card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1234567890123456"));
1168   credit_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("04"));
1169   credit_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2013"));
1170   table_->AddCreditCard(credit_card);
1171 
1172   // Set a mocked value for the credit card's creation time.
1173   const time_t kMockCreationDate = AutofillClock::Now().ToTimeT() - 13;
1174   sql::Statement s_mock_creation_date(
1175       db_->GetSQLConnection()->GetUniqueStatement(
1176           "UPDATE credit_cards SET date_modified = ?"));
1177   ASSERT_TRUE(s_mock_creation_date.is_valid());
1178   s_mock_creation_date.BindInt64(0, kMockCreationDate);
1179   ASSERT_TRUE(s_mock_creation_date.Run());
1180 
1181   // Get the credit card.
1182   std::unique_ptr<CreditCard> db_credit_card =
1183       table_->GetCreditCard(credit_card.guid());
1184   ASSERT_TRUE(db_credit_card);
1185   EXPECT_EQ(credit_card, *db_credit_card);
1186   sql::Statement s_original(db_->GetSQLConnection()->GetUniqueStatement(
1187       "SELECT date_modified FROM credit_cards"));
1188   ASSERT_TRUE(s_original.is_valid());
1189   ASSERT_TRUE(s_original.Step());
1190   EXPECT_EQ(kMockCreationDate, s_original.ColumnInt64(0));
1191   EXPECT_FALSE(s_original.Step());
1192 
1193   // Now, update the credit card and save the update to the database.
1194   // The modification date should change to reflect the update.
1195   credit_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("01"));
1196   table_->UpdateCreditCard(credit_card);
1197 
1198   // Get the credit card.
1199   db_credit_card = table_->GetCreditCard(credit_card.guid());
1200   ASSERT_TRUE(db_credit_card);
1201   EXPECT_EQ(credit_card, *db_credit_card);
1202   sql::Statement s_updated(db_->GetSQLConnection()->GetUniqueStatement(
1203       "SELECT date_modified FROM credit_cards"));
1204   ASSERT_TRUE(s_updated.is_valid());
1205   ASSERT_TRUE(s_updated.Step());
1206   EXPECT_LT(kMockCreationDate, s_updated.ColumnInt64(0));
1207   EXPECT_FALSE(s_updated.Step());
1208 
1209   // Set a mocked value for the credit card's modification time.
1210   const time_t mock_modification_date = AutofillClock::Now().ToTimeT() - 7;
1211   sql::Statement s_mock_modification_date(
1212       db_->GetSQLConnection()->GetUniqueStatement(
1213           "UPDATE credit_cards SET date_modified = ?"));
1214   ASSERT_TRUE(s_mock_modification_date.is_valid());
1215   s_mock_modification_date.BindInt64(0, mock_modification_date);
1216   ASSERT_TRUE(s_mock_modification_date.Run());
1217 
1218   // Finally, call into |UpdateCreditCard()| without changing the credit card.
1219   // The modification date should not change.
1220   table_->UpdateCreditCard(credit_card);
1221 
1222   // Get the credit card.
1223   db_credit_card = table_->GetCreditCard(credit_card.guid());
1224   ASSERT_TRUE(db_credit_card);
1225   EXPECT_EQ(credit_card, *db_credit_card);
1226   sql::Statement s_unchanged(db_->GetSQLConnection()->GetUniqueStatement(
1227       "SELECT date_modified FROM credit_cards"));
1228   ASSERT_TRUE(s_unchanged.is_valid());
1229   ASSERT_TRUE(s_unchanged.Step());
1230   EXPECT_EQ(mock_modification_date, s_unchanged.ColumnInt64(0));
1231   EXPECT_FALSE(s_unchanged.Step());
1232 }
1233 
TEST_F(AutofillTableTest,UpdateProfileOriginOnly)1234 TEST_F(AutofillTableTest, UpdateProfileOriginOnly) {
1235   // Add a profile to the db.
1236   AutofillProfile profile;
1237   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John"));
1238   profile.SetRawInfo(NAME_MIDDLE, ASCIIToUTF16("Q."));
1239   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1240   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("js@example.com"));
1241   profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Google"));
1242   profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 Apple Way"));
1243   profile.SetRawInfo(ADDRESS_HOME_LINE2, ASCIIToUTF16("unit 5"));
1244   profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Los Angeles"));
1245   profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1246   profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("90025"));
1247   profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
1248   profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("18181234567"));
1249   table_->AddAutofillProfile(profile);
1250 
1251   // Set a mocked value for the profile's creation time.
1252   const time_t kMockCreationDate = AutofillClock::Now().ToTimeT() - 13;
1253   sql::Statement s_mock_creation_date(
1254       db_->GetSQLConnection()->GetUniqueStatement(
1255           "UPDATE autofill_profiles SET date_modified = ?"));
1256   ASSERT_TRUE(s_mock_creation_date.is_valid());
1257   s_mock_creation_date.BindInt64(0, kMockCreationDate);
1258   ASSERT_TRUE(s_mock_creation_date.Run());
1259 
1260   // Get the profile.
1261   std::unique_ptr<AutofillProfile> db_profile =
1262       table_->GetAutofillProfile(profile.guid());
1263   ASSERT_TRUE(db_profile);
1264   EXPECT_EQ(profile, *db_profile);
1265   sql::Statement s_original(db_->GetSQLConnection()->GetUniqueStatement(
1266       "SELECT date_modified FROM autofill_profiles"));
1267   ASSERT_TRUE(s_original.is_valid());
1268   ASSERT_TRUE(s_original.Step());
1269   EXPECT_EQ(kMockCreationDate, s_original.ColumnInt64(0));
1270   EXPECT_FALSE(s_original.Step());
1271 
1272   // Now, update just the profile's origin and save the update to the database.
1273   // The modification date should change to reflect the update.
1274   profile.set_origin("https://www.example.com/");
1275   table_->UpdateAutofillProfile(profile);
1276 
1277   // Get the profile.
1278   db_profile = table_->GetAutofillProfile(profile.guid());
1279   ASSERT_TRUE(db_profile);
1280   EXPECT_EQ(profile, *db_profile);
1281   sql::Statement s_updated(db_->GetSQLConnection()->GetUniqueStatement(
1282       "SELECT date_modified FROM autofill_profiles"));
1283   ASSERT_TRUE(s_updated.is_valid());
1284   ASSERT_TRUE(s_updated.Step());
1285   EXPECT_LT(kMockCreationDate, s_updated.ColumnInt64(0));
1286   EXPECT_FALSE(s_updated.Step());
1287 }
1288 
TEST_F(AutofillTableTest,UpdateCreditCardOriginOnly)1289 TEST_F(AutofillTableTest, UpdateCreditCardOriginOnly) {
1290   // Add a credit card to the db.
1291   CreditCard credit_card;
1292   credit_card.SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Jack Torrance"));
1293   credit_card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1234567890123456"));
1294   credit_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("04"));
1295   credit_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2013"));
1296   table_->AddCreditCard(credit_card);
1297 
1298   // Set a mocked value for the credit card's creation time.
1299   const time_t kMockCreationDate = AutofillClock::Now().ToTimeT() - 13;
1300   sql::Statement s_mock_creation_date(
1301       db_->GetSQLConnection()->GetUniqueStatement(
1302           "UPDATE credit_cards SET date_modified = ?"));
1303   ASSERT_TRUE(s_mock_creation_date.is_valid());
1304   s_mock_creation_date.BindInt64(0, kMockCreationDate);
1305   ASSERT_TRUE(s_mock_creation_date.Run());
1306 
1307   // Get the credit card.
1308   std::unique_ptr<CreditCard> db_credit_card =
1309       table_->GetCreditCard(credit_card.guid());
1310   ASSERT_TRUE(db_credit_card);
1311   EXPECT_EQ(credit_card, *db_credit_card);
1312   sql::Statement s_original(db_->GetSQLConnection()->GetUniqueStatement(
1313       "SELECT date_modified FROM credit_cards"));
1314   ASSERT_TRUE(s_original.is_valid());
1315   ASSERT_TRUE(s_original.Step());
1316   EXPECT_EQ(kMockCreationDate, s_original.ColumnInt64(0));
1317   EXPECT_FALSE(s_original.Step());
1318 
1319   // Now, update just the credit card's origin and save the update to the
1320   // database.  The modification date should change to reflect the update.
1321   credit_card.set_origin("https://www.example.com/");
1322   table_->UpdateCreditCard(credit_card);
1323 
1324   // Get the credit card.
1325   db_credit_card = table_->GetCreditCard(credit_card.guid());
1326   ASSERT_TRUE(db_credit_card);
1327   EXPECT_EQ(credit_card, *db_credit_card);
1328   sql::Statement s_updated(db_->GetSQLConnection()->GetUniqueStatement(
1329       "SELECT date_modified FROM credit_cards"));
1330   ASSERT_TRUE(s_updated.is_valid());
1331   ASSERT_TRUE(s_updated.Step());
1332   EXPECT_LT(kMockCreationDate, s_updated.ColumnInt64(0));
1333   EXPECT_FALSE(s_updated.Step());
1334 }
1335 
TEST_F(AutofillTableTest,RemoveAutofillDataModifiedBetween)1336 TEST_F(AutofillTableTest, RemoveAutofillDataModifiedBetween) {
1337   // Populate the autofill_profiles and credit_cards tables.
1338   ASSERT_TRUE(db_->GetSQLConnection()->Execute(
1339       "INSERT INTO autofill_profiles (guid, date_modified) "
1340       "VALUES('00000000-0000-0000-0000-000000000000', 11);"
1341       "INSERT INTO autofill_profile_names (guid, full_name) "
1342       "VALUES('00000000-0000-0000-0000-000000000000', 'John Jones');"
1343       "INSERT INTO autofill_profile_emails (guid, email) "
1344       "VALUES('00000000-0000-0000-0000-000000000000', 'john@jones.com');"
1345       "INSERT INTO autofill_profile_phones (guid, number) "
1346       "VALUES('00000000-0000-0000-0000-000000000000', '111-111-1111');"
1347       "INSERT INTO autofill_profiles (guid, date_modified) "
1348       "VALUES('00000000-0000-0000-0000-000000000001', 21);"
1349       "INSERT INTO autofill_profile_names (guid, full_name) "
1350       "VALUES('00000000-0000-0000-0000-000000000001', 'John Jones2');"
1351       "INSERT INTO autofill_profile_emails (guid, email) "
1352       "VALUES('00000000-0000-0000-0000-000000000001', 'john@jones2.com');"
1353       "INSERT INTO autofill_profile_phones (guid, number) "
1354       "VALUES('00000000-0000-0000-0000-000000000001', '222-222-2222');"
1355       "INSERT INTO autofill_profiles (guid, date_modified) "
1356       "VALUES('00000000-0000-0000-0000-000000000002', 31);"
1357       "INSERT INTO autofill_profile_names (guid, full_name) "
1358       "VALUES('00000000-0000-0000-0000-000000000002', 'John Jones3');"
1359       "INSERT INTO autofill_profile_emails (guid, email) "
1360       "VALUES('00000000-0000-0000-0000-000000000002', 'john@jones3.com');"
1361       "INSERT INTO autofill_profile_phones (guid, number) "
1362       "VALUES('00000000-0000-0000-0000-000000000002', '333-333-3333');"
1363       "INSERT INTO autofill_profiles (guid, date_modified) "
1364       "VALUES('00000000-0000-0000-0000-000000000003', 41);"
1365       "INSERT INTO autofill_profile_names (guid, full_name) "
1366       "VALUES('00000000-0000-0000-0000-000000000003', 'John Jones4');"
1367       "INSERT INTO autofill_profile_emails (guid, email) "
1368       "VALUES('00000000-0000-0000-0000-000000000003', 'john@jones4.com');"
1369       "INSERT INTO autofill_profile_phones (guid, number) "
1370       "VALUES('00000000-0000-0000-0000-000000000003', '444-444-4444');"
1371       "INSERT INTO autofill_profiles (guid, date_modified) "
1372       "VALUES('00000000-0000-0000-0000-000000000004', 51);"
1373       "INSERT INTO autofill_profile_names (guid, full_name) "
1374       "VALUES('00000000-0000-0000-0000-000000000004', 'John Jones5');"
1375       "INSERT INTO autofill_profile_emails (guid, email) "
1376       "VALUES('00000000-0000-0000-0000-000000000004', 'john@jones5.com');"
1377       "INSERT INTO autofill_profile_phones (guid, number) "
1378       "VALUES('00000000-0000-0000-0000-000000000004', '555-555-5555');"
1379       "INSERT INTO autofill_profiles (guid, date_modified) "
1380       "VALUES('00000000-0000-0000-0000-000000000005', 61);"
1381       "INSERT INTO autofill_profile_names (guid, full_name) "
1382       "VALUES('00000000-0000-0000-0000-000000000005', 'John Jones6');"
1383       "INSERT INTO autofill_profile_emails (guid, email) "
1384       "VALUES('00000000-0000-0000-0000-000000000005', 'john@jones6.com');"
1385       "INSERT INTO autofill_profile_phones (guid, number) "
1386       "VALUES('00000000-0000-0000-0000-000000000005', '666-666-6666');"
1387       "INSERT INTO credit_cards (guid, date_modified) "
1388       "VALUES('00000000-0000-0000-0000-000000000006', 17);"
1389       "INSERT INTO credit_cards (guid, date_modified) "
1390       "VALUES('00000000-0000-0000-0000-000000000007', 27);"
1391       "INSERT INTO credit_cards (guid, date_modified) "
1392       "VALUES('00000000-0000-0000-0000-000000000008', 37);"
1393       "INSERT INTO credit_cards (guid, date_modified) "
1394       "VALUES('00000000-0000-0000-0000-000000000009', 47);"
1395       "INSERT INTO credit_cards (guid, date_modified) "
1396       "VALUES('00000000-0000-0000-0000-000000000010', 57);"
1397       "INSERT INTO credit_cards (guid, date_modified) "
1398       "VALUES('00000000-0000-0000-0000-000000000011', 67);"));
1399 
1400   // Remove all entries modified in the bounded time range [17,41).
1401   std::vector<std::unique_ptr<AutofillProfile>> profiles;
1402   std::vector<std::unique_ptr<CreditCard>> credit_cards;
1403   table_->RemoveAutofillDataModifiedBetween(
1404       Time::FromTimeT(17), Time::FromTimeT(41), &profiles, &credit_cards);
1405 
1406   // Two profiles should have been removed.
1407   ASSERT_EQ(2UL, profiles.size());
1408   EXPECT_EQ("00000000-0000-0000-0000-000000000001", profiles[0]->guid());
1409   EXPECT_EQ("00000000-0000-0000-0000-000000000002", profiles[1]->guid());
1410 
1411   // Make sure that only the expected profiles are still present.
1412   sql::Statement s_autofill_profiles_bounded(
1413       db_->GetSQLConnection()->GetUniqueStatement(
1414           "SELECT date_modified FROM autofill_profiles"));
1415   ASSERT_TRUE(s_autofill_profiles_bounded.is_valid());
1416   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1417   EXPECT_EQ(11, s_autofill_profiles_bounded.ColumnInt64(0));
1418   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1419   EXPECT_EQ(41, s_autofill_profiles_bounded.ColumnInt64(0));
1420   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1421   EXPECT_EQ(51, s_autofill_profiles_bounded.ColumnInt64(0));
1422   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1423   EXPECT_EQ(61, s_autofill_profiles_bounded.ColumnInt64(0));
1424   EXPECT_FALSE(s_autofill_profiles_bounded.Step());
1425 
1426   // Make sure that only the expected profile names are still present.
1427   sql::Statement s_autofill_profile_names_bounded(
1428       db_->GetSQLConnection()->GetUniqueStatement(
1429           "SELECT full_name FROM autofill_profile_names"));
1430   ASSERT_TRUE(s_autofill_profile_names_bounded.is_valid());
1431   ASSERT_TRUE(s_autofill_profile_names_bounded.Step());
1432   EXPECT_EQ("John Jones", s_autofill_profile_names_bounded.ColumnString(0));
1433   ASSERT_TRUE(s_autofill_profile_names_bounded.Step());
1434   EXPECT_EQ("John Jones4", s_autofill_profile_names_bounded.ColumnString(0));
1435   ASSERT_TRUE(s_autofill_profile_names_bounded.Step());
1436   EXPECT_EQ("John Jones5", s_autofill_profile_names_bounded.ColumnString(0));
1437   ASSERT_TRUE(s_autofill_profile_names_bounded.Step());
1438   EXPECT_EQ("John Jones6", s_autofill_profile_names_bounded.ColumnString(0));
1439   EXPECT_FALSE(s_autofill_profile_names_bounded.Step());
1440 
1441   // Make sure that only the expected profile emails are still present.
1442   sql::Statement s_autofill_profile_emails_bounded(
1443       db_->GetSQLConnection()->GetUniqueStatement(
1444           "SELECT email FROM autofill_profile_emails"));
1445   ASSERT_TRUE(s_autofill_profile_emails_bounded.is_valid());
1446   ASSERT_TRUE(s_autofill_profile_emails_bounded.Step());
1447   EXPECT_EQ("john@jones.com",
1448             s_autofill_profile_emails_bounded.ColumnString(0));
1449   ASSERT_TRUE(s_autofill_profile_emails_bounded.Step());
1450   EXPECT_EQ("john@jones4.com",
1451             s_autofill_profile_emails_bounded.ColumnString(0));
1452   ASSERT_TRUE(s_autofill_profile_emails_bounded.Step());
1453   EXPECT_EQ("john@jones5.com",
1454             s_autofill_profile_emails_bounded.ColumnString(0));
1455   ASSERT_TRUE(s_autofill_profile_emails_bounded.Step());
1456   EXPECT_EQ("john@jones6.com",
1457             s_autofill_profile_emails_bounded.ColumnString(0));
1458   EXPECT_FALSE(s_autofill_profile_emails_bounded.Step());
1459 
1460   // Make sure the expected profile phone numbers are still present.
1461   sql::Statement s_autofill_profile_phones_bounded(
1462       db_->GetSQLConnection()->GetUniqueStatement(
1463           "SELECT number FROM autofill_profile_phones"));
1464   ASSERT_TRUE(s_autofill_profile_phones_bounded.is_valid());
1465   ASSERT_TRUE(s_autofill_profile_phones_bounded.Step());
1466   EXPECT_EQ("111-111-1111", s_autofill_profile_phones_bounded.ColumnString(0));
1467   ASSERT_TRUE(s_autofill_profile_phones_bounded.Step());
1468   EXPECT_EQ("444-444-4444", s_autofill_profile_phones_bounded.ColumnString(0));
1469   ASSERT_TRUE(s_autofill_profile_phones_bounded.Step());
1470   EXPECT_EQ("555-555-5555", s_autofill_profile_phones_bounded.ColumnString(0));
1471   ASSERT_TRUE(s_autofill_profile_phones_bounded.Step());
1472   EXPECT_EQ("666-666-6666", s_autofill_profile_phones_bounded.ColumnString(0));
1473   EXPECT_FALSE(s_autofill_profile_phones_bounded.Step());
1474 
1475   // Three cards should have been removed.
1476   ASSERT_EQ(3UL, credit_cards.size());
1477   EXPECT_EQ("00000000-0000-0000-0000-000000000006", credit_cards[0]->guid());
1478   EXPECT_EQ("00000000-0000-0000-0000-000000000007", credit_cards[1]->guid());
1479   EXPECT_EQ("00000000-0000-0000-0000-000000000008", credit_cards[2]->guid());
1480 
1481   // Make sure the expected profiles are still present.
1482   sql::Statement s_credit_cards_bounded(
1483       db_->GetSQLConnection()->GetUniqueStatement(
1484           "SELECT date_modified FROM credit_cards"));
1485   ASSERT_TRUE(s_credit_cards_bounded.is_valid());
1486   ASSERT_TRUE(s_credit_cards_bounded.Step());
1487   EXPECT_EQ(47, s_credit_cards_bounded.ColumnInt64(0));
1488   ASSERT_TRUE(s_credit_cards_bounded.Step());
1489   EXPECT_EQ(57, s_credit_cards_bounded.ColumnInt64(0));
1490   ASSERT_TRUE(s_credit_cards_bounded.Step());
1491   EXPECT_EQ(67, s_credit_cards_bounded.ColumnInt64(0));
1492   EXPECT_FALSE(s_credit_cards_bounded.Step());
1493 
1494   // Remove all entries modified on or after time 51 (unbounded range).
1495   table_->RemoveAutofillDataModifiedBetween(Time::FromTimeT(51), Time(),
1496                                             &profiles, &credit_cards);
1497   ASSERT_EQ(2UL, profiles.size());
1498   EXPECT_EQ("00000000-0000-0000-0000-000000000004", profiles[0]->guid());
1499   EXPECT_EQ("00000000-0000-0000-0000-000000000005", profiles[1]->guid());
1500 
1501   // Make sure that only the expected profile names are still present.
1502   sql::Statement s_autofill_profiles_unbounded(
1503       db_->GetSQLConnection()->GetUniqueStatement(
1504           "SELECT date_modified FROM autofill_profiles"));
1505   ASSERT_TRUE(s_autofill_profiles_unbounded.is_valid());
1506   ASSERT_TRUE(s_autofill_profiles_unbounded.Step());
1507   EXPECT_EQ(11, s_autofill_profiles_unbounded.ColumnInt64(0));
1508   ASSERT_TRUE(s_autofill_profiles_unbounded.Step());
1509   EXPECT_EQ(41, s_autofill_profiles_unbounded.ColumnInt64(0));
1510   EXPECT_FALSE(s_autofill_profiles_unbounded.Step());
1511 
1512   // Make sure that only the expected profile names are still present.
1513   sql::Statement s_autofill_profile_names_unbounded(
1514       db_->GetSQLConnection()->GetUniqueStatement(
1515           "SELECT full_name FROM autofill_profile_names"));
1516   ASSERT_TRUE(s_autofill_profile_names_unbounded.is_valid());
1517   ASSERT_TRUE(s_autofill_profile_names_unbounded.Step());
1518   EXPECT_EQ("John Jones", s_autofill_profile_names_unbounded.ColumnString(0));
1519   ASSERT_TRUE(s_autofill_profile_names_unbounded.Step());
1520   EXPECT_EQ("John Jones4", s_autofill_profile_names_unbounded.ColumnString(0));
1521   EXPECT_FALSE(s_autofill_profile_names_unbounded.Step());
1522 
1523   // Make sure that only the expected profile emails are still present.
1524   sql::Statement s_autofill_profile_emails_unbounded(
1525       db_->GetSQLConnection()->GetUniqueStatement(
1526           "SELECT email FROM autofill_profile_emails"));
1527   ASSERT_TRUE(s_autofill_profile_emails_unbounded.is_valid());
1528   ASSERT_TRUE(s_autofill_profile_emails_unbounded.Step());
1529   EXPECT_EQ("john@jones.com",
1530             s_autofill_profile_emails_unbounded.ColumnString(0));
1531   ASSERT_TRUE(s_autofill_profile_emails_unbounded.Step());
1532   EXPECT_EQ("john@jones4.com",
1533             s_autofill_profile_emails_unbounded.ColumnString(0));
1534   EXPECT_FALSE(s_autofill_profile_emails_unbounded.Step());
1535 
1536   // Make sure the expected profile phone numbers are still present.
1537   sql::Statement s_autofill_profile_phones_unbounded(
1538       db_->GetSQLConnection()->GetUniqueStatement(
1539           "SELECT number FROM autofill_profile_phones"));
1540   ASSERT_TRUE(s_autofill_profile_phones_unbounded.is_valid());
1541   ASSERT_TRUE(s_autofill_profile_phones_unbounded.Step());
1542   EXPECT_EQ("111-111-1111",
1543             s_autofill_profile_phones_unbounded.ColumnString(0));
1544   ASSERT_TRUE(s_autofill_profile_phones_unbounded.Step());
1545   EXPECT_EQ("444-444-4444",
1546             s_autofill_profile_phones_unbounded.ColumnString(0));
1547   EXPECT_FALSE(s_autofill_profile_phones_unbounded.Step());
1548 
1549   // Two cards should have been removed.
1550   ASSERT_EQ(2UL, credit_cards.size());
1551   EXPECT_EQ("00000000-0000-0000-0000-000000000010", credit_cards[0]->guid());
1552   EXPECT_EQ("00000000-0000-0000-0000-000000000011", credit_cards[1]->guid());
1553 
1554   // Make sure the remaining card is the expected one.
1555   sql::Statement s_credit_cards_unbounded(
1556       db_->GetSQLConnection()->GetUniqueStatement(
1557           "SELECT date_modified FROM credit_cards"));
1558   ASSERT_TRUE(s_credit_cards_unbounded.is_valid());
1559   ASSERT_TRUE(s_credit_cards_unbounded.Step());
1560   EXPECT_EQ(47, s_credit_cards_unbounded.ColumnInt64(0));
1561   EXPECT_FALSE(s_credit_cards_unbounded.Step());
1562 
1563   // Remove all remaining entries.
1564   table_->RemoveAutofillDataModifiedBetween(Time(), Time(), &profiles,
1565                                             &credit_cards);
1566 
1567   // Two profiles should have been removed.
1568   ASSERT_EQ(2UL, profiles.size());
1569   EXPECT_EQ("00000000-0000-0000-0000-000000000000", profiles[0]->guid());
1570   EXPECT_EQ("00000000-0000-0000-0000-000000000003", profiles[1]->guid());
1571 
1572   // Make sure there are no profiles remaining.
1573   sql::Statement s_autofill_profiles_empty(
1574       db_->GetSQLConnection()->GetUniqueStatement(
1575           "SELECT date_modified FROM autofill_profiles"));
1576   ASSERT_TRUE(s_autofill_profiles_empty.is_valid());
1577   EXPECT_FALSE(s_autofill_profiles_empty.Step());
1578 
1579   // Make sure there are no profile names remaining.
1580   sql::Statement s_autofill_profile_names_empty(
1581       db_->GetSQLConnection()->GetUniqueStatement(
1582           "SELECT full_name FROM autofill_profile_names"));
1583   ASSERT_TRUE(s_autofill_profile_names_empty.is_valid());
1584   EXPECT_FALSE(s_autofill_profile_names_empty.Step());
1585 
1586   // Make sure there are no profile emails remaining.
1587   sql::Statement s_autofill_profile_emails_empty(
1588       db_->GetSQLConnection()->GetUniqueStatement(
1589           "SELECT email FROM autofill_profile_emails"));
1590   ASSERT_TRUE(s_autofill_profile_emails_empty.is_valid());
1591   EXPECT_FALSE(s_autofill_profile_emails_empty.Step());
1592 
1593   // Make sure there are no profile phones remaining.
1594   sql::Statement s_autofill_profile_phones_empty(
1595       db_->GetSQLConnection()->GetUniqueStatement(
1596           "SELECT number FROM autofill_profile_phones"));
1597   ASSERT_TRUE(s_autofill_profile_phones_empty.is_valid());
1598   EXPECT_FALSE(s_autofill_profile_phones_empty.Step());
1599 
1600   // One credit card should have been deleted.
1601   ASSERT_EQ(1UL, credit_cards.size());
1602   EXPECT_EQ("00000000-0000-0000-0000-000000000009", credit_cards[0]->guid());
1603 
1604   // There should be no cards left.
1605   sql::Statement s_credit_cards_empty(
1606       db_->GetSQLConnection()->GetUniqueStatement(
1607           "SELECT date_modified FROM credit_cards"));
1608   ASSERT_TRUE(s_credit_cards_empty.is_valid());
1609   EXPECT_FALSE(s_credit_cards_empty.Step());
1610 }
1611 
TEST_F(AutofillTableTest,RemoveOriginURLsModifiedBetween)1612 TEST_F(AutofillTableTest, RemoveOriginURLsModifiedBetween) {
1613   // Populate the autofill_profiles and credit_cards tables.
1614   ASSERT_TRUE(db_->GetSQLConnection()->Execute(
1615       "INSERT INTO autofill_profiles (guid, origin, date_modified) "
1616       "VALUES('00000000-0000-0000-0000-000000000000', '', 11);"
1617       "INSERT INTO autofill_profiles (guid, origin, date_modified) "
1618       "VALUES('00000000-0000-0000-0000-000000000001', "
1619       "       'https://www.example.com/', 21);"
1620       "INSERT INTO autofill_profiles (guid, origin, date_modified) "
1621       "VALUES('00000000-0000-0000-0000-000000000002', 'Chrome settings', 31);"
1622       "INSERT INTO credit_cards (guid, origin, date_modified) "
1623       "VALUES('00000000-0000-0000-0000-000000000003', '', 17);"
1624       "INSERT INTO credit_cards (guid, origin, date_modified) "
1625       "VALUES('00000000-0000-0000-0000-000000000004', "
1626       "       'https://www.example.com/', 27);"
1627       "INSERT INTO credit_cards (guid, origin, date_modified) "
1628       "VALUES('00000000-0000-0000-0000-000000000005', 'Chrome settings', "
1629       "       37);"));
1630 
1631   // Remove all origin URLs set in the bounded time range [21,27).
1632   std::vector<std::unique_ptr<AutofillProfile>> profiles;
1633   table_->RemoveOriginURLsModifiedBetween(Time::FromTimeT(21),
1634                                           Time::FromTimeT(27), &profiles);
1635   ASSERT_EQ(1UL, profiles.size());
1636   EXPECT_EQ("00000000-0000-0000-0000-000000000001", profiles[0]->guid());
1637   sql::Statement s_autofill_profiles_bounded(
1638       db_->GetSQLConnection()->GetUniqueStatement(
1639           "SELECT date_modified, origin FROM autofill_profiles"));
1640   ASSERT_TRUE(s_autofill_profiles_bounded.is_valid());
1641   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1642   EXPECT_EQ(11, s_autofill_profiles_bounded.ColumnInt64(0));
1643   EXPECT_EQ(std::string(), s_autofill_profiles_bounded.ColumnString(1));
1644   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1645   EXPECT_EQ(21, s_autofill_profiles_bounded.ColumnInt64(0));
1646   EXPECT_EQ(std::string(), s_autofill_profiles_bounded.ColumnString(1));
1647   ASSERT_TRUE(s_autofill_profiles_bounded.Step());
1648   EXPECT_EQ(31, s_autofill_profiles_bounded.ColumnInt64(0));
1649   EXPECT_EQ(kSettingsOrigin, s_autofill_profiles_bounded.ColumnString(1));
1650   sql::Statement s_credit_cards_bounded(
1651       db_->GetSQLConnection()->GetUniqueStatement(
1652           "SELECT date_modified, origin FROM credit_cards"));
1653   ASSERT_TRUE(s_credit_cards_bounded.is_valid());
1654   ASSERT_TRUE(s_credit_cards_bounded.Step());
1655   EXPECT_EQ(17, s_credit_cards_bounded.ColumnInt64(0));
1656   EXPECT_EQ(std::string(), s_credit_cards_bounded.ColumnString(1));
1657   ASSERT_TRUE(s_credit_cards_bounded.Step());
1658   EXPECT_EQ(27, s_credit_cards_bounded.ColumnInt64(0));
1659   EXPECT_EQ("https://www.example.com/", s_credit_cards_bounded.ColumnString(1));
1660   ASSERT_TRUE(s_credit_cards_bounded.Step());
1661   EXPECT_EQ(37, s_credit_cards_bounded.ColumnInt64(0));
1662   EXPECT_EQ(kSettingsOrigin, s_credit_cards_bounded.ColumnString(1));
1663 
1664   // Remove all origin URLS.
1665   profiles.clear();
1666   table_->RemoveOriginURLsModifiedBetween(Time(), Time(), &profiles);
1667   EXPECT_EQ(0UL, profiles.size());
1668   sql::Statement s_autofill_profiles_all(
1669       db_->GetSQLConnection()->GetUniqueStatement(
1670           "SELECT date_modified, origin FROM autofill_profiles"));
1671   ASSERT_TRUE(s_autofill_profiles_all.is_valid());
1672   ASSERT_TRUE(s_autofill_profiles_all.Step());
1673   EXPECT_EQ(11, s_autofill_profiles_all.ColumnInt64(0));
1674   EXPECT_EQ(std::string(), s_autofill_profiles_all.ColumnString(1));
1675   ASSERT_TRUE(s_autofill_profiles_all.Step());
1676   EXPECT_EQ(21, s_autofill_profiles_all.ColumnInt64(0));
1677   EXPECT_EQ(std::string(), s_autofill_profiles_all.ColumnString(1));
1678   ASSERT_TRUE(s_autofill_profiles_all.Step());
1679   EXPECT_EQ(31, s_autofill_profiles_all.ColumnInt64(0));
1680   EXPECT_EQ(kSettingsOrigin, s_autofill_profiles_all.ColumnString(1));
1681   sql::Statement s_credit_cards_all(db_->GetSQLConnection()->GetUniqueStatement(
1682       "SELECT date_modified, origin FROM credit_cards"));
1683   ASSERT_TRUE(s_credit_cards_all.is_valid());
1684   ASSERT_TRUE(s_credit_cards_all.Step());
1685   EXPECT_EQ(17, s_credit_cards_all.ColumnInt64(0));
1686   EXPECT_EQ(std::string(), s_credit_cards_all.ColumnString(1));
1687   ASSERT_TRUE(s_credit_cards_all.Step());
1688   EXPECT_EQ(27, s_credit_cards_all.ColumnInt64(0));
1689   EXPECT_EQ(std::string(), s_credit_cards_all.ColumnString(1));
1690   ASSERT_TRUE(s_credit_cards_all.Step());
1691   EXPECT_EQ(37, s_credit_cards_all.ColumnInt64(0));
1692   EXPECT_EQ(kSettingsOrigin, s_credit_cards_all.ColumnString(1));
1693 }
1694 
TEST_F(AutofillTableTest,Autofill_GetAllAutofillEntries_NoResults)1695 TEST_F(AutofillTableTest, Autofill_GetAllAutofillEntries_NoResults) {
1696   std::vector<AutofillEntry> entries;
1697   ASSERT_TRUE(table_->GetAllAutofillEntries(&entries));
1698 
1699   EXPECT_EQ(0U, entries.size());
1700 }
1701 
TEST_F(AutofillTableTest,Autofill_GetAllAutofillEntries_OneResult)1702 TEST_F(AutofillTableTest, Autofill_GetAllAutofillEntries_OneResult) {
1703   AutofillChangeList changes;
1704   std::map<std::string, std::vector<Time>> name_value_times_map;
1705 
1706   time_t start = 0;
1707   std::vector<Time> timestamps1;
1708   FormFieldData field;
1709   field.name = ASCIIToUTF16("Name");
1710   field.value = ASCIIToUTF16("Superman");
1711   EXPECT_TRUE(
1712       table_->AddFormFieldValueTime(field, &changes, Time::FromTimeT(start)));
1713   timestamps1.push_back(Time::FromTimeT(start));
1714   std::string key1("NameSuperman");
1715   name_value_times_map.insert(
1716       std::pair<std::string, std::vector<Time>>(key1, timestamps1));
1717 
1718   AutofillEntrySet expected_entries(CompareAutofillEntries);
1719   AutofillKey ak1(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"));
1720   AutofillEntry ae1(ak1, timestamps1.front(), timestamps1.back());
1721 
1722   expected_entries.insert(ae1);
1723 
1724   std::vector<AutofillEntry> entries;
1725   ASSERT_TRUE(table_->GetAllAutofillEntries(&entries));
1726   AutofillEntrySet entry_set(entries.begin(), entries.end(),
1727                              CompareAutofillEntries);
1728 
1729   CompareAutofillEntrySets(entry_set, expected_entries);
1730 }
1731 
TEST_F(AutofillTableTest,Autofill_GetAllAutofillEntries_TwoDistinct)1732 TEST_F(AutofillTableTest, Autofill_GetAllAutofillEntries_TwoDistinct) {
1733   AutofillChangeList changes;
1734   std::map<std::string, std::vector<Time>> name_value_times_map;
1735   time_t start = 0;
1736 
1737   std::vector<Time> timestamps1;
1738   FormFieldData field;
1739   field.name = ASCIIToUTF16("Name");
1740   field.value = ASCIIToUTF16("Superman");
1741   EXPECT_TRUE(
1742       table_->AddFormFieldValueTime(field, &changes, Time::FromTimeT(start)));
1743   timestamps1.push_back(Time::FromTimeT(start));
1744   std::string key1("NameSuperman");
1745   name_value_times_map.insert(
1746       std::pair<std::string, std::vector<Time>>(key1, timestamps1));
1747 
1748   ++start;
1749   std::vector<Time> timestamps2;
1750   field.name = ASCIIToUTF16("Name");
1751   field.value = ASCIIToUTF16("Clark Kent");
1752   EXPECT_TRUE(
1753       table_->AddFormFieldValueTime(field, &changes, Time::FromTimeT(start)));
1754   timestamps2.push_back(Time::FromTimeT(start));
1755   std::string key2("NameClark Kent");
1756   name_value_times_map.insert(
1757       std::pair<std::string, std::vector<Time>>(key2, timestamps2));
1758 
1759   AutofillEntrySet expected_entries(CompareAutofillEntries);
1760   AutofillKey ak1(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"));
1761   AutofillKey ak2(ASCIIToUTF16("Name"), ASCIIToUTF16("Clark Kent"));
1762   AutofillEntry ae1(ak1, timestamps1.front(), timestamps1.back());
1763   AutofillEntry ae2(ak2, timestamps2.front(), timestamps2.back());
1764 
1765   expected_entries.insert(ae1);
1766   expected_entries.insert(ae2);
1767 
1768   std::vector<AutofillEntry> entries;
1769   ASSERT_TRUE(table_->GetAllAutofillEntries(&entries));
1770   AutofillEntrySet entry_set(entries.begin(), entries.end(),
1771                              CompareAutofillEntries);
1772 
1773   CompareAutofillEntrySets(entry_set, expected_entries);
1774 }
1775 
TEST_F(AutofillTableTest,Autofill_GetAllAutofillEntries_TwoSame)1776 TEST_F(AutofillTableTest, Autofill_GetAllAutofillEntries_TwoSame) {
1777   AutofillChangeList changes;
1778   std::map<std::string, std::vector<Time>> name_value_times_map;
1779 
1780   std::vector<Time> timestamps;
1781   time_t start = 0;
1782   for (int i = 0; i < 2; ++i, ++start) {
1783     FormFieldData field;
1784     field.name = ASCIIToUTF16("Name");
1785     field.value = ASCIIToUTF16("Superman");
1786     EXPECT_TRUE(
1787         table_->AddFormFieldValueTime(field, &changes, Time::FromTimeT(start)));
1788     timestamps.push_back(Time::FromTimeT(start));
1789   }
1790 
1791   std::string key("NameSuperman");
1792   name_value_times_map.insert(
1793       std::pair<std::string, std::vector<Time>>(key, timestamps));
1794 
1795   AutofillEntrySet expected_entries(CompareAutofillEntries);
1796   AutofillKey ak1(ASCIIToUTF16("Name"), ASCIIToUTF16("Superman"));
1797   AutofillEntry ae1(ak1, timestamps.front(), timestamps.back());
1798 
1799   expected_entries.insert(ae1);
1800 
1801   std::vector<AutofillEntry> entries;
1802   ASSERT_TRUE(table_->GetAllAutofillEntries(&entries));
1803   AutofillEntrySet entry_set(entries.begin(), entries.end(),
1804                              CompareAutofillEntries);
1805 
1806   CompareAutofillEntrySets(entry_set, expected_entries);
1807 }
1808 
TEST_F(AutofillTableTest,AutofillProfileValidityBitfield)1809 TEST_F(AutofillTableTest, AutofillProfileValidityBitfield) {
1810   // Add an autofill profile with a non default validity state. The value itself
1811   // is insignificant for this test since only the serialization and
1812   // deserialization are tested.
1813   const int kValidityBitfieldValue = 1984;
1814   AutofillProfile profile;
1815   profile.set_origin(std::string());
1816   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John"));
1817   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1818   profile.SetClientValidityFromBitfieldValue(kValidityBitfieldValue);
1819 
1820   // Add the profile to the table.
1821   EXPECT_TRUE(table_->AddAutofillProfile(profile));
1822 
1823   // Get the profile from the table and make sure the validity was set.
1824   std::unique_ptr<AutofillProfile> db_profile =
1825       table_->GetAutofillProfile(profile.guid());
1826   ASSERT_TRUE(db_profile);
1827   EXPECT_EQ(kValidityBitfieldValue,
1828             db_profile->GetClientValidityBitfieldValue());
1829 
1830   // Modify the validity of the profile.
1831   const int kOtherValidityBitfieldValue = 1999;
1832   profile.SetClientValidityFromBitfieldValue(kOtherValidityBitfieldValue);
1833 
1834   // Update the profile in the table.
1835   EXPECT_TRUE(table_->UpdateAutofillProfile(profile));
1836 
1837   // Get the profile from the table and make sure the validity was updated.
1838   db_profile = table_->GetAutofillProfile(profile.guid());
1839   ASSERT_TRUE(db_profile);
1840   EXPECT_EQ(kOtherValidityBitfieldValue,
1841             db_profile->GetClientValidityBitfieldValue());
1842 }
1843 
TEST_F(AutofillTableTest,AutofillProfileIsClientValidityStatesUpdatedFlag)1844 TEST_F(AutofillTableTest, AutofillProfileIsClientValidityStatesUpdatedFlag) {
1845   AutofillProfile profile;
1846   profile.set_origin(std::string());
1847   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("John"));
1848   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1849   profile.set_is_client_validity_states_updated(true);
1850 
1851   // Add the profile to the table.
1852   EXPECT_TRUE(table_->AddAutofillProfile(profile));
1853   // Get the profile from the table and make sure the validity was set.
1854   std::unique_ptr<AutofillProfile> db_profile =
1855       table_->GetAutofillProfile(profile.guid());
1856   ASSERT_TRUE(db_profile);
1857   EXPECT_TRUE(db_profile->is_client_validity_states_updated());
1858 
1859   // Test if turning off the validity updated flag works.
1860   profile.set_is_client_validity_states_updated(false);
1861   // Update the profile in the table.
1862   EXPECT_TRUE(table_->UpdateAutofillProfile(profile));
1863   // Get the profile from the table and make sure the validity was updated.
1864   db_profile = table_->GetAutofillProfile(profile.guid());
1865   ASSERT_TRUE(db_profile);
1866   EXPECT_FALSE(db_profile->is_client_validity_states_updated());
1867 
1868   // Test if turning on the validity updated flag works.
1869   profile.set_is_client_validity_states_updated(true);
1870   // Update the profile in the table.
1871   EXPECT_TRUE(table_->UpdateAutofillProfile(profile));
1872   // Get the profile from the table and make sure the validity was updated.
1873   db_profile = table_->GetAutofillProfile(profile.guid());
1874   ASSERT_TRUE(db_profile);
1875   EXPECT_TRUE(db_profile->is_client_validity_states_updated());
1876 }
1877 
TEST_F(AutofillTableTest,SetGetServerCards)1878 TEST_F(AutofillTableTest, SetGetServerCards) {
1879   std::vector<CreditCard> inputs;
1880   inputs.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "a123"));
1881   inputs[0].SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Paul F. Tompkins"));
1882   inputs[0].SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("1"));
1883   inputs[0].SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2020"));
1884   inputs[0].SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("4111111111111111"));
1885 
1886   inputs.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "b456"));
1887   inputs[1].SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Rick Roman"));
1888   inputs[1].SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("12"));
1889   inputs[1].SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("1997"));
1890   inputs[1].SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1111"));
1891   inputs[1].SetNetworkForMaskedCard(kVisaCard);
1892   inputs[1].SetServerStatus(CreditCard::EXPIRED);
1893   base::string16 nickname = ASCIIToUTF16("Grocery card");
1894   inputs[1].set_nickname(nickname);
1895 
1896   test::SetServerCreditCards(table_.get(), inputs);
1897 
1898   std::vector<std::unique_ptr<CreditCard>> outputs;
1899   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
1900   ASSERT_EQ(inputs.size(), outputs.size());
1901 
1902   // Ordering isn't guaranteed, so fix the ordering if it's backwards.
1903   if (outputs[1]->server_id() == inputs[0].server_id())
1904     std::swap(outputs[0], outputs[1]);
1905 
1906   // GUIDs for server cards are dynamically generated so will be different
1907   // after reading from the DB. Check they're valid, but otherwise don't count
1908   // them in the comparison.
1909   inputs[0].set_guid(std::string());
1910   inputs[1].set_guid(std::string());
1911   outputs[0]->set_guid(std::string());
1912   outputs[1]->set_guid(std::string());
1913 
1914   EXPECT_EQ(inputs[0], *outputs[0]);
1915   EXPECT_EQ(inputs[1], *outputs[1]);
1916 
1917   EXPECT_EQ(CreditCard::OK, outputs[0]->GetServerStatus());
1918   EXPECT_EQ(CreditCard::EXPIRED, outputs[1]->GetServerStatus());
1919 
1920   EXPECT_TRUE(outputs[0]->nickname().empty());
1921   EXPECT_EQ(nickname, outputs[1]->nickname());
1922 }
1923 
TEST_F(AutofillTableTest,SetGetRemoveServerCardMetadata)1924 TEST_F(AutofillTableTest, SetGetRemoveServerCardMetadata) {
1925   // Create and set the metadata.
1926   AutofillMetadata input;
1927   input.id = "server id";
1928   input.use_count = 50;
1929   input.use_date = AutofillClock::Now();
1930   input.billing_address_id = "billing id";
1931   EXPECT_TRUE(table_->AddServerCardMetadata(input));
1932 
1933   // Make sure it was added correctly.
1934   std::map<std::string, AutofillMetadata> outputs;
1935   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
1936   ASSERT_EQ(1U, outputs.size());
1937   EXPECT_EQ(input, outputs[input.id]);
1938 
1939   // Remove the metadata from the table.
1940   EXPECT_TRUE(table_->RemoveServerCardMetadata(input.id));
1941 
1942   // Make sure it was removed correctly.
1943   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
1944   EXPECT_EQ(0U, outputs.size());
1945 }
1946 
TEST_F(AutofillTableTest,SetGetRemoveServerAddressMetadata)1947 TEST_F(AutofillTableTest, SetGetRemoveServerAddressMetadata) {
1948   // Create and set the metadata.
1949   AutofillMetadata input;
1950   input.id = "server id";
1951   input.use_count = 50;
1952   input.use_date = AutofillClock::Now();
1953   input.has_converted = true;
1954   table_->AddServerAddressMetadata(input);
1955 
1956   // Make sure it was added correctly.
1957   std::map<std::string, AutofillMetadata> outputs;
1958   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
1959   ASSERT_EQ(1U, outputs.size());
1960   EXPECT_EQ(input, outputs[input.id]);
1961 
1962   // Remove the metadata from the table.
1963   EXPECT_TRUE(table_->RemoveServerAddressMetadata(input.id));
1964 
1965   // Make sure it was removed correctly.
1966   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
1967   EXPECT_EQ(0U, outputs.size());
1968 }
1969 
TEST_F(AutofillTableTest,AddUpdateServerAddressMetadata)1970 TEST_F(AutofillTableTest, AddUpdateServerAddressMetadata) {
1971   // Create and set the metadata.
1972   AutofillMetadata input;
1973   input.id = "server id";
1974   input.use_count = 50;
1975   input.use_date = AutofillClock::Now();
1976   input.has_converted = true;
1977   ASSERT_TRUE(table_->AddServerAddressMetadata(input));
1978 
1979   // Make sure it was added correctly.
1980   std::map<std::string, AutofillMetadata> outputs;
1981   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
1982   ASSERT_EQ(1U, outputs.size());
1983   ASSERT_EQ(input, outputs[input.id]);
1984 
1985   // Update the metadata in the table.
1986   input.use_count = 51;
1987   EXPECT_TRUE(table_->UpdateServerAddressMetadata(input));
1988 
1989   // Make sure it was updated correctly.
1990   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
1991   ASSERT_EQ(1U, outputs.size());
1992   EXPECT_EQ(input, outputs[input.id]);
1993 
1994   // Insert a new entry using update - that should also be legal.
1995   input.id = "another server id";
1996   EXPECT_TRUE(table_->UpdateServerAddressMetadata(input));
1997   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
1998   ASSERT_EQ(2U, outputs.size());
1999 }
2000 
TEST_F(AutofillTableTest,AddUpdateServerCardMetadata)2001 TEST_F(AutofillTableTest, AddUpdateServerCardMetadata) {
2002   // Create and set the metadata.
2003   AutofillMetadata input;
2004   input.id = "server id";
2005   input.use_count = 50;
2006   input.use_date = AutofillClock::Now();
2007   input.billing_address_id = "billing id";
2008   ASSERT_TRUE(table_->AddServerCardMetadata(input));
2009 
2010   // Make sure it was added correctly.
2011   std::map<std::string, AutofillMetadata> outputs;
2012   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
2013   ASSERT_EQ(1U, outputs.size());
2014   ASSERT_EQ(input, outputs[input.id]);
2015 
2016   // Update the metadata in the table.
2017   input.use_count = 51;
2018   EXPECT_TRUE(table_->UpdateServerCardMetadata(input));
2019 
2020   // Make sure it was updated correctly.
2021   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
2022   ASSERT_EQ(1U, outputs.size());
2023   EXPECT_EQ(input, outputs[input.id]);
2024 
2025   // Insert a new entry using update - that should also be legal.
2026   input.id = "another server id";
2027   EXPECT_TRUE(table_->UpdateServerCardMetadata(input));
2028   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
2029   ASSERT_EQ(2U, outputs.size());
2030 }
2031 
TEST_F(AutofillTableTest,UpdateServerAddressMetadataDoesNotChangeData)2032 TEST_F(AutofillTableTest, UpdateServerAddressMetadataDoesNotChangeData) {
2033   AutofillProfile one(AutofillProfile::SERVER_PROFILE, "a123");
2034   std::vector<AutofillProfile> inputs;
2035   inputs.push_back(one);
2036   table_->SetServerProfiles(inputs);
2037 
2038   std::vector<std::unique_ptr<AutofillProfile>> outputs;
2039   table_->GetServerProfiles(&outputs);
2040   ASSERT_EQ(1u, outputs.size());
2041   EXPECT_EQ(one.server_id(), outputs[0]->server_id());
2042 
2043   // Update metadata in the profile.
2044   ASSERT_NE(outputs[0]->use_count(), 51u);
2045   outputs[0]->set_use_count(51);
2046 
2047   AutofillMetadata input_metadata = outputs[0]->GetMetadata();
2048   EXPECT_TRUE(table_->UpdateServerAddressMetadata(input_metadata));
2049 
2050   // Make sure it was updated correctly.
2051   std::map<std::string, AutofillMetadata> output_metadata;
2052   ASSERT_TRUE(table_->GetServerAddressesMetadata(&output_metadata));
2053   ASSERT_EQ(1U, output_metadata.size());
2054   EXPECT_EQ(input_metadata, output_metadata[input_metadata.id]);
2055 
2056   // Make sure nothing else got updated.
2057   std::vector<std::unique_ptr<AutofillProfile>> outputs2;
2058   table_->GetServerProfiles(&outputs2);
2059   ASSERT_EQ(1u, outputs2.size());
2060   EXPECT_TRUE(outputs[0]->EqualsForSyncPurposes(*outputs2[0]));
2061 }
2062 
TEST_F(AutofillTableTest,UpdateServerCardMetadataDoesNotChangeData)2063 TEST_F(AutofillTableTest, UpdateServerCardMetadataDoesNotChangeData) {
2064   std::vector<CreditCard> inputs;
2065   inputs.push_back(CreditCard(CreditCard::FULL_SERVER_CARD, "a123"));
2066   inputs[0].SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Paul F. Tompkins"));
2067   inputs[0].SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("1"));
2068   inputs[0].SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2020"));
2069   inputs[0].SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("4111111111111111"));
2070   test::SetServerCreditCards(table_.get(), inputs);
2071 
2072   std::vector<std::unique_ptr<CreditCard>> outputs;
2073   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2074   ASSERT_EQ(1u, outputs.size());
2075   EXPECT_EQ(inputs[0].server_id(), outputs[0]->server_id());
2076 
2077   // Update metadata in the profile.
2078   ASSERT_NE(outputs[0]->use_count(), 51u);
2079   outputs[0]->set_use_count(51);
2080 
2081   AutofillMetadata input_metadata = outputs[0]->GetMetadata();
2082   EXPECT_TRUE(table_->UpdateServerCardMetadata(input_metadata));
2083 
2084   // Make sure it was updated correctly.
2085   std::map<std::string, AutofillMetadata> output_metadata;
2086   ASSERT_TRUE(table_->GetServerCardsMetadata(&output_metadata));
2087   ASSERT_EQ(1U, output_metadata.size());
2088   EXPECT_EQ(input_metadata, output_metadata[input_metadata.id]);
2089 
2090   // Make sure nothing else got updated.
2091   std::vector<std::unique_ptr<CreditCard>> outputs2;
2092   table_->GetServerCreditCards(&outputs2);
2093   ASSERT_EQ(1u, outputs2.size());
2094   EXPECT_EQ(0, outputs[0]->Compare(*outputs2[0]));
2095 }
2096 
TEST_F(AutofillTableTest,RemoveWrongServerCardMetadata)2097 TEST_F(AutofillTableTest, RemoveWrongServerCardMetadata) {
2098   // Crete and set some metadata.
2099   AutofillMetadata input;
2100   input.id = "server id";
2101   input.use_count = 50;
2102   input.use_date = AutofillClock::Now();
2103   input.billing_address_id = "billing id";
2104   table_->AddServerCardMetadata(input);
2105 
2106   // Make sure it was added correctly.
2107   std::map<std::string, AutofillMetadata> outputs;
2108   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
2109   ASSERT_EQ(1U, outputs.size());
2110   EXPECT_EQ(input, outputs[input.id]);
2111 
2112   // Try removing some non-existent metadata.
2113   EXPECT_FALSE(table_->RemoveServerCardMetadata("a_wrong_id"));
2114 
2115   // Make sure the metadata was not removed.
2116   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
2117   ASSERT_EQ(1U, outputs.size());
2118 }
2119 
TEST_F(AutofillTableTest,SetServerCardsData)2120 TEST_F(AutofillTableTest, SetServerCardsData) {
2121   // Set a card data.
2122   std::vector<CreditCard> inputs;
2123   inputs.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "card1"));
2124   inputs[0].SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Rick Roman"));
2125   inputs[0].SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("12"));
2126   inputs[0].SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("1997"));
2127   inputs[0].SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1111"));
2128   inputs[0].SetNetworkForMaskedCard(kVisaCard);
2129   inputs[0].SetServerStatus(CreditCard::EXPIRED);
2130   inputs[0].set_nickname(ASCIIToUTF16("Grocery card"));
2131   table_->SetServerCardsData(inputs);
2132 
2133   // Make sure the card was added correctly.
2134   std::vector<std::unique_ptr<CreditCard>> outputs;
2135   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2136   ASSERT_EQ(inputs.size(), outputs.size());
2137 
2138   // GUIDs for server cards are dynamically generated so will be different
2139   // after reading from the DB. Check they're valid, but otherwise don't count
2140   // them in the comparison.
2141   inputs[0].set_guid(std::string());
2142   outputs[0]->set_guid(std::string());
2143 
2144   EXPECT_EQ(inputs[0], *outputs[0]);
2145   EXPECT_EQ(CreditCard::EXPIRED, outputs[0]->GetServerStatus());
2146 
2147   // Make sure no metadata was added.
2148   std::map<std::string, AutofillMetadata> metadata_map;
2149   ASSERT_TRUE(table_->GetServerCardsMetadata(&metadata_map));
2150   ASSERT_EQ(0U, metadata_map.size());
2151 
2152   // Set a different card.
2153   inputs[0] = CreditCard(CreditCard::MASKED_SERVER_CARD, "card2");
2154   table_->SetServerCardsData(inputs);
2155 
2156   // The original one should have been replaced.
2157   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2158   ASSERT_EQ(1U, outputs.size());
2159   EXPECT_EQ("card2", outputs[0]->server_id());
2160 
2161   // Make sure no metadata was added.
2162   ASSERT_TRUE(table_->GetServerCardsMetadata(&metadata_map));
2163   ASSERT_EQ(0U, metadata_map.size());
2164 }
2165 
2166 // Tests that adding server cards data does not delete the existing metadata.
TEST_F(AutofillTableTest,SetServerCardsData_ExistingMetadata)2167 TEST_F(AutofillTableTest, SetServerCardsData_ExistingMetadata) {
2168   // Create and set some metadata.
2169   AutofillMetadata input;
2170   input.id = "server id";
2171   input.use_count = 50;
2172   input.use_date = AutofillClock::Now();
2173   input.billing_address_id = "billing id";
2174   table_->AddServerCardMetadata(input);
2175 
2176   // Set a card data.
2177   std::vector<CreditCard> inputs;
2178   inputs.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "server id"));
2179   table_->SetServerCardsData(inputs);
2180 
2181   // Make sure the metadata is still intact.
2182   std::map<std::string, AutofillMetadata> outputs;
2183   ASSERT_TRUE(table_->GetServerCardsMetadata(&outputs));
2184   ASSERT_EQ(1U, outputs.size());
2185   EXPECT_EQ(input, outputs[input.id]);
2186 }
2187 
TEST_F(AutofillTableTest,SetServerAddressesData)2188 TEST_F(AutofillTableTest, SetServerAddressesData) {
2189   AutofillProfile one(AutofillProfile::SERVER_PROFILE, "a123");
2190   std::vector<AutofillProfile> inputs;
2191   inputs.push_back(one);
2192   table_->SetServerAddressesData(inputs);
2193 
2194   // Make sure the address was added correctly.
2195   std::vector<std::unique_ptr<AutofillProfile>> outputs;
2196   table_->GetServerProfiles(&outputs);
2197   ASSERT_EQ(1u, outputs.size());
2198   EXPECT_EQ(one.server_id(), outputs[0]->server_id());
2199 
2200   outputs.clear();
2201 
2202   // Make sure no metadata was added.
2203   std::map<std::string, AutofillMetadata> metadata_map;
2204   ASSERT_TRUE(table_->GetServerAddressesMetadata(&metadata_map));
2205   ASSERT_EQ(0U, metadata_map.size());
2206 
2207   // Set a different profile.
2208   AutofillProfile two(AutofillProfile::SERVER_PROFILE, "b456");
2209   inputs[0] = two;
2210   table_->SetServerAddressesData(inputs);
2211 
2212   // The original one should have been replaced.
2213   table_->GetServerProfiles(&outputs);
2214   ASSERT_EQ(1u, outputs.size());
2215   EXPECT_EQ(two.server_id(), outputs[0]->server_id());
2216 
2217   // Make sure no metadata was added.
2218   ASSERT_TRUE(table_->GetServerAddressesMetadata(&metadata_map));
2219   ASSERT_EQ(0U, metadata_map.size());
2220 }
2221 
2222 // Tests that adding server addresses data does not delete the existing
2223 // metadata.
TEST_F(AutofillTableTest,SetServerAddressesData_ExistingMetadata)2224 TEST_F(AutofillTableTest, SetServerAddressesData_ExistingMetadata) {
2225   // Create and set some metadata.
2226   AutofillMetadata input;
2227   input.id = "server id";
2228   input.use_count = 50;
2229   input.use_date = AutofillClock::Now();
2230   input.has_converted = true;
2231   table_->AddServerAddressMetadata(input);
2232 
2233   // Set an address data.
2234   std::vector<AutofillProfile> inputs;
2235   inputs.push_back(
2236       AutofillProfile(AutofillProfile::SERVER_PROFILE, "server id"));
2237   table_->SetServerAddressesData(inputs);
2238 
2239   // Make sure the metadata is still intact.
2240   std::map<std::string, AutofillMetadata> outputs;
2241   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
2242   ASSERT_EQ(1U, outputs.size());
2243   EXPECT_EQ(input, outputs[input.id]);
2244 }
2245 
TEST_F(AutofillTableTest,RemoveWrongServerAddressMetadata)2246 TEST_F(AutofillTableTest, RemoveWrongServerAddressMetadata) {
2247   // Crete and set some metadata.
2248   AutofillMetadata input;
2249   input.id = "server id";
2250   input.use_count = 50;
2251   input.use_date = AutofillClock::Now();
2252   input.has_converted = true;
2253   table_->AddServerAddressMetadata(input);
2254 
2255   // Make sure it was added correctly.
2256   std::map<std::string, AutofillMetadata> outputs;
2257   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
2258   ASSERT_EQ(1U, outputs.size());
2259   EXPECT_EQ(input, outputs[input.id]);
2260 
2261   // Try removing some non-existent metadata.
2262   EXPECT_FALSE(table_->RemoveServerAddressMetadata("a_wrong_id"));
2263 
2264   // Make sure the metadata was not removed.
2265   ASSERT_TRUE(table_->GetServerAddressesMetadata(&outputs));
2266   ASSERT_EQ(1U, outputs.size());
2267 }
2268 
TEST_F(AutofillTableTest,MaskUnmaskServerCards)2269 TEST_F(AutofillTableTest, MaskUnmaskServerCards) {
2270   base::string16 masked_number(ASCIIToUTF16("1111"));
2271   std::vector<CreditCard> inputs;
2272   inputs.push_back(CreditCard(CreditCard::MASKED_SERVER_CARD, "a123"));
2273   inputs[0].SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Jay Johnson"));
2274   inputs[0].SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("1"));
2275   inputs[0].SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2020"));
2276   inputs[0].SetRawInfo(CREDIT_CARD_NUMBER, masked_number);
2277   inputs[0].SetNetworkForMaskedCard(kVisaCard);
2278   test::SetServerCreditCards(table_.get(), inputs);
2279 
2280   // Unmask the number. The full number should be available.
2281   base::string16 full_number(ASCIIToUTF16("4111111111111111"));
2282   ASSERT_TRUE(table_->UnmaskServerCreditCard(inputs[0], full_number));
2283 
2284   std::vector<std::unique_ptr<CreditCard>> outputs;
2285   table_->GetServerCreditCards(&outputs);
2286   ASSERT_EQ(1u, outputs.size());
2287   EXPECT_TRUE(CreditCard::FULL_SERVER_CARD == outputs[0]->record_type());
2288   EXPECT_EQ(full_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2289 
2290   outputs.clear();
2291 
2292   // Re-mask the number, we should only get the last 4 digits out.
2293   ASSERT_TRUE(table_->MaskServerCreditCard(inputs[0].server_id()));
2294   table_->GetServerCreditCards(&outputs);
2295   ASSERT_EQ(1u, outputs.size());
2296   EXPECT_TRUE(CreditCard::MASKED_SERVER_CARD == outputs[0]->record_type());
2297   EXPECT_EQ(masked_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2298 
2299   outputs.clear();
2300 }
2301 
2302 // Calling SetServerCreditCards should replace all existing cards, but unmasked
2303 // cards should not be re-masked.
TEST_F(AutofillTableTest,SetServerCardModify)2304 TEST_F(AutofillTableTest, SetServerCardModify) {
2305   // Add a masked card.
2306   CreditCard masked_card(CreditCard::MASKED_SERVER_CARD, "a123");
2307   masked_card.SetRawInfo(CREDIT_CARD_NAME_FULL,
2308                          ASCIIToUTF16("Paul F. Tompkins"));
2309   masked_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("1"));
2310   masked_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2020"));
2311   masked_card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1111"));
2312   masked_card.SetNetworkForMaskedCard(kVisaCard);
2313 
2314   std::vector<CreditCard> inputs;
2315   inputs.push_back(masked_card);
2316   test::SetServerCreditCards(table_.get(), inputs);
2317 
2318   // Now unmask it.
2319   base::string16 full_number = ASCIIToUTF16("4111111111111111");
2320   table_->UnmaskServerCreditCard(masked_card, full_number);
2321 
2322   // The card should now be unmasked.
2323   std::vector<std::unique_ptr<CreditCard>> outputs;
2324   table_->GetServerCreditCards(&outputs);
2325   ASSERT_EQ(1u, outputs.size());
2326   EXPECT_TRUE(outputs[0]->record_type() == CreditCard::FULL_SERVER_CARD);
2327   EXPECT_EQ(full_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2328 
2329   outputs.clear();
2330 
2331   // Call set again with the masked number.
2332   inputs[0] = masked_card;
2333   test::SetServerCreditCards(table_.get(), inputs);
2334 
2335   // The card should stay unmasked.
2336   table_->GetServerCreditCards(&outputs);
2337   ASSERT_EQ(1u, outputs.size());
2338   EXPECT_TRUE(outputs[0]->record_type() == CreditCard::FULL_SERVER_CARD);
2339   EXPECT_EQ(full_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2340 
2341   outputs.clear();
2342 
2343   // Set inputs that do not include our old card.
2344   CreditCard random_card(CreditCard::MASKED_SERVER_CARD, "b456");
2345   random_card.SetRawInfo(CREDIT_CARD_NAME_FULL, ASCIIToUTF16("Rick Roman"));
2346   random_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("12"));
2347   random_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("1997"));
2348   random_card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("2222"));
2349   random_card.SetNetworkForMaskedCard(kVisaCard);
2350   inputs[0] = random_card;
2351   test::SetServerCreditCards(table_.get(), inputs);
2352 
2353   // We should have only the new card, the other one should have been deleted.
2354   table_->GetServerCreditCards(&outputs);
2355   ASSERT_EQ(1u, outputs.size());
2356   EXPECT_TRUE(outputs[0]->record_type() == CreditCard::MASKED_SERVER_CARD);
2357   EXPECT_EQ(random_card.server_id(), outputs[0]->server_id());
2358   EXPECT_EQ(ASCIIToUTF16("2222"), outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2359 
2360   outputs.clear();
2361 
2362   // Putting back the original card masked should make it masked (this tests
2363   // that the unmasked data was really deleted).
2364   inputs[0] = masked_card;
2365   test::SetServerCreditCards(table_.get(), inputs);
2366   table_->GetServerCreditCards(&outputs);
2367   ASSERT_EQ(1u, outputs.size());
2368   EXPECT_TRUE(outputs[0]->record_type() == CreditCard::MASKED_SERVER_CARD);
2369   EXPECT_EQ(masked_card.server_id(), outputs[0]->server_id());
2370   EXPECT_EQ(ASCIIToUTF16("1111"), outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2371 
2372   outputs.clear();
2373 }
2374 
TEST_F(AutofillTableTest,SetServerCardUpdateUsageStatsAndBillingAddress)2375 TEST_F(AutofillTableTest, SetServerCardUpdateUsageStatsAndBillingAddress) {
2376   // Add a masked card.
2377   CreditCard masked_card(CreditCard::MASKED_SERVER_CARD, "a123");
2378   masked_card.SetRawInfo(CREDIT_CARD_NAME_FULL,
2379                          ASCIIToUTF16("Paul F. Tompkins"));
2380   masked_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("1"));
2381   masked_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2020"));
2382   masked_card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("1111"));
2383   masked_card.set_billing_address_id("1");
2384   masked_card.SetNetworkForMaskedCard(kVisaCard);
2385 
2386   std::vector<CreditCard> inputs;
2387   inputs.push_back(masked_card);
2388   test::SetServerCreditCards(table_.get(), inputs);
2389 
2390   std::vector<std::unique_ptr<CreditCard>> outputs;
2391   table_->GetServerCreditCards(&outputs);
2392   ASSERT_EQ(1u, outputs.size());
2393   EXPECT_EQ(masked_card.server_id(), outputs[0]->server_id());
2394   EXPECT_EQ(1U, outputs[0]->use_count());
2395   EXPECT_NE(base::Time(), outputs[0]->use_date());
2396   // We don't track modification date for server cards. It should always be
2397   // base::Time().
2398   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2399   outputs.clear();
2400 
2401   // Update the usage stats; make sure they're reflected in GetServerProfiles.
2402   inputs.back().set_use_count(4U);
2403   inputs.back().set_use_date(base::Time());
2404   inputs.back().set_billing_address_id("2");
2405   table_->UpdateServerCardMetadata(inputs.back());
2406   table_->GetServerCreditCards(&outputs);
2407   ASSERT_EQ(1u, outputs.size());
2408   EXPECT_EQ(masked_card.server_id(), outputs[0]->server_id());
2409   EXPECT_EQ(4U, outputs[0]->use_count());
2410   EXPECT_EQ(base::Time(), outputs[0]->use_date());
2411   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2412   EXPECT_EQ("2", outputs[0]->billing_address_id());
2413   outputs.clear();
2414 
2415   // Setting the cards again shouldn't delete the usage stats.
2416   table_->SetServerCreditCards(inputs);
2417   table_->GetServerCreditCards(&outputs);
2418   ASSERT_EQ(1u, outputs.size());
2419   EXPECT_EQ(masked_card.server_id(), outputs[0]->server_id());
2420   EXPECT_EQ(4U, outputs[0]->use_count());
2421   EXPECT_EQ(base::Time(), outputs[0]->use_date());
2422   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2423   EXPECT_EQ("2", outputs[0]->billing_address_id());
2424   outputs.clear();
2425 
2426   // Set a card list where the card is missing --- this should clear metadata.
2427   CreditCard masked_card2(CreditCard::MASKED_SERVER_CARD, "b456");
2428   inputs.back() = masked_card2;
2429   table_->SetServerCreditCards(inputs);
2430 
2431   // Back to the original card list.
2432   inputs.back() = masked_card;
2433   table_->SetServerCreditCards(inputs);
2434   table_->GetServerCreditCards(&outputs);
2435   ASSERT_EQ(1u, outputs.size());
2436   EXPECT_EQ(masked_card.server_id(), outputs[0]->server_id());
2437   EXPECT_EQ(1U, outputs[0]->use_count());
2438   EXPECT_NE(base::Time(), outputs[0]->use_date());
2439   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2440   EXPECT_EQ("1", outputs[0]->billing_address_id());
2441   outputs.clear();
2442 }
2443 
TEST_F(AutofillTableTest,SetServerProfile)2444 TEST_F(AutofillTableTest, SetServerProfile) {
2445   AutofillProfile one(AutofillProfile::SERVER_PROFILE, "a123");
2446   std::vector<AutofillProfile> inputs;
2447   inputs.push_back(one);
2448   table_->SetServerProfiles(inputs);
2449 
2450   std::vector<std::unique_ptr<AutofillProfile>> outputs;
2451   table_->GetServerProfiles(&outputs);
2452   ASSERT_EQ(1u, outputs.size());
2453   EXPECT_EQ(one.server_id(), outputs[0]->server_id());
2454 
2455   outputs.clear();
2456 
2457   // Set a different profile.
2458   AutofillProfile two(AutofillProfile::SERVER_PROFILE, "b456");
2459   inputs[0] = two;
2460   table_->SetServerProfiles(inputs);
2461 
2462   // The original one should have been replaced.
2463   table_->GetServerProfiles(&outputs);
2464   ASSERT_EQ(1u, outputs.size());
2465   EXPECT_EQ(two.server_id(), outputs[0]->server_id());
2466 
2467   outputs.clear();
2468 }
2469 
TEST_F(AutofillTableTest,SetServerProfileUpdateUsageStats)2470 TEST_F(AutofillTableTest, SetServerProfileUpdateUsageStats) {
2471   AutofillProfile one(AutofillProfile::SERVER_PROFILE, "a123");
2472   std::vector<AutofillProfile> inputs;
2473   inputs.push_back(one);
2474   table_->SetServerProfiles(inputs);
2475 
2476   std::vector<std::unique_ptr<AutofillProfile>> outputs;
2477   table_->GetServerProfiles(&outputs);
2478   ASSERT_EQ(1u, outputs.size());
2479   EXPECT_EQ(one.server_id(), outputs[0]->server_id());
2480   EXPECT_EQ(1U, outputs[0]->use_count());
2481   EXPECT_NE(base::Time(), outputs[0]->use_date());
2482   // We don't track modification date for server profiles. It should always be
2483   // base::Time().
2484   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2485   outputs.clear();
2486 
2487   // Update the usage stats; make sure they're reflected in GetServerProfiles.
2488   inputs.back().set_use_count(4U);
2489   inputs.back().set_use_date(AutofillClock::Now());
2490   table_->UpdateServerAddressMetadata(inputs.back());
2491   table_->GetServerProfiles(&outputs);
2492   ASSERT_EQ(1u, outputs.size());
2493   EXPECT_EQ(one.server_id(), outputs[0]->server_id());
2494   EXPECT_EQ(4U, outputs[0]->use_count());
2495   EXPECT_NE(base::Time(), outputs[0]->use_date());
2496   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2497   outputs.clear();
2498 
2499   // Setting the profiles again shouldn't delete the usage stats.
2500   table_->SetServerProfiles(inputs);
2501   table_->GetServerProfiles(&outputs);
2502   ASSERT_EQ(1u, outputs.size());
2503   EXPECT_EQ(one.server_id(), outputs[0]->server_id());
2504   EXPECT_EQ(4U, outputs[0]->use_count());
2505   EXPECT_NE(base::Time(), outputs[0]->use_date());
2506   EXPECT_EQ(base::Time(), outputs[0]->modification_date());
2507   outputs.clear();
2508 }
2509 
2510 // Tests that deleting time ranges re-masks server credit cards that were
2511 // unmasked in that time.
TEST_F(AutofillTableTest,DeleteUnmaskedCard)2512 TEST_F(AutofillTableTest, DeleteUnmaskedCard) {
2513   // This isn't the exact unmasked time, since the database will use the
2514   // current time that it is called. The code below has to be approximate.
2515   base::Time unmasked_time = AutofillClock::Now();
2516 
2517   // Add a masked card.
2518   base::string16 masked_number = ASCIIToUTF16("1111");
2519   CreditCard masked_card(CreditCard::MASKED_SERVER_CARD, "a123");
2520   masked_card.SetRawInfo(CREDIT_CARD_NAME_FULL,
2521                          ASCIIToUTF16("Paul F. Tompkins"));
2522   masked_card.SetRawInfo(CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("1"));
2523   masked_card.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, ASCIIToUTF16("2020"));
2524   masked_card.SetRawInfo(CREDIT_CARD_NUMBER, masked_number);
2525   masked_card.SetNetworkForMaskedCard(kVisaCard);
2526 
2527   std::vector<CreditCard> inputs;
2528   inputs.push_back(masked_card);
2529   table_->SetServerCreditCards(inputs);
2530 
2531   // Unmask it.
2532   base::string16 full_number = ASCIIToUTF16("4111111111111111");
2533   table_->UnmaskServerCreditCard(masked_card, full_number);
2534 
2535   // Delete data in a range a year in the future.
2536   std::vector<std::unique_ptr<AutofillProfile>> profiles;
2537   std::vector<std::unique_ptr<CreditCard>> credit_cards;
2538   ASSERT_TRUE(table_->RemoveAutofillDataModifiedBetween(
2539       unmasked_time + base::TimeDelta::FromDays(365),
2540       unmasked_time + base::TimeDelta::FromDays(530), &profiles,
2541       &credit_cards));
2542 
2543   // This should not affect the unmasked card (should be unmasked).
2544   std::vector<std::unique_ptr<CreditCard>> outputs;
2545   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2546   ASSERT_EQ(1u, outputs.size());
2547   EXPECT_EQ(CreditCard::FULL_SERVER_CARD, outputs[0]->record_type());
2548   EXPECT_EQ(full_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2549   outputs.clear();
2550 
2551   // Delete data in the range of the last 24 hours.
2552   // Fudge |now| to make sure it's strictly greater than the |now| that
2553   // the database uses.
2554   base::Time now = AutofillClock::Now() + base::TimeDelta::FromSeconds(1);
2555   ASSERT_TRUE(table_->RemoveAutofillDataModifiedBetween(
2556       now - base::TimeDelta::FromDays(1), now, &profiles, &credit_cards));
2557 
2558   // This should re-mask.
2559   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2560   ASSERT_EQ(1u, outputs.size());
2561   EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, outputs[0]->record_type());
2562   EXPECT_EQ(masked_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2563   outputs.clear();
2564 
2565   // Unmask again, the card should be back.
2566   table_->UnmaskServerCreditCard(masked_card, full_number);
2567   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2568   ASSERT_EQ(1u, outputs.size());
2569   EXPECT_EQ(CreditCard::FULL_SERVER_CARD, outputs[0]->record_type());
2570   EXPECT_EQ(full_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2571   outputs.clear();
2572 
2573   // Delete all data.
2574   ASSERT_TRUE(table_->RemoveAutofillDataModifiedBetween(
2575       base::Time(), base::Time::Max(), &profiles, &credit_cards));
2576 
2577   // Should be masked again.
2578   ASSERT_TRUE(table_->GetServerCreditCards(&outputs));
2579   ASSERT_EQ(1u, outputs.size());
2580   EXPECT_EQ(CreditCard::MASKED_SERVER_CARD, outputs[0]->record_type());
2581   EXPECT_EQ(masked_number, outputs[0]->GetRawInfo(CREDIT_CARD_NUMBER));
2582   outputs.clear();
2583 }
2584 
2585 // Test that we can get what we set.
TEST_F(AutofillTableTest,SetGetPaymentsCustomerData)2586 TEST_F(AutofillTableTest, SetGetPaymentsCustomerData) {
2587   PaymentsCustomerData input{/*customer_id=*/"deadbeef"};
2588   table_->SetPaymentsCustomerData(&input);
2589 
2590   std::unique_ptr<PaymentsCustomerData> output;
2591   ASSERT_TRUE(table_->GetPaymentsCustomerData(&output));
2592   EXPECT_EQ(input, *output);
2593 }
2594 
2595 // We don't set anything in the table. Test that we don't crash.
TEST_F(AutofillTableTest,GetPaymentsCustomerData_NoData)2596 TEST_F(AutofillTableTest, GetPaymentsCustomerData_NoData) {
2597   std::unique_ptr<PaymentsCustomerData> output;
2598   ASSERT_TRUE(table_->GetPaymentsCustomerData(&output));
2599   EXPECT_FALSE(output);
2600 }
2601 
2602 // The latest PaymentsCustomerData that was set is returned.
TEST_F(AutofillTableTest,SetGetPaymentsCustomerData_MultipleSet)2603 TEST_F(AutofillTableTest, SetGetPaymentsCustomerData_MultipleSet) {
2604   PaymentsCustomerData input{/*customer_id=*/"deadbeef"};
2605   table_->SetPaymentsCustomerData(&input);
2606 
2607   PaymentsCustomerData input2{/*customer_id=*/"wallet"};
2608   table_->SetPaymentsCustomerData(&input2);
2609 
2610   PaymentsCustomerData input3{/*customer_id=*/"latest"};
2611   table_->SetPaymentsCustomerData(&input3);
2612 
2613   std::unique_ptr<PaymentsCustomerData> output;
2614   ASSERT_TRUE(table_->GetPaymentsCustomerData(&output));
2615   EXPECT_EQ(input3, *output);
2616 }
2617 
TEST_F(AutofillTableTest,SetGetCreditCardCloudData_OneTimeSet)2618 TEST_F(AutofillTableTest, SetGetCreditCardCloudData_OneTimeSet) {
2619   std::vector<CreditCardCloudTokenData> inputs;
2620   inputs.push_back(test::GetCreditCardCloudTokenData1());
2621   inputs.push_back(test::GetCreditCardCloudTokenData2());
2622   table_->SetCreditCardCloudTokenData(inputs);
2623 
2624   std::vector<std::unique_ptr<CreditCardCloudTokenData>> outputs;
2625   ASSERT_TRUE(table_->GetCreditCardCloudTokenData(&outputs));
2626   EXPECT_EQ(outputs.size(), inputs.size());
2627   EXPECT_EQ(0, outputs[0]->Compare(test::GetCreditCardCloudTokenData1()));
2628   EXPECT_EQ(0, outputs[1]->Compare(test::GetCreditCardCloudTokenData2()));
2629 }
2630 
TEST_F(AutofillTableTest,SetGetCreditCardCloudData_MultipleSet)2631 TEST_F(AutofillTableTest, SetGetCreditCardCloudData_MultipleSet) {
2632   std::vector<CreditCardCloudTokenData> inputs;
2633   CreditCardCloudTokenData input1 = test::GetCreditCardCloudTokenData1();
2634   inputs.push_back(input1);
2635   table_->SetCreditCardCloudTokenData(inputs);
2636 
2637   inputs.clear();
2638   CreditCardCloudTokenData input2 = test::GetCreditCardCloudTokenData2();
2639   inputs.push_back(input2);
2640   table_->SetCreditCardCloudTokenData(inputs);
2641 
2642   std::vector<std::unique_ptr<CreditCardCloudTokenData>> outputs;
2643   ASSERT_TRUE(table_->GetCreditCardCloudTokenData(&outputs));
2644   EXPECT_EQ(1u, outputs.size());
2645   EXPECT_EQ(0, outputs[0]->Compare(test::GetCreditCardCloudTokenData2()));
2646 }
2647 
TEST_F(AutofillTableTest,GetCreditCardCloudData_NoData)2648 TEST_F(AutofillTableTest, GetCreditCardCloudData_NoData) {
2649   std::vector<std::unique_ptr<CreditCardCloudTokenData>> output;
2650   ASSERT_TRUE(table_->GetCreditCardCloudTokenData(&output));
2651   EXPECT_TRUE(output.empty());
2652 }
2653 
2654 const size_t kMaxCount = 2;
2655 struct GetFormValuesTestCase {
2656   const char* const field_suggestion[kMaxCount];
2657   const char* const field_contents;
2658   size_t expected_suggestion_count;
2659   const char* const expected_suggestion[kMaxCount];
2660 };
2661 
2662 class GetFormValuesTest : public testing::TestWithParam<GetFormValuesTestCase> {
2663  public:
GetFormValuesTest()2664   GetFormValuesTest() {}
~GetFormValuesTest()2665   ~GetFormValuesTest() override {}
2666 
2667  protected:
SetUp()2668   void SetUp() override {
2669     OSCryptMocker::SetUp();
2670     ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
2671     file_ = temp_dir_.GetPath().AppendASCII("TestWebDatabase");
2672 
2673     table_.reset(new AutofillTable);
2674     db_.reset(new WebDatabase);
2675     db_->AddTable(table_.get());
2676     ASSERT_EQ(sql::INIT_OK, db_->Init(file_));
2677   }
2678 
TearDown()2679   void TearDown() override { OSCryptMocker::TearDown(); }
2680 
2681   base::FilePath file_;
2682   base::ScopedTempDir temp_dir_;
2683   std::unique_ptr<AutofillTable> table_;
2684   std::unique_ptr<WebDatabase> db_;
2685 
2686  private:
2687   DISALLOW_COPY_AND_ASSIGN(GetFormValuesTest);
2688 };
2689 
TEST_P(GetFormValuesTest,GetFormValuesForElementName_SubstringMatchEnabled)2690 TEST_P(GetFormValuesTest, GetFormValuesForElementName_SubstringMatchEnabled) {
2691   base::test::ScopedFeatureList features;
2692   features.InitAndEnableFeature(features::kAutofillTokenPrefixMatching);
2693 
2694   auto test_case = GetParam();
2695   SCOPED_TRACE(testing::Message()
2696                << "suggestion = " << test_case.field_suggestion[0]
2697                << ", contents = " << test_case.field_contents);
2698 
2699   Time t1 = AutofillClock::Now();
2700 
2701   // Simulate the submission of a handful of entries in a field called "Name".
2702   AutofillChangeList changes;
2703   FormFieldData field;
2704   for (size_t k = 0; k < kMaxCount; ++k) {
2705     field.name = ASCIIToUTF16("Name");
2706     field.value = ASCIIToUTF16(test_case.field_suggestion[k]);
2707     table_->AddFormFieldValue(field, &changes);
2708   }
2709 
2710   std::vector<AutofillEntry> v;
2711   table_->GetFormValuesForElementName(
2712       ASCIIToUTF16("Name"), ASCIIToUTF16(test_case.field_contents), &v, 6);
2713 
2714   EXPECT_EQ(test_case.expected_suggestion_count, v.size());
2715   for (size_t j = 0; j < test_case.expected_suggestion_count; ++j) {
2716     EXPECT_EQ(ASCIIToUTF16(test_case.expected_suggestion[j]),
2717               v[j].key().value());
2718   }
2719 
2720   changes.clear();
2721   table_->RemoveFormElementsAddedBetween(t1, Time(), &changes);
2722 }
2723 
2724 INSTANTIATE_TEST_SUITE_P(
2725     AutofillTableTest,
2726     GetFormValuesTest,
2727     testing::Values(GetFormValuesTestCase{{"user.test", "test_user"},
2728                                           "TEST",
2729                                           2,
2730                                           {"test_user", "user.test"}},
2731                     GetFormValuesTestCase{{"user test", "test-user"},
2732                                           "user",
2733                                           2,
2734                                           {"user test", "test-user"}},
2735                     GetFormValuesTestCase{{"user test", "test-rest"},
2736                                           "user",
2737                                           1,
2738                                           {"user test", nullptr}},
2739                     GetFormValuesTestCase{{"user@test", "test_user"},
2740                                           "user@t",
2741                                           1,
2742                                           {"user@test", nullptr}},
2743                     GetFormValuesTestCase{{"user.test", "test_user"},
2744                                           "er.tes",
2745                                           0,
2746                                           {nullptr, nullptr}},
2747                     GetFormValuesTestCase{{"user test", "test_user"},
2748                                           "_ser",
2749                                           0,
2750                                           {nullptr, nullptr}},
2751                     GetFormValuesTestCase{{"user.test", "test_user"},
2752                                           "%ser",
2753                                           0,
2754                                           {nullptr, nullptr}},
2755                     GetFormValuesTestCase{{"user.test", "test_user"},
2756                                           "; DROP TABLE autofill;",
2757                                           0,
2758                                           {nullptr, nullptr}}));
2759 
2760 class AutofillTableTestPerModelType
2761     : public AutofillTableTest,
2762       public testing::WithParamInterface<syncer::ModelType> {
2763  public:
AutofillTableTestPerModelType()2764   AutofillTableTestPerModelType() {}
~AutofillTableTestPerModelType()2765   ~AutofillTableTestPerModelType() override {}
2766 
2767  private:
2768   DISALLOW_COPY_AND_ASSIGN(AutofillTableTestPerModelType);
2769 };
2770 
TEST_P(AutofillTableTestPerModelType,AutofillNoMetadata)2771 TEST_P(AutofillTableTestPerModelType, AutofillNoMetadata) {
2772   syncer::ModelType model_type = GetParam();
2773   MetadataBatch metadata_batch;
2774   EXPECT_TRUE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2775   EXPECT_EQ(0u, metadata_batch.TakeAllMetadata().size());
2776   EXPECT_EQ(ModelTypeState().SerializeAsString(),
2777             metadata_batch.GetModelTypeState().SerializeAsString());
2778 }
2779 
TEST_P(AutofillTableTestPerModelType,AutofillGetAllSyncMetadata)2780 TEST_P(AutofillTableTestPerModelType, AutofillGetAllSyncMetadata) {
2781   syncer::ModelType model_type = GetParam();
2782   EntityMetadata metadata;
2783   std::string storage_key = "storage_key";
2784   std::string storage_key2 = "storage_key2";
2785   metadata.set_sequence_number(1);
2786 
2787   EXPECT_TRUE(table_->UpdateSyncMetadata(model_type, storage_key, metadata));
2788 
2789   ModelTypeState model_type_state;
2790   model_type_state.set_initial_sync_done(true);
2791 
2792   EXPECT_TRUE(table_->UpdateModelTypeState(model_type, model_type_state));
2793 
2794   metadata.set_sequence_number(2);
2795   EXPECT_TRUE(table_->UpdateSyncMetadata(model_type, storage_key2, metadata));
2796 
2797   MetadataBatch metadata_batch;
2798   EXPECT_TRUE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2799 
2800   EXPECT_TRUE(metadata_batch.GetModelTypeState().initial_sync_done());
2801 
2802   EntityMetadataMap metadata_records = metadata_batch.TakeAllMetadata();
2803 
2804   EXPECT_EQ(metadata_records.size(), 2u);
2805   EXPECT_EQ(metadata_records[storage_key]->sequence_number(), 1);
2806   EXPECT_EQ(metadata_records[storage_key2]->sequence_number(), 2);
2807 
2808   // Now check that a model type state update replaces the old value
2809   model_type_state.set_initial_sync_done(false);
2810   EXPECT_TRUE(table_->UpdateModelTypeState(model_type, model_type_state));
2811 
2812   EXPECT_TRUE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2813   EXPECT_FALSE(metadata_batch.GetModelTypeState().initial_sync_done());
2814 }
2815 
TEST_P(AutofillTableTestPerModelType,AutofillWriteThenDeleteSyncMetadata)2816 TEST_P(AutofillTableTestPerModelType, AutofillWriteThenDeleteSyncMetadata) {
2817   syncer::ModelType model_type = GetParam();
2818   EntityMetadata metadata;
2819   MetadataBatch metadata_batch;
2820   std::string storage_key = "storage_key";
2821   ModelTypeState model_type_state;
2822 
2823   model_type_state.set_initial_sync_done(true);
2824 
2825   metadata.set_client_tag_hash("client_hash");
2826 
2827   // Write the data into the store.
2828   EXPECT_TRUE(table_->UpdateSyncMetadata(model_type, storage_key, metadata));
2829   EXPECT_TRUE(table_->UpdateModelTypeState(model_type, model_type_state));
2830   // Delete the data we just wrote.
2831   EXPECT_TRUE(table_->ClearSyncMetadata(model_type, storage_key));
2832   // It shouldn't be there any more.
2833   EXPECT_TRUE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2834 
2835   EntityMetadataMap metadata_records = metadata_batch.TakeAllMetadata();
2836   EXPECT_EQ(metadata_records.size(), 0u);
2837 
2838   // Now delete the model type state.
2839   EXPECT_TRUE(table_->ClearModelTypeState(model_type));
2840   EXPECT_TRUE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2841   EXPECT_EQ(ModelTypeState().SerializeAsString(),
2842             metadata_batch.GetModelTypeState().SerializeAsString());
2843 }
2844 
TEST_P(AutofillTableTestPerModelType,AutofillCorruptSyncMetadata)2845 TEST_P(AutofillTableTestPerModelType, AutofillCorruptSyncMetadata) {
2846   syncer::ModelType model_type = GetParam();
2847   MetadataBatch metadata_batch;
2848   sql::Statement s(db_->GetSQLConnection()->GetUniqueStatement(
2849       "INSERT OR REPLACE INTO autofill_sync_metadata "
2850       "(model_type, storage_key, value) VALUES(?, ?, ?)"));
2851   s.BindInt(0, syncer::ModelTypeToStableIdentifier(model_type));
2852   s.BindString(1, "storage_key");
2853   s.BindString(2, "unparseable");
2854   EXPECT_TRUE(s.Run());
2855 
2856   EXPECT_FALSE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2857 }
2858 
TEST_P(AutofillTableTestPerModelType,AutofillCorruptModelTypeState)2859 TEST_P(AutofillTableTestPerModelType, AutofillCorruptModelTypeState) {
2860   syncer::ModelType model_type = GetParam();
2861   MetadataBatch metadata_batch;
2862   sql::Statement s(db_->GetSQLConnection()->GetUniqueStatement(
2863       "INSERT OR REPLACE INTO autofill_model_type_state "
2864       "(model_type, value) VALUES(?, ?)"));
2865   s.BindInt(0, syncer::ModelTypeToStableIdentifier(model_type));
2866   s.BindString(1, "unparseable");
2867   EXPECT_TRUE(s.Run());
2868 
2869   EXPECT_FALSE(table_->GetAllSyncMetadata(model_type, &metadata_batch));
2870 }
2871 
2872 INSTANTIATE_TEST_SUITE_P(AutofillTableTest,
2873                          AutofillTableTestPerModelType,
2874                          testing::Values(syncer::AUTOFILL,
2875                                          syncer::AUTOFILL_PROFILE));
2876 
TEST_F(AutofillTableTest,RemoveOrphanAutofillTableRows)2877 TEST_F(AutofillTableTest, RemoveOrphanAutofillTableRows) {
2878   // Populate the different tables.
2879   ASSERT_TRUE(db_->GetSQLConnection()->Execute(
2880       // Add a profile in all the tables
2881       "INSERT INTO autofill_profiles (guid, date_modified) "
2882       "VALUES('00000000-0000-0000-0000-000000000000', 11);"
2883       "INSERT INTO autofill_profile_names (guid, full_name) "
2884       "VALUES('00000000-0000-0000-0000-000000000000', 'John Jones');"
2885       "INSERT INTO autofill_profile_emails (guid, email) "
2886       "VALUES('00000000-0000-0000-0000-000000000000', 'john@jones.com');"
2887       "INSERT INTO autofill_profile_phones (guid, number) "
2888       "VALUES('00000000-0000-0000-0000-000000000000', '111-111-1111');"
2889 
2890       // Add a profile in profiles, names and emails tables.
2891       "INSERT INTO autofill_profiles (guid, date_modified) "
2892       "VALUES('00000000-0000-0000-0000-000000000001', 21);"
2893       "INSERT INTO autofill_profile_names (guid, full_name) "
2894       "VALUES('00000000-0000-0000-0000-000000000001', 'John Jones2');"
2895       "INSERT INTO autofill_profile_emails (guid, email) "
2896       "VALUES('00000000-0000-0000-0000-000000000001', 'john@jones2.com');"
2897 
2898       // Add a profile in profiles, names and phones tables.
2899       "INSERT INTO autofill_profiles (guid, date_modified) "
2900       "VALUES('00000000-0000-0000-0000-000000000002', 31);"
2901       "INSERT INTO autofill_profile_names (guid, full_name) "
2902       "VALUES('00000000-0000-0000-0000-000000000002', 'John Jones3');"
2903       "INSERT INTO autofill_profile_phones (guid, number) "
2904       "VALUES('00000000-0000-0000-0000-000000000002', '333-333-3333');"
2905 
2906       // Add a profile in profiles, emails and phones tables.
2907       "INSERT INTO autofill_profiles (guid, date_modified) "
2908       "VALUES('00000000-0000-0000-0000-000000000003', 41);"
2909       "INSERT INTO autofill_profile_emails (guid, email) "
2910       "VALUES('00000000-0000-0000-0000-000000000003', 'john@jones4.com');"
2911       "INSERT INTO autofill_profile_phones (guid, number) "
2912       "VALUES('00000000-0000-0000-0000-000000000003', '444-444-4444');"
2913 
2914       // Add a orphan profile in names, emails and phones tables.
2915       "INSERT INTO autofill_profile_names (guid, full_name) "
2916       "VALUES('00000000-0000-0000-0000-000000000004', 'John Jones5');"
2917       "INSERT INTO autofill_profile_emails (guid, email) "
2918       "VALUES('00000000-0000-0000-0000-000000000004', 'john@jones5.com');"
2919       "INSERT INTO autofill_profile_phones (guid, number) "
2920       "VALUES('00000000-0000-0000-0000-000000000004', '555-555-5555');"
2921 
2922       // Add a orphan profile in names and emails tables.
2923       "INSERT INTO autofill_profile_names (guid, full_name) "
2924       "VALUES('00000000-0000-0000-0000-000000000005', 'John Jones6');"
2925       "INSERT INTO autofill_profile_emails (guid, email) "
2926       "VALUES('00000000-0000-0000-0000-000000000005', 'john@jones6.com');"
2927 
2928       // Add a orphan profile in names and phones tables.
2929       "INSERT INTO autofill_profile_names (guid, full_name) "
2930       "VALUES('00000000-0000-0000-0000-000000000006', 'John Jones7');"
2931       "INSERT INTO autofill_profile_phones (guid, number) "
2932       "VALUES('00000000-0000-0000-0000-000000000006', '777-777-7777');"
2933 
2934       // Add a orphan profile in emails and phones tables.
2935       "INSERT INTO autofill_profile_emails (guid, email) "
2936       "VALUES('00000000-0000-0000-0000-000000000007', 'john@jones8.com');"
2937       "INSERT INTO autofill_profile_phones (guid, number) "
2938       "VALUES('00000000-0000-0000-0000-000000000007', '999-999-9999');"
2939 
2940       // Add a orphan profile in the names table.
2941       "INSERT INTO autofill_profile_names (guid, full_name) "
2942       "VALUES('00000000-0000-0000-0000-000000000008', 'John Jones9');"
2943 
2944       // Add a orphan profile in the emails table.
2945       "INSERT INTO autofill_profile_emails (guid, email) "
2946       "VALUES('00000000-0000-0000-0000-000000000009', 'john@jones10.com');"
2947 
2948       // Add a orphan profile in the phones table.
2949       "INSERT INTO autofill_profile_phones (guid, number) "
2950       "VALUES('00000000-0000-0000-0000-000000000010', '101-010-1010');"));
2951 
2952   ASSERT_TRUE(table_->RemoveOrphanAutofillTableRows());
2953 
2954   // Make sure that all the rows in the autofill_profiles table are still
2955   // present.
2956   sql::Statement s_autofill_profiles(
2957       db_->GetSQLConnection()->GetUniqueStatement(
2958           "SELECT guid FROM autofill_profiles"));
2959   ASSERT_TRUE(s_autofill_profiles.is_valid());
2960   ASSERT_TRUE(s_autofill_profiles.Step());
2961   EXPECT_EQ("00000000-0000-0000-0000-000000000000",
2962             s_autofill_profiles.ColumnString(0));
2963   ASSERT_TRUE(s_autofill_profiles.Step());
2964   EXPECT_EQ("00000000-0000-0000-0000-000000000001",
2965             s_autofill_profiles.ColumnString(0));
2966   ASSERT_TRUE(s_autofill_profiles.Step());
2967   EXPECT_EQ("00000000-0000-0000-0000-000000000002",
2968             s_autofill_profiles.ColumnString(0));
2969   ASSERT_TRUE(s_autofill_profiles.Step());
2970   EXPECT_EQ("00000000-0000-0000-0000-000000000003",
2971             s_autofill_profiles.ColumnString(0));
2972   EXPECT_FALSE(s_autofill_profiles.Step());
2973 
2974   // Make sure that only the rows present in the autofill_profiles table are
2975   // present in the autofill_profile_names table.
2976   sql::Statement s_autofill_profile_names(
2977       db_->GetSQLConnection()->GetUniqueStatement(
2978           "SELECT guid FROM autofill_profile_names"));
2979   ASSERT_TRUE(s_autofill_profile_names.is_valid());
2980   ASSERT_TRUE(s_autofill_profile_names.Step());
2981   EXPECT_EQ("00000000-0000-0000-0000-000000000000",
2982             s_autofill_profile_names.ColumnString(0));
2983   ASSERT_TRUE(s_autofill_profile_names.Step());
2984   EXPECT_EQ("00000000-0000-0000-0000-000000000001",
2985             s_autofill_profile_names.ColumnString(0));
2986   ASSERT_TRUE(s_autofill_profile_names.Step());
2987   EXPECT_EQ("00000000-0000-0000-0000-000000000002",
2988             s_autofill_profile_names.ColumnString(0));
2989   EXPECT_FALSE(s_autofill_profile_names.Step());
2990 
2991   // Make sure that only the rows present in the autofill_profiles table are
2992   // present in the autofill_profile_emails table.
2993   sql::Statement s_autofill_profile_emails(
2994       db_->GetSQLConnection()->GetUniqueStatement(
2995           "SELECT guid FROM autofill_profile_emails"));
2996   ASSERT_TRUE(s_autofill_profile_emails.is_valid());
2997   ASSERT_TRUE(s_autofill_profile_emails.Step());
2998   EXPECT_EQ("00000000-0000-0000-0000-000000000000",
2999             s_autofill_profile_emails.ColumnString(0));
3000   ASSERT_TRUE(s_autofill_profile_emails.Step());
3001   EXPECT_EQ("00000000-0000-0000-0000-000000000001",
3002             s_autofill_profile_emails.ColumnString(0));
3003   ASSERT_TRUE(s_autofill_profile_emails.Step());
3004   EXPECT_EQ("00000000-0000-0000-0000-000000000003",
3005             s_autofill_profile_emails.ColumnString(0));
3006   EXPECT_FALSE(s_autofill_profile_emails.Step());
3007 
3008   // Make sure that only the rows present in the autofill_profiles table are
3009   // present in the autofill_profile_phones table.
3010   sql::Statement s_autofill_profile_phones(
3011       db_->GetSQLConnection()->GetUniqueStatement(
3012           "SELECT guid FROM autofill_profile_phones"));
3013   ASSERT_TRUE(s_autofill_profile_phones.is_valid());
3014   ASSERT_TRUE(s_autofill_profile_phones.Step());
3015   EXPECT_EQ("00000000-0000-0000-0000-000000000000",
3016             s_autofill_profile_phones.ColumnString(0));
3017   ASSERT_TRUE(s_autofill_profile_phones.Step());
3018   EXPECT_EQ("00000000-0000-0000-0000-000000000002",
3019             s_autofill_profile_phones.ColumnString(0));
3020   ASSERT_TRUE(s_autofill_profile_phones.Step());
3021   EXPECT_EQ("00000000-0000-0000-0000-000000000003",
3022             s_autofill_profile_phones.ColumnString(0));
3023   EXPECT_FALSE(s_autofill_profile_phones.Step());
3024 }
3025 
TEST_F(AutofillTableTest,InsertUpiId)3026 TEST_F(AutofillTableTest, InsertUpiId) {
3027   EXPECT_TRUE(table_->InsertUpiId("name@indianbank"));
3028 
3029   sql::Statement s_inspect(db_->GetSQLConnection()->GetUniqueStatement(
3030       "SELECT vpa FROM payments_upi_vpa"));
3031 
3032   ASSERT_TRUE(s_inspect.is_valid());
3033   ASSERT_TRUE(s_inspect.Step());
3034   EXPECT_GE(s_inspect.ColumnString(0), "name@indianbank");
3035   EXPECT_FALSE(s_inspect.Step());
3036 }
3037 
TEST_F(AutofillTableTest,GetAllUpiIds)3038 TEST_F(AutofillTableTest, GetAllUpiIds) {
3039   constexpr char upi_id1[] = "name@indianbank";
3040   constexpr char upi_id2[] = "vpa@icici";
3041   EXPECT_TRUE(table_->InsertUpiId(upi_id1));
3042   EXPECT_TRUE(table_->InsertUpiId(upi_id2));
3043 
3044   std::vector<std::string> upi_ids = table_->GetAllUpiIds();
3045   ASSERT_THAT(upi_ids, UnorderedElementsAre(upi_id1, upi_id2));
3046 }
3047 
3048 }  // namespace autofill
3049