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