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