Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / components / autofill / core / browser / autofill_manager_unittest.cc
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 <algorithm>
6 #include <vector>
7
8 #include "base/command_line.h"
9 #include "base/format_macros.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/scoped_vector.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/run_loop.h"
16 #include "base/strings/string16.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/time/time.h"
22 #include "base/tuple.h"
23 #include "components/autofill/core/browser/autocomplete_history_manager.h"
24 #include "components/autofill/core/browser/autofill_manager.h"
25 #include "components/autofill/core/browser/autofill_metrics.h"
26 #include "components/autofill/core/browser/autofill_profile.h"
27 #include "components/autofill/core/browser/autofill_test_utils.h"
28 #include "components/autofill/core/browser/credit_card.h"
29 #include "components/autofill/core/browser/personal_data_manager.h"
30 #include "components/autofill/core/browser/popup_item_ids.h"
31 #include "components/autofill/core/browser/test_autofill_client.h"
32 #include "components/autofill/core/browser/test_autofill_driver.h"
33 #include "components/autofill/core/browser/test_autofill_external_delegate.h"
34 #include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
35 #include "components/autofill/core/common/autofill_pref_names.h"
36 #include "components/autofill/core/common/autofill_switches.h"
37 #include "components/autofill/core/common/form_data.h"
38 #include "components/autofill/core/common/form_field_data.h"
39 #include "grit/components_strings.h"
40 #include "testing/gmock/include/gmock/gmock.h"
41 #include "testing/gtest/include/gtest/gtest.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "ui/gfx/rect.h"
44 #include "url/gurl.h"
45
46 using base::ASCIIToUTF16;
47 using base::UTF8ToUTF16;
48 using testing::_;
49
50 namespace autofill {
51
52 typedef PersonalDataManager::GUIDPair GUIDPair;
53
54 namespace {
55
56 const int kDefaultPageID = 137;
57
58 class TestPersonalDataManager : public PersonalDataManager {
59  public:
60   TestPersonalDataManager() : PersonalDataManager("en-US") {
61     CreateTestAutofillProfiles(&web_profiles_);
62     CreateTestCreditCards(&credit_cards_);
63   }
64
65   using PersonalDataManager::set_database;
66   using PersonalDataManager::SetPrefService;
67
68   MOCK_METHOD1(SaveImportedProfile, std::string(const AutofillProfile&));
69
70   AutofillProfile* GetProfileWithGUID(const char* guid) {
71     for (std::vector<AutofillProfile *>::iterator it = web_profiles_.begin();
72          it != web_profiles_.end(); ++it) {
73       if (!(*it)->guid().compare(guid))
74         return *it;
75     }
76     return NULL;
77   }
78
79   CreditCard* GetCreditCardWithGUID(const char* guid) {
80     for (std::vector<CreditCard *>::iterator it = credit_cards_.begin();
81          it != credit_cards_.end(); ++it){
82       if (!(*it)->guid().compare(guid))
83         return *it;
84     }
85     return NULL;
86   }
87
88   void AddProfile(AutofillProfile* profile) {
89     web_profiles_.push_back(profile);
90   }
91
92   void AddCreditCard(CreditCard* credit_card) {
93     credit_cards_.push_back(credit_card);
94   }
95
96   virtual void RemoveByGUID(const std::string& guid) override {
97     CreditCard* credit_card = GetCreditCardWithGUID(guid.c_str());
98     if (credit_card) {
99       credit_cards_.erase(
100           std::find(credit_cards_.begin(), credit_cards_.end(), credit_card));
101     }
102
103     AutofillProfile* profile = GetProfileWithGUID(guid.c_str());
104     if (profile) {
105       web_profiles_.erase(
106           std::find(web_profiles_.begin(), web_profiles_.end(), profile));
107     }
108   }
109
110   // Do nothing (auxiliary profiles will be created in
111   // CreateTestAuxiliaryProfile).
112   virtual void LoadAuxiliaryProfiles(bool record_metrics) const override {}
113
114   void ClearAutofillProfiles() {
115     web_profiles_.clear();
116   }
117
118   void ClearCreditCards() {
119     credit_cards_.clear();
120   }
121
122   void CreateTestAuxiliaryProfiles() {
123     CreateTestAutofillProfiles(&auxiliary_profiles_);
124   }
125
126   void CreateTestCreditCardsYearAndMonth(const char* year, const char* month) {
127     ClearCreditCards();
128     CreditCard* credit_card = new CreditCard;
129     test::SetCreditCardInfo(credit_card, "Miku Hatsune",
130                             "4234567890654321", // Visa
131                             month, year);
132     credit_card->set_guid("00000000-0000-0000-0000-000000000007");
133     credit_cards_.push_back(credit_card);
134   }
135
136  private:
137   void CreateTestAutofillProfiles(ScopedVector<AutofillProfile>* profiles) {
138     AutofillProfile* profile = new AutofillProfile;
139     test::SetProfileInfo(profile, "Elvis", "Aaron",
140                          "Presley", "theking@gmail.com", "RCA",
141                          "3734 Elvis Presley Blvd.", "Apt. 10",
142                          "Memphis", "Tennessee", "38116", "US",
143                          "12345678901");
144     profile->set_guid("00000000-0000-0000-0000-000000000001");
145     profiles->push_back(profile);
146     profile = new AutofillProfile;
147     test::SetProfileInfo(profile, "Charles", "Hardin",
148                          "Holley", "buddy@gmail.com", "Decca",
149                          "123 Apple St.", "unit 6", "Lubbock",
150                          "Texas", "79401", "US", "23456789012");
151     profile->set_guid("00000000-0000-0000-0000-000000000002");
152     profiles->push_back(profile);
153     profile = new AutofillProfile;
154     test::SetProfileInfo(
155         profile, "", "", "", "", "", "", "", "", "", "", "", "");
156     profile->set_guid("00000000-0000-0000-0000-000000000003");
157     profiles->push_back(profile);
158   }
159
160   void CreateTestCreditCards(ScopedVector<CreditCard>* credit_cards) {
161     CreditCard* credit_card = new CreditCard;
162     test::SetCreditCardInfo(credit_card, "Elvis Presley",
163                             "4234 5678 9012 3456",  // Visa
164                             "04", "2012");
165     credit_card->set_guid("00000000-0000-0000-0000-000000000004");
166     credit_cards->push_back(credit_card);
167
168     credit_card = new CreditCard;
169     test::SetCreditCardInfo(credit_card, "Buddy Holly",
170                             "5187654321098765",  // Mastercard
171                             "10", "2014");
172     credit_card->set_guid("00000000-0000-0000-0000-000000000005");
173     credit_cards->push_back(credit_card);
174
175     credit_card = new CreditCard;
176     test::SetCreditCardInfo(credit_card, "", "", "", "");
177     credit_card->set_guid("00000000-0000-0000-0000-000000000006");
178     credit_cards->push_back(credit_card);
179   }
180
181   DISALLOW_COPY_AND_ASSIGN(TestPersonalDataManager);
182 };
183
184 // Populates |form| with data corresponding to a simple credit card form.
185 // Note that this actually appends fields to the form data, which can be useful
186 // for building up more complex test forms.
187 void CreateTestCreditCardFormData(FormData* form,
188                                   bool is_https,
189                                   bool use_month_type) {
190   form->name = ASCIIToUTF16("MyForm");
191   if (is_https) {
192     form->origin = GURL("https://myform.com/form.html");
193     form->action = GURL("https://myform.com/submit.html");
194   } else {
195     form->origin = GURL("http://myform.com/form.html");
196     form->action = GURL("http://myform.com/submit.html");
197   }
198   form->user_submitted = true;
199
200   FormFieldData field;
201   test::CreateTestFormField("Name on Card", "nameoncard", "", "text", &field);
202   form->fields.push_back(field);
203   test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
204   form->fields.push_back(field);
205   if (use_month_type) {
206     test::CreateTestFormField(
207         "Expiration Date", "ccmonth", "", "month", &field);
208     form->fields.push_back(field);
209   } else {
210     test::CreateTestFormField("Expiration Date", "ccmonth", "", "text", &field);
211     form->fields.push_back(field);
212     test::CreateTestFormField("", "ccyear", "", "text", &field);
213     form->fields.push_back(field);
214   }
215 }
216
217 void ExpectFilledField(const char* expected_label,
218                        const char* expected_name,
219                        const char* expected_value,
220                        const char* expected_form_control_type,
221                        const FormFieldData& field) {
222   SCOPED_TRACE(expected_label);
223   EXPECT_EQ(UTF8ToUTF16(expected_label), field.label);
224   EXPECT_EQ(UTF8ToUTF16(expected_name), field.name);
225   EXPECT_EQ(UTF8ToUTF16(expected_value), field.value);
226   EXPECT_EQ(expected_form_control_type, field.form_control_type);
227 }
228
229 // Verifies that the |filled_form| has been filled with the given data.
230 // Verifies address fields if |has_address_fields| is true, and verifies
231 // credit card fields if |has_credit_card_fields| is true. Verifies both if both
232 // are true. |use_month_type| is used for credit card input month type.
233 void ExpectFilledForm(int page_id,
234                       const FormData& filled_form,
235                       int expected_page_id,
236                       const char* first,
237                       const char* middle,
238                       const char* last,
239                       const char* address1,
240                       const char* address2,
241                       const char* city,
242                       const char* state,
243                       const char* postal_code,
244                       const char* country,
245                       const char* phone,
246                       const char* email,
247                       const char* name_on_card,
248                       const char* card_number,
249                       const char* expiration_month,
250                       const char* expiration_year,
251                       bool has_address_fields,
252                       bool has_credit_card_fields,
253                       bool use_month_type) {
254   // The number of fields in the address and credit card forms created above.
255   const size_t kAddressFormSize = 11;
256   const size_t kCreditCardFormSize = use_month_type ? 3 : 4;
257
258   EXPECT_EQ(expected_page_id, page_id);
259   EXPECT_EQ(ASCIIToUTF16("MyForm"), filled_form.name);
260   if (has_credit_card_fields) {
261     EXPECT_EQ(GURL("https://myform.com/form.html"), filled_form.origin);
262     EXPECT_EQ(GURL("https://myform.com/submit.html"), filled_form.action);
263   } else {
264     EXPECT_EQ(GURL("http://myform.com/form.html"), filled_form.origin);
265     EXPECT_EQ(GURL("http://myform.com/submit.html"), filled_form.action);
266   }
267   EXPECT_TRUE(filled_form.user_submitted);
268
269   size_t form_size = 0;
270   if (has_address_fields)
271     form_size += kAddressFormSize;
272   if (has_credit_card_fields)
273     form_size += kCreditCardFormSize;
274   ASSERT_EQ(form_size, filled_form.fields.size());
275
276   if (has_address_fields) {
277     ExpectFilledField("First Name", "firstname", first, "text",
278                       filled_form.fields[0]);
279     ExpectFilledField("Middle Name", "middlename", middle, "text",
280                       filled_form.fields[1]);
281     ExpectFilledField("Last Name", "lastname", last, "text",
282                       filled_form.fields[2]);
283     ExpectFilledField("Address Line 1", "addr1", address1, "text",
284                       filled_form.fields[3]);
285     ExpectFilledField("Address Line 2", "addr2", address2, "text",
286                       filled_form.fields[4]);
287     ExpectFilledField("City", "city", city, "text",
288                       filled_form.fields[5]);
289     ExpectFilledField("State", "state", state, "text",
290                       filled_form.fields[6]);
291     ExpectFilledField("Postal Code", "zipcode", postal_code, "text",
292                       filled_form.fields[7]);
293     ExpectFilledField("Country", "country", country, "text",
294                       filled_form.fields[8]);
295     ExpectFilledField("Phone Number", "phonenumber", phone, "tel",
296                       filled_form.fields[9]);
297     ExpectFilledField("Email", "email", email, "email",
298                       filled_form.fields[10]);
299   }
300
301   if (has_credit_card_fields) {
302     size_t offset = has_address_fields? kAddressFormSize : 0;
303     ExpectFilledField("Name on Card", "nameoncard", name_on_card, "text",
304                       filled_form.fields[offset + 0]);
305     ExpectFilledField("Card Number", "cardnumber", card_number, "text",
306                       filled_form.fields[offset + 1]);
307     if (use_month_type) {
308       std::string exp_year = expiration_year;
309       std::string exp_month = expiration_month;
310       std::string date;
311       if (!exp_year.empty() && !exp_month.empty())
312         date = exp_year + "-" + exp_month;
313
314       ExpectFilledField("Expiration Date", "ccmonth", date.c_str(), "month",
315                         filled_form.fields[offset + 2]);
316     } else {
317       ExpectFilledField("Expiration Date", "ccmonth", expiration_month, "text",
318                         filled_form.fields[offset + 2]);
319       ExpectFilledField("", "ccyear", expiration_year, "text",
320                         filled_form.fields[offset + 3]);
321     }
322   }
323 }
324
325 void ExpectFilledAddressFormElvis(int page_id,
326                                   const FormData& filled_form,
327                                   int expected_page_id,
328                                   bool has_credit_card_fields) {
329   ExpectFilledForm(page_id, filled_form, expected_page_id, "Elvis", "Aaron",
330                    "Presley", "3734 Elvis Presley Blvd.", "Apt. 10", "Memphis",
331                    "Tennessee", "38116", "United States", "12345678901",
332                    "theking@gmail.com", "", "", "", "", true,
333                    has_credit_card_fields, false);
334 }
335
336 void ExpectFilledCreditCardFormElvis(int page_id,
337                                      const FormData& filled_form,
338                                      int expected_page_id,
339                                      bool has_address_fields) {
340   ExpectFilledForm(page_id, filled_form, expected_page_id,
341                    "", "", "", "", "", "", "", "", "", "", "",
342                    "Elvis Presley", "4234567890123456", "04", "2012",
343                    has_address_fields, true, false);
344 }
345
346 void ExpectFilledCreditCardYearMonthWithYearMonth(int page_id,
347                                                   const FormData& filled_form,
348                                                   int expected_page_id,
349                                                   bool has_address_fields,
350                                                   const char* year,
351                                                   const char* month) {
352   ExpectFilledForm(page_id, filled_form, expected_page_id,
353                    "", "", "", "", "", "", "", "", "", "", "",
354                    "Miku Hatsune", "4234567890654321", month, year,
355                    has_address_fields, true, true);
356 }
357
358 class MockAutocompleteHistoryManager : public AutocompleteHistoryManager {
359  public:
360   MockAutocompleteHistoryManager(AutofillDriver* driver, AutofillClient* client)
361       : AutocompleteHistoryManager(driver, client) {}
362
363   MOCK_METHOD8(OnGetAutocompleteSuggestions, void(
364       int query_id,
365       const base::string16& name,
366       const base::string16& prefix,
367       const std::string& form_control_type,
368       const std::vector<base::string16>& autofill_values,
369       const std::vector<base::string16>& autofill_labels,
370       const std::vector<base::string16>& autofill_icons,
371       const std::vector<int>& autofill_unique_ids));
372   MOCK_METHOD1(OnFormSubmitted, void(const FormData& form));
373
374  private:
375   DISALLOW_COPY_AND_ASSIGN(MockAutocompleteHistoryManager);
376 };
377
378 class MockAutofillDriver : public TestAutofillDriver {
379  public:
380   MockAutofillDriver() {}
381
382   // Mock methods to enable testability.
383   MOCK_METHOD3(SendFormDataToRenderer, void(int query_id,
384                                             RendererFormDataAction action,
385                                             const FormData& data));
386
387  private:
388   DISALLOW_COPY_AND_ASSIGN(MockAutofillDriver);
389 };
390
391 class TestAutofillManager : public AutofillManager {
392  public:
393   TestAutofillManager(AutofillDriver* driver,
394                       autofill::AutofillClient* client,
395                       TestPersonalDataManager* personal_data)
396       : AutofillManager(driver, client, personal_data),
397         personal_data_(personal_data),
398         autofill_enabled_(true) {}
399   ~TestAutofillManager() override {}
400
401   bool IsAutofillEnabled() const override { return autofill_enabled_; }
402
403   void set_autofill_enabled(bool autofill_enabled) {
404     autofill_enabled_ = autofill_enabled;
405   }
406
407   void set_expected_submitted_field_types(
408       const std::vector<ServerFieldTypeSet>& expected_types) {
409     expected_submitted_field_types_ = expected_types;
410   }
411
412   void UploadFormDataAsyncCallback(
413       const FormStructure* submitted_form,
414       const base::TimeTicks& load_time,
415       const base::TimeTicks& interaction_time,
416       const base::TimeTicks& submission_time) override {
417     run_loop_->Quit();
418
419     // If we have expected field types set, make sure they match.
420     if (!expected_submitted_field_types_.empty()) {
421       ASSERT_EQ(expected_submitted_field_types_.size(),
422                 submitted_form->field_count());
423       for (size_t i = 0; i < expected_submitted_field_types_.size(); ++i) {
424         SCOPED_TRACE(
425             base::StringPrintf(
426                 "Field %d with value %s", static_cast<int>(i),
427                 base::UTF16ToUTF8(submitted_form->field(i)->value).c_str()));
428         const ServerFieldTypeSet& possible_types =
429             submitted_form->field(i)->possible_types();
430         EXPECT_EQ(expected_submitted_field_types_[i].size(),
431                   possible_types.size());
432         for (ServerFieldTypeSet::const_iterator it =
433                  expected_submitted_field_types_[i].begin();
434              it != expected_submitted_field_types_[i].end(); ++it) {
435           EXPECT_TRUE(possible_types.count(*it))
436               << "Expected type: " << AutofillType(*it).ToString();
437         }
438       }
439     }
440
441     AutofillManager::UploadFormDataAsyncCallback(submitted_form,
442                                                  load_time,
443                                                  interaction_time,
444                                                  submission_time);
445   }
446
447   // Resets the run loop so that it can wait for an asynchronous form
448   // submission to complete.
449   void ResetRunLoop() { run_loop_.reset(new base::RunLoop()); }
450
451   // Wait for the asynchronous OnFormSubmitted() call to complete.
452   void WaitForAsyncFormSubmit() { run_loop_->Run(); }
453
454   void UploadFormData(const FormStructure& submitted_form) override {
455     submitted_form_signature_ = submitted_form.FormSignature();
456   }
457
458   const std::string GetSubmittedFormSignature() {
459     return submitted_form_signature_;
460   }
461
462   AutofillProfile* GetProfileWithGUID(const char* guid) {
463     return personal_data_->GetProfileWithGUID(guid);
464   }
465
466   CreditCard* GetCreditCardWithGUID(const char* guid) {
467     return personal_data_->GetCreditCardWithGUID(guid);
468   }
469
470   void AddProfile(AutofillProfile* profile) {
471     personal_data_->AddProfile(profile);
472   }
473
474   void AddCreditCard(CreditCard* credit_card) {
475     personal_data_->AddCreditCard(credit_card);
476   }
477
478   int GetPackedCreditCardID(int credit_card_id) {
479     std::string credit_card_guid =
480         base::StringPrintf("00000000-0000-0000-0000-%012d", credit_card_id);
481
482     return PackGUIDs(GUIDPair(credit_card_guid, 0), GUIDPair(std::string(), 0));
483   }
484
485   void AddSeenForm(FormStructure* form) {
486     form_structures()->push_back(form);
487   }
488
489   void ClearFormStructures() {
490     form_structures()->clear();
491   }
492
493  private:
494   // Weak reference.
495   TestPersonalDataManager* personal_data_;
496
497   bool autofill_enabled_;
498
499   scoped_ptr<base::RunLoop> run_loop_;
500
501   std::string submitted_form_signature_;
502   std::vector<ServerFieldTypeSet> expected_submitted_field_types_;
503
504   DISALLOW_COPY_AND_ASSIGN(TestAutofillManager);
505 };
506
507 class TestAutofillExternalDelegate : public AutofillExternalDelegate {
508  public:
509   explicit TestAutofillExternalDelegate(AutofillManager* autofill_manager,
510                                         AutofillDriver* autofill_driver)
511       : AutofillExternalDelegate(autofill_manager, autofill_driver),
512         on_query_seen_(false),
513         on_suggestions_returned_seen_(false) {}
514   ~TestAutofillExternalDelegate() override {}
515
516   void OnQuery(int query_id,
517                const FormData& form,
518                const FormFieldData& field,
519                const gfx::RectF& bounds,
520                bool display_warning) override {
521     on_query_seen_ = true;
522     on_suggestions_returned_seen_ = false;
523   }
524
525   void OnSuggestionsReturned(
526       int query_id,
527       const std::vector<base::string16>& autofill_values,
528       const std::vector<base::string16>& autofill_labels,
529       const std::vector<base::string16>& autofill_icons,
530       const std::vector<int>& autofill_unique_ids) override {
531     on_suggestions_returned_seen_ = true;
532
533     query_id_ = query_id;
534     autofill_values_ = autofill_values;
535     autofill_labels_ = autofill_labels;
536     autofill_icons_ = autofill_icons;
537     autofill_unique_ids_ = autofill_unique_ids;
538   }
539
540   void CheckSuggestions(int expected_page_id,
541                         size_t expected_num_suggestions,
542                         const base::string16 expected_values[],
543                         const base::string16 expected_labels[],
544                         const base::string16 expected_icons[],
545                         const int expected_unique_ids[]) {
546     // Ensure that these results are from the most recent query.
547     EXPECT_TRUE(on_suggestions_returned_seen_);
548
549     EXPECT_EQ(expected_page_id, query_id_);
550     ASSERT_EQ(expected_num_suggestions, autofill_values_.size());
551     ASSERT_EQ(expected_num_suggestions, autofill_labels_.size());
552     ASSERT_EQ(expected_num_suggestions, autofill_icons_.size());
553     ASSERT_EQ(expected_num_suggestions, autofill_unique_ids_.size());
554     for (size_t i = 0; i < expected_num_suggestions; ++i) {
555       SCOPED_TRACE(base::StringPrintf("i: %" PRIuS, i));
556       EXPECT_EQ(expected_values[i], autofill_values_[i]);
557       EXPECT_EQ(expected_labels[i], autofill_labels_[i]);
558       EXPECT_EQ(expected_icons[i], autofill_icons_[i]);
559       EXPECT_EQ(expected_unique_ids[i], autofill_unique_ids_[i]);
560     }
561   }
562
563   bool on_query_seen() const {
564     return on_query_seen_;
565   }
566
567   bool on_suggestions_returned_seen() const {
568     return on_suggestions_returned_seen_;
569   }
570
571  private:
572   // Records if OnQuery has been called yet.
573   bool on_query_seen_;
574
575   // Records if OnSuggestionsReturned has been called after the most recent
576   // call to OnQuery.
577   bool on_suggestions_returned_seen_;
578
579   // The query id of the most recent Autofill query.
580   int query_id_;
581
582   // The results returned by the most recent Autofill query.
583   std::vector<base::string16> autofill_values_;
584   std::vector<base::string16> autofill_labels_;
585   std::vector<base::string16> autofill_icons_;
586   std::vector<int> autofill_unique_ids_;
587
588   DISALLOW_COPY_AND_ASSIGN(TestAutofillExternalDelegate);
589 };
590
591 }  // namespace
592
593 class AutofillManagerTest : public testing::Test {
594  public:
595   void SetUp() override {
596     autofill_client_.SetPrefs(test::PrefServiceForTesting());
597     personal_data_.set_database(autofill_client_.GetDatabase());
598     personal_data_.SetPrefService(autofill_client_.GetPrefs());
599     autofill_driver_.reset(new MockAutofillDriver());
600     autofill_manager_.reset(new TestAutofillManager(
601         autofill_driver_.get(), &autofill_client_, &personal_data_));
602
603     external_delegate_.reset(new TestAutofillExternalDelegate(
604         autofill_manager_.get(),
605         autofill_driver_.get()));
606     autofill_manager_->SetExternalDelegate(external_delegate_.get());
607   }
608
609   void TearDown() override {
610     // Order of destruction is important as AutofillManager relies on
611     // PersonalDataManager to be around when it gets destroyed.
612     autofill_manager_.reset();
613     autofill_driver_.reset();
614
615     // Remove the AutofillWebDataService so TestPersonalDataManager does not
616     // need to care about removing self as an observer in destruction.
617     personal_data_.set_database(scoped_refptr<AutofillWebDataService>(NULL));
618     personal_data_.SetPrefService(NULL);
619   }
620
621   void GetAutofillSuggestions(int query_id,
622                               const FormData& form,
623                               const FormFieldData& field) {
624     autofill_manager_->OnQueryFormFieldAutofill(query_id,
625                                                 form,
626                                                 field,
627                                                 gfx::Rect(),
628                                                 false);
629   }
630
631   void GetAutofillSuggestions(const FormData& form,
632                               const FormFieldData& field) {
633     GetAutofillSuggestions(kDefaultPageID, form, field);
634   }
635
636   void AutocompleteSuggestionsReturned(
637       const std::vector<base::string16>& result) {
638     autofill_manager_->autocomplete_history_manager_->SendSuggestions(&result);
639   }
640
641   void FormsSeen(const std::vector<FormData>& forms) {
642     autofill_manager_->OnFormsSeen(forms, base::TimeTicks());
643   }
644
645   void FormSubmitted(const FormData& form) {
646     autofill_manager_->ResetRunLoop();
647     if (autofill_manager_->OnFormSubmitted(form, base::TimeTicks::Now()))
648       autofill_manager_->WaitForAsyncFormSubmit();
649   }
650
651   void FillAutofillFormData(int query_id,
652                             const FormData& form,
653                             const FormFieldData& field,
654                             int unique_id) {
655     autofill_manager_->FillOrPreviewForm(
656         AutofillDriver::FORM_DATA_ACTION_FILL, query_id, form, field,
657         unique_id);
658   }
659
660   // Calls |autofill_manager_->OnFillAutofillFormData()| with the specified
661   // input parameters after setting up the expectation that the mock driver's
662   // |SendFormDataToRenderer()| method will be called and saving the parameters
663   // of that call into the |response_query_id| and |response_data| output
664   // parameters.
665   void FillAutofillFormDataAndSaveResults(int input_query_id,
666                                           const FormData& input_form,
667                                           const FormFieldData& input_field,
668                                           int unique_id,
669                                           int* response_query_id,
670                                           FormData* response_data) {
671     EXPECT_CALL(*autofill_driver_, SendFormDataToRenderer(_, _, _)).
672         WillOnce((DoAll(testing::SaveArg<0>(response_query_id),
673                         testing::SaveArg<2>(response_data))));
674     FillAutofillFormData(input_query_id, input_form, input_field, unique_id);
675   }
676
677   int PackGUIDs(const GUIDPair& cc_guid, const GUIDPair& profile_guid) const {
678     return autofill_manager_->PackGUIDs(cc_guid, profile_guid);
679   }
680
681  protected:
682   base::MessageLoop message_loop_;
683   TestAutofillClient autofill_client_;
684   scoped_ptr<MockAutofillDriver> autofill_driver_;
685   scoped_ptr<TestAutofillManager> autofill_manager_;
686   scoped_ptr<TestAutofillExternalDelegate> external_delegate_;
687   TestPersonalDataManager personal_data_;
688 };
689
690 class TestFormStructure : public FormStructure {
691  public:
692   explicit TestFormStructure(const FormData& form)
693       : FormStructure(form) {}
694   ~TestFormStructure() override {}
695
696   void SetFieldTypes(const std::vector<ServerFieldType>& heuristic_types,
697                      const std::vector<ServerFieldType>& server_types) {
698     ASSERT_EQ(field_count(), heuristic_types.size());
699     ASSERT_EQ(field_count(), server_types.size());
700
701     for (size_t i = 0; i < field_count(); ++i) {
702       AutofillField* form_field = field(i);
703       ASSERT_TRUE(form_field);
704       form_field->set_heuristic_type(heuristic_types[i]);
705       form_field->set_server_type(server_types[i]);
706     }
707
708     UpdateAutofillCount();
709   }
710
711  private:
712   DISALLOW_COPY_AND_ASSIGN(TestFormStructure);
713 };
714
715 // Test that we return all address profile suggestions when all form fields are
716 // empty.
717 TEST_F(AutofillManagerTest, GetProfileSuggestionsEmptyValue) {
718   // Set up our form data.
719   FormData form;
720   test::CreateTestAddressFormData(&form);
721   std::vector<FormData> forms(1, form);
722   FormsSeen(forms);
723
724   const FormFieldData& field = form.fields[0];
725   GetAutofillSuggestions(form, field);
726
727   // No suggestions provided, so send an empty vector as the results.
728   // This triggers the combined message send.
729   AutocompleteSuggestionsReturned(std::vector<base::string16>());
730
731   // Test that we sent the right values to the external delegate.
732   base::string16 expected_values[] = {
733     ASCIIToUTF16("Elvis"),
734     ASCIIToUTF16("Charles")
735   };
736   // Inferred labels include full first relevant field, which in this case is
737   // the address line 1.
738   base::string16 expected_labels[] = {
739     ASCIIToUTF16("3734 Elvis Presley Blvd."),
740     ASCIIToUTF16("123 Apple St.")
741   };
742   base::string16 expected_icons[] = {base::string16(), base::string16()};
743   int expected_unique_ids[] = {1, 2};
744   external_delegate_->CheckSuggestions(
745       kDefaultPageID, arraysize(expected_values), expected_values,
746       expected_labels, expected_icons, expected_unique_ids);
747 }
748
749 // Test that we return only matching address profile suggestions when the
750 // selected form field has been partially filled out.
751 TEST_F(AutofillManagerTest, GetProfileSuggestionsMatchCharacter) {
752   // Set up our form data.
753   FormData form;
754   test::CreateTestAddressFormData(&form);
755   std::vector<FormData> forms(1, form);
756   FormsSeen(forms);
757
758   FormFieldData field;
759   test::CreateTestFormField("First Name", "firstname", "E", "text",&field);
760   GetAutofillSuggestions(form, field);
761
762   // No suggestions provided, so send an empty vector as the results.
763   // This triggers the combined message send.
764   AutocompleteSuggestionsReturned(std::vector<base::string16>());
765
766   // Test that we sent the right values to the external delegate.
767   base::string16 expected_values[] = {ASCIIToUTF16("Elvis")};
768   base::string16 expected_labels[] = {ASCIIToUTF16("3734 Elvis Presley Blvd.")};
769   base::string16 expected_icons[] = {base::string16()};
770   int expected_unique_ids[] = {1};
771   external_delegate_->CheckSuggestions(
772       kDefaultPageID, arraysize(expected_values), expected_values,
773       expected_labels, expected_icons, expected_unique_ids);
774 }
775
776 // Test that we return no suggestions when the form has no relevant fields.
777 TEST_F(AutofillManagerTest, GetProfileSuggestionsUnknownFields) {
778   // Set up our form data.
779   FormData form;
780   form.name = ASCIIToUTF16("MyForm");
781   form.origin = GURL("http://myform.com/form.html");
782   form.action = GURL("http://myform.com/submit.html");
783   form.user_submitted = true;
784
785   FormFieldData field;
786   test::CreateTestFormField("Username", "username", "", "text",&field);
787   form.fields.push_back(field);
788   test::CreateTestFormField("Password", "password", "", "password",&field);
789   form.fields.push_back(field);
790   test::CreateTestFormField("Quest", "quest", "", "quest", &field);
791   form.fields.push_back(field);
792   test::CreateTestFormField("Color", "color", "", "text", &field);
793   form.fields.push_back(field);
794
795   std::vector<FormData> forms(1, form);
796   FormsSeen(forms);
797
798   GetAutofillSuggestions(form, field);
799   EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
800 }
801
802 // Test that we cull duplicate profile suggestions.
803 TEST_F(AutofillManagerTest, GetProfileSuggestionsWithDuplicates) {
804   // Set up our form data.
805   FormData form;
806   test::CreateTestAddressFormData(&form);
807   std::vector<FormData> forms(1, form);
808   FormsSeen(forms);
809
810   // Add a duplicate profile.
811   AutofillProfile* duplicate_profile =
812       new AutofillProfile(
813           *(autofill_manager_->GetProfileWithGUID(
814               "00000000-0000-0000-0000-000000000001")));
815   autofill_manager_->AddProfile(duplicate_profile);
816
817   const FormFieldData& field = form.fields[0];
818   GetAutofillSuggestions(form, field);
819
820   // No suggestions provided, so send an empty vector as the results.
821   // This triggers the combined message send.
822   AutocompleteSuggestionsReturned(std::vector<base::string16>());
823
824   // Test that we sent the right values to the external delegate.
825   base::string16 expected_values[] = {
826     ASCIIToUTF16("Elvis"),
827     ASCIIToUTF16("Charles")
828   };
829   base::string16 expected_labels[] = {
830     ASCIIToUTF16("3734 Elvis Presley Blvd."),
831     ASCIIToUTF16("123 Apple St.")
832   };
833   base::string16 expected_icons[] = {base::string16(), base::string16()};
834   int expected_unique_ids[] = {1, 2};
835   external_delegate_->CheckSuggestions(
836       kDefaultPageID, arraysize(expected_values), expected_values,
837       expected_labels, expected_icons, expected_unique_ids);
838 }
839
840 // Test that we return no suggestions when autofill is disabled.
841 TEST_F(AutofillManagerTest, GetProfileSuggestionsAutofillDisabledByUser) {
842   // Set up our form data.
843   FormData form;
844   test::CreateTestAddressFormData(&form);
845   std::vector<FormData> forms(1, form);
846   FormsSeen(forms);
847
848   // Disable Autofill.
849   autofill_manager_->set_autofill_enabled(false);
850
851   const FormFieldData& field = form.fields[0];
852   GetAutofillSuggestions(form, field);
853   EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
854 }
855
856 // Test that we return all credit card profile suggestions when all form fields
857 // are empty.
858 TEST_F(AutofillManagerTest, GetCreditCardSuggestionsEmptyValue) {
859   // Set up our form data.
860   FormData form;
861   CreateTestCreditCardFormData(&form, true, false);
862   std::vector<FormData> forms(1, form);
863   FormsSeen(forms);
864
865   FormFieldData field = form.fields[1];
866   GetAutofillSuggestions(form, field);
867
868   // No suggestions provided, so send an empty vector as the results.
869   // This triggers the combined message send.
870   AutocompleteSuggestionsReturned(std::vector<base::string16>());
871
872   // Test that we sent the right values to the external delegate.
873   base::string16 expected_values[] = {
874     ASCIIToUTF16("************3456"),
875     ASCIIToUTF16("************8765")
876   };
877   base::string16 expected_labels[] = { ASCIIToUTF16("04/12"),
878                                        ASCIIToUTF16("10/14")};
879   base::string16 expected_icons[] = {
880     ASCIIToUTF16(kVisaCard),
881     ASCIIToUTF16(kMasterCard)
882   };
883   int expected_unique_ids[] = {
884     autofill_manager_->GetPackedCreditCardID(4),
885     autofill_manager_->GetPackedCreditCardID(5)
886   };
887   external_delegate_->CheckSuggestions(
888       kDefaultPageID, arraysize(expected_values), expected_values,
889       expected_labels, expected_icons, expected_unique_ids);
890 }
891
892 // Test that we return only matching credit card profile suggestions when the
893 // selected form field has been partially filled out.
894 TEST_F(AutofillManagerTest, GetCreditCardSuggestionsMatchCharacter) {
895   // Set up our form data.
896   FormData form;
897   CreateTestCreditCardFormData(&form, true, false);
898   std::vector<FormData> forms(1, form);
899   FormsSeen(forms);
900
901   FormFieldData field;
902   test::CreateTestFormField("Card Number", "cardnumber", "78", "text", &field);
903   GetAutofillSuggestions(form, field);
904
905   // No suggestions provided, so send an empty vector as the results.
906   // This triggers the combined message send.
907   AutocompleteSuggestionsReturned(std::vector<base::string16>());
908
909   // Test that we sent the right values to the external delegate.
910   base::string16 expected_values[] = {ASCIIToUTF16("************3456")};
911   base::string16 expected_labels[] = {ASCIIToUTF16("04/12")};
912   base::string16 expected_icons[] = {ASCIIToUTF16(kVisaCard)};
913   int expected_unique_ids[] = {autofill_manager_->GetPackedCreditCardID(4)};
914   external_delegate_->CheckSuggestions(
915       kDefaultPageID, arraysize(expected_values), expected_values,
916       expected_labels, expected_icons, expected_unique_ids);
917 }
918
919 // Test that we return credit card profile suggestions when the selected form
920 // field is not the credit card number field.
921 TEST_F(AutofillManagerTest, GetCreditCardSuggestionsNonCCNumber) {
922   // Set up our form data.
923   FormData form;
924   CreateTestCreditCardFormData(&form, true, false);
925   std::vector<FormData> forms(1, form);
926   FormsSeen(forms);
927
928   const FormFieldData& field = form.fields[0];
929   GetAutofillSuggestions(form, field);
930
931   // No suggestions provided, so send an empty vector as the results.
932   // This triggers the combined message send.
933   AutocompleteSuggestionsReturned(std::vector<base::string16>());
934
935   // Test that we sent the right values to the external delegate.
936   base::string16 expected_values[] = {
937     ASCIIToUTF16("Elvis Presley"),
938     ASCIIToUTF16("Buddy Holly")
939   };
940   base::string16 expected_labels[] = { ASCIIToUTF16("*3456"),
941                                        ASCIIToUTF16("*8765") };
942   base::string16 expected_icons[] = {
943     ASCIIToUTF16(kVisaCard),
944     ASCIIToUTF16(kMasterCard)
945   };
946   int expected_unique_ids[] = {
947     autofill_manager_->GetPackedCreditCardID(4),
948     autofill_manager_->GetPackedCreditCardID(5)
949   };
950   external_delegate_->CheckSuggestions(
951       kDefaultPageID, arraysize(expected_values), expected_values,
952       expected_labels, expected_icons, expected_unique_ids);
953 }
954
955 // Test that we return a warning explaining that credit card profile suggestions
956 // are unavailable when the form is not https.
957 TEST_F(AutofillManagerTest, GetCreditCardSuggestionsNonHTTPS) {
958   // Set up our form data.
959   FormData form;
960   CreateTestCreditCardFormData(&form, false, false);
961   std::vector<FormData> forms(1, form);
962   FormsSeen(forms);
963
964   const FormFieldData& field = form.fields[0];
965   GetAutofillSuggestions(form, field);
966
967   // No suggestions provided, so send an empty vector as the results.
968   // This triggers the combined message send.
969   AutocompleteSuggestionsReturned(std::vector<base::string16>());
970
971   // Test that we sent the right values to the external delegate.
972   base::string16 expected_values[] = {
973     l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)
974   };
975   base::string16 expected_labels[] = {base::string16()};
976   base::string16 expected_icons[] = {base::string16()};
977   int expected_unique_ids[] = {-1};
978   external_delegate_->CheckSuggestions(
979       kDefaultPageID, arraysize(expected_values), expected_values,
980       expected_labels, expected_icons, expected_unique_ids);
981
982   // Now add some Autocomplete suggestions. We should show the autocomplete
983   // suggestions and the warning.
984   const int kPageID2 = 2;
985   GetAutofillSuggestions(kPageID2, form, field);
986
987   std::vector<base::string16> suggestions;
988   suggestions.push_back(ASCIIToUTF16("Jay"));
989   suggestions.push_back(ASCIIToUTF16("Jason"));
990   AutocompleteSuggestionsReturned(suggestions);
991
992   base::string16 expected_values2[] = {
993     l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION),
994     ASCIIToUTF16("Jay"),
995     ASCIIToUTF16("Jason")
996   };
997   base::string16 expected_labels2[] = { base::string16(), base::string16(),
998                                         base::string16() };
999   base::string16 expected_icons2[] = { base::string16(), base::string16(),
1000                                        base::string16() };
1001   int expected_unique_ids2[] = {-1, 0, 0};
1002   external_delegate_->CheckSuggestions(
1003       kPageID2, arraysize(expected_values2), expected_values2,
1004       expected_labels2, expected_icons2, expected_unique_ids2);
1005
1006   // Clear the test credit cards and try again -- we shouldn't return a warning.
1007   personal_data_.ClearCreditCards();
1008   GetAutofillSuggestions(form, field);
1009   EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1010 }
1011
1012 // Test that we return all credit card suggestions in the case that two cards
1013 // have the same obfuscated number.
1014 TEST_F(AutofillManagerTest, GetCreditCardSuggestionsRepeatedObfuscatedNumber) {
1015   // Add a credit card with the same obfuscated number as Elvis's.
1016   // |credit_card| will be owned by the mock PersonalDataManager.
1017   CreditCard* credit_card = new CreditCard;
1018   test::SetCreditCardInfo(credit_card, "Elvis Presley",
1019                           "5231567890123456",  // Mastercard
1020                           "05", "2012");
1021   credit_card->set_guid("00000000-0000-0000-0000-000000000007");
1022   autofill_manager_->AddCreditCard(credit_card);
1023
1024   // Set up our form data.
1025   FormData form;
1026   CreateTestCreditCardFormData(&form, true, false);
1027   std::vector<FormData> forms(1, form);
1028   FormsSeen(forms);
1029
1030   FormFieldData field = form.fields[1];
1031   GetAutofillSuggestions(form, field);
1032
1033   // No suggestions provided, so send an empty vector as the results.
1034   // This triggers the combined message send.
1035   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1036
1037   // Test that we sent the right values to the external delegate.
1038   base::string16 expected_values[] = {
1039     ASCIIToUTF16("************3456"),
1040     ASCIIToUTF16("************8765"),
1041     ASCIIToUTF16("************3456")
1042   };
1043   base::string16 expected_labels[] = {
1044     ASCIIToUTF16("04/12"),
1045     ASCIIToUTF16("10/14"),
1046     ASCIIToUTF16("05/12"),
1047   };
1048   base::string16 expected_icons[] = {
1049     ASCIIToUTF16(kVisaCard),
1050     ASCIIToUTF16(kMasterCard),
1051     ASCIIToUTF16(kMasterCard)
1052   };
1053   int expected_unique_ids[] = {
1054     autofill_manager_->GetPackedCreditCardID(4),
1055     autofill_manager_->GetPackedCreditCardID(5),
1056     autofill_manager_->GetPackedCreditCardID(7)
1057   };
1058   external_delegate_->CheckSuggestions(
1059       kDefaultPageID, arraysize(expected_values), expected_values,
1060       expected_labels, expected_icons, expected_unique_ids);
1061 }
1062
1063 // Test that we return profile and credit card suggestions for combined forms.
1064 TEST_F(AutofillManagerTest, GetAddressAndCreditCardSuggestions) {
1065   // Set up our form data.
1066   FormData form;
1067   test::CreateTestAddressFormData(&form);
1068   CreateTestCreditCardFormData(&form, true, false);
1069   std::vector<FormData> forms(1, form);
1070   FormsSeen(forms);
1071
1072   FormFieldData field = form.fields[0];
1073   GetAutofillSuggestions(form, field);
1074
1075   // No suggestions provided, so send an empty vector as the results.
1076   // This triggers the combined message send.
1077   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1078
1079   // Test that we sent the right address suggestions to the external delegate.
1080   base::string16 expected_values[] = {
1081     ASCIIToUTF16("Elvis"),
1082     ASCIIToUTF16("Charles")
1083   };
1084   base::string16 expected_labels[] = {
1085     ASCIIToUTF16("3734 Elvis Presley Blvd."),
1086     ASCIIToUTF16("123 Apple St.")
1087   };
1088   base::string16 expected_icons[] = {base::string16(), base::string16()};
1089   int expected_unique_ids[] = {1, 2};
1090   external_delegate_->CheckSuggestions(
1091       kDefaultPageID, arraysize(expected_values), expected_values,
1092       expected_labels, expected_icons, expected_unique_ids);
1093
1094   const int kPageID2 = 2;
1095   test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
1096   GetAutofillSuggestions(kPageID2, form, field);
1097
1098   // No suggestions provided, so send an empty vector as the results.
1099   // This triggers the combined message send.
1100   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1101
1102   // Test that we sent the credit card suggestions to the external delegate.
1103   base::string16 expected_values2[] = {
1104     ASCIIToUTF16("************3456"),
1105     ASCIIToUTF16("************8765")
1106   };
1107   base::string16 expected_labels2[] = { ASCIIToUTF16("04/12"),
1108                                         ASCIIToUTF16("10/14")};
1109   base::string16 expected_icons2[] = {
1110     ASCIIToUTF16(kVisaCard),
1111     ASCIIToUTF16(kMasterCard)
1112   };
1113   int expected_unique_ids2[] = {
1114     autofill_manager_->GetPackedCreditCardID(4),
1115     autofill_manager_->GetPackedCreditCardID(5)
1116   };
1117   external_delegate_->CheckSuggestions(
1118       kPageID2, arraysize(expected_values2), expected_values2,
1119       expected_labels2, expected_icons2, expected_unique_ids2);
1120 }
1121
1122 // Test that for non-https forms with both address and credit card fields, we
1123 // only return address suggestions. Instead of credit card suggestions, we
1124 // should return a warning explaining that credit card profile suggestions are
1125 // unavailable when the form is not https.
1126 TEST_F(AutofillManagerTest, GetAddressAndCreditCardSuggestionsNonHttps) {
1127   // Set up our form data.
1128   FormData form;
1129   test::CreateTestAddressFormData(&form);
1130   CreateTestCreditCardFormData(&form, false, false);
1131   std::vector<FormData> forms(1, form);
1132   FormsSeen(forms);
1133
1134   FormFieldData field = form.fields[0];
1135   GetAutofillSuggestions(form, field);
1136
1137   // No suggestions provided, so send an empty vector as the results.
1138   // This triggers the combined message send.
1139   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1140
1141   // Test that we sent the right suggestions to the external delegate.
1142   base::string16 expected_values[] = {
1143     ASCIIToUTF16("Elvis"),
1144     ASCIIToUTF16("Charles")
1145   };
1146   base::string16 expected_labels[] = {
1147     ASCIIToUTF16("3734 Elvis Presley Blvd."),
1148     ASCIIToUTF16("123 Apple St.")
1149   };
1150   base::string16 expected_icons[] = {base::string16(), base::string16()};
1151   int expected_unique_ids[] = {1, 2};
1152   external_delegate_->CheckSuggestions(
1153       kDefaultPageID, arraysize(expected_values), expected_values,
1154       expected_labels, expected_icons, expected_unique_ids);
1155
1156   test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
1157   const int kPageID2 = 2;
1158   GetAutofillSuggestions(kPageID2, form, field);
1159
1160   // No suggestions provided, so send an empty vector as the results.
1161   // This triggers the combined message send.
1162   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1163
1164   // Test that we sent the right values to the external delegate.
1165   base::string16 expected_values2[] = {
1166     l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)
1167   };
1168   base::string16 expected_labels2[] = {base::string16()};
1169   base::string16 expected_icons2[] = {base::string16()};
1170   int expected_unique_ids2[] = {-1};
1171   external_delegate_->CheckSuggestions(
1172       kPageID2, arraysize(expected_values2), expected_values2,
1173       expected_labels2, expected_icons2, expected_unique_ids2);
1174
1175   // Clear the test credit cards and try again -- we shouldn't return a warning.
1176   personal_data_.ClearCreditCards();
1177   GetAutofillSuggestions(form, field);
1178   EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1179 }
1180
1181 // Test that we correctly combine autofill and autocomplete suggestions.
1182 TEST_F(AutofillManagerTest, GetCombinedAutofillAndAutocompleteSuggestions) {
1183   // Set up our form data.
1184   FormData form;
1185   test::CreateTestAddressFormData(&form);
1186   std::vector<FormData> forms(1, form);
1187   FormsSeen(forms);
1188
1189   const FormFieldData& field = form.fields[0];
1190   GetAutofillSuggestions(form, field);
1191
1192   // Add some Autocomplete suggestions.
1193   // This triggers the combined message send.
1194   std::vector<base::string16> suggestions;
1195   suggestions.push_back(ASCIIToUTF16("Jay"));
1196   // This suggestion is a duplicate, and should be trimmed.
1197   suggestions.push_back(ASCIIToUTF16("Elvis"));
1198   suggestions.push_back(ASCIIToUTF16("Jason"));
1199   AutocompleteSuggestionsReturned(suggestions);
1200
1201   // Test that we sent the right values to the external delegate.
1202   base::string16 expected_values[] = {
1203     ASCIIToUTF16("Elvis"),
1204     ASCIIToUTF16("Charles"),
1205     ASCIIToUTF16("Jay"),
1206     ASCIIToUTF16("Jason")
1207   };
1208   base::string16 expected_labels[] = {
1209     ASCIIToUTF16("3734 Elvis Presley Blvd."),
1210     ASCIIToUTF16("123 Apple St."),
1211     base::string16(),
1212     base::string16()
1213   };
1214   base::string16 expected_icons[] = { base::string16(), base::string16(),
1215                                       base::string16(), base::string16()};
1216   int expected_unique_ids[] = {1, 2, 0, 0};
1217   external_delegate_->CheckSuggestions(
1218       kDefaultPageID, arraysize(expected_values), expected_values,
1219       expected_labels, expected_icons, expected_unique_ids);
1220 }
1221
1222 // Test that we return autocomplete-like suggestions when trying to autofill
1223 // already filled forms.
1224 TEST_F(AutofillManagerTest, GetFieldSuggestionsWhenFormIsAutofilled) {
1225   // Set up our form data.
1226   FormData form;
1227   test::CreateTestAddressFormData(&form);
1228   std::vector<FormData> forms(1, form);
1229   FormsSeen(forms);
1230
1231   // Mark one of the fields as filled.
1232   form.fields[2].is_autofilled = true;
1233   const FormFieldData& field = form.fields[0];
1234   GetAutofillSuggestions(form, field);
1235
1236   // No suggestions provided, so send an empty vector as the results.
1237   // This triggers the combined message send.
1238   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1239
1240   // Test that we sent the right values to the external delegate.
1241   base::string16 expected_values[] = {
1242     ASCIIToUTF16("Elvis"),
1243     ASCIIToUTF16("Charles")
1244   };
1245   base::string16 expected_labels[] = {base::string16(), base::string16()};
1246   base::string16 expected_icons[] = {base::string16(), base::string16()};
1247   int expected_unique_ids[] = {1, 2};
1248   external_delegate_->CheckSuggestions(
1249       kDefaultPageID, arraysize(expected_values), expected_values,
1250       expected_labels, expected_icons, expected_unique_ids);
1251 }
1252
1253 // Test that nothing breaks when there are autocomplete suggestions but no
1254 // autofill suggestions.
1255 TEST_F(AutofillManagerTest, GetFieldSuggestionsForAutocompleteOnly) {
1256   // Set up our form data.
1257   FormData form;
1258   test::CreateTestAddressFormData(&form);
1259   FormFieldData field;
1260   test::CreateTestFormField("Some Field", "somefield", "", "text", &field);
1261   form.fields.push_back(field);
1262   std::vector<FormData> forms(1, form);
1263   FormsSeen(forms);
1264
1265   GetAutofillSuggestions(form, field);
1266
1267   // Add some Autocomplete suggestions.
1268   // This triggers the combined message send.
1269   std::vector<base::string16> suggestions;
1270   suggestions.push_back(ASCIIToUTF16("one"));
1271   suggestions.push_back(ASCIIToUTF16("two"));
1272   AutocompleteSuggestionsReturned(suggestions);
1273
1274   // Test that we sent the right values to the external delegate.
1275   base::string16 expected_values[] = {
1276     ASCIIToUTF16("one"),
1277     ASCIIToUTF16("two")
1278   };
1279   base::string16 expected_labels[] = {base::string16(), base::string16()};
1280   base::string16 expected_icons[] = {base::string16(), base::string16()};
1281   int expected_unique_ids[] = {0, 0};
1282   external_delegate_->CheckSuggestions(
1283       kDefaultPageID, arraysize(expected_values), expected_values,
1284       expected_labels, expected_icons, expected_unique_ids);
1285 }
1286
1287 // Test that we do not return duplicate values drawn from multiple profiles when
1288 // filling an already filled field.
1289 TEST_F(AutofillManagerTest, GetFieldSuggestionsWithDuplicateValues) {
1290   // Set up our form data.
1291   FormData form;
1292   test::CreateTestAddressFormData(&form);
1293   std::vector<FormData> forms(1, form);
1294   FormsSeen(forms);
1295
1296   // |profile| will be owned by the mock PersonalDataManager.
1297   AutofillProfile* profile = new AutofillProfile;
1298   test::SetProfileInfo(
1299       profile, "Elvis", "", "", "", "", "", "", "", "", "", "", "");
1300   profile->set_guid("00000000-0000-0000-0000-000000000101");
1301   autofill_manager_->AddProfile(profile);
1302
1303   FormFieldData& field = form.fields[0];
1304   field.is_autofilled = true;
1305   field.value = ASCIIToUTF16("Elvis");
1306   GetAutofillSuggestions(form, field);
1307
1308   // No suggestions provided, so send an empty vector as the results.
1309   // This triggers the combined message send.
1310   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1311
1312   // Test that we sent the right values to the external delegate.
1313   base::string16 expected_values[] = { ASCIIToUTF16("Elvis") };
1314   base::string16 expected_labels[] = { base::string16() };
1315   base::string16 expected_icons[] = { base::string16() };
1316   int expected_unique_ids[] = { 1 };
1317   external_delegate_->CheckSuggestions(
1318       kDefaultPageID, arraysize(expected_values), expected_values,
1319       expected_labels, expected_icons, expected_unique_ids);
1320 }
1321
1322 // Test that a non-default value is suggested for multi-valued profile, on an
1323 // unfilled form.
1324 TEST_F(AutofillManagerTest, GetFieldSuggestionsForMultiValuedProfileUnfilled) {
1325   // Set up our form data.
1326   FormData form;
1327   test::CreateTestAddressFormData(&form);
1328   std::vector<FormData> forms(1, form);
1329   FormsSeen(forms);
1330
1331   // |profile| will be owned by the mock PersonalDataManager.
1332   AutofillProfile* profile = new AutofillProfile;
1333   test::SetProfileInfo(profile, "Elvis", "", "Presley", "me@x.com", "",
1334                        "", "", "", "", "", "", "");
1335   profile->set_guid("00000000-0000-0000-0000-000000000101");
1336   std::vector<base::string16> multi_values(2);
1337   multi_values[0] = ASCIIToUTF16("Elvis");
1338   multi_values[1] = ASCIIToUTF16("Elena");
1339   profile->SetRawMultiInfo(NAME_FIRST, multi_values);
1340   multi_values[0] = ASCIIToUTF16("Presley");
1341   multi_values[1] = ASCIIToUTF16("Love");
1342   profile->SetRawMultiInfo(NAME_LAST, multi_values);
1343   personal_data_.ClearAutofillProfiles();
1344   autofill_manager_->AddProfile(profile);
1345
1346   {
1347     // Get the first name field.
1348     // Start out with "E", hoping for either "Elvis" or "Elena.
1349     FormFieldData& field = form.fields[0];
1350     field.value = ASCIIToUTF16("E");
1351     field.is_autofilled = false;
1352     GetAutofillSuggestions(form, field);
1353
1354     // Trigger the |Send|.
1355     AutocompleteSuggestionsReturned(std::vector<base::string16>());
1356
1357     // Test that we sent the right values to the external delegate.
1358     base::string16 expected_values[] = {
1359       ASCIIToUTF16("Elvis"),
1360       ASCIIToUTF16("Elena")
1361     };
1362     base::string16 expected_labels[] = {
1363       ASCIIToUTF16("me@x.com"),
1364       ASCIIToUTF16("me@x.com")
1365     };
1366     base::string16 expected_icons[] = { base::string16(), base::string16() };
1367     int expected_unique_ids[] = { 1, 2 };
1368     external_delegate_->CheckSuggestions(
1369         kDefaultPageID, arraysize(expected_values), expected_values,
1370         expected_labels, expected_icons, expected_unique_ids);
1371   }
1372
1373   {
1374     // Get the first name field.
1375     // This time, start out with "Ele", hoping for "Elena".
1376     FormFieldData& field = form.fields[0];
1377     field.value = ASCIIToUTF16("Ele");
1378     field.is_autofilled = false;
1379     GetAutofillSuggestions(form, field);
1380
1381     // Trigger the |Send|.
1382     AutocompleteSuggestionsReturned(std::vector<base::string16>());
1383
1384     // Test that we sent the right values to the external delegate.
1385     base::string16 expected_values[] = { ASCIIToUTF16("Elena") };
1386     base::string16 expected_labels[] = { ASCIIToUTF16("me@x.com") };
1387     base::string16 expected_icons[] = { base::string16() };
1388     int expected_unique_ids[] = { 2 };
1389     external_delegate_->CheckSuggestions(
1390         kDefaultPageID, arraysize(expected_values), expected_values,
1391         expected_labels, expected_icons, expected_unique_ids);
1392   }
1393 }
1394
1395 // Test that all values are suggested for multi-valued profile, on a filled
1396 // form.  This is the per-field "override" case.
1397 TEST_F(AutofillManagerTest, GetFieldSuggestionsForMultiValuedProfileFilled) {
1398   // Set up our form data.
1399   FormData form;
1400   test::CreateTestAddressFormData(&form);
1401   std::vector<FormData> forms(1, form);
1402   FormsSeen(forms);
1403
1404   // |profile| will be owned by the mock PersonalDataManager.
1405   AutofillProfile* profile = new AutofillProfile;
1406   profile->set_guid("00000000-0000-0000-0000-000000000102");
1407   std::vector<base::string16> multi_values(3);
1408   multi_values[0] = ASCIIToUTF16("Travis");
1409   multi_values[1] = ASCIIToUTF16("Cynthia");
1410   multi_values[2] = ASCIIToUTF16("Zac");
1411   profile->SetRawMultiInfo(NAME_FIRST, multi_values);
1412   multi_values[0] = ASCIIToUTF16("Smith");
1413   multi_values[1] = ASCIIToUTF16("Love");
1414   multi_values[2] = ASCIIToUTF16("Mango");
1415   profile->SetRawMultiInfo(NAME_LAST, multi_values);
1416   autofill_manager_->AddProfile(profile);
1417
1418   // Get the first name field.  And start out with "Travis", hoping for all the
1419   // multi-valued variants as suggestions.
1420   FormFieldData& field = form.fields[0];
1421   field.value = ASCIIToUTF16("Travis");
1422   field.is_autofilled = true;
1423   GetAutofillSuggestions(form, field);
1424
1425   // Trigger the |Send|.
1426   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1427
1428   // Test that we sent the right values to the external delegate.
1429   base::string16 expected_values[] = {
1430     ASCIIToUTF16("Travis"),
1431     ASCIIToUTF16("Cynthia"),
1432     ASCIIToUTF16("Zac")
1433   };
1434   base::string16 expected_labels[] = { base::string16(), base::string16(),
1435                                        base::string16() };
1436   base::string16 expected_icons[] = { base::string16(), base::string16(),
1437                                       base::string16() };
1438   int expected_unique_ids[] = { 1, 2, 3 };
1439   external_delegate_->CheckSuggestions(
1440       kDefaultPageID, arraysize(expected_values), expected_values,
1441       expected_labels, expected_icons, expected_unique_ids);
1442 }
1443
1444 TEST_F(AutofillManagerTest, GetProfileSuggestionsFancyPhone) {
1445   // Set up our form data.
1446   FormData form;
1447   test::CreateTestAddressFormData(&form);
1448   std::vector<FormData> forms(1, form);
1449   FormsSeen(forms);
1450
1451   AutofillProfile* profile = new AutofillProfile;
1452   profile->set_guid("00000000-0000-0000-0000-000000000103");
1453   profile->SetInfo(AutofillType(NAME_FULL), ASCIIToUTF16("Natty Bumppo"),
1454                    "en-US");
1455   profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
1456                       ASCIIToUTF16("1800PRAIRIE"));
1457   autofill_manager_->AddProfile(profile);
1458
1459   const FormFieldData& field = form.fields[9];
1460   GetAutofillSuggestions(form, field);
1461
1462   // No suggestions provided, so send an empty vector as the results.
1463   // This triggers the combined message send.
1464   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1465
1466   // Test that we sent the right values to the external delegate.
1467   base::string16 expected_values[] = {
1468     ASCIIToUTF16("12345678901"),
1469     ASCIIToUTF16("23456789012"),
1470     ASCIIToUTF16("18007724743"),  // 1800PRAIRIE
1471   };
1472   // Inferred labels include full first relevant field, which in this case is
1473   // the address line 1.
1474   base::string16 expected_labels[] = {
1475     ASCIIToUTF16("Elvis Aaron Presley"),
1476     ASCIIToUTF16("Charles Hardin Holley"),
1477     ASCIIToUTF16("Natty Bumppo"),
1478   };
1479   base::string16 expected_icons[] = { base::string16(), base::string16(),
1480                                       base::string16()};
1481   int expected_unique_ids[] = {1, 2, 3};
1482   external_delegate_->CheckSuggestions(
1483       kDefaultPageID, arraysize(expected_values), expected_values,
1484       expected_labels, expected_icons, expected_unique_ids);
1485 }
1486
1487 TEST_F(AutofillManagerTest, GetProfileSuggestionsForPhonePrefixOrSuffix) {
1488   // Set up our form data.
1489   FormData form;
1490   form.name = ASCIIToUTF16("MyForm");
1491   form.origin = GURL("http://myform.com/form.html");
1492   form.action = GURL("http://myform.com/submit.html");
1493   form.user_submitted = true;
1494
1495   struct {
1496     const char* const label;
1497     const char* const name;
1498     size_t max_length;
1499     const char* const autocomplete_attribute;
1500   } test_fields[] = {{"country code", "country_code", 1, "tel-country-code"},
1501                      {"area code", "area_code", 3, "tel-area-code"},
1502                      {"phone", "phone_prefix", 3, "tel-local-prefix"},
1503                      {"-", "phone_suffix", 4, "tel-local-suffix"},
1504                      {"Phone Extension", "ext", 5, "tel-extension"}};
1505
1506   FormFieldData field;
1507   for (size_t i = 0; i < arraysize(test_fields); ++i) {
1508     test::CreateTestFormField(
1509         test_fields[i].label, test_fields[i].name, "", "text", &field);
1510     field.max_length = test_fields[i].max_length;
1511     field.autocomplete_attribute = std::string();
1512     form.fields.push_back(field);
1513   }
1514
1515   std::vector<FormData> forms(1, form);
1516   FormsSeen(forms);
1517
1518   AutofillProfile* profile = new AutofillProfile;
1519   profile->set_guid("00000000-0000-0000-0000-000000000104");
1520   std::vector<base::string16> multi_values(2);
1521   multi_values[0] = ASCIIToUTF16("1800FLOWERS");
1522   multi_values[1] = ASCIIToUTF16("14158889999");
1523
1524   profile->SetRawMultiInfo(PHONE_HOME_WHOLE_NUMBER, multi_values);
1525   personal_data_.ClearAutofillProfiles();
1526   autofill_manager_->AddProfile(profile);
1527
1528   const FormFieldData& phone_prefix = form.fields[2];
1529   GetAutofillSuggestions(form, phone_prefix);
1530   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1531   // Test that we sent the right prefix values to the external delegate.
1532   base::string16 expected_prefix_values[] = {ASCIIToUTF16("356"),
1533                                              ASCIIToUTF16("888")};
1534   base::string16 expected_prefix_labels[] = {ASCIIToUTF16("1"),
1535                                              ASCIIToUTF16("1")};
1536   base::string16 expected_prefix_icons[] = {base::string16(), base::string16()};
1537   int expected_unique_ids[] = {1, 2};
1538   external_delegate_->CheckSuggestions(kDefaultPageID,
1539                                        arraysize(expected_prefix_values),
1540                                        expected_prefix_values,
1541                                        expected_prefix_labels,
1542                                        expected_prefix_icons,
1543                                        expected_unique_ids);
1544
1545   const FormFieldData& phone_suffix = form.fields[3];
1546   GetAutofillSuggestions(form, phone_suffix);
1547   AutocompleteSuggestionsReturned(std::vector<base::string16>());
1548   // Test that we sent the right suffix values to the external delegate.
1549   base::string16 expected_suffix_values[] = {ASCIIToUTF16("9377"),
1550                                              ASCIIToUTF16("9999")};
1551   base::string16 expected_suffix_labels[] = {ASCIIToUTF16("1"),
1552                                              ASCIIToUTF16("1")};
1553   base::string16 expected_suffix_icons[] = {base::string16(), base::string16()};
1554   external_delegate_->CheckSuggestions(kDefaultPageID,
1555                                        arraysize(expected_suffix_values),
1556                                        expected_suffix_values,
1557                                        expected_suffix_labels,
1558                                        expected_suffix_icons,
1559                                        expected_unique_ids);
1560 }
1561
1562 // Test that we correctly fill an address form.
1563 TEST_F(AutofillManagerTest, FillAddressForm) {
1564   // Set up our form data.
1565   FormData form;
1566   test::CreateTestAddressFormData(&form);
1567   std::vector<FormData> forms(1, form);
1568   FormsSeen(forms);
1569
1570   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1571   GUIDPair empty(std::string(), 0);
1572   int response_page_id = 0;
1573   FormData response_data;
1574   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1575       PackGUIDs(empty, guid), &response_page_id, &response_data);
1576   ExpectFilledAddressFormElvis(
1577       response_page_id, response_data, kDefaultPageID, false);
1578 }
1579
1580 // Test that we correctly fill an address form from an auxiliary profile.
1581 TEST_F(AutofillManagerTest, FillAddressFormFromAuxiliaryProfile) {
1582   personal_data_.ClearAutofillProfiles();
1583 #if defined(OS_MACOSX) && !defined(OS_IOS)
1584   autofill_client_.GetPrefs()->SetBoolean(
1585       ::autofill::prefs::kAutofillUseMacAddressBook, true);
1586 #else
1587   autofill_client_.GetPrefs()->SetBoolean(
1588       ::autofill::prefs::kAutofillAuxiliaryProfilesEnabled, true);
1589 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
1590
1591   personal_data_.CreateTestAuxiliaryProfiles();
1592
1593   // Set up our form data.
1594   FormData form;
1595   test::CreateTestAddressFormData(&form);
1596   std::vector<FormData> forms(1, form);
1597   FormsSeen(forms);
1598
1599   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1600   GUIDPair empty(std::string(), 0);
1601   int response_page_id = 0;
1602   FormData response_data;
1603   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1604       PackGUIDs(empty, guid), &response_page_id, &response_data);
1605   ExpectFilledAddressFormElvis(
1606       response_page_id, response_data, kDefaultPageID, false);
1607 }
1608
1609 // Test that we correctly fill a credit card form.
1610 TEST_F(AutofillManagerTest, FillCreditCardForm) {
1611   // Set up our form data.
1612   FormData form;
1613   CreateTestCreditCardFormData(&form, true, false);
1614   std::vector<FormData> forms(1, form);
1615   FormsSeen(forms);
1616
1617   GUIDPair guid("00000000-0000-0000-0000-000000000004", 0);
1618   GUIDPair empty(std::string(), 0);
1619   int response_page_id = 0;
1620   FormData response_data;
1621   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1622       PackGUIDs(guid, empty), &response_page_id, &response_data);
1623   ExpectFilledCreditCardFormElvis(
1624       response_page_id, response_data, kDefaultPageID, false);
1625 }
1626
1627 // Test that we correctly fill a credit card form with month input type.
1628 // 1. year empty, month empty
1629 TEST_F(AutofillManagerTest, FillCreditCardFormNoYearNoMonth) {
1630   // Same as the SetUp(), but generate 4 credit cards with year month
1631   // combination.
1632   personal_data_.CreateTestCreditCardsYearAndMonth("", "");
1633   // Set up our form data.
1634   FormData form;
1635   CreateTestCreditCardFormData(&form, true, true);
1636   std::vector<FormData> forms(1, form);
1637   FormsSeen(forms);
1638
1639   GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1640   GUIDPair empty(std::string(), 0);
1641   int response_page_id = 0;
1642   FormData response_data;
1643   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1644       PackGUIDs(guid, empty), &response_page_id, &response_data);
1645   ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1646       kDefaultPageID, false, "", "");
1647 }
1648
1649
1650 // Test that we correctly fill a credit card form with month input type.
1651 // 2. year empty, month non-empty
1652 TEST_F(AutofillManagerTest, FillCreditCardFormNoYearMonth) {
1653   // Same as the SetUp(), but generate 4 credit cards with year month
1654   // combination.
1655   personal_data_.CreateTestCreditCardsYearAndMonth("", "04");
1656   // Set up our form data.
1657   FormData form;
1658   CreateTestCreditCardFormData(&form, true, true);
1659   std::vector<FormData> forms(1, form);
1660   FormsSeen(forms);
1661
1662   GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1663   GUIDPair empty(std::string(), 0);
1664   int response_page_id = 0;
1665   FormData response_data;
1666   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1667       PackGUIDs(guid, empty), &response_page_id, &response_data);
1668   ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1669       kDefaultPageID, false, "", "04");
1670 }
1671
1672 // Test that we correctly fill a credit card form with month input type.
1673 // 3. year non-empty, month empty
1674 TEST_F(AutofillManagerTest, FillCreditCardFormYearNoMonth) {
1675   // Same as the SetUp(), but generate 4 credit cards with year month
1676   // combination.
1677   personal_data_.CreateTestCreditCardsYearAndMonth("2012", "");
1678   // Set up our form data.
1679   FormData form;
1680   CreateTestCreditCardFormData(&form, true, true);
1681   std::vector<FormData> forms(1, form);
1682   FormsSeen(forms);
1683
1684   GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1685   GUIDPair empty(std::string(), 0);
1686   int response_page_id = 0;
1687   FormData response_data;
1688   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1689       PackGUIDs(guid, empty), &response_page_id, &response_data);
1690   ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1691       kDefaultPageID, false, "2012", "");
1692 }
1693
1694 // Test that we correctly fill a credit card form with month input type.
1695 // 4. year non-empty, month empty
1696 TEST_F(AutofillManagerTest, FillCreditCardFormYearMonth) {
1697   // Same as the SetUp(), but generate 4 credit cards with year month
1698   // combination.
1699   personal_data_.ClearCreditCards();
1700   personal_data_.CreateTestCreditCardsYearAndMonth("2012", "04");
1701   // Set up our form data.
1702   FormData form;
1703   CreateTestCreditCardFormData(&form, true, true);
1704   std::vector<FormData> forms(1, form);
1705   FormsSeen(forms);
1706
1707   GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1708   GUIDPair empty(std::string(), 0);
1709   int response_page_id = 0;
1710   FormData response_data;
1711   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1712       PackGUIDs(guid, empty), &response_page_id, &response_data);
1713   ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1714       kDefaultPageID, false, "2012", "04");
1715 }
1716
1717 // Test that we correctly fill a combined address and credit card form.
1718 TEST_F(AutofillManagerTest, FillAddressAndCreditCardForm) {
1719   // Set up our form data.
1720   FormData form;
1721   test::CreateTestAddressFormData(&form);
1722   CreateTestCreditCardFormData(&form, true, false);
1723   std::vector<FormData> forms(1, form);
1724   FormsSeen(forms);
1725
1726   // First fill the address data.
1727   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1728   GUIDPair empty(std::string(), 0);
1729   int response_page_id = 0;
1730   FormData response_data;
1731   {
1732     SCOPED_TRACE("Address");
1733     FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1734         PackGUIDs(empty, guid), &response_page_id, &response_data);
1735     ExpectFilledAddressFormElvis(
1736         response_page_id, response_data, kDefaultPageID, true);
1737   }
1738
1739   // Now fill the credit card data.
1740   const int kPageID2 = 2;
1741   GUIDPair guid2("00000000-0000-0000-0000-000000000004", 0);
1742   response_page_id = 0;
1743   {
1744     FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(),
1745         PackGUIDs(guid2, empty), &response_page_id, &response_data);
1746     SCOPED_TRACE("Credit card");
1747     ExpectFilledCreditCardFormElvis(
1748         response_page_id, response_data, kPageID2, true);
1749   }
1750 }
1751
1752 // Test that we correctly fill a form that has multiple logical sections, e.g.
1753 // both a billing and a shipping address.
1754 TEST_F(AutofillManagerTest, FillFormWithMultipleSections) {
1755   // Set up our form data.
1756   FormData form;
1757   test::CreateTestAddressFormData(&form);
1758   const size_t kAddressFormSize = form.fields.size();
1759   test::CreateTestAddressFormData(&form);
1760   for (size_t i = kAddressFormSize; i < form.fields.size(); ++i) {
1761     // Make sure the fields have distinct names.
1762     form.fields[i].name = form.fields[i].name + ASCIIToUTF16("_");
1763   }
1764   std::vector<FormData> forms(1, form);
1765   FormsSeen(forms);
1766
1767   // Fill the first section.
1768   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1769   GUIDPair empty(std::string(), 0);
1770   int response_page_id = 0;
1771   FormData response_data;
1772   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1773       PackGUIDs(empty, guid), &response_page_id, &response_data);
1774   {
1775     SCOPED_TRACE("Address 1");
1776     // The second address section should be empty.
1777     ASSERT_EQ(response_data.fields.size(), 2*kAddressFormSize);
1778     for (size_t i = kAddressFormSize; i < form.fields.size(); ++i) {
1779       EXPECT_EQ(base::string16(), response_data.fields[i].value);
1780     }
1781
1782     // The first address section should be filled with Elvis's data.
1783     response_data.fields.resize(kAddressFormSize);
1784     ExpectFilledAddressFormElvis(
1785         response_page_id, response_data, kDefaultPageID, false);
1786   }
1787
1788   // Fill the second section, with the initiating field somewhere in the middle
1789   // of the section.
1790   const int kPageID2 = 2;
1791   GUIDPair guid2("00000000-0000-0000-0000-000000000001", 0);
1792   ASSERT_LT(9U, kAddressFormSize);
1793   response_page_id = 0;
1794   FillAutofillFormDataAndSaveResults(
1795       kPageID2, form, form.fields[kAddressFormSize + 9],
1796       PackGUIDs(empty, guid2), &response_page_id, &response_data);
1797   {
1798     SCOPED_TRACE("Address 2");
1799     ASSERT_EQ(response_data.fields.size(), form.fields.size());
1800
1801     // The first address section should be empty.
1802     ASSERT_EQ(response_data.fields.size(), 2*kAddressFormSize);
1803     for (size_t i = 0; i < kAddressFormSize; ++i) {
1804       EXPECT_EQ(base::string16(), response_data.fields[i].value);
1805     }
1806
1807     // The second address section should be filled with Elvis's data.
1808     FormData secondSection = response_data;
1809     secondSection.fields.erase(secondSection.fields.begin(),
1810                                secondSection.fields.begin() + kAddressFormSize);
1811     for (size_t i = 0; i < kAddressFormSize; ++i) {
1812       // Restore the expected field names.
1813       base::string16 name = secondSection.fields[i].name;
1814       base::string16 original_name = name.substr(0, name.size() - 1);
1815       secondSection.fields[i].name = original_name;
1816     }
1817     ExpectFilledAddressFormElvis(
1818         response_page_id, secondSection, kPageID2, false);
1819   }
1820 }
1821
1822 // Test that we correctly fill a form that has author-specified sections, which
1823 // might not match our expected section breakdown.
1824 TEST_F(AutofillManagerTest, FillFormWithAuthorSpecifiedSections) {
1825   // Create a form with a billing section and an unnamed section, interleaved.
1826   // The billing section includes both address and credit card fields.
1827   FormData form;
1828   form.name = ASCIIToUTF16("MyForm");
1829   form.origin = GURL("https://myform.com/form.html");
1830   form.action = GURL("https://myform.com/submit.html");
1831   form.user_submitted = true;
1832
1833   FormFieldData field;
1834
1835   test::CreateTestFormField("", "country", "", "text", &field);
1836   field.autocomplete_attribute = "section-billing country";
1837   form.fields.push_back(field);
1838
1839   test::CreateTestFormField("", "firstname", "", "text", &field);
1840   field.autocomplete_attribute = "given-name";
1841   form.fields.push_back(field);
1842
1843   test::CreateTestFormField("", "lastname", "", "text", &field);
1844   field.autocomplete_attribute = "family-name";
1845   form.fields.push_back(field);
1846
1847   test::CreateTestFormField("", "address", "", "text", &field);
1848   field.autocomplete_attribute = "section-billing address-line1";
1849   form.fields.push_back(field);
1850
1851   test::CreateTestFormField("", "city", "", "text", &field);
1852   field.autocomplete_attribute = "section-billing locality";
1853   form.fields.push_back(field);
1854
1855   test::CreateTestFormField("", "state", "", "text", &field);
1856   field.autocomplete_attribute = "section-billing region";
1857   form.fields.push_back(field);
1858
1859   test::CreateTestFormField("", "zip", "", "text", &field);
1860   field.autocomplete_attribute = "section-billing postal-code";
1861   form.fields.push_back(field);
1862
1863   test::CreateTestFormField("", "ccname", "", "text", &field);
1864   field.autocomplete_attribute = "section-billing cc-name";
1865   form.fields.push_back(field);
1866
1867   test::CreateTestFormField("", "ccnumber", "", "text", &field);
1868   field.autocomplete_attribute = "section-billing cc-number";
1869   form.fields.push_back(field);
1870
1871   test::CreateTestFormField("", "ccexp", "", "text", &field);
1872   field.autocomplete_attribute = "section-billing cc-exp";
1873   form.fields.push_back(field);
1874
1875   test::CreateTestFormField("", "email", "", "text", &field);
1876   field.autocomplete_attribute = "email";
1877   form.fields.push_back(field);
1878
1879   std::vector<FormData> forms(1, form);
1880   FormsSeen(forms);
1881
1882   // Fill the unnamed section.
1883   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1884   GUIDPair empty(std::string(), 0);
1885   int response_page_id = 0;
1886   FormData response_data;
1887   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[1],
1888       PackGUIDs(empty, guid), &response_page_id, &response_data);
1889   {
1890     SCOPED_TRACE("Unnamed section");
1891     EXPECT_EQ(kDefaultPageID, response_page_id);
1892     EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
1893     EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
1894     EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
1895     EXPECT_TRUE(response_data.user_submitted);
1896     ASSERT_EQ(11U, response_data.fields.size());
1897
1898     ExpectFilledField("", "country", "", "text", response_data.fields[0]);
1899     ExpectFilledField("", "firstname", "Elvis", "text",
1900                       response_data.fields[1]);
1901     ExpectFilledField("", "lastname", "Presley", "text",
1902                       response_data.fields[2]);
1903     ExpectFilledField("", "address", "", "text", response_data.fields[3]);
1904     ExpectFilledField("", "city", "", "text", response_data.fields[4]);
1905     ExpectFilledField("", "state", "", "text", response_data.fields[5]);
1906     ExpectFilledField("", "zip", "", "text", response_data.fields[6]);
1907     ExpectFilledField("", "ccname", "", "text", response_data.fields[7]);
1908     ExpectFilledField("", "ccnumber", "", "text", response_data.fields[8]);
1909     ExpectFilledField("", "ccexp", "", "text", response_data.fields[9]);
1910     ExpectFilledField("", "email", "theking@gmail.com", "text",
1911                       response_data.fields[10]);
1912   }
1913
1914   // Fill the address portion of the billing section.
1915   const int kPageID2 = 2;
1916   GUIDPair guid2("00000000-0000-0000-0000-000000000001", 0);
1917   response_page_id = 0;
1918   FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields[0],
1919       PackGUIDs(empty, guid2), &response_page_id, &response_data);
1920   {
1921     SCOPED_TRACE("Billing address");
1922     EXPECT_EQ(kPageID2, response_page_id);
1923     EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
1924     EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
1925     EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
1926     EXPECT_TRUE(response_data.user_submitted);
1927     ASSERT_EQ(11U, response_data.fields.size());
1928
1929     ExpectFilledField("", "country", "US", "text",
1930                       response_data.fields[0]);
1931     ExpectFilledField("", "firstname", "", "text", response_data.fields[1]);
1932     ExpectFilledField("", "lastname", "", "text", response_data.fields[2]);
1933     ExpectFilledField("", "address", "3734 Elvis Presley Blvd.", "text",
1934                       response_data.fields[3]);
1935     ExpectFilledField("", "city", "Memphis", "text", response_data.fields[4]);
1936     ExpectFilledField("", "state", "Tennessee", "text",
1937                       response_data.fields[5]);
1938     ExpectFilledField("", "zip", "38116", "text", response_data.fields[6]);
1939     ExpectFilledField("", "ccname", "", "text", response_data.fields[7]);
1940     ExpectFilledField("", "ccnumber", "", "text", response_data.fields[8]);
1941     ExpectFilledField("", "ccexp", "", "text", response_data.fields[9]);
1942     ExpectFilledField("", "email", "", "text", response_data.fields[10]);
1943   }
1944
1945   // Fill the credit card portion of the billing section.
1946   const int kPageID3 = 3;
1947   GUIDPair guid3("00000000-0000-0000-0000-000000000004", 0);
1948   response_page_id = 0;
1949   FillAutofillFormDataAndSaveResults(
1950       kPageID3, form, form.fields[form.fields.size() - 2],
1951       PackGUIDs(guid3, empty), &response_page_id, &response_data);
1952   {
1953     SCOPED_TRACE("Credit card");
1954     EXPECT_EQ(kPageID3, response_page_id);
1955     EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
1956     EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
1957     EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
1958     EXPECT_TRUE(response_data.user_submitted);
1959     ASSERT_EQ(11U, response_data.fields.size());
1960
1961     ExpectFilledField("", "country", "", "text", response_data.fields[0]);
1962     ExpectFilledField("", "firstname", "", "text", response_data.fields[1]);
1963     ExpectFilledField("", "lastname", "", "text", response_data.fields[2]);
1964     ExpectFilledField("", "address", "", "text", response_data.fields[3]);
1965     ExpectFilledField("", "city", "", "text", response_data.fields[4]);
1966     ExpectFilledField("", "state", "", "text", response_data.fields[5]);
1967     ExpectFilledField("", "zip", "", "text", response_data.fields[6]);
1968     ExpectFilledField("", "ccname", "Elvis Presley", "text",
1969                       response_data.fields[7]);
1970     ExpectFilledField("", "ccnumber", "4234567890123456", "text",
1971                       response_data.fields[8]);
1972     ExpectFilledField("", "ccexp", "04/2012", "text", response_data.fields[9]);
1973     ExpectFilledField("", "email", "", "text", response_data.fields[10]);
1974   }
1975 }
1976
1977 // Test that we correctly fill a form that has a single logical section with
1978 // multiple email address fields.
1979 TEST_F(AutofillManagerTest, FillFormWithMultipleEmails) {
1980   // Set up our form data.
1981   FormData form;
1982   test::CreateTestAddressFormData(&form);
1983   FormFieldData field;
1984   test::CreateTestFormField("Confirm email", "email2", "", "text", &field);
1985   form.fields.push_back(field);
1986
1987   std::vector<FormData> forms(1, form);
1988   FormsSeen(forms);
1989
1990   // Fill the form.
1991   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1992   GUIDPair empty(std::string(), 0);
1993   int response_page_id = 0;
1994   FormData response_data;
1995   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1996       PackGUIDs(empty, guid), &response_page_id, &response_data);
1997
1998   // The second email address should be filled.
1999   EXPECT_EQ(ASCIIToUTF16("theking@gmail.com"),
2000             response_data.fields.back().value);
2001
2002   // The remainder of the form should be filled as usual.
2003   response_data.fields.pop_back();
2004   ExpectFilledAddressFormElvis(
2005       response_page_id, response_data, kDefaultPageID, false);
2006 }
2007
2008 // Test that we correctly fill a previously auto-filled form.
2009 TEST_F(AutofillManagerTest, FillAutofilledForm) {
2010   // Set up our form data.
2011   FormData form;
2012   test::CreateTestAddressFormData(&form);
2013   // Mark one of the address fields as autofilled.
2014   form.fields[4].is_autofilled = true;
2015   CreateTestCreditCardFormData(&form, true, false);
2016   std::vector<FormData> forms(1, form);
2017   FormsSeen(forms);
2018
2019   // First fill the address data.
2020   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2021   GUIDPair empty(std::string(), 0);
2022   int response_page_id = 0;
2023   FormData response_data;
2024   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
2025       PackGUIDs(empty, guid), &response_page_id, &response_data);
2026   {
2027     SCOPED_TRACE("Address");
2028     ExpectFilledForm(response_page_id, response_data, kDefaultPageID,
2029                      "Elvis", "", "", "", "", "", "", "", "", "", "", "", "",
2030                      "", "", true, true, false);
2031   }
2032
2033   // Now fill the credit card data.
2034   const int kPageID2 = 2;
2035   GUIDPair guid2("00000000-0000-0000-0000-000000000004", 0);
2036   response_page_id = 0;
2037   FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(),
2038       PackGUIDs(guid2, empty), &response_page_id, &response_data);
2039   {
2040     SCOPED_TRACE("Credit card 1");
2041     ExpectFilledCreditCardFormElvis(
2042         response_page_id, response_data, kPageID2, true);
2043   }
2044
2045   // Now set the credit card fields to also be auto-filled, and try again to
2046   // fill the credit card data
2047   for (std::vector<FormFieldData>::iterator iter = form.fields.begin();
2048        iter != form.fields.end();
2049        ++iter) {
2050     iter->is_autofilled = true;
2051   }
2052
2053   const int kPageID3 = 3;
2054   response_page_id = 0;
2055   FillAutofillFormDataAndSaveResults(kPageID3, form, *form.fields.rbegin(),
2056       PackGUIDs(guid2, empty), &response_page_id, &response_data);
2057   {
2058     SCOPED_TRACE("Credit card 2");
2059     ExpectFilledForm(response_page_id, response_data, kPageID3,
2060                      "", "", "", "", "", "", "", "", "", "", "", "", "", "",
2061                      "2012", true, true, false);
2062   }
2063 }
2064
2065 // Test that we correctly fill an address form with a non-default variant for a
2066 // multi-valued field.
2067 TEST_F(AutofillManagerTest, FillAddressFormWithVariantType) {
2068   // Set up our form data.
2069   FormData form;
2070   test::CreateTestAddressFormData(&form);
2071   std::vector<FormData> forms(1, form);
2072   FormsSeen(forms);
2073
2074   // Add a name variant to the Elvis profile.
2075   AutofillProfile* profile = autofill_manager_->GetProfileWithGUID(
2076       "00000000-0000-0000-0000-000000000001");
2077
2078   std::vector<base::string16> name_variants;
2079   name_variants.push_back(ASCIIToUTF16("Some"));
2080   name_variants.push_back(profile->GetRawInfo(NAME_FIRST));
2081   profile->SetRawMultiInfo(NAME_FIRST, name_variants);
2082
2083   name_variants.clear();
2084   name_variants.push_back(ASCIIToUTF16("Other"));
2085   name_variants.push_back(profile->GetRawInfo(NAME_MIDDLE));
2086   profile->SetRawMultiInfo(NAME_MIDDLE, name_variants);
2087
2088   name_variants.clear();
2089   name_variants.push_back(ASCIIToUTF16("Guy"));
2090   name_variants.push_back(profile->GetRawInfo(NAME_LAST));
2091   profile->SetRawMultiInfo(NAME_LAST, name_variants);
2092
2093   GUIDPair guid(profile->guid(), 1);
2094   GUIDPair empty(std::string(), 0);
2095   int response_page_id = 0;
2096   FormData response_data1;
2097   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2098       PackGUIDs(empty, guid), &response_page_id, &response_data1);
2099   {
2100     SCOPED_TRACE("Valid variant");
2101     ExpectFilledAddressFormElvis(
2102         response_page_id, response_data1, kDefaultPageID, false);
2103   }
2104
2105   // Try filling with a variant that doesn't exist.  The fields to which this
2106   // variant would normally apply should not be filled.
2107   const int kPageID2 = 2;
2108   GUIDPair guid2(profile->guid(), 2);
2109   response_page_id = 0;
2110   FormData response_data2;
2111   FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields[0],
2112       PackGUIDs(empty, guid2), &response_page_id, &response_data2);
2113   {
2114     SCOPED_TRACE("Invalid variant");
2115     ExpectFilledForm(response_page_id, response_data2, kPageID2, "", "", "",
2116                      "3734 Elvis Presley Blvd.", "Apt. 10", "Memphis",
2117                      "Tennessee", "38116", "United States", "12345678901",
2118                      "theking@gmail.com", "", "", "", "", true, false, false);
2119   }
2120 }
2121
2122 // Test that we correctly fill a phone number split across multiple fields.
2123 TEST_F(AutofillManagerTest, FillPhoneNumber) {
2124   // In one form, rely on the maxlength attribute to imply phone number parts.
2125   // In the other form, rely on the autocompletetype attribute.
2126   FormData form_with_maxlength;
2127   form_with_maxlength.name = ASCIIToUTF16("MyMaxlengthPhoneForm");
2128   form_with_maxlength.origin = GURL("http://myform.com/phone_form.html");
2129   form_with_maxlength.action = GURL("http://myform.com/phone_submit.html");
2130   form_with_maxlength.user_submitted = true;
2131   FormData form_with_autocompletetype = form_with_maxlength;
2132   form_with_autocompletetype.name = ASCIIToUTF16("MyAutocompletetypePhoneForm");
2133
2134   struct {
2135     const char* label;
2136     const char* name;
2137     size_t max_length;
2138     const char* autocomplete_attribute;
2139   } test_fields[] = {
2140     { "country code", "country_code", 1, "tel-country-code" },
2141     { "area code", "area_code", 3, "tel-area-code" },
2142     { "phone", "phone_prefix", 3, "tel-local-prefix" },
2143     { "-", "phone_suffix", 4, "tel-local-suffix" },
2144     { "Phone Extension", "ext", 3, "tel-extension" }
2145   };
2146
2147   FormFieldData field;
2148   const size_t default_max_length = field.max_length;
2149   for (size_t i = 0; i < arraysize(test_fields); ++i) {
2150     test::CreateTestFormField(
2151         test_fields[i].label, test_fields[i].name, "", "text", &field);
2152     field.max_length = test_fields[i].max_length;
2153     field.autocomplete_attribute = std::string();
2154     form_with_maxlength.fields.push_back(field);
2155
2156     field.max_length = default_max_length;
2157     field.autocomplete_attribute = test_fields[i].autocomplete_attribute;
2158     form_with_autocompletetype.fields.push_back(field);
2159   }
2160
2161   std::vector<FormData> forms;
2162   forms.push_back(form_with_maxlength);
2163   forms.push_back(form_with_autocompletetype);
2164   FormsSeen(forms);
2165
2166   // We should be able to fill prefix and suffix fields for US numbers.
2167   AutofillProfile* work_profile = autofill_manager_->GetProfileWithGUID(
2168       "00000000-0000-0000-0000-000000000002");
2169   ASSERT_TRUE(work_profile != NULL);
2170   work_profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
2171                            ASCIIToUTF16("16505554567"));
2172
2173   GUIDPair guid(work_profile->guid(), 0);
2174   GUIDPair empty(std::string(), 0);
2175   int page_id = 1;
2176   int response_page_id = 0;
2177   FormData response_data1;
2178   FillAutofillFormDataAndSaveResults(page_id, form_with_maxlength,
2179       *form_with_maxlength.fields.begin(),
2180       PackGUIDs(empty, guid), &response_page_id, &response_data1);
2181   EXPECT_EQ(1, response_page_id);
2182
2183   ASSERT_EQ(5U, response_data1.fields.size());
2184   EXPECT_EQ(ASCIIToUTF16("1"), response_data1.fields[0].value);
2185   EXPECT_EQ(ASCIIToUTF16("650"), response_data1.fields[1].value);
2186   EXPECT_EQ(ASCIIToUTF16("555"), response_data1.fields[2].value);
2187   EXPECT_EQ(ASCIIToUTF16("4567"), response_data1.fields[3].value);
2188   EXPECT_EQ(base::string16(), response_data1.fields[4].value);
2189
2190   page_id = 2;
2191   response_page_id = 0;
2192   FormData response_data2;
2193   FillAutofillFormDataAndSaveResults(page_id, form_with_autocompletetype,
2194       *form_with_autocompletetype.fields.begin(),
2195       PackGUIDs(empty, guid), &response_page_id, &response_data2);
2196   EXPECT_EQ(2, response_page_id);
2197
2198   ASSERT_EQ(5U, response_data2.fields.size());
2199   EXPECT_EQ(ASCIIToUTF16("1"), response_data2.fields[0].value);
2200   EXPECT_EQ(ASCIIToUTF16("650"), response_data2.fields[1].value);
2201   EXPECT_EQ(ASCIIToUTF16("555"), response_data2.fields[2].value);
2202   EXPECT_EQ(ASCIIToUTF16("4567"), response_data2.fields[3].value);
2203   EXPECT_EQ(base::string16(), response_data2.fields[4].value);
2204
2205   // We should not be able to fill prefix and suffix fields for international
2206   // numbers.
2207   work_profile->SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("GB"));
2208   work_profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
2209                            ASCIIToUTF16("447700954321"));
2210   page_id = 3;
2211   response_page_id = 0;
2212   FormData response_data3;
2213   FillAutofillFormDataAndSaveResults(page_id, form_with_maxlength,
2214       *form_with_maxlength.fields.begin(),
2215       PackGUIDs(empty, guid), &response_page_id, &response_data3);
2216   EXPECT_EQ(3, response_page_id);
2217
2218   ASSERT_EQ(5U, response_data3.fields.size());
2219   EXPECT_EQ(ASCIIToUTF16("44"), response_data3.fields[0].value);
2220   EXPECT_EQ(ASCIIToUTF16("7700"), response_data3.fields[1].value);
2221   EXPECT_EQ(ASCIIToUTF16("954321"), response_data3.fields[2].value);
2222   EXPECT_EQ(ASCIIToUTF16("954321"), response_data3.fields[3].value);
2223   EXPECT_EQ(base::string16(), response_data3.fields[4].value);
2224
2225   page_id = 4;
2226   response_page_id = 0;
2227   FormData response_data4;
2228   FillAutofillFormDataAndSaveResults(page_id, form_with_autocompletetype,
2229       *form_with_autocompletetype.fields.begin(),
2230       PackGUIDs(empty, guid), &response_page_id, &response_data4);
2231   EXPECT_EQ(4, response_page_id);
2232
2233   ASSERT_EQ(5U, response_data4.fields.size());
2234   EXPECT_EQ(ASCIIToUTF16("44"), response_data4.fields[0].value);
2235   EXPECT_EQ(ASCIIToUTF16("7700"), response_data4.fields[1].value);
2236   EXPECT_EQ(ASCIIToUTF16("954321"), response_data4.fields[2].value);
2237   EXPECT_EQ(ASCIIToUTF16("954321"), response_data4.fields[3].value);
2238   EXPECT_EQ(base::string16(), response_data4.fields[4].value);
2239
2240   // We should fill all phone fields with the same phone number variant.
2241   std::vector<base::string16> phone_variants;
2242   phone_variants.push_back(ASCIIToUTF16("16505554567"));
2243   phone_variants.push_back(ASCIIToUTF16("18887771234"));
2244   work_profile->SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
2245   work_profile->SetRawMultiInfo(PHONE_HOME_WHOLE_NUMBER, phone_variants);
2246
2247   page_id = 5;
2248   response_page_id = 0;
2249   FormData response_data5;
2250   GUIDPair variant_guid(work_profile->guid(), 1);
2251   FillAutofillFormDataAndSaveResults(page_id, form_with_maxlength,
2252       *form_with_maxlength.fields.begin(),
2253       PackGUIDs(empty, variant_guid), &response_page_id, &response_data5);
2254   EXPECT_EQ(5, response_page_id);
2255
2256   ASSERT_EQ(5U, response_data5.fields.size());
2257   EXPECT_EQ(ASCIIToUTF16("1"), response_data5.fields[0].value);
2258   EXPECT_EQ(ASCIIToUTF16("888"), response_data5.fields[1].value);
2259   EXPECT_EQ(ASCIIToUTF16("777"), response_data5.fields[2].value);
2260   EXPECT_EQ(ASCIIToUTF16("1234"), response_data5.fields[3].value);
2261   EXPECT_EQ(base::string16(), response_data5.fields[4].value);
2262 }
2263
2264 // Test that we can still fill a form when a field has been removed from it.
2265 TEST_F(AutofillManagerTest, FormChangesRemoveField) {
2266   // Set up our form data.
2267   FormData form;
2268   test::CreateTestAddressFormData(&form);
2269
2270   // Add a field -- we'll remove it again later.
2271   FormFieldData field;
2272   test::CreateTestFormField("Some", "field", "", "text", &field);
2273   form.fields.insert(form.fields.begin() + 3, field);
2274
2275   std::vector<FormData> forms(1, form);
2276   FormsSeen(forms);
2277
2278   // Now, after the call to |FormsSeen|, we remove the field before filling.
2279   form.fields.erase(form.fields.begin() + 3);
2280
2281   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2282   GUIDPair empty(std::string(), 0);
2283   int response_page_id = 0;
2284   FormData response_data;
2285   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2286       PackGUIDs(empty, guid), &response_page_id, &response_data);
2287   ExpectFilledAddressFormElvis(
2288       response_page_id, response_data, kDefaultPageID, false);
2289 }
2290
2291 // Test that we can still fill a form when a field has been added to it.
2292 TEST_F(AutofillManagerTest, FormChangesAddField) {
2293   // The offset of the phone field in the address form.
2294   const int kPhoneFieldOffset = 9;
2295
2296   // Set up our form data.
2297   FormData form;
2298   test::CreateTestAddressFormData(&form);
2299
2300   // Remove the phone field -- we'll add it back later.
2301   std::vector<FormFieldData>::iterator pos =
2302       form.fields.begin() + kPhoneFieldOffset;
2303   FormFieldData field = *pos;
2304   pos = form.fields.erase(pos);
2305
2306   std::vector<FormData> forms(1, form);
2307   FormsSeen(forms);
2308
2309   // Now, after the call to |FormsSeen|, we restore the field before filling.
2310   form.fields.insert(pos, field);
2311
2312   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2313   GUIDPair empty(std::string(), 0);
2314   int response_page_id = 0;
2315   FormData response_data;
2316   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2317       PackGUIDs(empty, guid), &response_page_id, &response_data);
2318   ExpectFilledAddressFormElvis(
2319       response_page_id, response_data, kDefaultPageID, false);
2320 }
2321
2322 // Test that we are able to save form data when forms are submitted.
2323 TEST_F(AutofillManagerTest, FormSubmitted) {
2324   // Set up our form data.
2325   FormData form;
2326   test::CreateTestAddressFormData(&form);
2327   std::vector<FormData> forms(1, form);
2328   FormsSeen(forms);
2329
2330   // Fill the form.
2331   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2332   GUIDPair empty(std::string(), 0);
2333   int response_page_id = 0;
2334   FormData response_data;
2335   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2336       PackGUIDs(empty, guid), &response_page_id, &response_data);
2337   ExpectFilledAddressFormElvis(
2338       response_page_id, response_data, kDefaultPageID, false);
2339
2340   // Simulate form submission. We should call into the PDM to try to save the
2341   // filled data.
2342   EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(1);
2343   FormSubmitted(response_data);
2344 }
2345
2346 // Test that when Autocomplete is enabled and Autofill is disabled,
2347 // form submissions are still received by AutocompleteHistoryManager.
2348 TEST_F(AutofillManagerTest, FormSubmittedAutocompleteEnabled) {
2349   TestAutofillClient client;
2350   autofill_manager_.reset(
2351       new TestAutofillManager(autofill_driver_.get(), &client, NULL));
2352   autofill_manager_->set_autofill_enabled(false);
2353   scoped_ptr<MockAutocompleteHistoryManager> autocomplete_history_manager;
2354   autocomplete_history_manager.reset(
2355       new MockAutocompleteHistoryManager(autofill_driver_.get(), &client));
2356   autofill_manager_->autocomplete_history_manager_ =
2357       autocomplete_history_manager.Pass();
2358
2359   // Set up our form data.
2360   FormData form;
2361   test::CreateTestAddressFormData(&form);
2362   MockAutocompleteHistoryManager* m = static_cast<
2363       MockAutocompleteHistoryManager*>(
2364           autofill_manager_->autocomplete_history_manager_.get());
2365   EXPECT_CALL(*m,
2366               OnFormSubmitted(_)).Times(1);
2367   FormSubmitted(form);
2368 }
2369
2370 // Test that when Autocomplete is enabled and Autofill is disabled,
2371 // Autocomplete suggestions are still received.
2372 TEST_F(AutofillManagerTest, AutocompleteSuggestionsWhenAutofillDisabled) {
2373   TestAutofillClient client;
2374   autofill_manager_.reset(
2375       new TestAutofillManager(autofill_driver_.get(), &client, NULL));
2376   autofill_manager_->set_autofill_enabled(false);
2377   autofill_manager_->SetExternalDelegate(external_delegate_.get());
2378
2379   // Set up our form data.
2380   FormData form;
2381   test::CreateTestAddressFormData(&form);
2382   std::vector<FormData> forms(1, form);
2383   FormsSeen(forms);
2384   const FormFieldData& field = form.fields[0];
2385   GetAutofillSuggestions(form, field);
2386
2387   // Add some Autocomplete suggestions. We should return the autocomplete
2388   // suggestions, these will be culled by the renderer.
2389   std::vector<base::string16> suggestions;
2390   suggestions.push_back(ASCIIToUTF16("Jay"));
2391   suggestions.push_back(ASCIIToUTF16("Jason"));
2392   AutocompleteSuggestionsReturned(suggestions);
2393
2394   base::string16 expected_values[] = {
2395     ASCIIToUTF16("Jay"),
2396     ASCIIToUTF16("Jason")
2397   };
2398   base::string16 expected_labels[] = { base::string16(), base::string16()};
2399   base::string16 expected_icons[] = { base::string16(), base::string16()};
2400   int expected_unique_ids[] = {0, 0};
2401   external_delegate_->CheckSuggestions(
2402       kDefaultPageID, arraysize(expected_values), expected_values,
2403       expected_labels, expected_icons, expected_unique_ids);
2404 }
2405
2406 TEST_F(AutofillManagerTest, AutocompleteOffRespected) {
2407   TestAutofillClient client;
2408   autofill_manager_.reset(
2409       new TestAutofillManager(autofill_driver_.get(), &client, NULL));
2410   autofill_manager_->set_autofill_enabled(false);
2411   autofill_manager_->SetExternalDelegate(external_delegate_.get());
2412
2413   scoped_ptr<MockAutocompleteHistoryManager> autocomplete_history_manager;
2414   autocomplete_history_manager.reset(
2415       new MockAutocompleteHistoryManager(autofill_driver_.get(), &client));
2416   autofill_manager_->autocomplete_history_manager_ =
2417       autocomplete_history_manager.Pass();
2418   MockAutocompleteHistoryManager* m = static_cast<
2419       MockAutocompleteHistoryManager*>(
2420           autofill_manager_->autocomplete_history_manager_.get());
2421   EXPECT_CALL(*m,
2422       OnGetAutocompleteSuggestions(_, _, _, _, _, _, _, _)).Times(0);
2423
2424   // Set up our form data.
2425   FormData form;
2426   test::CreateTestAddressFormData(&form);
2427   std::vector<FormData> forms(1, form);
2428   FormsSeen(forms);
2429   FormFieldData* field = &form.fields[0];
2430   field->should_autocomplete = false;
2431   GetAutofillSuggestions(form, *field);
2432 }
2433
2434 // Duplicate of the above test with the ignore-autocomplete-off-autofill switch.
2435 TEST_F(AutofillManagerTest, AutocompleteOffRespectedWithFlag) {
2436   CommandLine::ForCurrentProcess()->AppendSwitch(
2437       switches::kIgnoreAutocompleteOffForAutofill);
2438
2439   TestAutofillClient client;
2440   autofill_manager_.reset(
2441       new TestAutofillManager(autofill_driver_.get(), &client, NULL));
2442   autofill_manager_->set_autofill_enabled(false);
2443   autofill_manager_->SetExternalDelegate(external_delegate_.get());
2444
2445   scoped_ptr<MockAutocompleteHistoryManager> autocomplete_history_manager;
2446   autocomplete_history_manager.reset(
2447       new MockAutocompleteHistoryManager(autofill_driver_.get(), &client));
2448   autofill_manager_->autocomplete_history_manager_ =
2449       autocomplete_history_manager.Pass();
2450   MockAutocompleteHistoryManager* m = static_cast<
2451       MockAutocompleteHistoryManager*>(
2452           autofill_manager_->autocomplete_history_manager_.get());
2453   EXPECT_CALL(*m,
2454       OnGetAutocompleteSuggestions(_, _, _, _, _, _, _, _)).Times(0);
2455
2456   // Set up our form data.
2457   FormData form;
2458   test::CreateTestAddressFormData(&form);
2459   std::vector<FormData> forms(1, form);
2460   FormsSeen(forms);
2461   FormFieldData* field = &form.fields[0];
2462   field->should_autocomplete = false;
2463   GetAutofillSuggestions(form, *field);
2464 }
2465
2466 // Test that we are able to save form data when forms are submitted and we only
2467 // have server data for the field types.
2468 TEST_F(AutofillManagerTest, FormSubmittedServerTypes) {
2469   // Set up our form data.
2470   FormData form;
2471   test::CreateTestAddressFormData(&form);
2472
2473   // Simulate having seen this form on page load.
2474   // |form_structure| will be owned by |autofill_manager_|.
2475   TestFormStructure* form_structure = new TestFormStructure(form);
2476   AutofillMetrics metrics_logger;  // ignored
2477   form_structure->DetermineHeuristicTypes(metrics_logger);
2478
2479   // Clear the heuristic types, and instead set the appropriate server types.
2480   std::vector<ServerFieldType> heuristic_types, server_types;
2481   for (size_t i = 0; i < form.fields.size(); ++i) {
2482     heuristic_types.push_back(UNKNOWN_TYPE);
2483     server_types.push_back(form_structure->field(i)->heuristic_type());
2484   }
2485   form_structure->SetFieldTypes(heuristic_types, server_types);
2486   autofill_manager_->AddSeenForm(form_structure);
2487
2488   // Fill the form.
2489   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2490   GUIDPair empty(std::string(), 0);
2491   int response_page_id = 0;
2492   FormData response_data;
2493   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2494       PackGUIDs(empty, guid), &response_page_id, &response_data);
2495   ExpectFilledAddressFormElvis(
2496       response_page_id, response_data, kDefaultPageID, false);
2497
2498   // Simulate form submission. We should call into the PDM to try to save the
2499   // filled data.
2500   EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(1);
2501   FormSubmitted(response_data);
2502 }
2503
2504 // Test that the form signature for an uploaded form always matches the form
2505 // signature from the query.
2506 TEST_F(AutofillManagerTest, FormSubmittedWithDifferentFields) {
2507   // Set up our form data.
2508   FormData form;
2509   test::CreateTestAddressFormData(&form);
2510   std::vector<FormData> forms(1, form);
2511   FormsSeen(forms);
2512
2513   // Cache the expected form signature.
2514   std::string signature = FormStructure(form).FormSignature();
2515
2516   // Change the structure of the form prior to submission.
2517   // Websites would typically invoke JavaScript either on page load or on form
2518   // submit to achieve this.
2519   form.fields.pop_back();
2520   FormFieldData field = form.fields[3];
2521   form.fields[3] = form.fields[7];
2522   form.fields[7] = field;
2523
2524   // Simulate form submission.
2525   FormSubmitted(form);
2526   EXPECT_EQ(signature, autofill_manager_->GetSubmittedFormSignature());
2527 }
2528
2529 // Test that we do not save form data when submitted fields contain default
2530 // values.
2531 TEST_F(AutofillManagerTest, FormSubmittedWithDefaultValues) {
2532   // Set up our form data.
2533   FormData form;
2534   test::CreateTestAddressFormData(&form);
2535   form.fields[3].value = ASCIIToUTF16("Enter your address");
2536
2537   // Convert the state field to a <select> popup, to make sure that we only
2538   // reject default values for text fields.
2539   ASSERT_TRUE(form.fields[6].name == ASCIIToUTF16("state"));
2540   form.fields[6].form_control_type = "select-one";
2541   form.fields[6].value = ASCIIToUTF16("Tennessee");
2542
2543   std::vector<FormData> forms(1, form);
2544   FormsSeen(forms);
2545
2546   // Fill the form.
2547   GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2548   GUIDPair empty(std::string(), 0);
2549   int response_page_id = 0;
2550   FormData response_data;
2551   FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[3],
2552       PackGUIDs(empty, guid), &response_page_id, &response_data);
2553
2554   // Simulate form submission.  We should call into the PDM to try to save the
2555   // filled data.
2556   EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(1);
2557   FormSubmitted(response_data);
2558
2559   // Set the address field's value back to the default value.
2560   response_data.fields[3].value = ASCIIToUTF16("Enter your address");
2561
2562   // Simulate form submission.  We should not call into the PDM to try to save
2563   // the filled data, since the filled form is effectively missing an address.
2564   EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(0);
2565   FormSubmitted(response_data);
2566 }
2567
2568 // Checks that resetting the auxiliary profile enabled preference does the right
2569 // thing on all platforms.
2570 TEST_F(AutofillManagerTest, AuxiliaryProfilesReset) {
2571   PrefService* prefs = autofill_client_.GetPrefs();
2572 #if defined(OS_MACOSX)
2573   // Auxiliary profiles is implemented on Mac only.
2574   // OSX: This preference exists for legacy reasons. It is no longer used.
2575   ASSERT_TRUE(
2576       prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2577   prefs->SetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled,
2578                     false);
2579   prefs->ClearPref(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled);
2580   ASSERT_TRUE(
2581       prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2582 #else
2583   ASSERT_FALSE(
2584       prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2585   prefs->SetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled, true);
2586   prefs->ClearPref(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled);
2587   ASSERT_FALSE(
2588       prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2589 #endif  // defined(OS_MACOSX)
2590 }
2591
2592 TEST_F(AutofillManagerTest, DeterminePossibleFieldTypesForUpload) {
2593   FormData form;
2594   form.name = ASCIIToUTF16("MyForm");
2595   form.origin = GURL("http://myform.com/form.html");
2596   form.action = GURL("http://myform.com/submit.html");
2597   form.user_submitted = true;
2598
2599   std::vector<ServerFieldTypeSet> expected_types;
2600
2601   // These fields should all match.
2602   FormFieldData field;
2603   ServerFieldTypeSet types;
2604   test::CreateTestFormField("", "1", "Elvis", "text", &field);
2605   types.clear();
2606   types.insert(NAME_FIRST);
2607   form.fields.push_back(field);
2608   expected_types.push_back(types);
2609
2610   test::CreateTestFormField("", "2", "Aaron", "text", &field);
2611   types.clear();
2612   types.insert(NAME_MIDDLE);
2613   form.fields.push_back(field);
2614   expected_types.push_back(types);
2615
2616   test::CreateTestFormField("", "3", "A", "text", &field);
2617   types.clear();
2618   types.insert(NAME_MIDDLE_INITIAL);
2619   form.fields.push_back(field);
2620   expected_types.push_back(types);
2621
2622   test::CreateTestFormField("", "4", "Presley", "text", &field);
2623   types.clear();
2624   types.insert(NAME_LAST);
2625   form.fields.push_back(field);
2626   expected_types.push_back(types);
2627
2628   test::CreateTestFormField("", "5", "Elvis Presley", "text", &field);
2629   types.clear();
2630   types.insert(CREDIT_CARD_NAME);
2631   form.fields.push_back(field);
2632   expected_types.push_back(types);
2633
2634   test::CreateTestFormField("", "6", "Elvis Aaron Presley", "text",
2635                                      &field);
2636   types.clear();
2637   types.insert(NAME_FULL);
2638   form.fields.push_back(field);
2639   expected_types.push_back(types);
2640
2641   test::CreateTestFormField("", "7", "theking@gmail.com", "email",
2642                                      &field);
2643   types.clear();
2644   types.insert(EMAIL_ADDRESS);
2645   form.fields.push_back(field);
2646   expected_types.push_back(types);
2647
2648   test::CreateTestFormField("", "8", "RCA", "text", &field);
2649   types.clear();
2650   types.insert(COMPANY_NAME);
2651   form.fields.push_back(field);
2652   expected_types.push_back(types);
2653
2654   test::CreateTestFormField("", "9", "3734 Elvis Presley Blvd.",
2655                                      "text", &field);
2656   types.clear();
2657   types.insert(ADDRESS_HOME_LINE1);
2658   form.fields.push_back(field);
2659   expected_types.push_back(types);
2660
2661   test::CreateTestFormField("", "10", "Apt. 10", "text", &field);
2662   types.clear();
2663   types.insert(ADDRESS_HOME_LINE2);
2664   form.fields.push_back(field);
2665   expected_types.push_back(types);
2666
2667   test::CreateTestFormField("", "11", "Memphis", "text", &field);
2668   types.clear();
2669   types.insert(ADDRESS_HOME_CITY);
2670   form.fields.push_back(field);
2671   expected_types.push_back(types);
2672
2673   test::CreateTestFormField("", "12", "Tennessee", "text", &field);
2674   types.clear();
2675   types.insert(ADDRESS_HOME_STATE);
2676   form.fields.push_back(field);
2677   expected_types.push_back(types);
2678
2679   test::CreateTestFormField("", "13", "38116", "text", &field);
2680   types.clear();
2681   types.insert(ADDRESS_HOME_ZIP);
2682   form.fields.push_back(field);
2683   expected_types.push_back(types);
2684
2685   test::CreateTestFormField("", "14", "USA", "text", &field);
2686   types.clear();
2687   types.insert(ADDRESS_HOME_COUNTRY);
2688   form.fields.push_back(field);
2689   expected_types.push_back(types);
2690
2691   test::CreateTestFormField("", "15", "United States", "text", &field);
2692   types.clear();
2693   types.insert(ADDRESS_HOME_COUNTRY);
2694   form.fields.push_back(field);
2695   expected_types.push_back(types);
2696
2697   test::CreateTestFormField("", "16", "+1 (234) 567-8901", "text",
2698                                      &field);
2699   types.clear();
2700   types.insert(PHONE_HOME_WHOLE_NUMBER);
2701   form.fields.push_back(field);
2702   expected_types.push_back(types);
2703
2704   test::CreateTestFormField("", "17", "2345678901", "text", &field);
2705   types.clear();
2706   types.insert(PHONE_HOME_CITY_AND_NUMBER);
2707   form.fields.push_back(field);
2708   expected_types.push_back(types);
2709
2710   test::CreateTestFormField("", "18", "1", "text", &field);
2711   types.clear();
2712   types.insert(PHONE_HOME_COUNTRY_CODE);
2713   form.fields.push_back(field);
2714   expected_types.push_back(types);
2715
2716   test::CreateTestFormField("", "19", "234", "text", &field);
2717   types.clear();
2718   types.insert(PHONE_HOME_CITY_CODE);
2719   form.fields.push_back(field);
2720   expected_types.push_back(types);
2721
2722   test::CreateTestFormField("", "20", "5678901", "text", &field);
2723   types.clear();
2724   types.insert(PHONE_HOME_NUMBER);
2725   form.fields.push_back(field);
2726   expected_types.push_back(types);
2727
2728   test::CreateTestFormField("", "21", "567", "text", &field);
2729   types.clear();
2730   types.insert(PHONE_HOME_NUMBER);
2731   form.fields.push_back(field);
2732   expected_types.push_back(types);
2733
2734   test::CreateTestFormField("", "22", "8901", "text", &field);
2735   types.clear();
2736   types.insert(PHONE_HOME_NUMBER);
2737   form.fields.push_back(field);
2738   expected_types.push_back(types);
2739
2740   test::CreateTestFormField("", "23", "4234-5678-9012-3456", "text",
2741                                      &field);
2742   types.clear();
2743   types.insert(CREDIT_CARD_NUMBER);
2744   form.fields.push_back(field);
2745   expected_types.push_back(types);
2746
2747   test::CreateTestFormField("", "24", "04", "text", &field);
2748   types.clear();
2749   types.insert(CREDIT_CARD_EXP_MONTH);
2750   form.fields.push_back(field);
2751   expected_types.push_back(types);
2752
2753   test::CreateTestFormField("", "25", "April", "text", &field);
2754   types.clear();
2755   types.insert(CREDIT_CARD_EXP_MONTH);
2756   form.fields.push_back(field);
2757   expected_types.push_back(types);
2758
2759   test::CreateTestFormField("", "26", "2012", "text", &field);
2760   types.clear();
2761   types.insert(CREDIT_CARD_EXP_4_DIGIT_YEAR);
2762   form.fields.push_back(field);
2763   expected_types.push_back(types);
2764
2765   test::CreateTestFormField("", "27", "12", "text", &field);
2766   types.clear();
2767   types.insert(CREDIT_CARD_EXP_2_DIGIT_YEAR);
2768   form.fields.push_back(field);
2769   expected_types.push_back(types);
2770
2771   test::CreateTestFormField("", "28", "04/2012", "text", &field);
2772   types.clear();
2773   types.insert(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR);
2774   form.fields.push_back(field);
2775   expected_types.push_back(types);
2776
2777   // Make sure that we trim whitespace properly.
2778   test::CreateTestFormField("", "29", "", "text", &field);
2779   types.clear();
2780   types.insert(EMPTY_TYPE);
2781   form.fields.push_back(field);
2782   expected_types.push_back(types);
2783
2784   test::CreateTestFormField("", "30", " ", "text", &field);
2785   types.clear();
2786   types.insert(EMPTY_TYPE);
2787   form.fields.push_back(field);
2788   expected_types.push_back(types);
2789
2790   test::CreateTestFormField("", "31", " Elvis", "text", &field);
2791   types.clear();
2792   types.insert(NAME_FIRST);
2793   form.fields.push_back(field);
2794   expected_types.push_back(types);
2795
2796   test::CreateTestFormField("", "32", "Elvis ", "text", &field);
2797   types.clear();
2798   types.insert(NAME_FIRST);
2799   form.fields.push_back(field);
2800   expected_types.push_back(types);
2801
2802   // These fields should not match, as they differ by case.
2803   test::CreateTestFormField("", "33", "elvis", "text", &field);
2804   types.clear();
2805   types.insert(UNKNOWN_TYPE);
2806   form.fields.push_back(field);
2807   expected_types.push_back(types);
2808
2809   test::CreateTestFormField("", "34", "3734 Elvis Presley BLVD",
2810                                      "text", &field);
2811   types.clear();
2812   types.insert(UNKNOWN_TYPE);
2813   form.fields.push_back(field);
2814   expected_types.push_back(types);
2815
2816   // These fields should not match, as they are unsupported variants.
2817   test::CreateTestFormField("", "35", "Elvis Aaron", "text", &field);
2818   types.clear();
2819   types.insert(UNKNOWN_TYPE);
2820   form.fields.push_back(field);
2821   expected_types.push_back(types);
2822
2823   test::CreateTestFormField("", "36", "Mr. Presley", "text", &field);
2824   types.clear();
2825   types.insert(UNKNOWN_TYPE);
2826   form.fields.push_back(field);
2827   expected_types.push_back(types);
2828
2829   test::CreateTestFormField("", "37", "3734 Elvis Presley", "text",
2830                                      &field);
2831   types.clear();
2832   types.insert(UNKNOWN_TYPE);
2833   form.fields.push_back(field);
2834   expected_types.push_back(types);
2835
2836   test::CreateTestFormField("", "38", "TN", "text", &field);
2837   types.clear();
2838   types.insert(UNKNOWN_TYPE);
2839   form.fields.push_back(field);
2840   expected_types.push_back(types);
2841
2842   test::CreateTestFormField("", "39", "38116-1023", "text", &field);
2843   types.clear();
2844   types.insert(UNKNOWN_TYPE);
2845   form.fields.push_back(field);
2846   expected_types.push_back(types);
2847
2848   test::CreateTestFormField("", "20", "5", "text", &field);
2849   types.clear();
2850   types.insert(UNKNOWN_TYPE);
2851   form.fields.push_back(field);
2852   expected_types.push_back(types);
2853
2854   test::CreateTestFormField("", "20", "56", "text", &field);
2855   types.clear();
2856   types.insert(UNKNOWN_TYPE);
2857   form.fields.push_back(field);
2858   expected_types.push_back(types);
2859
2860   test::CreateTestFormField("", "20", "901", "text", &field);
2861   types.clear();
2862   types.insert(UNKNOWN_TYPE);
2863   form.fields.push_back(field);
2864   expected_types.push_back(types);
2865
2866   test::CreateTestFormField("", "40", "mypassword", "password", &field);
2867   types.clear();
2868   types.insert(PASSWORD);
2869   form.fields.push_back(field);
2870   expected_types.push_back(types);
2871
2872   autofill_manager_->set_expected_submitted_field_types(expected_types);
2873   FormSubmitted(form);
2874 }
2875
2876 TEST_F(AutofillManagerTest, RemoveProfile) {
2877   // Add and remove an Autofill profile.
2878   AutofillProfile* profile = new AutofillProfile;
2879   std::string guid = "00000000-0000-0000-0000-000000000102";
2880   profile->set_guid(guid.c_str());
2881   autofill_manager_->AddProfile(profile);
2882
2883   GUIDPair guid_pair(guid, 0);
2884   GUIDPair empty(std::string(), 0);
2885   int id = PackGUIDs(empty, guid_pair);
2886
2887   autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
2888
2889   EXPECT_FALSE(autofill_manager_->GetProfileWithGUID(guid.c_str()));
2890 }
2891
2892 TEST_F(AutofillManagerTest, RemoveCreditCard){
2893   // Add and remove an Autofill credit card.
2894   CreditCard* credit_card = new CreditCard;
2895   std::string guid = "00000000-0000-0000-0000-000000100007";
2896   credit_card->set_guid(guid.c_str());
2897   autofill_manager_->AddCreditCard(credit_card);
2898
2899   GUIDPair guid_pair(guid, 0);
2900   GUIDPair empty(std::string(), 0);
2901   int id = PackGUIDs(guid_pair, empty);
2902
2903   autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
2904
2905   EXPECT_FALSE(autofill_manager_->GetCreditCardWithGUID(guid.c_str()));
2906 }
2907
2908 TEST_F(AutofillManagerTest, RemoveProfileVariant) {
2909   // Add and remove an Autofill profile.
2910   AutofillProfile* profile = new AutofillProfile;
2911   std::string guid = "00000000-0000-0000-0000-000000000102";
2912   profile->set_guid(guid.c_str());
2913   autofill_manager_->AddProfile(profile);
2914
2915   GUIDPair guid_pair(guid, 1);
2916   GUIDPair empty(std::string(), 0);
2917   int id = PackGUIDs(empty, guid_pair);
2918
2919   autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
2920
2921   // TODO(csharp): Currently variants should not be deleted, but once they are
2922   // update these expectations.
2923   // http://crbug.com/124211
2924   EXPECT_TRUE(autofill_manager_->GetProfileWithGUID(guid.c_str()));
2925 }
2926
2927 #if defined(OS_MACOSX) && !defined(OS_IOS)
2928 TEST_F(AutofillManagerTest, AccessAddressBookPrompt) {
2929   FormData form;
2930   test::CreateTestAddressFormData(&form);
2931   std::vector<FormData> forms(1, form);
2932   FormsSeen(forms);
2933   FormFieldData& field = form.fields[0];
2934   field.should_autocomplete = true;
2935
2936   // A profile already exists.
2937   EXPECT_FALSE(
2938       autofill_manager_->ShouldShowAccessAddressBookSuggestion(form, field));
2939
2940   // Remove all profiles.
2941   personal_data_.ClearAutofillProfiles();
2942   EXPECT_TRUE(
2943       autofill_manager_->ShouldShowAccessAddressBookSuggestion(form, field));
2944
2945   field.should_autocomplete = false;
2946   EXPECT_FALSE(
2947       autofill_manager_->ShouldShowAccessAddressBookSuggestion(form, field));
2948 }
2949 #endif  // defined(OS_MACOSX) && !defined(OS_IOS)
2950
2951 namespace {
2952
2953 class MockAutofillClient : public TestAutofillClient {
2954  public:
2955   MockAutofillClient() {}
2956
2957   ~MockAutofillClient() override {}
2958
2959   void ShowRequestAutocompleteDialog(const FormData& form,
2960                                      const GURL& source_url,
2961                                      const ResultCallback& callback) override {
2962     callback.Run(user_supplied_data_ ? AutocompleteResultSuccess :
2963                                        AutocompleteResultErrorDisabled,
2964                  base::string16(),
2965                  user_supplied_data_.get());
2966   }
2967
2968   void SetUserSuppliedData(scoped_ptr<FormStructure> user_supplied_data) {
2969     user_supplied_data_.reset(user_supplied_data.release());
2970   }
2971
2972  private:
2973   scoped_ptr<FormStructure> user_supplied_data_;
2974
2975   DISALLOW_COPY_AND_ASSIGN(MockAutofillClient);
2976 };
2977
2978 }  // namespace
2979
2980 // Test our external delegate is called at the right time.
2981 TEST_F(AutofillManagerTest, TestExternalDelegate) {
2982   FormData form;
2983   test::CreateTestAddressFormData(&form);
2984   std::vector<FormData> forms(1, form);
2985   FormsSeen(forms);
2986   const FormFieldData& field = form.fields[0];
2987   GetAutofillSuggestions(form, field);  // should call the delegate's OnQuery()
2988
2989   EXPECT_TRUE(external_delegate_->on_query_seen());
2990 }
2991
2992 // Test to verify suggestions appears for forms having credit card number split
2993 // across fields.
2994 TEST_F(AutofillManagerTest, GetCreditCardSuggestionsForNumberSpitAcrossFields) {
2995   // Set up our form data with credit card number split across fields.
2996   FormData form;
2997   form.name = ASCIIToUTF16("MyForm");
2998   form.origin = GURL("https://myform.com/form.html");
2999   form.action = GURL("https://myform.com/submit.html");
3000   form.user_submitted = true;
3001
3002   FormFieldData name_field;
3003   test::CreateTestFormField("Name on Card", "nameoncard", "", "text",
3004                             &name_field);
3005   form.fields.push_back(name_field);
3006
3007   // Add new 4 |card_number_field|s to the |form|.
3008   FormFieldData card_number_field;
3009   card_number_field.max_length = 4;
3010   test::CreateTestFormField("Card Number", "cardnumber_1", "", "text",
3011                             &card_number_field);
3012   form.fields.push_back(card_number_field);
3013
3014   test::CreateTestFormField("", "cardnumber_2", "", "text", &card_number_field);
3015   form.fields.push_back(card_number_field);
3016
3017   test::CreateTestFormField("", "cardnumber_3", "", "text", &card_number_field);
3018   form.fields.push_back(card_number_field);
3019
3020   test::CreateTestFormField("", "cardnumber_4", "", "text", &card_number_field);
3021   form.fields.push_back(card_number_field);
3022
3023   FormFieldData exp_field;
3024   test::CreateTestFormField("Expiration Date", "ccmonth", "", "text",
3025                             &exp_field);
3026   form.fields.push_back(exp_field);
3027
3028   test::CreateTestFormField("", "ccyear", "", "text", &exp_field);
3029   form.fields.push_back(exp_field);
3030
3031   std::vector<FormData> forms(1, form);
3032   FormsSeen(forms);
3033
3034   // Verify whether suggestions are populated correctly for one of the middle
3035   // credit card number fields when filled partially.
3036   FormFieldData number_field = form.fields[3];
3037   number_field.value = ASCIIToUTF16("901");
3038
3039   // Get the suggestions for already filled credit card |number_field|.
3040   GetAutofillSuggestions(form, number_field);
3041
3042   // No autocomplete suggestions provided, so send an empty vector as the
3043   // results. This triggers the combined message send.
3044   AutocompleteSuggestionsReturned(std::vector<base::string16>());
3045
3046   base::string16 expected_values[] = {ASCIIToUTF16("************3456")};
3047   base::string16 expected_labels[] = {ASCIIToUTF16("04/12")};
3048   base::string16 expected_icons[] = {ASCIIToUTF16(kVisaCard)};
3049   int expected_unique_ids[] = {autofill_manager_->GetPackedCreditCardID(4)};
3050   external_delegate_->CheckSuggestions(
3051       kDefaultPageID, arraysize(expected_values), expected_values,
3052       expected_labels, expected_icons, expected_unique_ids);
3053 }
3054
3055 }  // namespace autofill