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