autofill_manager_unittest.cc revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
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, void(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  void set_autocheckout_url_prefix(const std::string& autocheckout_url_prefix) {
483    autocheckout_url_prefix_ = autocheckout_url_prefix;
484  }
485
486  virtual std::string GetAutocheckoutURLPrefix() const OVERRIDE {
487    return autocheckout_url_prefix_;
488  }
489
490  const std::vector<std::pair<WebFormElement::AutocompleteResult, FormData> >&
491      request_autocomplete_results() const {
492    return request_autocomplete_results_;
493  }
494
495
496  void set_expected_submitted_field_types(
497      const std::vector<FieldTypeSet>& expected_types) {
498    expected_submitted_field_types_ = expected_types;
499  }
500
501  virtual void UploadFormDataAsyncCallback(
502      const FormStructure* submitted_form,
503      const base::TimeTicks& load_time,
504      const base::TimeTicks& interaction_time,
505      const base::TimeTicks& submission_time) OVERRIDE {
506    message_loop_runner_->Quit();
507
508    // If we have expected field types set, make sure they match.
509    if (!expected_submitted_field_types_.empty()) {
510      ASSERT_EQ(expected_submitted_field_types_.size(),
511                submitted_form->field_count());
512      for (size_t i = 0; i < expected_submitted_field_types_.size(); ++i) {
513        SCOPED_TRACE(
514            base::StringPrintf(
515                "Field %d with value %s", static_cast<int>(i),
516                UTF16ToUTF8(submitted_form->field(i)->value).c_str()));
517        const FieldTypeSet& possible_types =
518            submitted_form->field(i)->possible_types();
519        EXPECT_EQ(expected_submitted_field_types_[i].size(),
520                  possible_types.size());
521        for (FieldTypeSet::const_iterator it =
522                 expected_submitted_field_types_[i].begin();
523             it != expected_submitted_field_types_[i].end(); ++it) {
524          EXPECT_TRUE(possible_types.count(*it))
525              << "Expected type: " << AutofillType::FieldTypeToString(*it);
526        }
527      }
528    }
529
530    AutofillManager::UploadFormDataAsyncCallback(submitted_form,
531                                                 load_time,
532                                                 interaction_time,
533                                                 submission_time);
534  }
535
536  virtual void OnMaybeShowAutocheckoutBubble(
537      const FormData& form,
538      const gfx::RectF& bounding_box) OVERRIDE {
539    AutofillManager::OnMaybeShowAutocheckoutBubble(form, bounding_box);
540    // Needed for AutocheckoutManager to post task on IO thread.
541    content::RunAllPendingInMessageLoop(content::BrowserThread::IO);
542  }
543
544  // Resets the MessageLoopRunner so that it can wait for an asynchronous form
545  // submission to complete.
546  void ResetMessageLoopRunner() {
547    message_loop_runner_ = new content::MessageLoopRunner();
548  }
549
550  // Wait for the asynchronous OnFormSubmitted() call to complete.
551  void WaitForAsyncFormSubmit() {
552    message_loop_runner_->Run();
553  }
554
555  virtual void UploadFormData(const FormStructure& submitted_form) OVERRIDE {
556    submitted_form_signature_ = submitted_form.FormSignature();
557  }
558
559  const std::string GetSubmittedFormSignature() {
560    return submitted_form_signature_;
561  }
562
563  AutofillProfile* GetProfileWithGUID(const char* guid) {
564    return personal_data_->GetProfileWithGUID(guid);
565  }
566
567  CreditCard* GetCreditCardWithGUID(const char* guid) {
568    return personal_data_->GetCreditCardWithGUID(guid);
569  }
570
571  void AddProfile(AutofillProfile* profile) {
572    personal_data_->AddProfile(profile);
573  }
574
575  void AddCreditCard(CreditCard* credit_card) {
576    personal_data_->AddCreditCard(credit_card);
577  }
578
579  int GetPackedCreditCardID(int credit_card_id) {
580    std::string credit_card_guid =
581        base::StringPrintf("00000000-0000-0000-0000-%012d", credit_card_id);
582
583    return PackGUIDs(GUIDPair(credit_card_guid, 0), GUIDPair(std::string(), 0));
584  }
585
586  void AddSeenForm(FormStructure* form) {
587    form_structures()->push_back(form);
588  }
589
590  void ClearFormStructures() {
591    form_structures()->clear();
592  }
593
594  virtual void ReturnAutocompleteResult(
595      WebFormElement::AutocompleteResult result,
596      const FormData& form_data) OVERRIDE {
597    request_autocomplete_results_.push_back(std::make_pair(result, form_data));
598  }
599
600  // Set autocheckout manager's page meta data to first page on Autocheckout
601  // flow.
602  void MarkAsFirstPageInAutocheckoutFlow() {
603    scoped_ptr<AutocheckoutPageMetaData> start_of_flow(
604        new AutocheckoutPageMetaData());
605    start_of_flow->current_page_number = 0;
606    start_of_flow->total_pages = 3;
607    WebElementDescriptor* proceed_element =
608        &start_of_flow->proceed_element_descriptor;
609    proceed_element->descriptor = "#foo";
610    proceed_element->retrieval_method = WebElementDescriptor::ID;
611    autocheckout_manager()->OnLoadedPageMetaData(start_of_flow.Pass());
612  }
613
614  // Set autocheckout manager's page meta data to first page on Autocheckout
615  // flow.
616  void MarkAsFirstPageInAutocheckoutFlowIgnoringAjax() {
617    scoped_ptr<AutocheckoutPageMetaData> start_of_flow(
618        new AutocheckoutPageMetaData());
619    start_of_flow->current_page_number = 0;
620    start_of_flow->total_pages = 3;
621    start_of_flow->ignore_ajax = true;
622    WebElementDescriptor* proceed_element =
623        &start_of_flow->proceed_element_descriptor;
624    proceed_element->descriptor = "#foo";
625    proceed_element->retrieval_method = WebElementDescriptor::ID;
626    autocheckout_manager()->OnLoadedPageMetaData(start_of_flow.Pass());
627  }
628
629 private:
630  // Weak reference.
631  TestPersonalDataManager* personal_data_;
632
633  bool autofill_enabled_;
634  std::vector<std::pair<WebFormElement::AutocompleteResult, FormData> >
635      request_autocomplete_results_;
636
637  scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
638
639  std::string autocheckout_url_prefix_;
640  std::string submitted_form_signature_;
641  std::vector<FieldTypeSet> expected_submitted_field_types_;
642
643  DISALLOW_COPY_AND_ASSIGN(TestAutofillManager);
644};
645
646class TestAutofillExternalDelegate : public AutofillExternalDelegate {
647 public:
648  explicit TestAutofillExternalDelegate(content::WebContents* web_contents,
649                                        AutofillManager* autofill_manager,
650                                        AutofillDriver* autofill_driver)
651      : AutofillExternalDelegate(web_contents, autofill_manager,
652                                 autofill_driver),
653        on_query_seen_(false),
654        on_suggestions_returned_seen_(false) {}
655  virtual ~TestAutofillExternalDelegate() {}
656
657  virtual void OnQuery(int query_id,
658                       const FormData& form,
659                       const FormFieldData& field,
660                       const gfx::RectF& bounds,
661                       bool display_warning) OVERRIDE {
662    on_query_seen_ = true;
663    on_suggestions_returned_seen_ = false;
664  }
665
666  virtual void OnSuggestionsReturned(
667      int query_id,
668      const std::vector<base::string16>& autofill_values,
669      const std::vector<base::string16>& autofill_labels,
670      const std::vector<base::string16>& autofill_icons,
671      const std::vector<int>& autofill_unique_ids) OVERRIDE {
672    on_suggestions_returned_seen_ = true;
673
674    query_id_ = query_id;
675    autofill_values_ = autofill_values;
676    autofill_labels_ = autofill_labels;
677    autofill_icons_ = autofill_icons;
678    autofill_unique_ids_ = autofill_unique_ids;
679  }
680
681  void CheckSuggestions(int expected_page_id,
682                        size_t expected_num_suggestions,
683                        const base::string16 expected_values[],
684                        const base::string16 expected_labels[],
685                        const base::string16 expected_icons[],
686                        const int expected_unique_ids[]) {
687    // Ensure that these results are from the most recent query.
688    EXPECT_TRUE(on_suggestions_returned_seen_);
689
690    EXPECT_EQ(expected_page_id, query_id_);
691    ASSERT_EQ(expected_num_suggestions, autofill_values_.size());
692    ASSERT_EQ(expected_num_suggestions, autofill_labels_.size());
693    ASSERT_EQ(expected_num_suggestions, autofill_icons_.size());
694    ASSERT_EQ(expected_num_suggestions, autofill_unique_ids_.size());
695    for (size_t i = 0; i < expected_num_suggestions; ++i) {
696      SCOPED_TRACE(base::StringPrintf("i: %" PRIuS, i));
697      EXPECT_EQ(expected_values[i], autofill_values_[i]);
698      EXPECT_EQ(expected_labels[i], autofill_labels_[i]);
699      EXPECT_EQ(expected_icons[i], autofill_icons_[i]);
700      EXPECT_EQ(expected_unique_ids[i], autofill_unique_ids_[i]);
701    }
702  }
703
704  bool on_query_seen() const {
705    return on_query_seen_;
706  }
707
708  bool on_suggestions_returned_seen() const {
709    return on_suggestions_returned_seen_;
710  }
711
712 private:
713  // Records if OnQuery has been called yet.
714  bool on_query_seen_;
715
716  // Records if OnSuggestionsReturned has been called after the most recent
717  // call to OnQuery.
718  bool on_suggestions_returned_seen_;
719
720  // The query id of the most recent Autofill query.
721  int query_id_;
722
723  // The results returned by the most recent Autofill query.
724  std::vector<base::string16> autofill_values_;
725  std::vector<base::string16> autofill_labels_;
726  std::vector<base::string16> autofill_icons_;
727  std::vector<int> autofill_unique_ids_;
728
729  DISALLOW_COPY_AND_ASSIGN(TestAutofillExternalDelegate);
730};
731
732}  // namespace
733
734class AutofillManagerTest : public ChromeRenderViewHostTestHarness {
735 public:
736  virtual void SetUp() OVERRIDE {
737    ChromeRenderViewHostTestHarness::SetUp();
738
739    autofill::PersonalDataManagerFactory::GetInstance()->SetTestingFactory(
740        profile(), TestPersonalDataManager::Build);
741
742
743    autofill::TabAutofillManagerDelegate::CreateForWebContents(web_contents());
744
745    personal_data_.SetBrowserContext(profile());
746    autofill_driver_.reset(new MockAutofillDriver(web_contents()));
747    autofill_manager_.reset(new TestAutofillManager(
748        autofill_driver_.get(),
749        autofill::TabAutofillManagerDelegate::FromWebContents(web_contents()),
750        &personal_data_));
751
752    external_delegate_.reset(new TestAutofillExternalDelegate(
753        web_contents(),
754        autofill_manager_.get(),
755        autofill_driver_.get()));
756    autofill_manager_->SetExternalDelegate(external_delegate_.get());
757  }
758
759  virtual void TearDown() OVERRIDE {
760    // Order of destruction is important as AutofillManager relies on
761    // PersonalDataManager to be around when it gets destroyed. Also, a real
762    // AutofillManager is tied to the lifetime of the WebContents, so it must
763    // be destroyed at the destruction of the WebContents.
764    autofill_manager_.reset();
765    autofill_driver_.reset();
766    ChromeRenderViewHostTestHarness::TearDown();
767
768    // Remove the BrowserContext so TestPersonalDataManager does not need to
769    // care about removing self as an observer in destruction.
770    personal_data_.SetBrowserContext(NULL);
771  }
772
773  virtual content::BrowserContext* CreateBrowserContext() OVERRIDE {
774    TestingProfile* profile = new TestingProfile();
775    profile->CreateRequestContext();
776    return profile;
777  }
778
779  void GetAutofillSuggestions(int query_id,
780                              const FormData& form,
781                              const FormFieldData& field) {
782    autofill_manager_->OnQueryFormFieldAutofill(query_id,
783                                                form,
784                                                field,
785                                                gfx::Rect(),
786                                                false);
787  }
788
789  void GetAutofillSuggestions(const FormData& form,
790                              const FormFieldData& field) {
791    GetAutofillSuggestions(kDefaultPageID, form, field);
792  }
793
794  void AutocompleteSuggestionsReturned(
795      const std::vector<base::string16>& result) {
796    autofill_manager_->autocomplete_history_manager_->SendSuggestions(&result);
797  }
798
799  void FormsSeen(const std::vector<FormData>& forms) {
800    autofill_manager_->OnFormsSeen(forms, base::TimeTicks(),
801                                   autofill::NO_SPECIAL_FORMS_SEEN);
802  }
803
804  void PartialFormsSeen(const std::vector<FormData>& forms) {
805    autofill_manager_->OnFormsSeen(forms, base::TimeTicks(),
806                                   autofill::PARTIAL_FORMS_SEEN);
807  }
808
809  void DynamicFormsSeen(const std::vector<FormData>& forms) {
810    autofill_manager_->OnFormsSeen(forms, base::TimeTicks(),
811                                   autofill::DYNAMIC_FORMS_SEEN);
812  }
813
814  void FormSubmitted(const FormData& form) {
815    autofill_manager_->ResetMessageLoopRunner();
816    if (autofill_manager_->OnFormSubmitted(form, base::TimeTicks::Now()))
817      autofill_manager_->WaitForAsyncFormSubmit();
818  }
819
820  void FillAutofillFormData(int query_id,
821                            const FormData& form,
822                            const FormFieldData& field,
823                            int unique_id) {
824    autofill_manager_->OnFillAutofillFormData(query_id, form, field, unique_id);
825  }
826
827  // Calls |autofill_manager_->OnFillAutofillFormData()| with the specified
828  // input parameters after setting up the expectation that the mock driver's
829  // |SendFormDataToRenderer()| method will be called and saving the parameters
830  // of that call into the |response_query_id| and |response_data| output
831  // parameters.
832  void FillAutofillFormDataAndSaveResults(int input_query_id,
833                                          const FormData& input_form,
834                                          const FormFieldData& input_field,
835                                          int unique_id,
836                                          int* response_query_id,
837                                          FormData* response_data) {
838    EXPECT_CALL(*autofill_driver_, SendFormDataToRenderer(_, _)).
839        WillOnce((DoAll(testing::SaveArg<0>(response_query_id),
840                        testing::SaveArg<1>(response_data))));
841    FillAutofillFormData(input_query_id, input_form, input_field, unique_id);
842  }
843
844  int PackGUIDs(const GUIDPair& cc_guid, const GUIDPair& profile_guid) const {
845    return autofill_manager_->PackGUIDs(cc_guid, profile_guid);
846  }
847
848
849  bool HasSeenAutofillGetAllFormsMessage() {
850    const uint32 kMsgID = AutofillMsg_GetAllForms::ID;
851    const IPC::Message* message =
852        process()->sink().GetFirstMessageMatching(kMsgID);
853    return message != NULL;
854  }
855
856 protected:
857  scoped_ptr<MockAutofillDriver> autofill_driver_;
858  scoped_ptr<TestAutofillManager> autofill_manager_;
859  scoped_ptr<TestAutofillExternalDelegate> external_delegate_;
860  TestPersonalDataManager personal_data_;
861
862  // Used when we want an off the record profile. This will store the original
863  // profile from which the off the record profile is derived.
864  scoped_ptr<Profile> other_browser_context_;
865};
866
867class TestFormStructure : public FormStructure {
868 public:
869  explicit TestFormStructure(const FormData& form)
870      : FormStructure(form, std::string()) {}
871  virtual ~TestFormStructure() {}
872
873  void SetFieldTypes(const std::vector<AutofillFieldType>& heuristic_types,
874                     const std::vector<AutofillFieldType>& server_types) {
875    ASSERT_EQ(field_count(), heuristic_types.size());
876    ASSERT_EQ(field_count(), server_types.size());
877
878    for (size_t i = 0; i < field_count(); ++i) {
879      AutofillField* form_field = field(i);
880      ASSERT_TRUE(form_field);
881      form_field->set_heuristic_type(heuristic_types[i]);
882      form_field->set_server_type(server_types[i]);
883    }
884
885    UpdateAutofillCount();
886  }
887
888 private:
889  DISALLOW_COPY_AND_ASSIGN(TestFormStructure);
890};
891
892// Test that browser asks for all forms when Autocheckout is enabled.
893TEST_F(AutofillManagerTest, GetAllForms) {
894  FormData form;
895  test::CreateTestAddressFormData(&form);
896  std::vector<FormData> forms(1, form);
897  // Enable autocheckout.
898  autofill_manager_->set_autocheckout_url_prefix("test-prefix");
899
900  PartialFormsSeen(forms);
901
902  ASSERT_TRUE(HasSeenAutofillGetAllFormsMessage());
903}
904
905// Test that we return all address profile suggestions when all form fields are
906// empty.
907TEST_F(AutofillManagerTest, GetProfileSuggestionsEmptyValue) {
908  // Set up our form data.
909  FormData form;
910  test::CreateTestAddressFormData(&form);
911  std::vector<FormData> forms(1, form);
912  FormsSeen(forms);
913
914  const FormFieldData& field = form.fields[0];
915  GetAutofillSuggestions(form, field);
916
917  // No suggestions provided, so send an empty vector as the results.
918  // This triggers the combined message send.
919  AutocompleteSuggestionsReturned(std::vector<base::string16>());
920
921  // Test that we sent the right values to the external delegate.
922  base::string16 expected_values[] = {
923    ASCIIToUTF16("Elvis"),
924    ASCIIToUTF16("Charles")
925  };
926  // Inferred labels include full first relevant field, which in this case is
927  // the address line 1.
928  base::string16 expected_labels[] = {
929    ASCIIToUTF16("3734 Elvis Presley Blvd."),
930    ASCIIToUTF16("123 Apple St.")
931  };
932  base::string16 expected_icons[] = {base::string16(), base::string16()};
933  int expected_unique_ids[] = {1, 2};
934  external_delegate_->CheckSuggestions(
935      kDefaultPageID, arraysize(expected_values), expected_values,
936      expected_labels, expected_icons, expected_unique_ids);
937}
938
939// Test that in the case of Autocheckout, forms seen are in order supplied.
940TEST_F(AutofillManagerTest, AutocheckoutFormsSeen) {
941  FormData shipping_options;
942  CreateTestShippingOptionsFormData(&shipping_options);
943  FormData user_supplied;
944  CreateTestFormWithAutocompleteAttribute(&user_supplied);
945  FormData address;
946  test::CreateTestAddressFormData(&address);
947
948  // Push user_supplied before address and observe order changing when
949  // Autocheckout is not enabled..
950  std::vector<FormData> forms;
951  forms.push_back(shipping_options);
952  forms.push_back(user_supplied);
953  forms.push_back(address);
954
955  // Test without enabling Autocheckout. FormStructure should only contain
956  // form1. Shipping Options form will not qualify as parsable form.
957  FormsSeen(forms);
958  std::vector<FormStructure*> form_structures;
959  form_structures = autofill_manager_->GetFormStructures();
960  ASSERT_EQ(2U, form_structures.size());
961  EXPECT_EQ("/form.html", form_structures[0]->source_url().path());
962  EXPECT_EQ("/userspecified.html", form_structures[1]->source_url().path());
963  autofill_manager_->ClearFormStructures();
964
965  // Test after enabling Autocheckout. Order should be shipping_options,
966  // userspecified and then address form.
967  autofill_manager_->set_autocheckout_url_prefix("yes-autocheckout");
968  FormsSeen(forms);
969  form_structures = autofill_manager_->GetFormStructures();
970  ASSERT_EQ(3U, form_structures.size());
971  EXPECT_EQ("/shipping.html", form_structures[0]->source_url().path());
972  EXPECT_EQ("/userspecified.html", form_structures[1]->source_url().path());
973  EXPECT_EQ("/form.html", form_structures[2]->source_url().path());
974}
975
976// Test that in the case of Autocheckout, forms seen are in order supplied.
977TEST_F(AutofillManagerTest, DynamicFormsSeen) {
978  FormData shipping_options;
979  CreateTestShippingOptionsFormData(&shipping_options);
980  FormData user_supplied;
981  CreateTestFormWithAutocompleteAttribute(&user_supplied);
982  FormData address;
983  test::CreateTestAddressFormData(&address);
984
985  autofill_manager_->set_autocheckout_url_prefix("test-prefix");
986  // Push user_supplied only
987  std::vector<FormData> forms;
988  forms.push_back(user_supplied);
989
990  // Make sure normal form is handled correctly.
991  FormsSeen(forms);
992  std::vector<FormStructure*> form_structures;
993  form_structures = autofill_manager_->GetFormStructures();
994  ASSERT_EQ(1U, form_structures.size());
995  EXPECT_EQ("/userspecified.html", form_structures[0]->source_url().path());
996
997  // Push other forms
998  forms.push_back(shipping_options);
999  forms.push_back(address);
1000
1001  // FormStructure should contain three and only three forms. Otherwise, it
1002  // would indicate that the manager didn't reset upon being notified of
1003  // the new forms;
1004  DynamicFormsSeen(forms);
1005  form_structures = autofill_manager_->GetFormStructures();
1006  ASSERT_EQ(3U, form_structures.size());
1007  EXPECT_EQ("/userspecified.html", form_structures[0]->source_url().path());
1008  EXPECT_EQ("/shipping.html", form_structures[1]->source_url().path());
1009  EXPECT_EQ("/form.html", form_structures[2]->source_url().path());
1010}
1011
1012// Test that we return only matching address profile suggestions when the
1013// selected form field has been partially filled out.
1014TEST_F(AutofillManagerTest, GetProfileSuggestionsMatchCharacter) {
1015  // Set up our form data.
1016  FormData form;
1017  test::CreateTestAddressFormData(&form);
1018  std::vector<FormData> forms(1, form);
1019  FormsSeen(forms);
1020
1021  FormFieldData field;
1022  test::CreateTestFormField("First Name", "firstname", "E", "text",&field);
1023  GetAutofillSuggestions(form, field);
1024
1025  // No suggestions provided, so send an empty vector as the results.
1026  // This triggers the combined message send.
1027  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1028
1029  // Test that we sent the right values to the external delegate.
1030  base::string16 expected_values[] = {ASCIIToUTF16("Elvis")};
1031  base::string16 expected_labels[] = {ASCIIToUTF16("3734 Elvis Presley Blvd.")};
1032  base::string16 expected_icons[] = {base::string16()};
1033  int expected_unique_ids[] = {1};
1034  external_delegate_->CheckSuggestions(
1035      kDefaultPageID, arraysize(expected_values), expected_values,
1036      expected_labels, expected_icons, expected_unique_ids);
1037}
1038
1039// Test that we return no suggestions when the form has no relevant fields.
1040TEST_F(AutofillManagerTest, GetProfileSuggestionsUnknownFields) {
1041  // Set up our form data.
1042  FormData form;
1043  form.name = ASCIIToUTF16("MyForm");
1044  form.method = ASCIIToUTF16("POST");
1045  form.origin = GURL("http://myform.com/form.html");
1046  form.action = GURL("http://myform.com/submit.html");
1047  form.user_submitted = true;
1048
1049  FormFieldData field;
1050  test::CreateTestFormField("Username", "username", "", "text",&field);
1051  form.fields.push_back(field);
1052  test::CreateTestFormField("Password", "password", "", "password",&field);
1053  form.fields.push_back(field);
1054  test::CreateTestFormField("Quest", "quest", "", "quest", &field);
1055  form.fields.push_back(field);
1056  test::CreateTestFormField("Color", "color", "", "text", &field);
1057  form.fields.push_back(field);
1058
1059  std::vector<FormData> forms(1, form);
1060  FormsSeen(forms);
1061
1062  GetAutofillSuggestions(form, field);
1063  EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1064}
1065
1066// Test that we cull duplicate profile suggestions.
1067TEST_F(AutofillManagerTest, GetProfileSuggestionsWithDuplicates) {
1068  // Set up our form data.
1069  FormData form;
1070  test::CreateTestAddressFormData(&form);
1071  std::vector<FormData> forms(1, form);
1072  FormsSeen(forms);
1073
1074  // Add a duplicate profile.
1075  AutofillProfile* duplicate_profile =
1076      new AutofillProfile(
1077          *(autofill_manager_->GetProfileWithGUID(
1078              "00000000-0000-0000-0000-000000000001")));
1079  autofill_manager_->AddProfile(duplicate_profile);
1080
1081  const FormFieldData& field = form.fields[0];
1082  GetAutofillSuggestions(form, field);
1083
1084  // No suggestions provided, so send an empty vector as the results.
1085  // This triggers the combined message send.
1086  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1087
1088  // Test that we sent the right values to the external delegate.
1089  base::string16 expected_values[] = {
1090    ASCIIToUTF16("Elvis"),
1091    ASCIIToUTF16("Charles")
1092  };
1093  base::string16 expected_labels[] = {
1094    ASCIIToUTF16("3734 Elvis Presley Blvd."),
1095    ASCIIToUTF16("123 Apple St.")
1096  };
1097  base::string16 expected_icons[] = {base::string16(), base::string16()};
1098  int expected_unique_ids[] = {1, 2};
1099  external_delegate_->CheckSuggestions(
1100      kDefaultPageID, arraysize(expected_values), expected_values,
1101      expected_labels, expected_icons, expected_unique_ids);
1102}
1103
1104// Test that we return no suggestions when autofill is disabled.
1105TEST_F(AutofillManagerTest, GetProfileSuggestionsAutofillDisabledByUser) {
1106  // Set up our form data.
1107  FormData form;
1108  test::CreateTestAddressFormData(&form);
1109  std::vector<FormData> forms(1, form);
1110  FormsSeen(forms);
1111
1112  // Disable Autofill.
1113  autofill_manager_->set_autofill_enabled(false);
1114
1115  const FormFieldData& field = form.fields[0];
1116  GetAutofillSuggestions(form, field);
1117  EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1118}
1119
1120// Test that we return a warning explaining that autofill suggestions are
1121// unavailable when the form method is GET rather than POST.
1122TEST_F(AutofillManagerTest, GetProfileSuggestionsMethodGet) {
1123  // Set up our form data.
1124  FormData form;
1125  test::CreateTestAddressFormData(&form);
1126  form.method = ASCIIToUTF16("GET");
1127  std::vector<FormData> forms(1, form);
1128  FormsSeen(forms);
1129
1130  const FormFieldData& field = form.fields[0];
1131  GetAutofillSuggestions(form, field);
1132
1133  // No suggestions provided, so send an empty vector as the results.
1134  // This triggers the combined message send.
1135  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1136
1137  // Test that we sent the right values to the external delegate.
1138  base::string16 expected_values[] = {
1139    l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_FORM_DISABLED)
1140  };
1141  base::string16 expected_labels[] = {base::string16()};
1142  base::string16 expected_icons[] = {base::string16()};
1143  int expected_unique_ids[] =
1144      {WebKit::WebAutofillClient::MenuItemIDWarningMessage};
1145  external_delegate_->CheckSuggestions(
1146      kDefaultPageID, arraysize(expected_values), expected_values,
1147      expected_labels, expected_icons, expected_unique_ids);
1148
1149  // Now add some Autocomplete suggestions. We should return the autocomplete
1150  // suggestions and the warning; these will be culled by the renderer.
1151  const int kPageID2 = 2;
1152  GetAutofillSuggestions(kPageID2, form, field);
1153
1154  std::vector<base::string16> suggestions;
1155  suggestions.push_back(ASCIIToUTF16("Jay"));
1156  suggestions.push_back(ASCIIToUTF16("Jason"));
1157  AutocompleteSuggestionsReturned(suggestions);
1158
1159  base::string16 expected_values2[] = {
1160    l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_FORM_DISABLED),
1161    ASCIIToUTF16("Jay"),
1162    ASCIIToUTF16("Jason")
1163  };
1164  base::string16 expected_labels2[] = { base::string16(), base::string16(),
1165                                        base::string16()};
1166  base::string16 expected_icons2[] = { base::string16(), base::string16(),
1167                                       base::string16()};
1168  int expected_unique_ids2[] = {-1, 0, 0};
1169  external_delegate_->CheckSuggestions(
1170      kPageID2, arraysize(expected_values2), expected_values2,
1171      expected_labels2, expected_icons2, expected_unique_ids2);
1172
1173  // Now clear the test profiles and try again -- we shouldn't return a warning.
1174  personal_data_.ClearAutofillProfiles();
1175  GetAutofillSuggestions(form, field);
1176  EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1177}
1178
1179// Test that we return all credit card profile suggestions when all form fields
1180// are empty.
1181TEST_F(AutofillManagerTest, GetCreditCardSuggestionsEmptyValue) {
1182  // Set up our form data.
1183  FormData form;
1184  CreateTestCreditCardFormData(&form, true, false);
1185  std::vector<FormData> forms(1, form);
1186  FormsSeen(forms);
1187
1188  FormFieldData field = form.fields[1];
1189  GetAutofillSuggestions(form, field);
1190
1191  // No suggestions provided, so send an empty vector as the results.
1192  // This triggers the combined message send.
1193  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1194
1195  // Test that we sent the right values to the external delegate.
1196  base::string16 expected_values[] = {
1197    ASCIIToUTF16("************3456"),
1198    ASCIIToUTF16("************8765")
1199  };
1200  base::string16 expected_labels[] = { ASCIIToUTF16("*3456"),
1201                                       ASCIIToUTF16("*8765")};
1202  base::string16 expected_icons[] = {
1203    ASCIIToUTF16(kVisaCard),
1204    ASCIIToUTF16(kMasterCard)
1205  };
1206  int expected_unique_ids[] = {
1207    autofill_manager_->GetPackedCreditCardID(4),
1208    autofill_manager_->GetPackedCreditCardID(5)
1209  };
1210  external_delegate_->CheckSuggestions(
1211      kDefaultPageID, arraysize(expected_values), expected_values,
1212      expected_labels, expected_icons, expected_unique_ids);
1213}
1214
1215// Test that we return only matching credit card profile suggestions when the
1216// selected form field has been partially filled out.
1217TEST_F(AutofillManagerTest, GetCreditCardSuggestionsMatchCharacter) {
1218  // Set up our form data.
1219  FormData form;
1220  CreateTestCreditCardFormData(&form, true, false);
1221  std::vector<FormData> forms(1, form);
1222  FormsSeen(forms);
1223
1224  FormFieldData field;
1225  test::CreateTestFormField("Card Number", "cardnumber", "4", "text", &field);
1226  GetAutofillSuggestions(form, field);
1227
1228  // No suggestions provided, so send an empty vector as the results.
1229  // This triggers the combined message send.
1230  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1231
1232  // Test that we sent the right values to the external delegate.
1233  base::string16 expected_values[] = {ASCIIToUTF16("************3456")};
1234  base::string16 expected_labels[] = {ASCIIToUTF16("*3456")};
1235  base::string16 expected_icons[] = {ASCIIToUTF16(kVisaCard)};
1236  int expected_unique_ids[] = {autofill_manager_->GetPackedCreditCardID(4)};
1237  external_delegate_->CheckSuggestions(
1238      kDefaultPageID, arraysize(expected_values), expected_values,
1239      expected_labels, expected_icons, expected_unique_ids);
1240}
1241
1242// Test that we return credit card profile suggestions when the selected form
1243// field is not the credit card number field.
1244TEST_F(AutofillManagerTest, GetCreditCardSuggestionsNonCCNumber) {
1245  // Set up our form data.
1246  FormData form;
1247  CreateTestCreditCardFormData(&form, true, false);
1248  std::vector<FormData> forms(1, form);
1249  FormsSeen(forms);
1250
1251  const FormFieldData& field = form.fields[0];
1252  GetAutofillSuggestions(form, field);
1253
1254  // No suggestions provided, so send an empty vector as the results.
1255  // This triggers the combined message send.
1256  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1257
1258  // Test that we sent the right values to the external delegate.
1259  base::string16 expected_values[] = {
1260    ASCIIToUTF16("Elvis Presley"),
1261    ASCIIToUTF16("Buddy Holly")
1262  };
1263  base::string16 expected_labels[] = { ASCIIToUTF16("*3456"),
1264                                       ASCIIToUTF16("*8765") };
1265  base::string16 expected_icons[] = {
1266    ASCIIToUTF16(kVisaCard),
1267    ASCIIToUTF16(kMasterCard)
1268  };
1269  int expected_unique_ids[] = {
1270    autofill_manager_->GetPackedCreditCardID(4),
1271    autofill_manager_->GetPackedCreditCardID(5)
1272  };
1273  external_delegate_->CheckSuggestions(
1274      kDefaultPageID, arraysize(expected_values), expected_values,
1275      expected_labels, expected_icons, expected_unique_ids);
1276}
1277
1278// Test that we return a warning explaining that credit card profile suggestions
1279// are unavailable when the form is not https.
1280TEST_F(AutofillManagerTest, GetCreditCardSuggestionsNonHTTPS) {
1281  // Set up our form data.
1282  FormData form;
1283  CreateTestCreditCardFormData(&form, false, false);
1284  std::vector<FormData> forms(1, form);
1285  FormsSeen(forms);
1286
1287  const FormFieldData& field = form.fields[0];
1288  GetAutofillSuggestions(form, field);
1289
1290  // No suggestions provided, so send an empty vector as the results.
1291  // This triggers the combined message send.
1292  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1293
1294  // Test that we sent the right values to the external delegate.
1295  base::string16 expected_values[] = {
1296    l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)
1297  };
1298  base::string16 expected_labels[] = {base::string16()};
1299  base::string16 expected_icons[] = {base::string16()};
1300  int expected_unique_ids[] = {-1};
1301  external_delegate_->CheckSuggestions(
1302      kDefaultPageID, arraysize(expected_values), expected_values,
1303      expected_labels, expected_icons, expected_unique_ids);
1304
1305  // Now add some Autocomplete suggestions. We should show the autocomplete
1306  // suggestions and the warning.
1307  const int kPageID2 = 2;
1308  GetAutofillSuggestions(kPageID2, form, field);
1309
1310  std::vector<base::string16> suggestions;
1311  suggestions.push_back(ASCIIToUTF16("Jay"));
1312  suggestions.push_back(ASCIIToUTF16("Jason"));
1313  AutocompleteSuggestionsReturned(suggestions);
1314
1315  base::string16 expected_values2[] = {
1316    l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION),
1317    ASCIIToUTF16("Jay"),
1318    ASCIIToUTF16("Jason")
1319  };
1320  base::string16 expected_labels2[] = { base::string16(), base::string16(),
1321                                        base::string16() };
1322  base::string16 expected_icons2[] = { base::string16(), base::string16(),
1323                                       base::string16() };
1324  int expected_unique_ids2[] = {-1, 0, 0};
1325  external_delegate_->CheckSuggestions(
1326      kPageID2, arraysize(expected_values2), expected_values2,
1327      expected_labels2, expected_icons2, expected_unique_ids2);
1328
1329  // Clear the test credit cards and try again -- we shouldn't return a warning.
1330  personal_data_.ClearCreditCards();
1331  GetAutofillSuggestions(form, field);
1332  EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1333}
1334
1335// Test that we return all credit card suggestions in the case that two cards
1336// have the same obfuscated number.
1337TEST_F(AutofillManagerTest, GetCreditCardSuggestionsRepeatedObfuscatedNumber) {
1338  // Add a credit card with the same obfuscated number as Elvis's.
1339  // |credit_card| will be owned by the mock PersonalDataManager.
1340  CreditCard* credit_card = new CreditCard;
1341  test::SetCreditCardInfo(credit_card, "Elvis Presley",
1342                          "5231567890123456",  // Mastercard
1343                          "04", "2012");
1344  credit_card->set_guid("00000000-0000-0000-0000-000000000007");
1345  autofill_manager_->AddCreditCard(credit_card);
1346
1347  // Set up our form data.
1348  FormData form;
1349  CreateTestCreditCardFormData(&form, true, false);
1350  std::vector<FormData> forms(1, form);
1351  FormsSeen(forms);
1352
1353  FormFieldData field = form.fields[1];
1354  GetAutofillSuggestions(form, field);
1355
1356  // No suggestions provided, so send an empty vector as the results.
1357  // This triggers the combined message send.
1358  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1359
1360  // Test that we sent the right values to the external delegate.
1361  base::string16 expected_values[] = {
1362    ASCIIToUTF16("************3456"),
1363    ASCIIToUTF16("************8765"),
1364    ASCIIToUTF16("************3456")
1365  };
1366  base::string16 expected_labels[] = {
1367    ASCIIToUTF16("*3456"),
1368    ASCIIToUTF16("*8765"),
1369    ASCIIToUTF16("*3456"),
1370  };
1371  base::string16 expected_icons[] = {
1372    ASCIIToUTF16(kVisaCard),
1373    ASCIIToUTF16(kMasterCard),
1374    ASCIIToUTF16(kMasterCard)
1375  };
1376  int expected_unique_ids[] = {
1377    autofill_manager_->GetPackedCreditCardID(4),
1378    autofill_manager_->GetPackedCreditCardID(5),
1379    autofill_manager_->GetPackedCreditCardID(7)
1380  };
1381  external_delegate_->CheckSuggestions(
1382      kDefaultPageID, arraysize(expected_values), expected_values,
1383      expected_labels, expected_icons, expected_unique_ids);
1384}
1385
1386// Test that we return profile and credit card suggestions for combined forms.
1387TEST_F(AutofillManagerTest, GetAddressAndCreditCardSuggestions) {
1388  // Set up our form data.
1389  FormData form;
1390  test::CreateTestAddressFormData(&form);
1391  CreateTestCreditCardFormData(&form, true, false);
1392  std::vector<FormData> forms(1, form);
1393  FormsSeen(forms);
1394
1395  FormFieldData field = form.fields[0];
1396  GetAutofillSuggestions(form, field);
1397
1398  // No suggestions provided, so send an empty vector as the results.
1399  // This triggers the combined message send.
1400  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1401
1402  // Test that we sent the right address suggestions to the external delegate.
1403  base::string16 expected_values[] = {
1404    ASCIIToUTF16("Elvis"),
1405    ASCIIToUTF16("Charles")
1406  };
1407  base::string16 expected_labels[] = {
1408    ASCIIToUTF16("3734 Elvis Presley Blvd."),
1409    ASCIIToUTF16("123 Apple St.")
1410  };
1411  base::string16 expected_icons[] = {base::string16(), base::string16()};
1412  int expected_unique_ids[] = {1, 2};
1413  external_delegate_->CheckSuggestions(
1414      kDefaultPageID, arraysize(expected_values), expected_values,
1415      expected_labels, expected_icons, expected_unique_ids);
1416
1417  const int kPageID2 = 2;
1418  test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
1419  GetAutofillSuggestions(kPageID2, form, field);
1420
1421  // No suggestions provided, so send an empty vector as the results.
1422  // This triggers the combined message send.
1423  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1424
1425  // Test that we sent the credit card suggestions to the external delegate.
1426  base::string16 expected_values2[] = {
1427    ASCIIToUTF16("************3456"),
1428    ASCIIToUTF16("************8765")
1429  };
1430  base::string16 expected_labels2[] = { ASCIIToUTF16("*3456"),
1431                                        ASCIIToUTF16("*8765")};
1432  base::string16 expected_icons2[] = {
1433    ASCIIToUTF16(kVisaCard),
1434    ASCIIToUTF16(kMasterCard)
1435  };
1436  int expected_unique_ids2[] = {
1437    autofill_manager_->GetPackedCreditCardID(4),
1438    autofill_manager_->GetPackedCreditCardID(5)
1439  };
1440  external_delegate_->CheckSuggestions(
1441      kPageID2, arraysize(expected_values2), expected_values2,
1442      expected_labels2, expected_icons2, expected_unique_ids2);
1443}
1444
1445// Test that for non-https forms with both address and credit card fields, we
1446// only return address suggestions. Instead of credit card suggestions, we
1447// should return a warning explaining that credit card profile suggestions are
1448// unavailable when the form is not https.
1449TEST_F(AutofillManagerTest, GetAddressAndCreditCardSuggestionsNonHttps) {
1450  // Set up our form data.
1451  FormData form;
1452  test::CreateTestAddressFormData(&form);
1453  CreateTestCreditCardFormData(&form, false, false);
1454  std::vector<FormData> forms(1, form);
1455  FormsSeen(forms);
1456
1457  FormFieldData field = form.fields[0];
1458  GetAutofillSuggestions(form, field);
1459
1460  // No suggestions provided, so send an empty vector as the results.
1461  // This triggers the combined message send.
1462  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1463
1464  // Test that we sent the right suggestions to the external delegate.
1465  base::string16 expected_values[] = {
1466    ASCIIToUTF16("Elvis"),
1467    ASCIIToUTF16("Charles")
1468  };
1469  base::string16 expected_labels[] = {
1470    ASCIIToUTF16("3734 Elvis Presley Blvd."),
1471    ASCIIToUTF16("123 Apple St.")
1472  };
1473  base::string16 expected_icons[] = {base::string16(), base::string16()};
1474  int expected_unique_ids[] = {1, 2};
1475  external_delegate_->CheckSuggestions(
1476      kDefaultPageID, arraysize(expected_values), expected_values,
1477      expected_labels, expected_icons, expected_unique_ids);
1478
1479  test::CreateTestFormField("Card Number", "cardnumber", "", "text", &field);
1480  const int kPageID2 = 2;
1481  GetAutofillSuggestions(kPageID2, form, field);
1482
1483  // No suggestions provided, so send an empty vector as the results.
1484  // This triggers the combined message send.
1485  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1486
1487  // Test that we sent the right values to the external delegate.
1488  base::string16 expected_values2[] = {
1489    l10n_util::GetStringUTF16(IDS_AUTOFILL_WARNING_INSECURE_CONNECTION)
1490  };
1491  base::string16 expected_labels2[] = {base::string16()};
1492  base::string16 expected_icons2[] = {base::string16()};
1493  int expected_unique_ids2[] = {-1};
1494  external_delegate_->CheckSuggestions(
1495      kPageID2, arraysize(expected_values2), expected_values2,
1496      expected_labels2, expected_icons2, expected_unique_ids2);
1497
1498  // Clear the test credit cards and try again -- we shouldn't return a warning.
1499  personal_data_.ClearCreditCards();
1500  GetAutofillSuggestions(form, field);
1501  EXPECT_FALSE(external_delegate_->on_suggestions_returned_seen());
1502}
1503
1504// Test that we correctly combine autofill and autocomplete suggestions.
1505TEST_F(AutofillManagerTest, GetCombinedAutofillAndAutocompleteSuggestions) {
1506  // Set up our form data.
1507  FormData form;
1508  test::CreateTestAddressFormData(&form);
1509  std::vector<FormData> forms(1, form);
1510  FormsSeen(forms);
1511
1512  const FormFieldData& field = form.fields[0];
1513  GetAutofillSuggestions(form, field);
1514
1515  // Add some Autocomplete suggestions.
1516  // This triggers the combined message send.
1517  std::vector<base::string16> suggestions;
1518  suggestions.push_back(ASCIIToUTF16("Jay"));
1519  // This suggestion is a duplicate, and should be trimmed.
1520  suggestions.push_back(ASCIIToUTF16("Elvis"));
1521  suggestions.push_back(ASCIIToUTF16("Jason"));
1522  AutocompleteSuggestionsReturned(suggestions);
1523
1524  // Test that we sent the right values to the external delegate.
1525  base::string16 expected_values[] = {
1526    ASCIIToUTF16("Elvis"),
1527    ASCIIToUTF16("Charles"),
1528    ASCIIToUTF16("Jay"),
1529    ASCIIToUTF16("Jason")
1530  };
1531  base::string16 expected_labels[] = {
1532    ASCIIToUTF16("3734 Elvis Presley Blvd."),
1533    ASCIIToUTF16("123 Apple St."),
1534    base::string16(),
1535    base::string16()
1536  };
1537  base::string16 expected_icons[] = { base::string16(), base::string16(),
1538                                      base::string16(), base::string16()};
1539  int expected_unique_ids[] = {1, 2, 0, 0};
1540  external_delegate_->CheckSuggestions(
1541      kDefaultPageID, arraysize(expected_values), expected_values,
1542      expected_labels, expected_icons, expected_unique_ids);
1543}
1544
1545// Test that we return autocomplete-like suggestions when trying to autofill
1546// already filled forms.
1547TEST_F(AutofillManagerTest, GetFieldSuggestionsWhenFormIsAutofilled) {
1548  // Set up our form data.
1549  FormData form;
1550  test::CreateTestAddressFormData(&form);
1551  std::vector<FormData> forms(1, form);
1552  FormsSeen(forms);
1553
1554  // Mark one of the fields as filled.
1555  form.fields[2].is_autofilled = true;
1556  const FormFieldData& field = form.fields[0];
1557  GetAutofillSuggestions(form, field);
1558
1559  // No suggestions provided, so send an empty vector as the results.
1560  // This triggers the combined message send.
1561  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1562
1563  // Test that we sent the right values to the external delegate.
1564  base::string16 expected_values[] = {
1565    ASCIIToUTF16("Elvis"),
1566    ASCIIToUTF16("Charles")
1567  };
1568  base::string16 expected_labels[] = {base::string16(), base::string16()};
1569  base::string16 expected_icons[] = {base::string16(), base::string16()};
1570  int expected_unique_ids[] = {1, 2};
1571  external_delegate_->CheckSuggestions(
1572      kDefaultPageID, arraysize(expected_values), expected_values,
1573      expected_labels, expected_icons, expected_unique_ids);
1574}
1575
1576// Test that nothing breaks when there are autocomplete suggestions but no
1577// autofill suggestions.
1578TEST_F(AutofillManagerTest, GetFieldSuggestionsForAutocompleteOnly) {
1579  // Set up our form data.
1580  FormData form;
1581  test::CreateTestAddressFormData(&form);
1582  FormFieldData field;
1583  test::CreateTestFormField("Some Field", "somefield", "", "text", &field);
1584  form.fields.push_back(field);
1585  std::vector<FormData> forms(1, form);
1586  FormsSeen(forms);
1587
1588  GetAutofillSuggestions(form, field);
1589
1590  // Add some Autocomplete suggestions.
1591  // This triggers the combined message send.
1592  std::vector<base::string16> suggestions;
1593  suggestions.push_back(ASCIIToUTF16("one"));
1594  suggestions.push_back(ASCIIToUTF16("two"));
1595  AutocompleteSuggestionsReturned(suggestions);
1596
1597  // Test that we sent the right values to the external delegate.
1598  base::string16 expected_values[] = {
1599    ASCIIToUTF16("one"),
1600    ASCIIToUTF16("two")
1601  };
1602  base::string16 expected_labels[] = {base::string16(), base::string16()};
1603  base::string16 expected_icons[] = {base::string16(), base::string16()};
1604  int expected_unique_ids[] = {0, 0};
1605  external_delegate_->CheckSuggestions(
1606      kDefaultPageID, arraysize(expected_values), expected_values,
1607      expected_labels, expected_icons, expected_unique_ids);
1608}
1609
1610// Test that we do not return duplicate values drawn from multiple profiles when
1611// filling an already filled field.
1612TEST_F(AutofillManagerTest, GetFieldSuggestionsWithDuplicateValues) {
1613  // Set up our form data.
1614  FormData form;
1615  test::CreateTestAddressFormData(&form);
1616  std::vector<FormData> forms(1, form);
1617  FormsSeen(forms);
1618
1619  // |profile| will be owned by the mock PersonalDataManager.
1620  AutofillProfile* profile = new AutofillProfile;
1621  test::SetProfileInfo(
1622      profile, "Elvis", "", "", "", "", "", "", "", "", "", "", "");
1623  profile->set_guid("00000000-0000-0000-0000-000000000101");
1624  autofill_manager_->AddProfile(profile);
1625
1626  FormFieldData& field = form.fields[0];
1627  field.is_autofilled = true;
1628  field.value = ASCIIToUTF16("Elvis");
1629  GetAutofillSuggestions(form, field);
1630
1631  // No suggestions provided, so send an empty vector as the results.
1632  // This triggers the combined message send.
1633  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1634
1635  // Test that we sent the right values to the external delegate.
1636  base::string16 expected_values[] = { ASCIIToUTF16("Elvis") };
1637  base::string16 expected_labels[] = { base::string16() };
1638  base::string16 expected_icons[] = { base::string16() };
1639  int expected_unique_ids[] = { 1 };
1640  external_delegate_->CheckSuggestions(
1641      kDefaultPageID, arraysize(expected_values), expected_values,
1642      expected_labels, expected_icons, expected_unique_ids);
1643}
1644
1645// Test that a non-default value is suggested for multi-valued profile, on an
1646// unfilled form.
1647TEST_F(AutofillManagerTest, GetFieldSuggestionsForMultiValuedProfileUnfilled) {
1648  // Set up our form data.
1649  FormData form;
1650  test::CreateTestAddressFormData(&form);
1651  std::vector<FormData> forms(1, form);
1652  FormsSeen(forms);
1653
1654  // |profile| will be owned by the mock PersonalDataManager.
1655  AutofillProfile* profile = new AutofillProfile;
1656  test::SetProfileInfo(profile, "Elvis", "", "Presley", "me@x.com", "",
1657                       "", "", "", "", "", "", "");
1658  profile->set_guid("00000000-0000-0000-0000-000000000101");
1659  std::vector<base::string16> multi_values(2);
1660  multi_values[0] = ASCIIToUTF16("Elvis Presley");
1661  multi_values[1] = ASCIIToUTF16("Elena Love");
1662  profile->SetRawMultiInfo(NAME_FULL, multi_values);
1663  personal_data_.ClearAutofillProfiles();
1664  autofill_manager_->AddProfile(profile);
1665
1666  {
1667    // Get the first name field.
1668    // Start out with "E", hoping for either "Elvis" or "Elena.
1669    FormFieldData& field = form.fields[0];
1670    field.value = ASCIIToUTF16("E");
1671    field.is_autofilled = false;
1672    GetAutofillSuggestions(form, field);
1673
1674    // Trigger the |Send|.
1675    AutocompleteSuggestionsReturned(std::vector<base::string16>());
1676
1677    // Test that we sent the right values to the external delegate.
1678    base::string16 expected_values[] = {
1679      ASCIIToUTF16("Elvis"),
1680      ASCIIToUTF16("Elena")
1681    };
1682    base::string16 expected_labels[] = {
1683      ASCIIToUTF16("me@x.com"),
1684      ASCIIToUTF16("me@x.com")
1685    };
1686    base::string16 expected_icons[] = { base::string16(), base::string16() };
1687    int expected_unique_ids[] = { 1, 2 };
1688    external_delegate_->CheckSuggestions(
1689        kDefaultPageID, arraysize(expected_values), expected_values,
1690        expected_labels, expected_icons, expected_unique_ids);
1691  }
1692
1693  {
1694    // Get the first name field.
1695    // This time, start out with "Ele", hoping for "Elena".
1696    FormFieldData& field = form.fields[0];
1697    field.value = ASCIIToUTF16("Ele");
1698    field.is_autofilled = false;
1699    GetAutofillSuggestions(form, field);
1700
1701    // Trigger the |Send|.
1702    AutocompleteSuggestionsReturned(std::vector<base::string16>());
1703
1704    // Test that we sent the right values to the external delegate.
1705    base::string16 expected_values[] = { ASCIIToUTF16("Elena") };
1706    base::string16 expected_labels[] = { ASCIIToUTF16("me@x.com") };
1707    base::string16 expected_icons[] = { base::string16() };
1708    int expected_unique_ids[] = { 2 };
1709    external_delegate_->CheckSuggestions(
1710        kDefaultPageID, arraysize(expected_values), expected_values,
1711        expected_labels, expected_icons, expected_unique_ids);
1712  }
1713}
1714
1715// Test that all values are suggested for multi-valued profile, on a filled
1716// form.  This is the per-field "override" case.
1717TEST_F(AutofillManagerTest, GetFieldSuggestionsForMultiValuedProfileFilled) {
1718  // Set up our form data.
1719  FormData form;
1720  test::CreateTestAddressFormData(&form);
1721  std::vector<FormData> forms(1, form);
1722  FormsSeen(forms);
1723
1724  // |profile| will be owned by the mock PersonalDataManager.
1725  AutofillProfile* profile = new AutofillProfile;
1726  profile->set_guid("00000000-0000-0000-0000-000000000102");
1727  std::vector<base::string16> multi_values(3);
1728  multi_values[0] = ASCIIToUTF16("Travis Smith");
1729  multi_values[1] = ASCIIToUTF16("Cynthia Love");
1730  multi_values[2] = ASCIIToUTF16("Zac Mango");
1731  profile->SetRawMultiInfo(NAME_FULL, multi_values);
1732  autofill_manager_->AddProfile(profile);
1733
1734  // Get the first name field.  And start out with "Travis", hoping for all the
1735  // multi-valued variants as suggestions.
1736  FormFieldData& field = form.fields[0];
1737  field.value = ASCIIToUTF16("Travis");
1738  field.is_autofilled = true;
1739  GetAutofillSuggestions(form, field);
1740
1741  // Trigger the |Send|.
1742  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1743
1744  // Test that we sent the right values to the external delegate.
1745  base::string16 expected_values[] = {
1746    ASCIIToUTF16("Travis"),
1747    ASCIIToUTF16("Cynthia"),
1748    ASCIIToUTF16("Zac")
1749  };
1750  base::string16 expected_labels[] = { base::string16(), base::string16(),
1751                                       base::string16() };
1752  base::string16 expected_icons[] = { base::string16(), base::string16(),
1753                                      base::string16() };
1754  int expected_unique_ids[] = { 1, 2, 3 };
1755  external_delegate_->CheckSuggestions(
1756      kDefaultPageID, arraysize(expected_values), expected_values,
1757      expected_labels, expected_icons, expected_unique_ids);
1758}
1759
1760TEST_F(AutofillManagerTest, GetProfileSuggestionsFancyPhone) {
1761  // Set up our form data.
1762  FormData form;
1763  test::CreateTestAddressFormData(&form);
1764  std::vector<FormData> forms(1, form);
1765  FormsSeen(forms);
1766
1767  AutofillProfile* profile = new AutofillProfile;
1768  profile->set_guid("00000000-0000-0000-0000-000000000103");
1769  std::vector<base::string16> multi_values(1);
1770  multi_values[0] = ASCIIToUTF16("Natty Bumppo");
1771  profile->SetRawMultiInfo(NAME_FULL, multi_values);
1772  multi_values[0] = ASCIIToUTF16("1800PRAIRIE");
1773  profile->SetRawMultiInfo(PHONE_HOME_WHOLE_NUMBER, multi_values);
1774  autofill_manager_->AddProfile(profile);
1775
1776  const FormFieldData& field = form.fields[9];
1777  GetAutofillSuggestions(form, field);
1778
1779  // No suggestions provided, so send an empty vector as the results.
1780  // This triggers the combined message send.
1781  AutocompleteSuggestionsReturned(std::vector<base::string16>());
1782
1783  // Test that we sent the right values to the external delegate.
1784  base::string16 expected_values[] = {
1785    ASCIIToUTF16("12345678901"),
1786    ASCIIToUTF16("23456789012"),
1787    ASCIIToUTF16("18007724743"),  // 1800PRAIRIE
1788  };
1789  // Inferred labels include full first relevant field, which in this case is
1790  // the address line 1.
1791  base::string16 expected_labels[] = {
1792    ASCIIToUTF16("Elvis Aaron Presley"),
1793    ASCIIToUTF16("Charles Hardin Holley"),
1794    ASCIIToUTF16("Natty Bumppo"),
1795  };
1796  base::string16 expected_icons[] = { base::string16(), base::string16(),
1797                                      base::string16()};
1798  int expected_unique_ids[] = {1, 2, 3};
1799  external_delegate_->CheckSuggestions(
1800      kDefaultPageID, arraysize(expected_values), expected_values,
1801      expected_labels, expected_icons, expected_unique_ids);
1802}
1803
1804// Test that we correctly fill an address form.
1805TEST_F(AutofillManagerTest, FillAddressForm) {
1806  // Set up our form data.
1807  FormData form;
1808  test::CreateTestAddressFormData(&form);
1809  std::vector<FormData> forms(1, form);
1810  FormsSeen(forms);
1811
1812  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1813  GUIDPair empty(std::string(), 0);
1814  int response_page_id = 0;
1815  FormData response_data;
1816  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1817      PackGUIDs(empty, guid), &response_page_id, &response_data);
1818  ExpectFilledAddressFormElvis(
1819      response_page_id, response_data, kDefaultPageID, false);
1820}
1821
1822// Test that we correctly fill an address form from an auxiliary profile.
1823TEST_F(AutofillManagerTest, FillAddressFormFromAuxiliaryProfile) {
1824  personal_data_.ClearAutofillProfiles();
1825  PrefService* prefs = user_prefs::UserPrefs::Get(profile());
1826  prefs->SetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled, true);
1827  personal_data_.CreateTestAuxiliaryProfiles();
1828
1829  // Set up our form data.
1830  FormData form;
1831  test::CreateTestAddressFormData(&form);
1832  std::vector<FormData> forms(1, form);
1833  FormsSeen(forms);
1834
1835  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1836  GUIDPair empty(std::string(), 0);
1837  int response_page_id = 0;
1838  FormData response_data;
1839  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1840      PackGUIDs(empty, guid), &response_page_id, &response_data);
1841  ExpectFilledAddressFormElvis(
1842      response_page_id, response_data, kDefaultPageID, false);
1843}
1844
1845// Test that we correctly fill a credit card form.
1846TEST_F(AutofillManagerTest, FillCreditCardForm) {
1847  // Set up our form data.
1848  FormData form;
1849  CreateTestCreditCardFormData(&form, true, false);
1850  std::vector<FormData> forms(1, form);
1851  FormsSeen(forms);
1852
1853  GUIDPair guid("00000000-0000-0000-0000-000000000004", 0);
1854  GUIDPair empty(std::string(), 0);
1855  int response_page_id = 0;
1856  FormData response_data;
1857  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1858      PackGUIDs(guid, empty), &response_page_id, &response_data);
1859  ExpectFilledCreditCardFormElvis(
1860      response_page_id, response_data, kDefaultPageID, false);
1861}
1862
1863// Test that we correctly fill a credit card form with month input type.
1864// 1. year empty, month empty
1865TEST_F(AutofillManagerTest, FillCreditCardFormNoYearNoMonth) {
1866  // Same as the SetUp(), but generate 4 credit cards with year month
1867  // combination.
1868  personal_data_.CreateTestCreditCardsYearAndMonth("", "");
1869  // Set up our form data.
1870  FormData form;
1871  CreateTestCreditCardFormData(&form, true, true);
1872  std::vector<FormData> forms(1, form);
1873  FormsSeen(forms);
1874
1875  GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1876  GUIDPair empty(std::string(), 0);
1877  int response_page_id = 0;
1878  FormData response_data;
1879  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1880      PackGUIDs(guid, empty), &response_page_id, &response_data);
1881  ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1882      kDefaultPageID, false, "", "");
1883}
1884
1885
1886// Test that we correctly fill a credit card form with month input type.
1887// 2. year empty, month non-empty
1888TEST_F(AutofillManagerTest, FillCreditCardFormNoYearMonth) {
1889  // Same as the SetUp(), but generate 4 credit cards with year month
1890  // combination.
1891  personal_data_.CreateTestCreditCardsYearAndMonth("", "04");
1892  // Set up our form data.
1893  FormData form;
1894  CreateTestCreditCardFormData(&form, true, true);
1895  std::vector<FormData> forms(1, form);
1896  FormsSeen(forms);
1897
1898  GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1899  GUIDPair empty(std::string(), 0);
1900  int response_page_id = 0;
1901  FormData response_data;
1902  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1903      PackGUIDs(guid, empty), &response_page_id, &response_data);
1904  ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1905      kDefaultPageID, false, "", "04");
1906}
1907
1908// Test that we correctly fill a credit card form with month input type.
1909// 3. year non-empty, month empty
1910TEST_F(AutofillManagerTest, FillCreditCardFormYearNoMonth) {
1911  // Same as the SetUp(), but generate 4 credit cards with year month
1912  // combination.
1913  personal_data_.CreateTestCreditCardsYearAndMonth("2012", "");
1914  // Set up our form data.
1915  FormData form;
1916  CreateTestCreditCardFormData(&form, true, true);
1917  std::vector<FormData> forms(1, form);
1918  FormsSeen(forms);
1919
1920  GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1921  GUIDPair empty(std::string(), 0);
1922  int response_page_id = 0;
1923  FormData response_data;
1924  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1925      PackGUIDs(guid, empty), &response_page_id, &response_data);
1926  ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1927      kDefaultPageID, false, "2012", "");
1928}
1929
1930// Test that we correctly fill a credit card form with month input type.
1931// 4. year non-empty, month empty
1932TEST_F(AutofillManagerTest, FillCreditCardFormYearMonth) {
1933  // Same as the SetUp(), but generate 4 credit cards with year month
1934  // combination.
1935  personal_data_.ClearCreditCards();
1936  personal_data_.CreateTestCreditCardsYearAndMonth("2012", "04");
1937  // Set up our form data.
1938  FormData form;
1939  CreateTestCreditCardFormData(&form, true, true);
1940  std::vector<FormData> forms(1, form);
1941  FormsSeen(forms);
1942
1943  GUIDPair guid("00000000-0000-0000-0000-000000000007", 0);
1944  GUIDPair empty(std::string(), 0);
1945  int response_page_id = 0;
1946  FormData response_data;
1947  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
1948      PackGUIDs(guid, empty), &response_page_id, &response_data);
1949  ExpectFilledCreditCardYearMonthWithYearMonth(response_page_id, response_data,
1950      kDefaultPageID, false, "2012", "04");
1951}
1952
1953// Test that we correctly fill a combined address and credit card form.
1954TEST_F(AutofillManagerTest, FillAddressAndCreditCardForm) {
1955  // Set up our form data.
1956  FormData form;
1957  test::CreateTestAddressFormData(&form);
1958  CreateTestCreditCardFormData(&form, true, false);
1959  std::vector<FormData> forms(1, form);
1960  FormsSeen(forms);
1961
1962  // First fill the address data.
1963  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
1964  GUIDPair empty(std::string(), 0);
1965  int response_page_id = 0;
1966  FormData response_data;
1967  {
1968    SCOPED_TRACE("Address");
1969    FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
1970        PackGUIDs(empty, guid), &response_page_id, &response_data);
1971    ExpectFilledAddressFormElvis(
1972        response_page_id, response_data, kDefaultPageID, true);
1973  }
1974
1975  // Now fill the credit card data.
1976  const int kPageID2 = 2;
1977  GUIDPair guid2("00000000-0000-0000-0000-000000000004", 0);
1978  response_page_id = 0;
1979  {
1980    FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(),
1981        PackGUIDs(guid2, empty), &response_page_id, &response_data);
1982    SCOPED_TRACE("Credit card");
1983    ExpectFilledCreditCardFormElvis(
1984        response_page_id, response_data, kPageID2, true);
1985  }
1986}
1987
1988// Test that we correctly fill a form that has multiple logical sections, e.g.
1989// both a billing and a shipping address.
1990TEST_F(AutofillManagerTest, FillFormWithMultipleSections) {
1991  // Set up our form data.
1992  FormData form;
1993  test::CreateTestAddressFormData(&form);
1994  const size_t kAddressFormSize = form.fields.size();
1995  test::CreateTestAddressFormData(&form);
1996  for (size_t i = kAddressFormSize; i < form.fields.size(); ++i) {
1997    // Make sure the fields have distinct names.
1998    form.fields[i].name = form.fields[i].name + ASCIIToUTF16("_");
1999  }
2000  std::vector<FormData> forms(1, form);
2001  FormsSeen(forms);
2002
2003  // Fill the first section.
2004  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2005  GUIDPair empty(std::string(), 0);
2006  int response_page_id = 0;
2007  FormData response_data;
2008  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2009      PackGUIDs(empty, guid), &response_page_id, &response_data);
2010  {
2011    SCOPED_TRACE("Address 1");
2012    // The second address section should be empty.
2013    ASSERT_EQ(response_data.fields.size(), 2*kAddressFormSize);
2014    for (size_t i = kAddressFormSize; i < form.fields.size(); ++i) {
2015      EXPECT_EQ(base::string16(), response_data.fields[i].value);
2016    }
2017
2018    // The first address section should be filled with Elvis's data.
2019    response_data.fields.resize(kAddressFormSize);
2020    ExpectFilledAddressFormElvis(
2021        response_page_id, response_data, kDefaultPageID, false);
2022  }
2023
2024  // Fill the second section, with the initiating field somewhere in the middle
2025  // of the section.
2026  const int kPageID2 = 2;
2027  GUIDPair guid2("00000000-0000-0000-0000-000000000001", 0);
2028  ASSERT_LT(9U, kAddressFormSize);
2029  response_page_id = 0;
2030  FillAutofillFormDataAndSaveResults(
2031      kPageID2, form, form.fields[kAddressFormSize + 9],
2032      PackGUIDs(empty, guid2), &response_page_id, &response_data);
2033  {
2034    SCOPED_TRACE("Address 2");
2035    ASSERT_EQ(response_data.fields.size(), form.fields.size());
2036
2037    // The first address section should be empty.
2038    ASSERT_EQ(response_data.fields.size(), 2*kAddressFormSize);
2039    for (size_t i = 0; i < kAddressFormSize; ++i) {
2040      EXPECT_EQ(base::string16(), response_data.fields[i].value);
2041    }
2042
2043    // The second address section should be filled with Elvis's data.
2044    FormData secondSection = response_data;
2045    secondSection.fields.erase(secondSection.fields.begin(),
2046                               secondSection.fields.begin() + kAddressFormSize);
2047    for (size_t i = 0; i < kAddressFormSize; ++i) {
2048      // Restore the expected field names.
2049      base::string16 name = secondSection.fields[i].name;
2050      base::string16 original_name = name.substr(0, name.size() - 1);
2051      secondSection.fields[i].name = original_name;
2052    }
2053    ExpectFilledAddressFormElvis(
2054        response_page_id, secondSection, kPageID2, false);
2055  }
2056}
2057
2058// Test that we correctly fill a form that has author-specified sections, which
2059// might not match our expected section breakdown.
2060TEST_F(AutofillManagerTest, FillFormWithAuthorSpecifiedSections) {
2061  // Create a form with a billing section and an unnamed section, interleaved.
2062  // The billing section includes both address and credit card fields.
2063  FormData form;
2064  form.name = ASCIIToUTF16("MyForm");
2065  form.method = ASCIIToUTF16("POST");
2066  form.origin = GURL("https://myform.com/form.html");
2067  form.action = GURL("https://myform.com/submit.html");
2068  form.user_submitted = true;
2069
2070  FormFieldData field;
2071
2072  test::CreateTestFormField("", "country", "", "text", &field);
2073  field.autocomplete_attribute = "section-billing country";
2074  form.fields.push_back(field);
2075
2076  test::CreateTestFormField("", "firstname", "", "text", &field);
2077  field.autocomplete_attribute = "given-name";
2078  form.fields.push_back(field);
2079
2080  test::CreateTestFormField("", "lastname", "", "text", &field);
2081  field.autocomplete_attribute = "family-name";
2082  form.fields.push_back(field);
2083
2084  test::CreateTestFormField("", "address", "", "text", &field);
2085  field.autocomplete_attribute = "section-billing street-address";
2086  form.fields.push_back(field);
2087
2088  test::CreateTestFormField("", "city", "", "text", &field);
2089  field.autocomplete_attribute = "section-billing locality";
2090  form.fields.push_back(field);
2091
2092  test::CreateTestFormField("", "state", "", "text", &field);
2093  field.autocomplete_attribute = "section-billing region";
2094  form.fields.push_back(field);
2095
2096  test::CreateTestFormField("", "zip", "", "text", &field);
2097  field.autocomplete_attribute = "section-billing postal-code";
2098  form.fields.push_back(field);
2099
2100  test::CreateTestFormField("", "ccname", "", "text", &field);
2101  field.autocomplete_attribute = "section-billing cc-name";
2102  form.fields.push_back(field);
2103
2104  test::CreateTestFormField("", "ccnumber", "", "text", &field);
2105  field.autocomplete_attribute = "section-billing cc-number";
2106  form.fields.push_back(field);
2107
2108  test::CreateTestFormField("", "ccexp", "", "text", &field);
2109  field.autocomplete_attribute = "section-billing cc-exp";
2110  form.fields.push_back(field);
2111
2112  test::CreateTestFormField("", "email", "", "text", &field);
2113  field.autocomplete_attribute = "email";
2114  form.fields.push_back(field);
2115
2116  std::vector<FormData> forms(1, form);
2117  FormsSeen(forms);
2118
2119  // Fill the unnamed section.
2120  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2121  GUIDPair empty(std::string(), 0);
2122  int response_page_id = 0;
2123  FormData response_data;
2124  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[1],
2125      PackGUIDs(empty, guid), &response_page_id, &response_data);
2126  {
2127    SCOPED_TRACE("Unnamed section");
2128    EXPECT_EQ(kDefaultPageID, response_page_id);
2129    EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
2130    EXPECT_EQ(ASCIIToUTF16("POST"), response_data.method);
2131    EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
2132    EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
2133    EXPECT_TRUE(response_data.user_submitted);
2134    ASSERT_EQ(11U, response_data.fields.size());
2135
2136    ExpectFilledField("", "country", "", "text", response_data.fields[0]);
2137    ExpectFilledField("", "firstname", "Elvis", "text",
2138                      response_data.fields[1]);
2139    ExpectFilledField("", "lastname", "Presley", "text",
2140                      response_data.fields[2]);
2141    ExpectFilledField("", "address", "", "text", response_data.fields[3]);
2142    ExpectFilledField("", "city", "", "text", response_data.fields[4]);
2143    ExpectFilledField("", "state", "", "text", response_data.fields[5]);
2144    ExpectFilledField("", "zip", "", "text", response_data.fields[6]);
2145    ExpectFilledField("", "ccname", "", "text", response_data.fields[7]);
2146    ExpectFilledField("", "ccnumber", "", "text", response_data.fields[8]);
2147    ExpectFilledField("", "ccexp", "", "text", response_data.fields[9]);
2148    ExpectFilledField("", "email", "theking@gmail.com", "text",
2149                      response_data.fields[10]);
2150  }
2151
2152  // Fill the address portion of the billing section.
2153  const int kPageID2 = 2;
2154  GUIDPair guid2("00000000-0000-0000-0000-000000000001", 0);
2155  response_page_id = 0;
2156  FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields[0],
2157      PackGUIDs(empty, guid2), &response_page_id, &response_data);
2158  {
2159    SCOPED_TRACE("Billing address");
2160    EXPECT_EQ(kPageID2, response_page_id);
2161    EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
2162    EXPECT_EQ(ASCIIToUTF16("POST"), response_data.method);
2163    EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
2164    EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
2165    EXPECT_TRUE(response_data.user_submitted);
2166    ASSERT_EQ(11U, response_data.fields.size());
2167
2168    ExpectFilledField("", "country", "United States", "text",
2169                      response_data.fields[0]);
2170    ExpectFilledField("", "firstname", "", "text", response_data.fields[1]);
2171    ExpectFilledField("", "lastname", "", "text", response_data.fields[2]);
2172    ExpectFilledField("", "address", "3734 Elvis Presley Blvd.", "text",
2173                      response_data.fields[3]);
2174    ExpectFilledField("", "city", "Memphis", "text", response_data.fields[4]);
2175    ExpectFilledField("", "state", "Tennessee", "text",
2176                      response_data.fields[5]);
2177    ExpectFilledField("", "zip", "38116", "text", response_data.fields[6]);
2178    ExpectFilledField("", "ccname", "", "text", response_data.fields[7]);
2179    ExpectFilledField("", "ccnumber", "", "text", response_data.fields[8]);
2180    ExpectFilledField("", "ccexp", "", "text", response_data.fields[9]);
2181    ExpectFilledField("", "email", "", "text", response_data.fields[10]);
2182  }
2183
2184  // Fill the credit card portion of the billing section.
2185  const int kPageID3 = 3;
2186  GUIDPair guid3("00000000-0000-0000-0000-000000000004", 0);
2187  response_page_id = 0;
2188  FillAutofillFormDataAndSaveResults(
2189      kPageID3, form, form.fields[form.fields.size() - 2],
2190      PackGUIDs(guid3, empty), &response_page_id, &response_data);
2191  {
2192    SCOPED_TRACE("Credit card");
2193    EXPECT_EQ(kPageID3, response_page_id);
2194    EXPECT_EQ(ASCIIToUTF16("MyForm"), response_data.name);
2195    EXPECT_EQ(ASCIIToUTF16("POST"), response_data.method);
2196    EXPECT_EQ(GURL("https://myform.com/form.html"), response_data.origin);
2197    EXPECT_EQ(GURL("https://myform.com/submit.html"), response_data.action);
2198    EXPECT_TRUE(response_data.user_submitted);
2199    ASSERT_EQ(11U, response_data.fields.size());
2200
2201    ExpectFilledField("", "country", "", "text", response_data.fields[0]);
2202    ExpectFilledField("", "firstname", "", "text", response_data.fields[1]);
2203    ExpectFilledField("", "lastname", "", "text", response_data.fields[2]);
2204    ExpectFilledField("", "address", "", "text", response_data.fields[3]);
2205    ExpectFilledField("", "city", "", "text", response_data.fields[4]);
2206    ExpectFilledField("", "state", "", "text", response_data.fields[5]);
2207    ExpectFilledField("", "zip", "", "text", response_data.fields[6]);
2208    ExpectFilledField("", "ccname", "Elvis Presley", "text",
2209                      response_data.fields[7]);
2210    ExpectFilledField("", "ccnumber", "4234567890123456", "text",
2211                      response_data.fields[8]);
2212    ExpectFilledField("", "ccexp", "04/2012", "text", response_data.fields[9]);
2213    ExpectFilledField("", "email", "", "text", response_data.fields[10]);
2214  }
2215}
2216
2217// Test that we correctly fill a form that has a single logical section with
2218// multiple email address fields.
2219TEST_F(AutofillManagerTest, FillFormWithMultipleEmails) {
2220  // Set up our form data.
2221  FormData form;
2222  test::CreateTestAddressFormData(&form);
2223  FormFieldData field;
2224  test::CreateTestFormField("Confirm email", "email2", "", "text", &field);
2225  form.fields.push_back(field);
2226
2227  std::vector<FormData> forms(1, form);
2228  FormsSeen(forms);
2229
2230  // Fill the form.
2231  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2232  GUIDPair empty(std::string(), 0);
2233  int response_page_id = 0;
2234  FormData response_data;
2235  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2236      PackGUIDs(empty, guid), &response_page_id, &response_data);
2237
2238  // The second email address should be filled.
2239  EXPECT_EQ(ASCIIToUTF16("theking@gmail.com"),
2240            response_data.fields.back().value);
2241
2242  // The remainder of the form should be filled as usual.
2243  response_data.fields.pop_back();
2244  ExpectFilledAddressFormElvis(
2245      response_page_id, response_data, kDefaultPageID, false);
2246}
2247
2248// Test that we correctly fill a previously auto-filled form.
2249TEST_F(AutofillManagerTest, FillAutofilledForm) {
2250  // Set up our form data.
2251  FormData form;
2252  test::CreateTestAddressFormData(&form);
2253  // Mark one of the address fields as autofilled.
2254  form.fields[4].is_autofilled = true;
2255  CreateTestCreditCardFormData(&form, true, false);
2256  std::vector<FormData> forms(1, form);
2257  FormsSeen(forms);
2258
2259  // First fill the address data.
2260  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2261  GUIDPair empty(std::string(), 0);
2262  int response_page_id = 0;
2263  FormData response_data;
2264  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, *form.fields.begin(),
2265      PackGUIDs(empty, guid), &response_page_id, &response_data);
2266  {
2267    SCOPED_TRACE("Address");
2268    ExpectFilledForm(response_page_id, response_data, kDefaultPageID,
2269                     "Elvis", "", "", "", "", "", "", "", "", "", "", "", "",
2270                     "", "", true, true, false);
2271  }
2272
2273  // Now fill the credit card data.
2274  const int kPageID2 = 2;
2275  GUIDPair guid2("00000000-0000-0000-0000-000000000004", 0);
2276  response_page_id = 0;
2277  FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields.back(),
2278      PackGUIDs(guid2, empty), &response_page_id, &response_data);
2279  {
2280    SCOPED_TRACE("Credit card 1");
2281    ExpectFilledCreditCardFormElvis(
2282        response_page_id, response_data, kPageID2, true);
2283  }
2284
2285  // Now set the credit card fields to also be auto-filled, and try again to
2286  // fill the credit card data
2287  for (std::vector<FormFieldData>::iterator iter = form.fields.begin();
2288       iter != form.fields.end();
2289       ++iter) {
2290    iter->is_autofilled = true;
2291  }
2292
2293  const int kPageID3 = 3;
2294  response_page_id = 0;
2295  FillAutofillFormDataAndSaveResults(kPageID3, form, *form.fields.rbegin(),
2296      PackGUIDs(guid2, empty), &response_page_id, &response_data);
2297  {
2298    SCOPED_TRACE("Credit card 2");
2299    ExpectFilledForm(response_page_id, response_data, kPageID3,
2300                     "", "", "", "", "", "", "", "", "", "", "", "", "", "",
2301                     "2012", true, true, false);
2302  }
2303}
2304
2305// Test that we correctly fill an address form with a non-default variant for a
2306// multi-valued field.
2307TEST_F(AutofillManagerTest, FillAddressFormWithVariantType) {
2308  // Set up our form data.
2309  FormData form;
2310  test::CreateTestAddressFormData(&form);
2311  std::vector<FormData> forms(1, form);
2312  FormsSeen(forms);
2313
2314  // Add a name variant to the Elvis profile.
2315  AutofillProfile* profile = autofill_manager_->GetProfileWithGUID(
2316      "00000000-0000-0000-0000-000000000001");
2317  const base::string16 elvis_name = profile->GetRawInfo(NAME_FULL);
2318
2319  std::vector<base::string16> name_variants;
2320  name_variants.push_back(ASCIIToUTF16("Some Other Guy"));
2321  name_variants.push_back(elvis_name);
2322  profile->SetRawMultiInfo(NAME_FULL, name_variants);
2323
2324  GUIDPair guid(profile->guid(), 1);
2325  GUIDPair empty(std::string(), 0);
2326  int response_page_id = 0;
2327  FormData response_data1;
2328  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2329      PackGUIDs(empty, guid), &response_page_id, &response_data1);
2330  {
2331    SCOPED_TRACE("Valid variant");
2332    ExpectFilledAddressFormElvis(
2333        response_page_id, response_data1, kDefaultPageID, false);
2334  }
2335
2336  // Try filling with a variant that doesn't exist.  The fields to which this
2337  // variant would normally apply should not be filled.
2338  const int kPageID2 = 2;
2339  GUIDPair guid2(profile->guid(), 2);
2340  response_page_id = 0;
2341  FormData response_data2;
2342  FillAutofillFormDataAndSaveResults(kPageID2, form, form.fields[0],
2343      PackGUIDs(empty, guid2), &response_page_id, &response_data2);
2344  {
2345    SCOPED_TRACE("Invalid variant");
2346    ExpectFilledForm(response_page_id, response_data2, kPageID2, "", "", "",
2347                     "3734 Elvis Presley Blvd.", "Apt. 10", "Memphis",
2348                     "Tennessee", "38116", "United States", "12345678901",
2349                     "theking@gmail.com", "", "", "", "", true, false, false);
2350  }
2351}
2352
2353// Test that we correctly fill a phone number split across multiple fields.
2354TEST_F(AutofillManagerTest, FillPhoneNumber) {
2355  // In one form, rely on the maxlength attribute to imply phone number parts.
2356  // In the other form, rely on the autocompletetype attribute.
2357  FormData form_with_maxlength;
2358  form_with_maxlength.name = ASCIIToUTF16("MyMaxlengthPhoneForm");
2359  form_with_maxlength.method = ASCIIToUTF16("POST");
2360  form_with_maxlength.origin = GURL("http://myform.com/phone_form.html");
2361  form_with_maxlength.action = GURL("http://myform.com/phone_submit.html");
2362  form_with_maxlength.user_submitted = true;
2363  FormData form_with_autocompletetype = form_with_maxlength;
2364  form_with_autocompletetype.name = ASCIIToUTF16("MyAutocompletetypePhoneForm");
2365
2366  struct {
2367    const char* label;
2368    const char* name;
2369    size_t max_length;
2370    const char* autocomplete_attribute;
2371  } test_fields[] = {
2372    { "country code", "country_code", 1, "tel-country-code" },
2373    { "area code", "area_code", 3, "tel-area-code" },
2374    { "phone", "phone_prefix", 3, "tel-local-prefix" },
2375    { "-", "phone_suffix", 4, "tel-local-suffix" },
2376    { "Phone Extension", "ext", 3, "tel-extension" }
2377  };
2378
2379  FormFieldData field;
2380  const size_t default_max_length = field.max_length;
2381  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_fields); ++i) {
2382    test::CreateTestFormField(
2383        test_fields[i].label, test_fields[i].name, "", "text", &field);
2384    field.max_length = test_fields[i].max_length;
2385    field.autocomplete_attribute = std::string();
2386    form_with_maxlength.fields.push_back(field);
2387
2388    field.max_length = default_max_length;
2389    field.autocomplete_attribute = test_fields[i].autocomplete_attribute;
2390    form_with_autocompletetype.fields.push_back(field);
2391  }
2392
2393  std::vector<FormData> forms;
2394  forms.push_back(form_with_maxlength);
2395  forms.push_back(form_with_autocompletetype);
2396  FormsSeen(forms);
2397
2398  // We should be able to fill prefix and suffix fields for US numbers.
2399  AutofillProfile* work_profile = autofill_manager_->GetProfileWithGUID(
2400      "00000000-0000-0000-0000-000000000002");
2401  ASSERT_TRUE(work_profile != NULL);
2402  work_profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
2403                           ASCIIToUTF16("16505554567"));
2404
2405  GUIDPair guid(work_profile->guid(), 0);
2406  GUIDPair empty(std::string(), 0);
2407  int page_id = 1;
2408  int response_page_id = 0;
2409  FormData response_data1;
2410  FillAutofillFormDataAndSaveResults(page_id, form_with_maxlength,
2411      *form_with_maxlength.fields.begin(),
2412      PackGUIDs(empty, guid), &response_page_id, &response_data1);
2413  EXPECT_EQ(1, response_page_id);
2414
2415  ASSERT_EQ(5U, response_data1.fields.size());
2416  EXPECT_EQ(ASCIIToUTF16("1"), response_data1.fields[0].value);
2417  EXPECT_EQ(ASCIIToUTF16("650"), response_data1.fields[1].value);
2418  EXPECT_EQ(ASCIIToUTF16("555"), response_data1.fields[2].value);
2419  EXPECT_EQ(ASCIIToUTF16("4567"), response_data1.fields[3].value);
2420  EXPECT_EQ(base::string16(), response_data1.fields[4].value);
2421
2422  page_id = 2;
2423  response_page_id = 0;
2424  FormData response_data2;
2425  FillAutofillFormDataAndSaveResults(page_id, form_with_autocompletetype,
2426      *form_with_autocompletetype.fields.begin(),
2427      PackGUIDs(empty, guid), &response_page_id, &response_data2);
2428  EXPECT_EQ(2, response_page_id);
2429
2430  ASSERT_EQ(5U, response_data2.fields.size());
2431  EXPECT_EQ(ASCIIToUTF16("1"), response_data2.fields[0].value);
2432  EXPECT_EQ(ASCIIToUTF16("650"), response_data2.fields[1].value);
2433  EXPECT_EQ(ASCIIToUTF16("555"), response_data2.fields[2].value);
2434  EXPECT_EQ(ASCIIToUTF16("4567"), response_data2.fields[3].value);
2435  EXPECT_EQ(base::string16(), response_data2.fields[4].value);
2436
2437  // We should not be able to fill prefix and suffix fields for international
2438  // numbers.
2439  work_profile->SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("GB"));
2440  work_profile->SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
2441                           ASCIIToUTF16("447700954321"));
2442  page_id = 3;
2443  response_page_id = 0;
2444  FormData response_data3;
2445  FillAutofillFormDataAndSaveResults(page_id, form_with_maxlength,
2446      *form_with_maxlength.fields.begin(),
2447      PackGUIDs(empty, guid), &response_page_id, &response_data3);
2448  EXPECT_EQ(3, response_page_id);
2449
2450  ASSERT_EQ(5U, response_data3.fields.size());
2451  EXPECT_EQ(ASCIIToUTF16("44"), response_data3.fields[0].value);
2452  EXPECT_EQ(ASCIIToUTF16("7700"), response_data3.fields[1].value);
2453  EXPECT_EQ(ASCIIToUTF16("954321"), response_data3.fields[2].value);
2454  EXPECT_EQ(ASCIIToUTF16("954321"), response_data3.fields[3].value);
2455  EXPECT_EQ(base::string16(), response_data3.fields[4].value);
2456
2457  page_id = 4;
2458  response_page_id = 0;
2459  FormData response_data4;
2460  FillAutofillFormDataAndSaveResults(page_id, form_with_autocompletetype,
2461      *form_with_autocompletetype.fields.begin(),
2462      PackGUIDs(empty, guid), &response_page_id, &response_data4);
2463  EXPECT_EQ(4, response_page_id);
2464
2465  ASSERT_EQ(5U, response_data4.fields.size());
2466  EXPECT_EQ(ASCIIToUTF16("44"), response_data4.fields[0].value);
2467  EXPECT_EQ(ASCIIToUTF16("7700"), response_data4.fields[1].value);
2468  EXPECT_EQ(ASCIIToUTF16("954321"), response_data4.fields[2].value);
2469  EXPECT_EQ(ASCIIToUTF16("954321"), response_data4.fields[3].value);
2470  EXPECT_EQ(base::string16(), response_data4.fields[4].value);
2471
2472  // We should fill all phone fields with the same phone number variant.
2473  std::vector<base::string16> phone_variants;
2474  phone_variants.push_back(ASCIIToUTF16("16505554567"));
2475  phone_variants.push_back(ASCIIToUTF16("18887771234"));
2476  work_profile->SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
2477  work_profile->SetRawMultiInfo(PHONE_HOME_WHOLE_NUMBER, phone_variants);
2478
2479  page_id = 5;
2480  response_page_id = 0;
2481  FormData response_data5;
2482  GUIDPair variant_guid(work_profile->guid(), 1);
2483  FillAutofillFormDataAndSaveResults(page_id, form_with_maxlength,
2484      *form_with_maxlength.fields.begin(),
2485      PackGUIDs(empty, variant_guid), &response_page_id, &response_data5);
2486  EXPECT_EQ(5, response_page_id);
2487
2488  ASSERT_EQ(5U, response_data5.fields.size());
2489  EXPECT_EQ(ASCIIToUTF16("1"), response_data5.fields[0].value);
2490  EXPECT_EQ(ASCIIToUTF16("888"), response_data5.fields[1].value);
2491  EXPECT_EQ(ASCIIToUTF16("777"), response_data5.fields[2].value);
2492  EXPECT_EQ(ASCIIToUTF16("1234"), response_data5.fields[3].value);
2493  EXPECT_EQ(base::string16(), response_data5.fields[4].value);
2494}
2495
2496// Test that we can still fill a form when a field has been removed from it.
2497TEST_F(AutofillManagerTest, FormChangesRemoveField) {
2498  // Set up our form data.
2499  FormData form;
2500  test::CreateTestAddressFormData(&form);
2501
2502  // Add a field -- we'll remove it again later.
2503  FormFieldData field;
2504  test::CreateTestFormField("Some", "field", "", "text", &field);
2505  form.fields.insert(form.fields.begin() + 3, field);
2506
2507  std::vector<FormData> forms(1, form);
2508  FormsSeen(forms);
2509
2510  // Now, after the call to |FormsSeen|, we remove the field before filling.
2511  form.fields.erase(form.fields.begin() + 3);
2512
2513  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2514  GUIDPair empty(std::string(), 0);
2515  int response_page_id = 0;
2516  FormData response_data;
2517  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2518      PackGUIDs(empty, guid), &response_page_id, &response_data);
2519  ExpectFilledAddressFormElvis(
2520      response_page_id, response_data, kDefaultPageID, false);
2521}
2522
2523// Test that we can still fill a form when a field has been added to it.
2524TEST_F(AutofillManagerTest, FormChangesAddField) {
2525  // The offset of the phone field in the address form.
2526  const int kPhoneFieldOffset = 9;
2527
2528  // Set up our form data.
2529  FormData form;
2530  test::CreateTestAddressFormData(&form);
2531
2532  // Remove the phone field -- we'll add it back later.
2533  std::vector<FormFieldData>::iterator pos =
2534      form.fields.begin() + kPhoneFieldOffset;
2535  FormFieldData field = *pos;
2536  pos = form.fields.erase(pos);
2537
2538  std::vector<FormData> forms(1, form);
2539  FormsSeen(forms);
2540
2541  // Now, after the call to |FormsSeen|, we restore the field before filling.
2542  form.fields.insert(pos, field);
2543
2544  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2545  GUIDPair empty(std::string(), 0);
2546  int response_page_id = 0;
2547  FormData response_data;
2548  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2549      PackGUIDs(empty, guid), &response_page_id, &response_data);
2550  ExpectFilledAddressFormElvis(
2551      response_page_id, response_data, kDefaultPageID, false);
2552}
2553
2554// Test that we are able to save form data when forms are submitted.
2555TEST_F(AutofillManagerTest, FormSubmitted) {
2556  // Set up our form data.
2557  FormData form;
2558  test::CreateTestAddressFormData(&form);
2559  std::vector<FormData> forms(1, form);
2560  FormsSeen(forms);
2561
2562  // Fill the form.
2563  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2564  GUIDPair empty(std::string(), 0);
2565  int response_page_id = 0;
2566  FormData response_data;
2567  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2568      PackGUIDs(empty, guid), &response_page_id, &response_data);
2569  ExpectFilledAddressFormElvis(
2570      response_page_id, response_data, kDefaultPageID, false);
2571
2572  // Simulate form submission. We should call into the PDM to try to save the
2573  // filled data.
2574  EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(1);
2575  FormSubmitted(response_data);
2576}
2577
2578// Test that when Autocomplete is enabled and Autofill is disabled,
2579// form submissions are still received by AutocompleteHistoryManager.
2580TEST_F(AutofillManagerTest, FormSubmittedAutocompleteEnabled) {
2581  TestAutofillManagerDelegate delegate;
2582  autofill_manager_.reset(new TestAutofillManager(
2583      autofill_driver_.get(),
2584      &delegate,
2585      NULL));
2586  autofill_manager_->set_autofill_enabled(false);
2587  scoped_ptr<MockAutocompleteHistoryManager> autocomplete_history_manager;
2588  autocomplete_history_manager.reset(
2589      new MockAutocompleteHistoryManager(autofill_driver_.get(), &delegate));
2590  autofill_manager_->autocomplete_history_manager_ =
2591      autocomplete_history_manager.Pass();
2592
2593  // Set up our form data.
2594  FormData form;
2595  test::CreateTestAddressFormData(&form);
2596  form.method = ASCIIToUTF16("GET");
2597  MockAutocompleteHistoryManager* m = static_cast<
2598      MockAutocompleteHistoryManager*>(
2599          autofill_manager_->autocomplete_history_manager_.get());
2600  EXPECT_CALL(*m,
2601              OnFormSubmitted(_)).Times(1);
2602  FormSubmitted(form);
2603}
2604
2605// Test that when Autocomplete is enabled and Autofill is disabled,
2606// Autocomplete suggestions are still received.
2607TEST_F(AutofillManagerTest, AutocompleteSuggestionsWhenAutofillDisabled) {
2608  TestAutofillManagerDelegate delegate;
2609  autofill_manager_.reset(new TestAutofillManager(
2610      autofill_driver_.get(),
2611      &delegate,
2612      NULL));
2613  autofill_manager_->set_autofill_enabled(false);
2614  autofill_manager_->SetExternalDelegate(external_delegate_.get());
2615
2616  // Set up our form data.
2617  FormData form;
2618  test::CreateTestAddressFormData(&form);
2619  form.method = ASCIIToUTF16("GET");
2620  std::vector<FormData> forms(1, form);
2621  FormsSeen(forms);
2622  const FormFieldData& field = form.fields[0];
2623  GetAutofillSuggestions(form, field);
2624
2625  // Add some Autocomplete suggestions. We should return the autocomplete
2626  // suggestions, these will be culled by the renderer.
2627  std::vector<base::string16> suggestions;
2628  suggestions.push_back(ASCIIToUTF16("Jay"));
2629  suggestions.push_back(ASCIIToUTF16("Jason"));
2630  AutocompleteSuggestionsReturned(suggestions);
2631
2632  base::string16 expected_values[] = {
2633    ASCIIToUTF16("Jay"),
2634    ASCIIToUTF16("Jason")
2635  };
2636  base::string16 expected_labels[] = { base::string16(), base::string16()};
2637  base::string16 expected_icons[] = { base::string16(), base::string16()};
2638  int expected_unique_ids[] = {0, 0};
2639  external_delegate_->CheckSuggestions(
2640      kDefaultPageID, arraysize(expected_values), expected_values,
2641      expected_labels, expected_icons, expected_unique_ids);
2642}
2643
2644// Test that we are able to save form data when forms are submitted and we only
2645// have server data for the field types.
2646TEST_F(AutofillManagerTest, FormSubmittedServerTypes) {
2647  // Set up our form data.
2648  FormData form;
2649  test::CreateTestAddressFormData(&form);
2650
2651  // Simulate having seen this form on page load.
2652  // |form_structure| will be owned by |autofill_manager_|.
2653  TestFormStructure* form_structure = new TestFormStructure(form);
2654  AutofillMetrics metrics_logger;  // ignored
2655  form_structure->DetermineHeuristicTypes(metrics_logger);
2656
2657  // Clear the heuristic types, and instead set the appropriate server types.
2658  std::vector<AutofillFieldType> heuristic_types, server_types;
2659  for (size_t i = 0; i < form.fields.size(); ++i) {
2660    heuristic_types.push_back(UNKNOWN_TYPE);
2661    server_types.push_back(form_structure->field(i)->type());
2662  }
2663  form_structure->SetFieldTypes(heuristic_types, server_types);
2664  autofill_manager_->AddSeenForm(form_structure);
2665
2666  // Fill the form.
2667  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2668  GUIDPair empty(std::string(), 0);
2669  int response_page_id = 0;
2670  FormData response_data;
2671  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[0],
2672      PackGUIDs(empty, guid), &response_page_id, &response_data);
2673  ExpectFilledAddressFormElvis(
2674      response_page_id, response_data, kDefaultPageID, false);
2675
2676  // Simulate form submission. We should call into the PDM to try to save the
2677  // filled data.
2678  EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(1);
2679  FormSubmitted(response_data);
2680}
2681
2682// Test that the form signature for an uploaded form always matches the form
2683// signature from the query.
2684TEST_F(AutofillManagerTest, FormSubmittedWithDifferentFields) {
2685  // Set up our form data.
2686  FormData form;
2687  test::CreateTestAddressFormData(&form);
2688  std::vector<FormData> forms(1, form);
2689  FormsSeen(forms);
2690
2691  // Cache the expected form signature.
2692  std::string signature = FormStructure(form, std::string()).FormSignature();
2693
2694  // Change the structure of the form prior to submission.
2695  // Websites would typically invoke JavaScript either on page load or on form
2696  // submit to achieve this.
2697  form.fields.pop_back();
2698  FormFieldData field = form.fields[3];
2699  form.fields[3] = form.fields[7];
2700  form.fields[7] = field;
2701
2702  // Simulate form submission.
2703  FormSubmitted(form);
2704  EXPECT_EQ(signature, autofill_manager_->GetSubmittedFormSignature());
2705}
2706
2707// Test that we do not save form data when submitted fields contain default
2708// values.
2709TEST_F(AutofillManagerTest, FormSubmittedWithDefaultValues) {
2710  // Set up our form data.
2711  FormData form;
2712  test::CreateTestAddressFormData(&form);
2713  form.fields[3].value = ASCIIToUTF16("Enter your address");
2714
2715  // Convert the state field to a <select> popup, to make sure that we only
2716  // reject default values for text fields.
2717  ASSERT_TRUE(form.fields[6].name == ASCIIToUTF16("state"));
2718  form.fields[6].form_control_type = "select-one";
2719  form.fields[6].value = ASCIIToUTF16("Tennessee");
2720
2721  std::vector<FormData> forms(1, form);
2722  FormsSeen(forms);
2723
2724  // Fill the form.
2725  GUIDPair guid("00000000-0000-0000-0000-000000000001", 0);
2726  GUIDPair empty(std::string(), 0);
2727  int response_page_id = 0;
2728  FormData response_data;
2729  FillAutofillFormDataAndSaveResults(kDefaultPageID, form, form.fields[3],
2730      PackGUIDs(empty, guid), &response_page_id, &response_data);
2731
2732  // Simulate form submission.  We should call into the PDM to try to save the
2733  // filled data.
2734  EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(1);
2735  FormSubmitted(response_data);
2736
2737  // Set the address field's value back to the default value.
2738  response_data.fields[3].value = ASCIIToUTF16("Enter your address");
2739
2740  // Simulate form submission.  We should not call into the PDM to try to save
2741  // the filled data, since the filled form is effectively missing an address.
2742  EXPECT_CALL(personal_data_, SaveImportedProfile(::testing::_)).Times(0);
2743  FormSubmitted(response_data);
2744}
2745
2746// Checks that resetting the auxiliary profile enabled preference does the right
2747// thing on all platforms.
2748TEST_F(AutofillManagerTest, AuxiliaryProfilesReset) {
2749  PrefService* prefs = user_prefs::UserPrefs::Get(profile());
2750#if defined(OS_MACOSX) || defined(OS_ANDROID)
2751  // Auxiliary profiles is implemented on Mac and Android only.
2752  // OSX: enables Mac Address Book integration.
2753  // Android: enables integration with user's contact profile.
2754  ASSERT_TRUE(
2755      prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2756  prefs->SetBoolean(
2757      ::autofill::prefs::kAutofillAuxiliaryProfilesEnabled, false);
2758  prefs->ClearPref(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled);
2759  ASSERT_TRUE(
2760      prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2761#else
2762  ASSERT_FALSE(
2763      prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2764  prefs->SetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled, true);
2765  prefs->ClearPref(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled);
2766  ASSERT_FALSE(
2767      prefs->GetBoolean(::autofill::prefs::kAutofillAuxiliaryProfilesEnabled));
2768#endif
2769}
2770
2771TEST_F(AutofillManagerTest, DeterminePossibleFieldTypesForUpload) {
2772  FormData form;
2773  form.name = ASCIIToUTF16("MyForm");
2774  form.method = ASCIIToUTF16("POST");
2775  form.origin = GURL("http://myform.com/form.html");
2776  form.action = GURL("http://myform.com/submit.html");
2777  form.user_submitted = true;
2778
2779  std::vector<FieldTypeSet> expected_types;
2780
2781  // These fields should all match.
2782  FormFieldData field;
2783  FieldTypeSet types;
2784  test::CreateTestFormField("", "1", "Elvis", "text", &field);
2785  types.clear();
2786  types.insert(NAME_FIRST);
2787  form.fields.push_back(field);
2788  expected_types.push_back(types);
2789
2790  test::CreateTestFormField("", "2", "Aaron", "text", &field);
2791  types.clear();
2792  types.insert(NAME_MIDDLE);
2793  form.fields.push_back(field);
2794  expected_types.push_back(types);
2795
2796  test::CreateTestFormField("", "3", "A", "text", &field);
2797  types.clear();
2798  types.insert(NAME_MIDDLE_INITIAL);
2799  form.fields.push_back(field);
2800  expected_types.push_back(types);
2801
2802  test::CreateTestFormField("", "4", "Presley", "text", &field);
2803  types.clear();
2804  types.insert(NAME_LAST);
2805  form.fields.push_back(field);
2806  expected_types.push_back(types);
2807
2808  test::CreateTestFormField("", "5", "Elvis Presley", "text", &field);
2809  types.clear();
2810  types.insert(CREDIT_CARD_NAME);
2811  form.fields.push_back(field);
2812  expected_types.push_back(types);
2813
2814  test::CreateTestFormField("", "6", "Elvis Aaron Presley", "text",
2815                                     &field);
2816  types.clear();
2817  types.insert(NAME_FULL);
2818  form.fields.push_back(field);
2819  expected_types.push_back(types);
2820
2821  test::CreateTestFormField("", "7", "theking@gmail.com", "email",
2822                                     &field);
2823  types.clear();
2824  types.insert(EMAIL_ADDRESS);
2825  form.fields.push_back(field);
2826  expected_types.push_back(types);
2827
2828  test::CreateTestFormField("", "8", "RCA", "text", &field);
2829  types.clear();
2830  types.insert(COMPANY_NAME);
2831  form.fields.push_back(field);
2832  expected_types.push_back(types);
2833
2834  test::CreateTestFormField("", "9", "3734 Elvis Presley Blvd.",
2835                                     "text", &field);
2836  types.clear();
2837  types.insert(ADDRESS_HOME_LINE1);
2838  form.fields.push_back(field);
2839  expected_types.push_back(types);
2840
2841  test::CreateTestFormField("", "10", "Apt. 10", "text", &field);
2842  types.clear();
2843  types.insert(ADDRESS_HOME_LINE2);
2844  form.fields.push_back(field);
2845  expected_types.push_back(types);
2846
2847  test::CreateTestFormField("", "11", "Memphis", "text", &field);
2848  types.clear();
2849  types.insert(ADDRESS_HOME_CITY);
2850  form.fields.push_back(field);
2851  expected_types.push_back(types);
2852
2853  test::CreateTestFormField("", "12", "Tennessee", "text", &field);
2854  types.clear();
2855  types.insert(ADDRESS_HOME_STATE);
2856  form.fields.push_back(field);
2857  expected_types.push_back(types);
2858
2859  test::CreateTestFormField("", "13", "38116", "text", &field);
2860  types.clear();
2861  types.insert(ADDRESS_HOME_ZIP);
2862  form.fields.push_back(field);
2863  expected_types.push_back(types);
2864
2865  test::CreateTestFormField("", "14", "USA", "text", &field);
2866  types.clear();
2867  types.insert(ADDRESS_HOME_COUNTRY);
2868  form.fields.push_back(field);
2869  expected_types.push_back(types);
2870
2871  test::CreateTestFormField("", "15", "United States", "text", &field);
2872  types.clear();
2873  types.insert(ADDRESS_HOME_COUNTRY);
2874  form.fields.push_back(field);
2875  expected_types.push_back(types);
2876
2877  test::CreateTestFormField("", "16", "+1 (234) 567-8901", "text",
2878                                     &field);
2879  types.clear();
2880  types.insert(PHONE_HOME_WHOLE_NUMBER);
2881  form.fields.push_back(field);
2882  expected_types.push_back(types);
2883
2884  test::CreateTestFormField("", "17", "2345678901", "text", &field);
2885  types.clear();
2886  types.insert(PHONE_HOME_CITY_AND_NUMBER);
2887  form.fields.push_back(field);
2888  expected_types.push_back(types);
2889
2890  test::CreateTestFormField("", "18", "1", "text", &field);
2891  types.clear();
2892  types.insert(PHONE_HOME_COUNTRY_CODE);
2893  form.fields.push_back(field);
2894  expected_types.push_back(types);
2895
2896  test::CreateTestFormField("", "19", "234", "text", &field);
2897  types.clear();
2898  types.insert(PHONE_HOME_CITY_CODE);
2899  form.fields.push_back(field);
2900  expected_types.push_back(types);
2901
2902  test::CreateTestFormField("", "20", "5678901", "text", &field);
2903  types.clear();
2904  types.insert(PHONE_HOME_NUMBER);
2905  form.fields.push_back(field);
2906  expected_types.push_back(types);
2907
2908  test::CreateTestFormField("", "21", "567", "text", &field);
2909  types.clear();
2910  types.insert(PHONE_HOME_NUMBER);
2911  form.fields.push_back(field);
2912  expected_types.push_back(types);
2913
2914  test::CreateTestFormField("", "22", "8901", "text", &field);
2915  types.clear();
2916  types.insert(PHONE_HOME_NUMBER);
2917  form.fields.push_back(field);
2918  expected_types.push_back(types);
2919
2920  test::CreateTestFormField("", "23", "4234-5678-9012-3456", "text",
2921                                     &field);
2922  types.clear();
2923  types.insert(CREDIT_CARD_NUMBER);
2924  form.fields.push_back(field);
2925  expected_types.push_back(types);
2926
2927  test::CreateTestFormField("", "24", "04", "text", &field);
2928  types.clear();
2929  types.insert(CREDIT_CARD_EXP_MONTH);
2930  form.fields.push_back(field);
2931  expected_types.push_back(types);
2932
2933  test::CreateTestFormField("", "25", "April", "text", &field);
2934  types.clear();
2935  types.insert(CREDIT_CARD_EXP_MONTH);
2936  form.fields.push_back(field);
2937  expected_types.push_back(types);
2938
2939  test::CreateTestFormField("", "26", "2012", "text", &field);
2940  types.clear();
2941  types.insert(CREDIT_CARD_EXP_4_DIGIT_YEAR);
2942  form.fields.push_back(field);
2943  expected_types.push_back(types);
2944
2945  test::CreateTestFormField("", "27", "12", "text", &field);
2946  types.clear();
2947  types.insert(CREDIT_CARD_EXP_2_DIGIT_YEAR);
2948  form.fields.push_back(field);
2949  expected_types.push_back(types);
2950
2951  test::CreateTestFormField("", "28", "04/2012", "text", &field);
2952  types.clear();
2953  types.insert(CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR);
2954  form.fields.push_back(field);
2955  expected_types.push_back(types);
2956
2957  // Make sure that we trim whitespace properly.
2958  test::CreateTestFormField("", "29", "", "text", &field);
2959  types.clear();
2960  types.insert(EMPTY_TYPE);
2961  form.fields.push_back(field);
2962  expected_types.push_back(types);
2963
2964  test::CreateTestFormField("", "30", " ", "text", &field);
2965  types.clear();
2966  types.insert(EMPTY_TYPE);
2967  form.fields.push_back(field);
2968  expected_types.push_back(types);
2969
2970  test::CreateTestFormField("", "31", " Elvis", "text", &field);
2971  types.clear();
2972  types.insert(NAME_FIRST);
2973  form.fields.push_back(field);
2974  expected_types.push_back(types);
2975
2976  test::CreateTestFormField("", "32", "Elvis ", "text", &field);
2977  types.clear();
2978  types.insert(NAME_FIRST);
2979  form.fields.push_back(field);
2980  expected_types.push_back(types);
2981
2982  // These fields should not match, as they differ by case.
2983  test::CreateTestFormField("", "33", "elvis", "text", &field);
2984  types.clear();
2985  types.insert(UNKNOWN_TYPE);
2986  form.fields.push_back(field);
2987  expected_types.push_back(types);
2988
2989  test::CreateTestFormField("", "34", "3734 Elvis Presley BLVD",
2990                                     "text", &field);
2991  types.clear();
2992  types.insert(UNKNOWN_TYPE);
2993  form.fields.push_back(field);
2994  expected_types.push_back(types);
2995
2996  // These fields should not match, as they are unsupported variants.
2997  test::CreateTestFormField("", "35", "Elvis Aaron", "text", &field);
2998  types.clear();
2999  types.insert(UNKNOWN_TYPE);
3000  form.fields.push_back(field);
3001  expected_types.push_back(types);
3002
3003  test::CreateTestFormField("", "36", "Mr. Presley", "text", &field);
3004  types.clear();
3005  types.insert(UNKNOWN_TYPE);
3006  form.fields.push_back(field);
3007  expected_types.push_back(types);
3008
3009  test::CreateTestFormField("", "37", "3734 Elvis Presley", "text",
3010                                     &field);
3011  types.clear();
3012  types.insert(UNKNOWN_TYPE);
3013  form.fields.push_back(field);
3014  expected_types.push_back(types);
3015
3016  test::CreateTestFormField("", "38", "TN", "text", &field);
3017  types.clear();
3018  types.insert(UNKNOWN_TYPE);
3019  form.fields.push_back(field);
3020  expected_types.push_back(types);
3021
3022  test::CreateTestFormField("", "39", "38116-1023", "text", &field);
3023  types.clear();
3024  types.insert(UNKNOWN_TYPE);
3025  form.fields.push_back(field);
3026  expected_types.push_back(types);
3027
3028  test::CreateTestFormField("", "20", "5", "text", &field);
3029  types.clear();
3030  types.insert(UNKNOWN_TYPE);
3031  form.fields.push_back(field);
3032  expected_types.push_back(types);
3033
3034  test::CreateTestFormField("", "20", "56", "text", &field);
3035  types.clear();
3036  types.insert(UNKNOWN_TYPE);
3037  form.fields.push_back(field);
3038  expected_types.push_back(types);
3039
3040  test::CreateTestFormField("", "20", "901", "text", &field);
3041  types.clear();
3042  types.insert(UNKNOWN_TYPE);
3043  form.fields.push_back(field);
3044  expected_types.push_back(types);
3045
3046  autofill_manager_->set_expected_submitted_field_types(expected_types);
3047  FormSubmitted(form);
3048}
3049
3050TEST_F(AutofillManagerTest, RemoveProfile) {
3051  // Add and remove an Autofill profile.
3052  AutofillProfile* profile = new AutofillProfile;
3053  std::string guid = "00000000-0000-0000-0000-000000000102";
3054  profile->set_guid(guid.c_str());
3055  autofill_manager_->AddProfile(profile);
3056
3057  GUIDPair guid_pair(guid, 0);
3058  GUIDPair empty(std::string(), 0);
3059  int id = PackGUIDs(empty, guid_pair);
3060
3061  autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
3062
3063  EXPECT_FALSE(autofill_manager_->GetProfileWithGUID(guid.c_str()));
3064}
3065
3066TEST_F(AutofillManagerTest, RemoveCreditCard){
3067  // Add and remove an Autofill credit card.
3068  CreditCard* credit_card = new CreditCard;
3069  std::string guid = "00000000-0000-0000-0000-000000100007";
3070  credit_card->set_guid(guid.c_str());
3071  autofill_manager_->AddCreditCard(credit_card);
3072
3073  GUIDPair guid_pair(guid, 0);
3074  GUIDPair empty(std::string(), 0);
3075  int id = PackGUIDs(guid_pair, empty);
3076
3077  autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
3078
3079  EXPECT_FALSE(autofill_manager_->GetCreditCardWithGUID(guid.c_str()));
3080}
3081
3082TEST_F(AutofillManagerTest, RemoveProfileVariant) {
3083  // Add and remove an Autofill profile.
3084  AutofillProfile* profile = new AutofillProfile;
3085  std::string guid = "00000000-0000-0000-0000-000000000102";
3086  profile->set_guid(guid.c_str());
3087  autofill_manager_->AddProfile(profile);
3088
3089  GUIDPair guid_pair(guid, 1);
3090  GUIDPair empty(std::string(), 0);
3091  int id = PackGUIDs(empty, guid_pair);
3092
3093  autofill_manager_->RemoveAutofillProfileOrCreditCard(id);
3094
3095  // TODO(csharp): Currently variants should not be deleted, but once they are
3096  // update these expectations.
3097  // http://crbug.com/124211
3098  EXPECT_TRUE(autofill_manager_->GetProfileWithGUID(guid.c_str()));
3099}
3100
3101TEST_F(AutofillManagerTest, DisabledAutofillDispatchesError) {
3102  EXPECT_TRUE(autofill_manager_->request_autocomplete_results().empty());
3103
3104  autofill_manager_->set_autofill_enabled(false);
3105  autofill_manager_->OnRequestAutocomplete(FormData(),
3106                                           GURL());
3107
3108  EXPECT_EQ(1U, autofill_manager_->request_autocomplete_results().size());
3109  EXPECT_EQ(WebFormElement::AutocompleteResultErrorDisabled,
3110            autofill_manager_->request_autocomplete_results()[0].first);
3111}
3112
3113namespace {
3114
3115class MockAutofillManagerDelegate : public TestAutofillManagerDelegate {
3116 public:
3117  MockAutofillManagerDelegate()
3118      : autocheckout_bubble_shown_(false) {}
3119
3120  virtual ~MockAutofillManagerDelegate() {}
3121
3122  virtual void ShowAutocheckoutBubble(
3123      const gfx::RectF& bounds,
3124      bool is_google_user,
3125      const base::Callback<void(AutocheckoutBubbleState)>& callback) OVERRIDE {
3126    autocheckout_bubble_shown_ = true;
3127    callback.Run(AUTOCHECKOUT_BUBBLE_ACCEPTED);
3128  }
3129
3130  virtual void ShowRequestAutocompleteDialog(
3131      const FormData& form,
3132      const GURL& source_url,
3133      DialogType dialog_type,
3134      const base::Callback<void(const FormStructure*,
3135                                const std::string&)>& callback) OVERRIDE {
3136    callback.Run(user_supplied_data_.get(), "google_transaction_id");
3137  }
3138
3139  void SetUserSuppliedData(scoped_ptr<FormStructure> user_supplied_data) {
3140    user_supplied_data_.reset(user_supplied_data.release());
3141  }
3142
3143  bool autocheckout_bubble_shown() const {
3144    return autocheckout_bubble_shown_;
3145  }
3146
3147 private:
3148  bool autocheckout_bubble_shown_;
3149  scoped_ptr<FormStructure> user_supplied_data_;
3150
3151 DISALLOW_COPY_AND_ASSIGN(MockAutofillManagerDelegate);
3152};
3153
3154}  // namespace
3155
3156// Test that Autocheckout bubble is offered when server specifies field types.
3157TEST_F(AutofillManagerTest, TestBubbleShown) {
3158  MockAutofillManagerDelegate delegate;
3159  autofill_manager_.reset(new TestAutofillManager(
3160      autofill_driver_.get(), &delegate, &personal_data_));
3161  autofill_manager_->set_autofill_enabled(true);
3162  autofill_manager_->MarkAsFirstPageInAutocheckoutFlow();
3163
3164  FormData form;
3165  test::CreateTestAddressFormData(&form);
3166
3167  TestFormStructure* form_structure = new TestFormStructure(form);
3168  AutofillMetrics metrics_logger;  // ignored
3169  form_structure->DetermineHeuristicTypes(metrics_logger);
3170
3171  // Build and add form structure with server data.
3172  std::vector<AutofillFieldType> heuristic_types, server_types;
3173  for (size_t i = 0; i < form.fields.size(); ++i) {
3174    heuristic_types.push_back(UNKNOWN_TYPE);
3175    server_types.push_back(form_structure->field(i)->type());
3176  }
3177  form_structure->SetFieldTypes(heuristic_types, server_types);
3178  autofill_manager_->AddSeenForm(form_structure);
3179
3180  autofill_manager_->OnMaybeShowAutocheckoutBubble(form, gfx::RectF());
3181
3182  EXPECT_TRUE(delegate.autocheckout_bubble_shown());
3183}
3184
3185// Test that Autocheckout bubble is not offered when server doesn't have data
3186// for the form.
3187TEST_F(AutofillManagerTest, TestAutocheckoutBubbleNotShown) {
3188  MockAutofillManagerDelegate delegate;
3189  autofill_manager_.reset(new TestAutofillManager(
3190      autofill_driver_.get(), &delegate, &personal_data_));
3191  autofill_manager_->set_autofill_enabled(true);
3192  autofill_manager_->MarkAsFirstPageInAutocheckoutFlow();
3193
3194  FormData form;
3195  test::CreateTestAddressFormData(&form);
3196
3197  TestFormStructure* form_structure = new TestFormStructure(form);
3198  AutofillMetrics metrics_logger;  // ignored
3199  form_structure->DetermineHeuristicTypes(metrics_logger);
3200
3201  // Build form structure without server data.
3202  std::vector<AutofillFieldType> heuristic_types, server_types;
3203  for (size_t i = 0; i < form.fields.size(); ++i) {
3204    heuristic_types.push_back(form_structure->field(i)->type());
3205    server_types.push_back(NO_SERVER_DATA);
3206  }
3207  form_structure->SetFieldTypes(heuristic_types, server_types);
3208  autofill_manager_->AddSeenForm(form_structure);
3209
3210  autofill_manager_->OnMaybeShowAutocheckoutBubble(form, gfx::RectF());
3211
3212  EXPECT_FALSE(delegate.autocheckout_bubble_shown());
3213}
3214
3215// Test our external delegate is called at the right time.
3216TEST_F(AutofillManagerTest, TestExternalDelegate) {
3217  FormData form;
3218  test::CreateTestAddressFormData(&form);
3219  std::vector<FormData> forms(1, form);
3220  FormsSeen(forms);
3221  const FormFieldData& field = form.fields[0];
3222  GetAutofillSuggestions(form, field);  // should call the delegate's OnQuery()
3223
3224  EXPECT_TRUE(external_delegate_->on_query_seen());
3225}
3226
3227// Test that in the case of Autocheckout, forms seen are in order supplied.
3228TEST_F(AutofillManagerTest, DynamicFormsSeenAndIgnored) {
3229  MockAutofillManagerDelegate delegate;
3230  autofill_manager_.reset(new TestAutofillManager(
3231      autofill_driver_.get(), &delegate, &personal_data_));
3232  FormData shipping_options;
3233  CreateTestShippingOptionsFormData(&shipping_options);
3234  FormData user_supplied;
3235  CreateTestFormWithAutocompleteAttribute(&user_supplied);
3236  FormData address;
3237  test::CreateTestAddressFormData(&address);
3238
3239  autofill_manager_->set_autocheckout_url_prefix("test-prefix");
3240  // Push address only
3241  std::vector<FormData> forms;
3242  forms.push_back(address);
3243
3244  // Build and add form structure with server data.
3245  scoped_ptr<TestFormStructure> form_structure(new TestFormStructure(address));
3246  std::vector<AutofillFieldType> heuristic_types, server_types;
3247  for (size_t i = 0; i < address.fields.size(); ++i) {
3248    heuristic_types.push_back(UNKNOWN_TYPE);
3249    server_types.push_back(form_structure->field(i)->type());
3250  }
3251  form_structure->SetFieldTypes(heuristic_types, server_types);
3252  autofill_manager_->AddSeenForm(form_structure.release());
3253
3254  // Make sure normal form is handled correctly.
3255  autofill_manager_->MarkAsFirstPageInAutocheckoutFlowIgnoringAjax();
3256  std::vector<FormStructure*> form_structures;
3257  form_structures = autofill_manager_->GetFormStructures();
3258  ASSERT_EQ(1U, form_structures.size());
3259  EXPECT_EQ("/form.html", form_structures[0]->source_url().path());
3260
3261  scoped_ptr<FormStructure> filled_form(new TestFormStructure(address));
3262  delegate.SetUserSuppliedData(filled_form.Pass());
3263  autofill_manager_->OnMaybeShowAutocheckoutBubble(address, gfx::RectF());
3264
3265  // Push other forms
3266  forms.push_back(shipping_options);
3267  forms.push_back(user_supplied);
3268
3269  // FormStructure should contain the same forms as before.
3270  DynamicFormsSeen(forms);
3271  form_structures = autofill_manager_->GetFormStructures();
3272  ASSERT_EQ(1U, form_structures.size());
3273  EXPECT_EQ("/form.html", form_structures[0]->source_url().path());
3274}
3275
3276}  // namespace autofill
3277