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