autofill_browsertest.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
1// Copyright (c) 2012 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 <string>
6
7#include "base/basictypes.h"
8#include "base/command_line.h"
9#include "base/file_util.h"
10#include "base/memory/ref_counted.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/rand_util.h"
13#include "base/strings/string16.h"
14#include "base/strings/string_number_conversions.h"
15#include "base/strings/string_split.h"
16#include "base/strings/utf_string_conversions.h"
17#include "base/time/time.h"
18#include "chrome/browser/autofill/personal_data_manager_factory.h"
19#include "chrome/browser/chrome_notification_types.h"
20#include "chrome/browser/infobars/confirm_infobar_delegate.h"
21#include "chrome/browser/infobars/infobar_service.h"
22#include "chrome/browser/profiles/profile.h"
23#include "chrome/browser/translate/translate_infobar_delegate.h"
24#include "chrome/browser/translate/translate_manager.h"
25#include "chrome/browser/ui/browser.h"
26#include "chrome/browser/ui/browser_window.h"
27#include "chrome/browser/ui/tabs/tab_strip_model.h"
28#include "chrome/common/render_messages.h"
29#include "chrome/test/base/in_process_browser_test.h"
30#include "chrome/test/base/test_switches.h"
31#include "chrome/test/base/ui_test_utils.h"
32#include "components/autofill/content/browser/autofill_driver_impl.h"
33#include "components/autofill/core/browser/autofill_common_test.h"
34#include "components/autofill/core/browser/autofill_external_delegate.h"
35#include "components/autofill/core/browser/autofill_manager.h"
36#include "components/autofill/core/browser/autofill_manager_test_delegate.h"
37#include "components/autofill/core/browser/autofill_profile.h"
38#include "components/autofill/core/browser/credit_card.h"
39#include "components/autofill/core/browser/personal_data_manager.h"
40#include "components/autofill/core/browser/personal_data_manager_observer.h"
41#include "components/autofill/core/browser/validation.h"
42#include "content/public/browser/navigation_controller.h"
43#include "content/public/browser/notification_observer.h"
44#include "content/public/browser/notification_registrar.h"
45#include "content/public/browser/notification_service.h"
46#include "content/public/browser/render_view_host.h"
47#include "content/public/browser/web_contents.h"
48#include "content/public/test/browser_test_utils.h"
49#include "content/public/test/test_renderer_host.h"
50#include "content/public/test/test_utils.h"
51#include "net/url_request/test_url_fetcher_factory.h"
52#include "testing/gmock/include/gmock/gmock.h"
53#include "testing/gtest/include/gtest/gtest.h"
54#include "ui/base/keycodes/keyboard_codes.h"
55
56namespace autofill {
57
58static const char* kDataURIPrefix = "data:text/html;charset=utf-8,";
59static const char* kTestFormString =
60    "<form action=\"http://www.example.com/\" method=\"POST\">"
61    "<label for=\"firstname\">First name:</label>"
62    " <input type=\"text\" id=\"firstname\""
63    "        onFocus=\"domAutomationController.send(true)\"><br>"
64    "<label for=\"lastname\">Last name:</label>"
65    " <input type=\"text\" id=\"lastname\"><br>"
66    "<label for=\"address1\">Address line 1:</label>"
67    " <input type=\"text\" id=\"address1\"><br>"
68    "<label for=\"address2\">Address line 2:</label>"
69    " <input type=\"text\" id=\"address2\"><br>"
70    "<label for=\"city\">City:</label>"
71    " <input type=\"text\" id=\"city\"><br>"
72    "<label for=\"state\">State:</label>"
73    " <select id=\"state\">"
74    " <option value=\"\" selected=\"yes\">--</option>"
75    " <option value=\"CA\">California</option>"
76    " <option value=\"TX\">Texas</option>"
77    " </select><br>"
78    "<label for=\"zip\">ZIP code:</label>"
79    " <input type=\"text\" id=\"zip\"><br>"
80    "<label for=\"country\">Country:</label>"
81    " <select id=\"country\">"
82    " <option value=\"\" selected=\"yes\">--</option>"
83    " <option value=\"CA\">Canada</option>"
84    " <option value=\"US\">United States</option>"
85    " </select><br>"
86    "<label for=\"phone\">Phone number:</label>"
87    " <input type=\"text\" id=\"phone\"><br>"
88    "</form>";
89
90class AutofillManagerTestDelegateImpl
91    : public autofill::AutofillManagerTestDelegate {
92 public:
93  AutofillManagerTestDelegateImpl() {}
94
95  virtual void DidPreviewFormData() OVERRIDE {
96    loop_runner_->Quit();
97  }
98
99  virtual void DidFillFormData() OVERRIDE {
100    loop_runner_->Quit();
101  }
102
103  virtual void DidShowSuggestions() OVERRIDE {
104    loop_runner_->Quit();
105  }
106
107  void Reset() {
108    loop_runner_ = new content::MessageLoopRunner();
109  }
110
111  void Wait() {
112    loop_runner_->Run();
113  }
114
115 private:
116  scoped_refptr<content::MessageLoopRunner> loop_runner_;
117
118  DISALLOW_COPY_AND_ASSIGN(AutofillManagerTestDelegateImpl);
119};
120
121class WindowedPersonalDataManagerObserver
122    : public PersonalDataManagerObserver,
123      public content::NotificationObserver {
124 public:
125  explicit WindowedPersonalDataManagerObserver(Browser* browser)
126      : alerted_(false),
127        has_run_message_loop_(false),
128        browser_(browser),
129        infobar_service_(NULL) {
130    PersonalDataManagerFactory::GetForProfile(browser_->profile())->
131        AddObserver(this);
132    registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
133                   content::NotificationService::AllSources());
134  }
135
136  virtual ~WindowedPersonalDataManagerObserver() {
137    if (infobar_service_ && (infobar_service_->infobar_count() > 0))
138      infobar_service_->RemoveInfoBar(infobar_service_->infobar_at(0));
139  }
140
141  void Wait() {
142    if (!alerted_) {
143      has_run_message_loop_ = true;
144      content::RunMessageLoop();
145    }
146    PersonalDataManagerFactory::GetForProfile(browser_->profile())->
147        RemoveObserver(this);
148  }
149
150  // PersonalDataManagerObserver:
151  virtual void OnPersonalDataChanged() OVERRIDE {
152    if (has_run_message_loop_) {
153      base::MessageLoopForUI::current()->Quit();
154      has_run_message_loop_ = false;
155    }
156    alerted_ = true;
157  }
158
159  virtual void OnInsufficientFormData() OVERRIDE {
160    OnPersonalDataChanged();
161  }
162
163  // content::NotificationObserver:
164  virtual void Observe(int type,
165                       const content::NotificationSource& source,
166                       const content::NotificationDetails& details) OVERRIDE {
167    EXPECT_EQ(chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, type);
168    infobar_service_ = InfoBarService::FromWebContents(
169        browser_->tab_strip_model()->GetActiveWebContents());
170    ConfirmInfoBarDelegate* infobar_delegate =
171        infobar_service_->infobar_at(0)->AsConfirmInfoBarDelegate();
172    ASSERT_TRUE(infobar_delegate);
173    infobar_delegate->Accept();
174  }
175
176 private:
177  bool alerted_;
178  bool has_run_message_loop_;
179  Browser* browser_;
180  content::NotificationRegistrar registrar_;
181  InfoBarService* infobar_service_;
182};
183
184class TestAutofillExternalDelegate : public AutofillExternalDelegate {
185 public:
186  TestAutofillExternalDelegate(content::WebContents* web_contents,
187                               AutofillManager* autofill_manager,
188                               AutofillDriver* autofill_driver)
189      : AutofillExternalDelegate(web_contents, autofill_manager,
190                                 autofill_driver),
191        keyboard_listener_(NULL) {
192  }
193  virtual ~TestAutofillExternalDelegate() {}
194
195  virtual void OnPopupShown(content::KeyboardListener* listener) OVERRIDE {
196    AutofillExternalDelegate::OnPopupShown(listener);
197    keyboard_listener_ = listener;
198  }
199
200  virtual void OnPopupHidden(content::KeyboardListener* listener) OVERRIDE {
201    keyboard_listener_ = NULL;
202    AutofillExternalDelegate::OnPopupHidden(listener);
203  }
204
205  content::KeyboardListener* keyboard_listener() {
206    return keyboard_listener_;
207  }
208
209 private:
210  // The popup that is currently registered as a keyboard listener, or NULL if
211  // there is none.
212  content::KeyboardListener* keyboard_listener_;
213
214  DISALLOW_COPY_AND_ASSIGN(TestAutofillExternalDelegate);
215};
216
217class AutofillTest : public InProcessBrowserTest {
218 protected:
219  AutofillTest() {}
220
221  virtual void SetUpOnMainThread() OVERRIDE {
222    // Don't want Keychain coming up on Mac.
223    test::DisableSystemServices(browser()->profile());
224
225    // When testing the native UI, hook up a test external delegate, which
226    // allows us to forward keyboard events to the popup directly.
227    content::WebContents* web_contents =
228        browser()->tab_strip_model()->GetActiveWebContents();
229    AutofillDriverImpl* autofill_driver =
230        AutofillDriverImpl::FromWebContents(web_contents);
231    AutofillManager* autofill_manager = autofill_driver->autofill_manager();
232    scoped_ptr<AutofillExternalDelegate> external_delegate(
233        new TestAutofillExternalDelegate(web_contents, autofill_manager,
234                                         autofill_driver));
235    autofill_driver->SetAutofillExternalDelegate(external_delegate.Pass());
236    autofill_manager->SetTestDelegate(&test_delegate_);
237  }
238
239  virtual void CleanUpOnMainThread() OVERRIDE {
240    // Make sure to close any showing popups prior to tearing down the UI.
241    content::WebContents* web_contents =
242        browser()->tab_strip_model()->GetActiveWebContents();
243    AutofillManager* autofill_manager =
244        AutofillDriverImpl::FromWebContents(web_contents)->autofill_manager();
245    autofill_manager->delegate()->HideAutofillPopup();
246  }
247
248  PersonalDataManager* personal_data_manager() {
249    return PersonalDataManagerFactory::GetForProfile(browser()->profile());
250  }
251
252  void CreateTestProfile() {
253    AutofillProfile profile;
254    test::SetProfileInfo(
255        &profile, "Milton", "C.", "Waddams",
256        "red.swingline@initech.com", "Initech", "4120 Freidrich Lane",
257        "Basement", "Austin", "Texas", "78744", "US", "5125551234");
258
259    WindowedPersonalDataManagerObserver observer(browser());
260    personal_data_manager()->AddProfile(profile);
261
262    // AddProfile is asynchronous. Wait for it to finish before continuing the
263    // tests.
264    observer.Wait();
265  }
266
267  void SetProfiles(std::vector<AutofillProfile>* profiles) {
268    WindowedPersonalDataManagerObserver observer(browser());
269    personal_data_manager()->SetProfiles(profiles);
270    observer.Wait();
271  }
272
273  void SetProfile(const AutofillProfile& profile) {
274    std::vector<AutofillProfile> profiles;
275    profiles.push_back(profile);
276    SetProfiles(&profiles);
277  }
278
279  void SetCards(std::vector<CreditCard>* cards) {
280    WindowedPersonalDataManagerObserver observer(browser());
281    personal_data_manager()->SetCreditCards(cards);
282    observer.Wait();
283  }
284
285  void SetCard(const CreditCard& card) {
286    std::vector<CreditCard> cards;
287    cards.push_back(card);
288    SetCards(&cards);
289  }
290
291  typedef std::map<std::string, std::string> FormMap;
292  // Navigate to the form, input values into the fields, and submit the form.
293  // The function returns after the PersonalDataManager is updated.
294  void FillFormAndSubmit(const std::string& filename, const FormMap& data) {
295    GURL url = test_server()->GetURL("files/autofill/" + filename);
296    ui_test_utils::NavigateToURL(browser(), url);
297
298    std::string js;
299    for (FormMap::const_iterator i = data.begin(); i != data.end(); ++i) {
300      js += "document.getElementById('" + i->first + "').value = '" +
301            i->second + "';";
302    }
303    js += "document.getElementById('testform').submit();";
304
305    WindowedPersonalDataManagerObserver observer(browser());
306    ASSERT_TRUE(content::ExecuteScript(render_view_host(), js));
307    observer.Wait();
308  }
309
310  void SubmitCreditCard(const char* name,
311                        const char* number,
312                        const char* exp_month,
313                        const char* exp_year) {
314    FormMap data;
315    data["CREDIT_CARD_NAME"] = name;
316    data["CREDIT_CARD_NUMBER"] = number;
317    data["CREDIT_CARD_EXP_MONTH"] = exp_month;
318    data["CREDIT_CARD_EXP_4_DIGIT_YEAR"] = exp_year;
319    FillFormAndSubmit("autofill_creditcard_form.html", data);
320  }
321
322  // Populates a webpage form using autofill data and keypress events.
323  // This function focuses the specified input field in the form, and then
324  // sends keypress events to the tab to cause the form to be populated.
325  void PopulateForm(const std::string& field_id) {
326    std::string js("document.getElementById('" + field_id + "').focus();");
327    ASSERT_TRUE(content::ExecuteScript(render_view_host(), js));
328
329    SendKeyToPageAndWait(ui::VKEY_DOWN);
330    SendKeyToPopupAndWait(ui::VKEY_DOWN);
331    SendKeyToPopupAndWait(ui::VKEY_RETURN);
332  }
333
334  // Aggregate profiles from forms into Autofill preferences. Returns the number
335  // of parsed profiles.
336  int AggregateProfilesIntoAutofillPrefs(const std::string& filename) {
337    CHECK(test_server()->Start());
338
339    std::string data;
340    base::FilePath data_file =
341        ui_test_utils::GetTestFilePath(base::FilePath().AppendASCII("autofill"),
342                                       base::FilePath().AppendASCII(filename));
343    CHECK(file_util::ReadFileToString(data_file, &data));
344    std::vector<std::string> lines;
345    base::SplitString(data, '\n', &lines);
346    for (size_t i = 0; i < lines.size(); ++i) {
347      if (StartsWithASCII(lines[i], "#", false))
348        continue;
349      std::vector<std::string> fields;
350      base::SplitString(lines[i], '|', &fields);
351      if (fields.empty())
352        continue;  // Blank line.
353      CHECK_EQ(12u, fields.size());
354
355      FormMap data;
356      data["NAME_FIRST"] = fields[0];
357      data["NAME_MIDDLE"] = fields[1];
358      data["NAME_LAST"] = fields[2];
359      data["EMAIL_ADDRESS"] = fields[3];
360      data["COMPANY_NAME"] = fields[4];
361      data["ADDRESS_HOME_LINE1"] = fields[5];
362      data["ADDRESS_HOME_LINE2"] = fields[6];
363      data["ADDRESS_HOME_CITY"] = fields[7];
364      data["ADDRESS_HOME_STATE"] = fields[8];
365      data["ADDRESS_HOME_ZIP"] = fields[9];
366      data["ADDRESS_HOME_COUNTRY"] = fields[10];
367      data["PHONE_HOME_WHOLE_NUMBER"] = fields[11];
368
369      FillFormAndSubmit("duplicate_profiles_test.html", data);
370    }
371    return lines.size();
372  }
373
374  void ExpectFieldValue(const std::string& field_name,
375                        const std::string& expected_value) {
376    std::string value;
377    ASSERT_TRUE(content::ExecuteScriptAndExtractString(
378        browser()->tab_strip_model()->GetActiveWebContents(),
379        "window.domAutomationController.send("
380        "    document.getElementById('" + field_name + "').value);",
381        &value));
382    EXPECT_EQ(expected_value, value);
383  }
384
385  content::RenderViewHost* render_view_host() {
386    return browser()->tab_strip_model()->GetActiveWebContents()->
387        GetRenderViewHost();
388  }
389
390  void SimulateURLFetch(bool success) {
391    net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
392    ASSERT_TRUE(fetcher);
393    net::URLRequestStatus status;
394    status.set_status(success ? net::URLRequestStatus::SUCCESS :
395                                net::URLRequestStatus::FAILED);
396
397    std::string script = " var google = {};"
398        "google.translate = (function() {"
399        "  return {"
400        "    TranslateService: function() {"
401        "      return {"
402        "        isAvailable : function() {"
403        "          return true;"
404        "        },"
405        "        restore : function() {"
406        "          return;"
407        "        },"
408        "        getDetectedLanguage : function() {"
409        "          return \"ja\";"
410        "        },"
411        "        translatePage : function(originalLang, targetLang,"
412        "                                 onTranslateProgress) {"
413        "          document.getElementsByTagName(\"body\")[0].innerHTML = '" +
414        std::string(kTestFormString) +
415        "              ';"
416        "          onTranslateProgress(100, true, false);"
417        "        }"
418        "      };"
419        "    }"
420        "  };"
421        "})();";
422
423    fetcher->set_url(fetcher->GetOriginalURL());
424    fetcher->set_status(status);
425    fetcher->set_response_code(success ? 200 : 500);
426    fetcher->SetResponseString(script);
427    fetcher->delegate()->OnURLFetchComplete(fetcher);
428  }
429
430  void FocusFirstNameField() {
431    LOG(WARNING) << "Clicking on the tab.";
432    content::SimulateMouseClick(
433        browser()->tab_strip_model()->GetActiveWebContents(),
434        0,
435        WebKit::WebMouseEvent::ButtonLeft);
436
437    LOG(WARNING) << "Focusing the first name field.";
438    bool result = false;
439    ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
440        render_view_host(),
441        "if (document.readyState === 'complete')"
442        "  document.getElementById('firstname').focus();"
443        "else"
444        "  domAutomationController.send(false);",
445        &result));
446    ASSERT_TRUE(result);
447  }
448
449  void ExpectFilledTestForm() {
450    ExpectFieldValue("firstname", "Milton");
451    ExpectFieldValue("lastname", "Waddams");
452    ExpectFieldValue("address1", "4120 Freidrich Lane");
453    ExpectFieldValue("address2", "Basement");
454    ExpectFieldValue("city", "Austin");
455    ExpectFieldValue("state", "TX");
456    ExpectFieldValue("zip", "78744");
457    ExpectFieldValue("country", "US");
458    ExpectFieldValue("phone", "5125551234");
459  }
460
461  void SendKeyToPageAndWait(ui::KeyboardCode key) {
462    test_delegate_.Reset();
463    content::SimulateKeyPress(
464        browser()->tab_strip_model()->GetActiveWebContents(),
465        key, false, false, false, false);
466    test_delegate_.Wait();
467  }
468
469  void SendKeyToPopupAndWait(ui::KeyboardCode key) {
470    // When testing the native UI, route popup-targeted key presses via the
471    // external delegate.
472    content::NativeWebKeyboardEvent event;
473    event.windowsKeyCode = key;
474    test_delegate_.Reset();
475    external_delegate()->keyboard_listener()->HandleKeyPressEvent(event);
476    test_delegate_.Wait();
477  }
478
479  void TryBasicFormFill() {
480    FocusFirstNameField();
481
482    // Start filling the first name field with "M" and wait for the popup to be
483    // shown.
484    LOG(WARNING) << "Typing 'M' to bring up the Autofill popup.";
485    SendKeyToPageAndWait(ui::VKEY_M);
486
487    // Press the down arrow to select the suggestion and preview the autofilled
488    // form.
489    LOG(WARNING) << "Simulating down arrow press to initiate Autofill preview.";
490    SendKeyToPopupAndWait(ui::VKEY_DOWN);
491
492    // The previewed values should not be accessible to JavaScript.
493    ExpectFieldValue("firstname", "M");
494    ExpectFieldValue("lastname", std::string());
495    ExpectFieldValue("address1", std::string());
496    ExpectFieldValue("address2", std::string());
497    ExpectFieldValue("city", std::string());
498    ExpectFieldValue("state", std::string());
499    ExpectFieldValue("zip", std::string());
500    ExpectFieldValue("country", std::string());
501    ExpectFieldValue("phone", std::string());
502    // TODO(isherman): It would be nice to test that the previewed values are
503    // displayed: http://crbug.com/57220
504
505    // Press Enter to accept the autofill suggestions.
506    LOG(WARNING) << "Simulating Return press to fill the form.";
507    SendKeyToPopupAndWait(ui::VKEY_RETURN);
508
509    // The form should be filled.
510    ExpectFilledTestForm();
511  }
512
513  TestAutofillExternalDelegate* external_delegate() {
514    content::WebContents* web_contents =
515        browser()->tab_strip_model()->GetActiveWebContents();
516    AutofillDriverImpl* autofill_driver =
517        AutofillDriverImpl::FromWebContents(web_contents);
518    return static_cast<TestAutofillExternalDelegate*>(
519        autofill_driver->autofill_external_delegate());
520  }
521
522  AutofillManagerTestDelegateImpl test_delegate_;
523
524 private:
525  net::TestURLFetcherFactory url_fetcher_factory_;
526};
527
528// http://crbug.com/150084
529#if defined(OS_MACOSX)
530#define MAYBE_BasicFormFill BasicFormFill
531#else
532#define MAYBE_BasicFormFill DISABLED_BasicFormFill
533#endif
534// Test that basic form fill is working.
535IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_BasicFormFill) {
536  CreateTestProfile();
537
538  // Load the test page.
539  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
540      GURL(std::string(kDataURIPrefix) + kTestFormString)));
541
542  // Invoke Autofill.
543  TryBasicFormFill();
544}
545
546// http://crbug.com/150084
547#if defined(OS_MACOSX)
548#define MAYBE_AutofillViaDownArrow AutofillViaDownArrow
549#else
550#define MAYBE_AutofillViaDownArrow DISABLED_AutofillViaDownArrow
551#endif
552// Test that form filling can be initiated by pressing the down arrow.
553IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_AutofillViaDownArrow) {
554  CreateTestProfile();
555
556  // Load the test page.
557  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
558      GURL(std::string(kDataURIPrefix) + kTestFormString)));
559
560  // Focus a fillable field.
561  FocusFirstNameField();
562
563  // Press the down arrow to initiate Autofill and wait for the popup to be
564  // shown.
565  SendKeyToPageAndWait(ui::VKEY_DOWN);
566
567  // Press the down arrow to select the suggestion and preview the autofilled
568  // form.
569  SendKeyToPopupAndWait(ui::VKEY_DOWN);
570
571  // Press Enter to accept the autofill suggestions.
572  SendKeyToPopupAndWait(ui::VKEY_RETURN);
573
574  // The form should be filled.
575  ExpectFilledTestForm();
576}
577
578// http://crbug.com/150084
579#if defined(OS_MACOSX)
580#define MAYBE_OnChangeAfterAutofill OnChangeAfterAutofill
581#else
582#define MAYBE_OnChangeAfterAutofill DISABLED_OnChangeAfterAutofill
583#endif
584// Test that a JavaScript onchange event is fired after auto-filling a form.
585IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_OnChangeAfterAutofill) {
586  CreateTestProfile();
587
588  const char* kOnChangeScript =
589      "<script>"
590      "focused_fired = false;"
591      "unfocused_fired = false;"
592      "changed_select_fired = false;"
593      "unchanged_select_fired = false;"
594      "document.getElementById('firstname').onchange = function() {"
595      "  focused_fired = true;"
596      "};"
597      "document.getElementById('lastname').onchange = function() {"
598      "  unfocused_fired = true;"
599      "};"
600      "document.getElementById('state').onchange = function() {"
601      "  changed_select_fired = true;"
602      "};"
603      "document.getElementById('country').onchange = function() {"
604      "  unchanged_select_fired = true;"
605      "};"
606      "document.getElementById('country').value = 'US';"
607      "</script>";
608
609  // Load the test page.
610  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
611      GURL(std::string(kDataURIPrefix) + kTestFormString + kOnChangeScript)));
612
613  // Invoke Autofill.
614  FocusFirstNameField();
615
616  // Start filling the first name field with "M" and wait for the popup to be
617  // shown.
618  SendKeyToPageAndWait(ui::VKEY_M);
619
620  // Press the down arrow to select the suggestion and preview the autofilled
621  // form.
622  SendKeyToPopupAndWait(ui::VKEY_DOWN);
623
624  // Press Enter to accept the autofill suggestions.
625  SendKeyToPopupAndWait(ui::VKEY_RETURN);
626
627  // The form should be filled.
628  ExpectFilledTestForm();
629
630  // The change event should have already fired for unfocused fields, both of
631  // <input> and of <select> type. However, it should not yet have fired for the
632  // focused field.
633  bool focused_fired = false;
634  bool unfocused_fired = false;
635  bool changed_select_fired = false;
636  bool unchanged_select_fired = false;
637  ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
638      render_view_host(),
639      "domAutomationController.send(focused_fired);",
640      &focused_fired));
641  ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
642      render_view_host(),
643      "domAutomationController.send(unfocused_fired);",
644      &unfocused_fired));
645  ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
646      render_view_host(),
647      "domAutomationController.send(changed_select_fired);",
648      &changed_select_fired));
649  ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
650      render_view_host(),
651      "domAutomationController.send(unchanged_select_fired);",
652      &unchanged_select_fired));
653  EXPECT_FALSE(focused_fired);
654  EXPECT_TRUE(unfocused_fired);
655  EXPECT_TRUE(changed_select_fired);
656  EXPECT_FALSE(unchanged_select_fired);
657
658  // Unfocus the first name field. Its change event should fire.
659  ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
660      render_view_host(),
661      "document.getElementById('firstname').blur();"
662      "domAutomationController.send(focused_fired);", &focused_fired));
663  EXPECT_TRUE(focused_fired);
664}
665
666// Test that we can autofill forms distinguished only by their |id| attribute.
667// DISABLED: http://crbug.com/150084
668IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_AutofillFormsDistinguishedById) {
669  CreateTestProfile();
670
671  // Load the test page.
672  const std::string kURL =
673      std::string(kDataURIPrefix) + kTestFormString +
674      "<script>"
675      "var mainForm = document.forms[0];"
676      "mainForm.id = 'mainForm';"
677      "var newForm = document.createElement('form');"
678      "newForm.action = mainForm.action;"
679      "newForm.method = mainForm.method;"
680      "newForm.id = 'newForm';"
681      "mainForm.parentNode.insertBefore(newForm, mainForm);"
682      "</script>";
683  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(), GURL(kURL)));
684
685  // Invoke Autofill.
686  TryBasicFormFill();
687}
688
689// Test that we properly autofill forms with repeated fields.
690// In the wild, the repeated fields are typically either email fields
691// (duplicated for "confirmation"); or variants that are hot-swapped via
692// JavaScript, with only one actually visible at any given time.
693// DISABLED: http://crbug.com/150084
694IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_AutofillFormWithRepeatedField) {
695  CreateTestProfile();
696
697  // Load the test page.
698  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
699      GURL(std::string(kDataURIPrefix) +
700           "<form action=\"http://www.example.com/\" method=\"POST\">"
701           "<label for=\"firstname\">First name:</label>"
702           " <input type=\"text\" id=\"firstname\""
703           "        onFocus=\"domAutomationController.send(true)\"><br>"
704           "<label for=\"lastname\">Last name:</label>"
705           " <input type=\"text\" id=\"lastname\"><br>"
706           "<label for=\"address1\">Address line 1:</label>"
707           " <input type=\"text\" id=\"address1\"><br>"
708           "<label for=\"address2\">Address line 2:</label>"
709           " <input type=\"text\" id=\"address2\"><br>"
710           "<label for=\"city\">City:</label>"
711           " <input type=\"text\" id=\"city\"><br>"
712           "<label for=\"state\">State:</label>"
713           " <select id=\"state\">"
714           " <option value=\"\" selected=\"yes\">--</option>"
715           " <option value=\"CA\">California</option>"
716           " <option value=\"TX\">Texas</option>"
717           " </select><br>"
718           "<label for=\"state_freeform\" style=\"display:none\">State:</label>"
719           " <input type=\"text\" id=\"state_freeform\""
720           "        style=\"display:none\"><br>"
721           "<label for=\"zip\">ZIP code:</label>"
722           " <input type=\"text\" id=\"zip\"><br>"
723           "<label for=\"country\">Country:</label>"
724           " <select id=\"country\">"
725           " <option value=\"\" selected=\"yes\">--</option>"
726           " <option value=\"CA\">Canada</option>"
727           " <option value=\"US\">United States</option>"
728           " </select><br>"
729           "<label for=\"phone\">Phone number:</label>"
730           " <input type=\"text\" id=\"phone\"><br>"
731           "</form>")));
732
733  // Invoke Autofill.
734  TryBasicFormFill();
735  ExpectFieldValue("state_freeform", std::string());
736}
737
738// http://crbug.com/150084
739#if defined(OS_MACOSX)
740#define MAYBE_AutofillFormWithNonAutofillableField \
741    AutofillFormWithNonAutofillableField
742#else
743#define MAYBE_AutofillFormWithNonAutofillableField \
744    DISABLED_AutofillFormWithNonAutofillableField
745#endif
746
747// Test that we properly autofill forms with non-autofillable fields.
748IN_PROC_BROWSER_TEST_F(AutofillTest,
749                       MAYBE_AutofillFormWithNonAutofillableField) {
750  CreateTestProfile();
751
752  // Load the test page.
753  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
754      GURL(std::string(kDataURIPrefix) +
755           "<form action=\"http://www.example.com/\" method=\"POST\">"
756           "<label for=\"firstname\">First name:</label>"
757           " <input type=\"text\" id=\"firstname\""
758           "        onFocus=\"domAutomationController.send(true)\"><br>"
759           "<label for=\"middlename\">Middle name:</label>"
760           " <input type=\"text\" id=\"middlename\" autocomplete=\"off\" /><br>"
761           "<label for=\"lastname\">Last name:</label>"
762           " <input type=\"text\" id=\"lastname\"><br>"
763           "<label for=\"address1\">Address line 1:</label>"
764           " <input type=\"text\" id=\"address1\"><br>"
765           "<label for=\"address2\">Address line 2:</label>"
766           " <input type=\"text\" id=\"address2\"><br>"
767           "<label for=\"city\">City:</label>"
768           " <input type=\"text\" id=\"city\"><br>"
769           "<label for=\"state\">State:</label>"
770           " <select id=\"state\">"
771           " <option value=\"\" selected=\"yes\">--</option>"
772           " <option value=\"CA\">California</option>"
773           " <option value=\"TX\">Texas</option>"
774           " </select><br>"
775           "<label for=\"zip\">ZIP code:</label>"
776           " <input type=\"text\" id=\"zip\"><br>"
777           "<label for=\"country\">Country:</label>"
778           " <select id=\"country\">"
779           " <option value=\"\" selected=\"yes\">--</option>"
780           " <option value=\"CA\">Canada</option>"
781           " <option value=\"US\">United States</option>"
782           " </select><br>"
783           "<label for=\"phone\">Phone number:</label>"
784           " <input type=\"text\" id=\"phone\"><br>"
785           "</form>")));
786
787  // Invoke Autofill.
788  TryBasicFormFill();
789}
790
791// Test that we can Autofill dynamically generated forms.
792// DISABLED: http://crbug.com/150084
793IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_DynamicFormFill) {
794  CreateTestProfile();
795
796  // Load the test page.
797  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
798      GURL(std::string(kDataURIPrefix) +
799           "<form id=\"form\" action=\"http://www.example.com/\""
800           "      method=\"POST\"></form>"
801           "<script>"
802           "function AddElement(name, label) {"
803           "  var form = document.getElementById('form');"
804           ""
805           "  var label_text = document.createTextNode(label);"
806           "  var label_element = document.createElement('label');"
807           "  label_element.setAttribute('for', name);"
808           "  label_element.appendChild(label_text);"
809           "  form.appendChild(label_element);"
810           ""
811           "  if (name === 'state' || name === 'country') {"
812           "    var select_element = document.createElement('select');"
813           "    select_element.setAttribute('id', name);"
814           "    select_element.setAttribute('name', name);"
815           ""
816           "    /* Add an empty selected option. */"
817           "    var default_option = new Option('--', '', true);"
818           "    select_element.appendChild(default_option);"
819           ""
820           "    /* Add the other options. */"
821           "    if (name == 'state') {"
822           "      var option1 = new Option('California', 'CA');"
823           "      select_element.appendChild(option1);"
824           "      var option2 = new Option('Texas', 'TX');"
825           "      select_element.appendChild(option2);"
826           "    } else {"
827           "      var option1 = new Option('Canada', 'CA');"
828           "      select_element.appendChild(option1);"
829           "      var option2 = new Option('United States', 'US');"
830           "      select_element.appendChild(option2);"
831           "    }"
832           ""
833           "    form.appendChild(select_element);"
834           "  } else {"
835           "    var input_element = document.createElement('input');"
836           "    input_element.setAttribute('id', name);"
837           "    input_element.setAttribute('name', name);"
838           ""
839           "    /* Add the onFocus listener to the 'firstname' field. */"
840           "    if (name === 'firstname') {"
841           "      input_element.setAttribute("
842           "          'onFocus', 'domAutomationController.send(true)');"
843           "    }"
844           ""
845           "    form.appendChild(input_element);"
846           "  }"
847           ""
848           "  form.appendChild(document.createElement('br'));"
849           "};"
850           ""
851           "function BuildForm() {"
852           "  var elements = ["
853           "    ['firstname', 'First name:'],"
854           "    ['lastname', 'Last name:'],"
855           "    ['address1', 'Address line 1:'],"
856           "    ['address2', 'Address line 2:'],"
857           "    ['city', 'City:'],"
858           "    ['state', 'State:'],"
859           "    ['zip', 'ZIP code:'],"
860           "    ['country', 'Country:'],"
861           "    ['phone', 'Phone number:'],"
862           "  ];"
863           ""
864           "  for (var i = 0; i < elements.length; i++) {"
865           "    var name = elements[i][0];"
866           "    var label = elements[i][1];"
867           "    AddElement(name, label);"
868           "  }"
869           "};"
870           "</script>")));
871
872  // Dynamically construct the form.
873  ASSERT_TRUE(content::ExecuteScript(render_view_host(), "BuildForm();"));
874
875  // Invoke Autofill.
876  TryBasicFormFill();
877}
878
879// Test that form filling works after reloading the current page.
880// This test brought to you by http://crbug.com/69204
881#if defined(OS_MACOSX)
882// Now flaky on everything but mac.
883// http://crbug.com/150084
884#define MAYBE_AutofillAfterReload AutofillAfterReload
885#else
886#define MAYBE_AutofillAfterReload DISABLED_AutofillAfterReload
887#endif
888IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_AutofillAfterReload) {
889  LOG(WARNING) << "Creating test profile.";
890  CreateTestProfile();
891
892  // Load the test page.
893  LOG(WARNING) << "Bringing browser window to front.";
894  LOG(WARNING) << "Navigating to URL.";
895  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
896      GURL(std::string(kDataURIPrefix) + kTestFormString)));
897
898  // Reload the page.
899  LOG(WARNING) << "Reloading the page.";
900  content::WebContents* web_contents =
901      browser()->tab_strip_model()->GetActiveWebContents();
902  web_contents->GetController().Reload(false);
903  content::WaitForLoadStop(web_contents);
904
905  // Invoke Autofill.
906  LOG(WARNING) << "Trying to fill the form.";
907  TryBasicFormFill();
908}
909
910// DISABLED: http://crbug.com/150084
911IN_PROC_BROWSER_TEST_F(AutofillTest, DISABLED_AutofillAfterTranslate) {
912  CreateTestProfile();
913
914  GURL url(std::string(kDataURIPrefix) +
915               "<form action=\"http://www.example.com/\" method=\"POST\">"
916               "<label for=\"fn\">なまえ</label>"
917               " <input type=\"text\" id=\"fn\""
918               "        onFocus=\"domAutomationController.send(true)\""
919               "><br>"
920               "<label for=\"ln\">みょうじ</label>"
921               " <input type=\"text\" id=\"ln\"><br>"
922               "<label for=\"a1\">Address line 1:</label>"
923               " <input type=\"text\" id=\"a1\"><br>"
924               "<label for=\"a2\">Address line 2:</label>"
925               " <input type=\"text\" id=\"a2\"><br>"
926               "<label for=\"ci\">City:</label>"
927               " <input type=\"text\" id=\"ci\"><br>"
928               "<label for=\"st\">State:</label>"
929               " <select id=\"st\">"
930               " <option value=\"\" selected=\"yes\">--</option>"
931               " <option value=\"CA\">California</option>"
932               " <option value=\"TX\">Texas</option>"
933               " </select><br>"
934               "<label for=\"z\">ZIP code:</label>"
935               " <input type=\"text\" id=\"z\"><br>"
936               "<label for=\"co\">Country:</label>"
937               " <select id=\"co\">"
938               " <option value=\"\" selected=\"yes\">--</option>"
939               " <option value=\"CA\">Canada</option>"
940               " <option value=\"US\">United States</option>"
941               " </select><br>"
942               "<label for=\"ph\">Phone number:</label>"
943               " <input type=\"text\" id=\"ph\"><br>"
944               "</form>");
945  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(), url));
946
947  // Get translation bar.
948  LanguageDetectionDetails details;
949  details.adopted_language = "ja";
950  content::RenderViewHostTester::TestOnMessageReceived(
951      render_view_host(),
952      ChromeViewHostMsg_TranslateLanguageDetermined(0, details, true));
953  TranslateInfoBarDelegate* delegate = InfoBarService::FromWebContents(
954      browser()->tab_strip_model()->GetActiveWebContents())->infobar_at(0)->
955          AsTranslateInfoBarDelegate();
956  ASSERT_TRUE(delegate);
957  EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE,
958            delegate->infobar_type());
959
960  // Simulate translation button press.
961  delegate->Translate();
962
963  // Simulate the translate script being retrieved.
964  // Pass fake google.translate lib as the translate script.
965  SimulateURLFetch(true);
966
967  content::WindowedNotificationObserver translation_observer(
968      chrome::NOTIFICATION_PAGE_TRANSLATED,
969      content::NotificationService::AllSources());
970
971  // Simulate translation to kick onTranslateElementLoad.
972  // But right now, the call stucks here.
973  // Once click the text field, it starts again.
974  ASSERT_TRUE(content::ExecuteScript(
975      render_view_host(), "cr.googleTranslate.onTranslateElementLoad();"));
976
977  // Simulate the render notifying the translation has been done.
978  translation_observer.Wait();
979
980  TryBasicFormFill();
981}
982
983// Test filling profiles with unicode strings and crazy characters.
984// TODO(isherman): rewrite as unit test under PersonalDataManagerTest.
985IN_PROC_BROWSER_TEST_F(AutofillTest, FillProfileCrazyCharacters) {
986  std::vector<AutofillProfile> profiles;
987  AutofillProfile profile1;
988  profile1.SetRawInfo(NAME_FIRST,
989                      WideToUTF16(L"\u0623\u0648\u0628\u0627\u0645\u0627 "
990                                  L"\u064a\u0639\u062a\u0630\u0631 "
991                                  L"\u0647\u0627\u062a\u0641\u064a\u0627 "
992                                  L"\u0644\u0645\u0648\u0638\u0641\u0629 "
993                                  L"\u0633\u0648\u062f\u0627\u0621 "
994                                  L"\u0627\u0633\u062a\u0642\u0627\u0644\u062a "
995                                  L"\u0628\u0633\u0628\u0628 "
996                                  L"\u062a\u0635\u0631\u064a\u062d\u0627\u062a "
997                                  L"\u0645\u062c\u062a\u0632\u0623\u0629"));
998  profile1.SetRawInfo(NAME_MIDDLE, WideToUTF16(L"BANK\xcBERF\xc4LLE"));
999  profile1.SetRawInfo(EMAIL_ADDRESS,
1000                      WideToUTF16(L"\uacbd\uc81c \ub274\uc2a4 "
1001                                  L"\ub354\ubcf4\uae30@google.com"));
1002  profile1.SetRawInfo(ADDRESS_HOME_LINE1,
1003                      WideToUTF16(L"\uad6d\uc815\uc6d0\xb7\uac80\ucc30, "
1004                                  L"\ub178\ubb34\ud604\uc815\ubd80 "
1005                                  L"\ub300\ubd81\uc811\ucd09 \ub2f4\ub2f9 "
1006                                  L"\uc778\uc0ac\ub4e4 \uc870\uc0ac"));
1007  profile1.SetRawInfo(ADDRESS_HOME_CITY,
1008                      WideToUTF16(L"\u653f\u5e9c\u4e0d\u6392\u9664\u7acb\u6cd5"
1009                                  L"\u898f\u7ba1\u5c0e\u904a"));
1010  profile1.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"YOHO_54676"));
1011  profile1.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, WideToUTF16(L"861088828000"));
1012  profile1.SetInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"India"), "en-US");
1013  profiles.push_back(profile1);
1014
1015  AutofillProfile profile2;
1016  profile2.SetRawInfo(NAME_FIRST,
1017                      WideToUTF16(L"\u4e0a\u6d77\u5e02\u91d1\u5c71\u533a "
1018                                  L"\u677e\u9690\u9547\u4ead\u67ab\u516c"
1019                                  L"\u8def1915\u53f7"));
1020  profile2.SetRawInfo(NAME_LAST, WideToUTF16(L"aguantó"));
1021  profile2.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"HOME 94043"));
1022  profiles.push_back(profile2);
1023
1024  AutofillProfile profile3;
1025  profile3.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"sue@example.com"));
1026  profile3.SetRawInfo(COMPANY_NAME, WideToUTF16(L"Company X"));
1027  profiles.push_back(profile3);
1028
1029  AutofillProfile profile4;
1030  profile4.SetRawInfo(NAME_FIRST, WideToUTF16(L"Joe 3254"));
1031  profile4.SetRawInfo(NAME_LAST, WideToUTF16(L"\u8bb0\u8d262\u5e74\u591a"));
1032  profile4.SetRawInfo(ADDRESS_HOME_ZIP,
1033                      WideToUTF16(L"\uff08\u90ae\u7f16\uff1a201504\uff09"));
1034  profile4.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"télévision@example.com"));
1035  profile4.SetRawInfo(COMPANY_NAME,
1036                      WideToUTF16(L"\u0907\u0932\u0947\u0915\u093f\u091f\u094d"
1037                                  L"\u0930\u0928\u093f\u0915\u094d\u0938, "
1038                                  L"\u0905\u092a\u094b\u0932\u094b "
1039                                  L"\u091f\u093e\u092f\u0930\u094d\u0938 "
1040                                  L"\u0906\u0926\u093f"));
1041  profiles.push_back(profile4);
1042
1043  AutofillProfile profile5;
1044  profile5.SetRawInfo(NAME_FIRST, WideToUTF16(L"Larry"));
1045  profile5.SetRawInfo(NAME_LAST,
1046                      WideToUTF16(L"\u0938\u094d\u091f\u093e\u0902\u092a "
1047                                  L"\u0921\u094d\u092f\u0942\u091f\u0940"));
1048  profile5.SetRawInfo(ADDRESS_HOME_ZIP,
1049                      WideToUTF16(L"111111111111110000GOOGLE"));
1050  profile5.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"page@000000.com"));
1051  profile5.SetRawInfo(COMPANY_NAME, WideToUTF16(L"Google"));
1052  profiles.push_back(profile5);
1053
1054  AutofillProfile profile6;
1055  profile6.SetRawInfo(NAME_FIRST,
1056                      WideToUTF16(L"\u4e0a\u6d77\u5e02\u91d1\u5c71\u533a "
1057                                  L"\u677e\u9690\u9547\u4ead\u67ab\u516c"
1058                                  L"\u8def1915\u53f7"));
1059  profile6.SetRawInfo(NAME_LAST,
1060                      WideToUTF16(L"\u0646\u062c\u0627\u0645\u064a\u0646\u0627 "
1061                                  L"\u062f\u0639\u0645\u0647\u0627 "
1062                                  L"\u0644\u0644\u0631\u0626\u064a\u0633 "
1063                                  L"\u0627\u0644\u0633\u0648\u062f\u0627\u0646"
1064                                  L"\u064a \u0639\u0645\u0631 "
1065                                  L"\u0627\u0644\u0628\u0634\u064a\u0631"));
1066  profile6.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"HOME 94043"));
1067  profiles.push_back(profile6);
1068
1069  AutofillProfile profile7;
1070  profile7.SetRawInfo(NAME_FIRST, WideToUTF16(L"&$%$$$ TESTO *&*&^&^& MOKO"));
1071  profile7.SetRawInfo(NAME_MIDDLE, WideToUTF16(L"WOHOOOO$$$$$$$$****"));
1072  profile7.SetRawInfo(EMAIL_ADDRESS, WideToUTF16(L"yuvu@example.com"));
1073  profile7.SetRawInfo(ADDRESS_HOME_LINE1,
1074                      WideToUTF16(L"34544, anderson ST.(120230)"));
1075  profile7.SetRawInfo(ADDRESS_HOME_CITY, WideToUTF16(L"Sunnyvale"));
1076  profile7.SetRawInfo(ADDRESS_HOME_STATE, WideToUTF16(L"CA"));
1077  profile7.SetRawInfo(ADDRESS_HOME_ZIP, WideToUTF16(L"94086"));
1078  profile7.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, WideToUTF16(L"15466784565"));
1079  profile7.SetInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"United States"),
1080                   "en-US");
1081  profiles.push_back(profile7);
1082
1083  SetProfiles(&profiles);
1084  ASSERT_EQ(profiles.size(), personal_data_manager()->GetProfiles().size());
1085  for (size_t i = 0; i < profiles.size(); ++i)
1086    ASSERT_EQ(profiles[i], *personal_data_manager()->GetProfiles()[i]);
1087
1088  std::vector<CreditCard> cards;
1089  CreditCard card1;
1090  card1.SetRawInfo(CREDIT_CARD_NAME,
1091                   WideToUTF16(L"\u751f\u6d3b\u5f88\u6709\u89c4\u5f8b "
1092                               L"\u4ee5\u73a9\u4e3a\u4e3b"));
1093  card1.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"6011111111111117"));
1094  card1.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"12"));
1095  card1.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2011"));
1096  cards.push_back(card1);
1097
1098  CreditCard card2;
1099  card2.SetRawInfo(CREDIT_CARD_NAME, WideToUTF16(L"John Williams"));
1100  card2.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"WokoAwesome12345"));
1101  card2.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"10"));
1102  card2.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2015"));
1103  cards.push_back(card2);
1104
1105  CreditCard card3;
1106  card3.SetRawInfo(CREDIT_CARD_NAME,
1107                   WideToUTF16(L"\u0623\u062d\u0645\u062f\u064a "
1108                               L"\u0646\u062c\u0627\u062f "
1109                               L"\u0644\u0645\u062d\u0627\u0648\u0644\u0647 "
1110                               L"\u0627\u063a\u062a\u064a\u0627\u0644 "
1111                               L"\u0641\u064a \u0645\u062f\u064a\u0646\u0629 "
1112                               L"\u0647\u0645\u062f\u0627\u0646 "));
1113  card3.SetRawInfo(CREDIT_CARD_NUMBER,
1114                   WideToUTF16(L"\u092a\u0941\u0928\u0930\u094d\u091c\u0940"
1115                               L"\u0935\u093f\u0924 \u0939\u094b\u0917\u093e "
1116                               L"\u0928\u093e\u0932\u0902\u0926\u093e"));
1117  card3.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"10"));
1118  card3.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2015"));
1119  cards.push_back(card3);
1120
1121  CreditCard card4;
1122  card4.SetRawInfo(CREDIT_CARD_NAME,
1123                   WideToUTF16(L"\u039d\u03ad\u03b5\u03c2 "
1124                               L"\u03c3\u03c5\u03b3\u03c7\u03c9\u03bd\u03b5"
1125                               L"\u03cd\u03c3\u03b5\u03b9\u03c2 "
1126                               L"\u03ba\u03b1\u03b9 "
1127                               L"\u03ba\u03b1\u03c4\u03b1\u03c1\u03b3\u03ae"
1128                               L"\u03c3\u03b5\u03b9\u03c2"));
1129  card4.SetRawInfo(CREDIT_CARD_NUMBER, WideToUTF16(L"00000000000000000000000"));
1130  card4.SetRawInfo(CREDIT_CARD_EXP_MONTH, WideToUTF16(L"01"));
1131  card4.SetRawInfo(CREDIT_CARD_EXP_4_DIGIT_YEAR, WideToUTF16(L"2016"));
1132  cards.push_back(card4);
1133
1134  SetCards(&cards);
1135  ASSERT_EQ(cards.size(), personal_data_manager()->GetCreditCards().size());
1136  for (size_t i = 0; i < cards.size(); ++i)
1137    ASSERT_EQ(cards[i], *personal_data_manager()->GetCreditCards()[i]);
1138}
1139
1140// Test filling in invalid values for profiles are saved as-is. Phone
1141// information entered into the prefs UI is not validated or rejected except for
1142// duplicates.
1143// TODO(isherman): rewrite as WebUI test?
1144IN_PROC_BROWSER_TEST_F(AutofillTest, Invalid) {
1145  // First try profiles with invalid ZIP input.
1146  AutofillProfile without_invalid;
1147  without_invalid.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Will"));
1148  without_invalid.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("Sunnyvale"));
1149  without_invalid.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1150  without_invalid.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("my_zip"));
1151  without_invalid.SetInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("United States"),
1152                          "en-US");
1153
1154  AutofillProfile with_invalid = without_invalid;
1155  with_invalid.SetRawInfo(PHONE_HOME_WHOLE_NUMBER,
1156                          ASCIIToUTF16("Invalid_Phone_Number"));
1157  SetProfile(with_invalid);
1158
1159  ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size());
1160  AutofillProfile profile = *personal_data_manager()->GetProfiles()[0];
1161  ASSERT_NE(without_invalid.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1162            profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER));
1163}
1164
1165// Test invalid credit card numbers typed in prefs should be saved as-is.
1166// TODO(isherman): rewrite as WebUI test?
1167IN_PROC_BROWSER_TEST_F(AutofillTest, PrefsStringSavedAsIs) {
1168  CreditCard card;
1169  card.SetRawInfo(CREDIT_CARD_NUMBER, ASCIIToUTF16("Not_0123-5Checked"));
1170  SetCard(card);
1171
1172  ASSERT_EQ(1u, personal_data_manager()->GetCreditCards().size());
1173  ASSERT_EQ(card, *personal_data_manager()->GetCreditCards()[0]);
1174}
1175
1176// Test credit card info with an invalid number is not aggregated.
1177// When filling out a form with an invalid credit card number (one that does not
1178// pass the Luhn test) the credit card info should not be saved into Autofill
1179// preferences.
1180IN_PROC_BROWSER_TEST_F(AutofillTest, InvalidCreditCardNumberIsNotAggregated) {
1181#if defined(OS_WIN) && defined(USE_ASH)
1182  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1183  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1184    return;
1185#endif
1186
1187  ASSERT_TRUE(test_server()->Start());
1188  std::string card("4408 0412 3456 7890");
1189  ASSERT_FALSE(autofill::IsValidCreditCardNumber(ASCIIToUTF16(card)));
1190  SubmitCreditCard("Bob Smith", card.c_str(), "12", "2014");
1191  ASSERT_EQ(0u,
1192            InfoBarService::FromWebContents(
1193                browser()->tab_strip_model()->GetActiveWebContents())->
1194                    infobar_count());
1195}
1196
1197// Test whitespaces and separator chars are stripped for valid CC numbers.
1198// The credit card numbers used in this test pass the Luhn test. For reference:
1199// http://www.merriampark.com/anatomycc.htm
1200IN_PROC_BROWSER_TEST_F(AutofillTest,
1201                       WhitespacesAndSeparatorCharsStrippedForValidCCNums) {
1202#if defined(OS_WIN) && defined(USE_ASH)
1203  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1204  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1205    return;
1206#endif
1207
1208  ASSERT_TRUE(test_server()->Start());
1209  SubmitCreditCard("Bob Smith", "4408 0412 3456 7893", "12", "2014");
1210  SubmitCreditCard("Jane Doe", "4417-1234-5678-9113", "10", "2013");
1211
1212  ASSERT_EQ(2u, personal_data_manager()->GetCreditCards().size());
1213  string16 cc1 = personal_data_manager()->GetCreditCards()[0]->GetRawInfo(
1214      CREDIT_CARD_NUMBER);
1215  ASSERT_TRUE(autofill::IsValidCreditCardNumber(cc1));
1216  string16 cc2 = personal_data_manager()->GetCreditCards()[1]->GetRawInfo(
1217      CREDIT_CARD_NUMBER);
1218  ASSERT_TRUE(autofill::IsValidCreditCardNumber(cc2));
1219}
1220
1221// Test that Autofill aggregates a minimum valid profile.
1222// The minimum required address fields must be specified: First Name, Last Name,
1223// Address Line 1, City, Zip Code, and State.
1224IN_PROC_BROWSER_TEST_F(AutofillTest, AggregatesMinValidProfile) {
1225  ASSERT_TRUE(test_server()->Start());
1226  FormMap data;
1227  data["NAME_FIRST"] = "Bob";
1228  data["NAME_LAST"] = "Smith";
1229  data["ADDRESS_HOME_LINE1"] = "1234 H St.";
1230  data["ADDRESS_HOME_CITY"] = "Mountain View";
1231  data["ADDRESS_HOME_STATE"] = "CA";
1232  data["ADDRESS_HOME_ZIP"] = "94043";
1233  FillFormAndSubmit("duplicate_profiles_test.html", data);
1234
1235  ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size());
1236}
1237
1238// Test Autofill does not aggregate profiles with no address info.
1239// The minimum required address fields must be specified: First Name, Last Name,
1240// Address Line 1, City, Zip Code, and State.
1241IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithNoAddress) {
1242  ASSERT_TRUE(test_server()->Start());
1243  FormMap data;
1244  data["NAME_FIRST"] = "Bob";
1245  data["NAME_LAST"] = "Smith";
1246  data["EMAIL_ADDRESS"] = "bsmith@example.com";
1247  data["COMPANY_NAME"] = "Mountain View";
1248  data["ADDRESS_HOME_CITY"] = "Mountain View";
1249  data["PHONE_HOME_WHOLE_NUMBER"] = "650-555-4567";
1250  FillFormAndSubmit("duplicate_profiles_test.html", data);
1251
1252  ASSERT_TRUE(personal_data_manager()->GetProfiles().empty());
1253}
1254
1255// Test Autofill does not aggregate profiles with an invalid email.
1256IN_PROC_BROWSER_TEST_F(AutofillTest, ProfilesNotAggregatedWithInvalidEmail) {
1257  ASSERT_TRUE(test_server()->Start());
1258  FormMap data;
1259  data["NAME_FIRST"] = "Bob";
1260  data["NAME_LAST"] = "Smith";
1261  data["EMAIL_ADDRESS"] = "garbage";
1262  data["ADDRESS_HOME_LINE1"] = "1234 H St.";
1263  data["ADDRESS_HOME_CITY"] = "San Jose";
1264  data["ADDRESS_HOME_STATE"] = "CA";
1265  data["ADDRESS_HOME_ZIP"] = "95110";
1266  data["COMPANY_NAME"] = "Company X";
1267  data["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567";
1268  FillFormAndSubmit("duplicate_profiles_test.html", data);
1269
1270  ASSERT_TRUE(personal_data_manager()->GetProfiles().empty());
1271}
1272
1273// http://crbug.com/150084
1274#if defined(OS_MACOSX)
1275#define MAYBE_ComparePhoneNumbers ComparePhoneNumbers
1276#else
1277#define MAYBE_ComparePhoneNumbers DISABLED_ComparePhoneNumbers
1278#endif
1279// Test phone fields parse correctly from a given profile.
1280// The high level key presses execute the following: Select the first text
1281// field, invoke the autofill popup list, select the first profile within the
1282// list, and commit to the profile to populate the form.
1283IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_ComparePhoneNumbers) {
1284  ASSERT_TRUE(test_server()->Start());
1285
1286  AutofillProfile profile;
1287  profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
1288  profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1289  profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 H St."));
1290  profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
1291  profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1292  profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
1293  profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("1-408-555-4567"));
1294  SetProfile(profile);
1295
1296  GURL url = test_server()->GetURL("files/autofill/form_phones.html");
1297  ui_test_utils::NavigateToURL(browser(), url);
1298  PopulateForm("NAME_FIRST");
1299
1300  ExpectFieldValue("NAME_FIRST", "Bob");
1301  ExpectFieldValue("NAME_LAST", "Smith");
1302  ExpectFieldValue("ADDRESS_HOME_LINE1", "1234 H St.");
1303  ExpectFieldValue("ADDRESS_HOME_CITY", "San Jose");
1304  ExpectFieldValue("ADDRESS_HOME_STATE", "CA");
1305  ExpectFieldValue("ADDRESS_HOME_ZIP", "95110");
1306  ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "14085554567");
1307  ExpectFieldValue("PHONE_HOME_CITY_CODE-1", "408");
1308  ExpectFieldValue("PHONE_HOME_CITY_CODE-2", "408");
1309  ExpectFieldValue("PHONE_HOME_NUMBER", "5554567");
1310  ExpectFieldValue("PHONE_HOME_NUMBER_3-1", "555");
1311  ExpectFieldValue("PHONE_HOME_NUMBER_3-2", "555");
1312  ExpectFieldValue("PHONE_HOME_NUMBER_4-1", "4567");
1313  ExpectFieldValue("PHONE_HOME_NUMBER_4-2", "4567");
1314  ExpectFieldValue("PHONE_HOME_EXT-1", std::string());
1315  ExpectFieldValue("PHONE_HOME_EXT-2", std::string());
1316  ExpectFieldValue("PHONE_HOME_COUNTRY_CODE-1", "1");
1317}
1318
1319// Test profile is saved if phone number is valid in selected country.
1320// The data file contains two profiles with valid phone numbers and two
1321// profiles with invalid phone numbers from their respective country.
1322// DISABLED: http://crbug.com/150084
1323IN_PROC_BROWSER_TEST_F(AutofillTest,
1324                       DISABLED_ProfileSavedWithValidCountryPhone) {
1325  ASSERT_TRUE(test_server()->Start());
1326  std::vector<FormMap> profiles;
1327
1328  FormMap data1;
1329  data1["NAME_FIRST"] = "Bob";
1330  data1["NAME_LAST"] = "Smith";
1331  data1["ADDRESS_HOME_LINE1"] = "123 Cherry Ave";
1332  data1["ADDRESS_HOME_CITY"] = "Mountain View";
1333  data1["ADDRESS_HOME_STATE"] = "CA";
1334  data1["ADDRESS_HOME_ZIP"] = "94043";
1335  data1["ADDRESS_HOME_COUNTRY"] = "United States";
1336  data1["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567";
1337  profiles.push_back(data1);
1338
1339  FormMap data2;
1340  data2["NAME_FIRST"] = "John";
1341  data2["NAME_LAST"] = "Doe";
1342  data2["ADDRESS_HOME_LINE1"] = "987 H St";
1343  data2["ADDRESS_HOME_CITY"] = "San Jose";
1344  data2["ADDRESS_HOME_STATE"] = "CA";
1345  data2["ADDRESS_HOME_ZIP"] = "95510";
1346  data2["ADDRESS_HOME_COUNTRY"] = "United States";
1347  data2["PHONE_HOME_WHOLE_NUMBER"] = "408-123-456";
1348  profiles.push_back(data2);
1349
1350  FormMap data3;
1351  data3["NAME_FIRST"] = "Jane";
1352  data3["NAME_LAST"] = "Doe";
1353  data3["ADDRESS_HOME_LINE1"] = "1523 Garcia St";
1354  data3["ADDRESS_HOME_CITY"] = "Mountain View";
1355  data3["ADDRESS_HOME_STATE"] = "CA";
1356  data3["ADDRESS_HOME_ZIP"] = "94043";
1357  data3["ADDRESS_HOME_COUNTRY"] = "Germany";
1358  data3["PHONE_HOME_WHOLE_NUMBER"] = "+49 40-80-81-79-000";
1359  profiles.push_back(data3);
1360
1361  FormMap data4;
1362  data4["NAME_FIRST"] = "Bonnie";
1363  data4["NAME_LAST"] = "Smith";
1364  data4["ADDRESS_HOME_LINE1"] = "6723 Roadway Rd";
1365  data4["ADDRESS_HOME_CITY"] = "San Jose";
1366  data4["ADDRESS_HOME_STATE"] = "CA";
1367  data4["ADDRESS_HOME_ZIP"] = "95510";
1368  data4["ADDRESS_HOME_COUNTRY"] = "Germany";
1369  data4["PHONE_HOME_WHOLE_NUMBER"] = "+21 08450 777 777";
1370  profiles.push_back(data4);
1371
1372  for (size_t i = 0; i < profiles.size(); ++i)
1373    FillFormAndSubmit("autofill_test_form.html", profiles[i]);
1374
1375  ASSERT_EQ(2u, personal_data_manager()->GetProfiles().size());
1376  ASSERT_EQ(ASCIIToUTF16("(408) 871-4567"),
1377            personal_data_manager()->GetProfiles()[0]->GetRawInfo(
1378                PHONE_HOME_WHOLE_NUMBER));
1379  ASSERT_EQ(ASCIIToUTF16("+49 40/808179000"),
1380            personal_data_manager()->GetProfiles()[1]->GetRawInfo(
1381                PHONE_HOME_WHOLE_NUMBER));
1382}
1383
1384// Test Autofill appends country codes to aggregated phone numbers.
1385// The country code is added for the following case:
1386//   The phone number contains the correct national number size and
1387//   is a valid format.
1388IN_PROC_BROWSER_TEST_F(AutofillTest, AppendCountryCodeForAggregatedPhones) {
1389  ASSERT_TRUE(test_server()->Start());
1390  FormMap data;
1391  data["NAME_FIRST"] = "Bob";
1392  data["NAME_LAST"] = "Smith";
1393  data["ADDRESS_HOME_LINE1"] = "1234 H St.";
1394  data["ADDRESS_HOME_CITY"] = "San Jose";
1395  data["ADDRESS_HOME_STATE"] = "CA";
1396  data["ADDRESS_HOME_ZIP"] = "95110";
1397  data["ADDRESS_HOME_COUNTRY"] = "Germany";
1398  data["PHONE_HOME_WHOLE_NUMBER"] = "(08) 450 777-777";
1399  FillFormAndSubmit("autofill_test_form.html", data);
1400
1401  ASSERT_EQ(1u, personal_data_manager()->GetProfiles().size());
1402  string16 phone = personal_data_manager()->GetProfiles()[0]->GetRawInfo(
1403      PHONE_HOME_WHOLE_NUMBER);
1404  ASSERT_TRUE(StartsWith(phone, ASCIIToUTF16("+49"), true));
1405}
1406
1407// Test CC info not offered to be saved when autocomplete=off for CC field.
1408// If the credit card number field has autocomplete turned off, then the credit
1409// card infobar should not offer to save the credit card info. The credit card
1410// number must be a valid Luhn number.
1411IN_PROC_BROWSER_TEST_F(AutofillTest, CCInfoNotStoredWhenAutocompleteOff) {
1412#if defined(OS_WIN) && defined(USE_ASH)
1413  // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1414  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1415    return;
1416#endif
1417
1418  ASSERT_TRUE(test_server()->Start());
1419  FormMap data;
1420  data["CREDIT_CARD_NAME"] = "Bob Smith";
1421  data["CREDIT_CARD_NUMBER"] = "4408041234567893";
1422  data["CREDIT_CARD_EXP_MONTH"] = "12";
1423  data["CREDIT_CARD_EXP_4_DIGIT_YEAR"] = "2014";
1424  FillFormAndSubmit("cc_autocomplete_off_test.html", data);
1425
1426  ASSERT_EQ(0u,
1427            InfoBarService::FromWebContents(
1428                browser()->tab_strip_model()->GetActiveWebContents())->
1429                    infobar_count());
1430}
1431
1432// http://crbug.com/150084
1433#if defined(OS_MACOSX)
1434#define MAYBE_NoAutofillForReadOnlyFields NoAutofillForReadOnlyFields
1435#else
1436#define MAYBE_NoAutofillForReadOnlyFields DISABLED_NoAutofillForReadOnlyFields
1437#endif
1438// Test that Autofill does not fill in read-only fields.
1439IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_NoAutofillForReadOnlyFields) {
1440  ASSERT_TRUE(test_server()->Start());
1441
1442  std::string addr_line1("1234 H St.");
1443
1444  AutofillProfile profile;
1445  profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
1446  profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1447  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("bsmith@gmail.com"));
1448  profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16(addr_line1));
1449  profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
1450  profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1451  profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
1452  profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Company X"));
1453  profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("408-871-4567"));
1454  SetProfile(profile);
1455
1456  GURL url = test_server()->GetURL("files/autofill/read_only_field_test.html");
1457  ui_test_utils::NavigateToURL(browser(), url);
1458  PopulateForm("firstname");
1459
1460  ExpectFieldValue("email", std::string());
1461  ExpectFieldValue("address", addr_line1);
1462}
1463
1464// http://crbug.com/150084
1465#if defined(OS_MACOSX)
1466#define MAYBE_FormFillableOnReset FormFillableOnReset
1467#else
1468#define MAYBE_FormFillableOnReset DISABLED_FormFillableOnReset
1469#endif
1470// Test form is fillable from a profile after form was reset.
1471// Steps:
1472//   1. Fill form using a saved profile.
1473//   2. Reset the form.
1474//   3. Fill form using a saved profile.
1475IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_FormFillableOnReset) {
1476  ASSERT_TRUE(test_server()->Start());
1477
1478  CreateTestProfile();
1479
1480  GURL url = test_server()->GetURL("files/autofill/autofill_test_form.html");
1481  ui_test_utils::NavigateToURL(browser(), url);
1482  PopulateForm("NAME_FIRST");
1483
1484  ASSERT_TRUE(content::ExecuteScript(
1485      browser()->tab_strip_model()->GetActiveWebContents(),
1486      "document.getElementById('testform').reset()"));
1487
1488  PopulateForm("NAME_FIRST");
1489
1490  ExpectFieldValue("NAME_FIRST", "Milton");
1491  ExpectFieldValue("NAME_LAST", "Waddams");
1492  ExpectFieldValue("EMAIL_ADDRESS", "red.swingline@initech.com");
1493  ExpectFieldValue("ADDRESS_HOME_LINE1", "4120 Freidrich Lane");
1494  ExpectFieldValue("ADDRESS_HOME_CITY", "Austin");
1495  ExpectFieldValue("ADDRESS_HOME_STATE", "Texas");
1496  ExpectFieldValue("ADDRESS_HOME_ZIP", "78744");
1497  ExpectFieldValue("ADDRESS_HOME_COUNTRY", "United States");
1498  ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "5125551234");
1499}
1500
1501// http://crbug.com/150084
1502#if defined(OS_MACOSX)
1503#define MAYBE_DistinguishMiddleInitialWithinName \
1504    DistinguishMiddleInitialWithinName
1505#else
1506#define MAYBE_DistinguishMiddleInitialWithinName \
1507    DISABLED_DistinguishMiddleInitialWithinName
1508#endif
1509// Test Autofill distinguishes a middle initial in a name.
1510IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_DistinguishMiddleInitialWithinName) {
1511  ASSERT_TRUE(test_server()->Start());
1512
1513  CreateTestProfile();
1514
1515  GURL url = test_server()->GetURL(
1516      "files/autofill/autofill_middleinit_form.html");
1517  ui_test_utils::NavigateToURL(browser(), url);
1518  PopulateForm("NAME_FIRST");
1519
1520  ExpectFieldValue("NAME_MIDDLE", "C");
1521}
1522
1523// http://crbug.com/150084
1524#if defined(OS_MACOSX)
1525#define MAYBE_MultipleEmailFilledByOneUserGesture \
1526    MultipleEmailFilledByOneUserGesture
1527#else
1528#define MAYBE_MultipleEmailFilledByOneUserGesture \
1529    DISABLED_MultipleEmailFilledByOneUserGesture
1530#endif
1531// Test forms with multiple email addresses are filled properly.
1532// Entire form should be filled with one user gesture.
1533IN_PROC_BROWSER_TEST_F(AutofillTest,
1534                       MAYBE_MultipleEmailFilledByOneUserGesture) {
1535  ASSERT_TRUE(test_server()->Start());
1536
1537  std::string email("bsmith@gmail.com");
1538
1539  AutofillProfile profile;
1540  profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
1541  profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1542  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(email));
1543  profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("4088714567"));
1544  SetProfile(profile);
1545
1546  GURL url = test_server()->GetURL(
1547      "files/autofill/autofill_confirmemail_form.html");
1548  ui_test_utils::NavigateToURL(browser(), url);
1549  PopulateForm("NAME_FIRST");
1550
1551  ExpectFieldValue("EMAIL_CONFIRM", email);
1552  // TODO(isherman): verify entire form.
1553}
1554
1555// Test profile not aggregated if email found in non-email field.
1556IN_PROC_BROWSER_TEST_F(AutofillTest, ProfileWithEmailInOtherFieldNotSaved) {
1557  ASSERT_TRUE(test_server()->Start());
1558
1559  FormMap data;
1560  data["NAME_FIRST"] = "Bob";
1561  data["NAME_LAST"] = "Smith";
1562  data["ADDRESS_HOME_LINE1"] = "bsmith@gmail.com";
1563  data["ADDRESS_HOME_CITY"] = "San Jose";
1564  data["ADDRESS_HOME_STATE"] = "CA";
1565  data["ADDRESS_HOME_ZIP"] = "95110";
1566  data["COMPANY_NAME"] = "Company X";
1567  data["PHONE_HOME_WHOLE_NUMBER"] = "408-871-4567";
1568  FillFormAndSubmit("duplicate_profiles_test.html", data);
1569
1570  ASSERT_EQ(0u, personal_data_manager()->GetProfiles().size());
1571}
1572
1573// http://crbug.com/150084
1574#if defined(OS_MACOSX)
1575#define MAYBE_FormFillLatencyAfterSubmit FormFillLatencyAfterSubmit
1576#else
1577#define MAYBE_FormFillLatencyAfterSubmit DISABLED_FormFillLatencyAfterSubmit
1578#endif
1579// Test latency time on form submit with lots of stored Autofill profiles.
1580// This test verifies when a profile is selected from the Autofill dictionary
1581// that consists of thousands of profiles, the form does not hang after being
1582// submitted.
1583IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_FormFillLatencyAfterSubmit) {
1584  ASSERT_TRUE(test_server()->Start());
1585
1586  std::vector<std::string> cities;
1587  cities.push_back("San Jose");
1588  cities.push_back("San Francisco");
1589  cities.push_back("Sacramento");
1590  cities.push_back("Los Angeles");
1591
1592  std::vector<std::string> streets;
1593  streets.push_back("St");
1594  streets.push_back("Ave");
1595  streets.push_back("Ln");
1596  streets.push_back("Ct");
1597
1598  const int kNumProfiles = 1500;
1599  base::Time start_time = base::Time::Now();
1600  std::vector<AutofillProfile> profiles;
1601  for (int i = 0; i < kNumProfiles; i++) {
1602    AutofillProfile profile;
1603    string16 name(base::IntToString16(i));
1604    string16 email(name + ASCIIToUTF16("@example.com"));
1605    string16 street = ASCIIToUTF16(
1606        base::IntToString(base::RandInt(0, 10000)) + " " +
1607        streets[base::RandInt(0, streets.size() - 1)]);
1608    string16 city = ASCIIToUTF16(cities[base::RandInt(0, cities.size() - 1)]);
1609    string16 zip(base::IntToString16(base::RandInt(0, 10000)));
1610    profile.SetRawInfo(NAME_FIRST, name);
1611    profile.SetRawInfo(EMAIL_ADDRESS, email);
1612    profile.SetRawInfo(ADDRESS_HOME_LINE1, street);
1613    profile.SetRawInfo(ADDRESS_HOME_CITY, city);
1614    profile.SetRawInfo(ADDRESS_HOME_STATE, WideToUTF16(L"CA"));
1615    profile.SetRawInfo(ADDRESS_HOME_ZIP, zip);
1616    profile.SetRawInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"US"));
1617    profiles.push_back(profile);
1618  }
1619  SetProfiles(&profiles);
1620  // TODO(isherman): once we're sure this test doesn't timeout on any bots, this
1621  // can be removd.
1622  LOG(INFO) << "Created " << kNumProfiles << " profiles in " <<
1623               (base::Time::Now() - start_time).InSeconds() << " seconds.";
1624
1625  GURL url = test_server()->GetURL(
1626      "files/autofill/latency_after_submit_test.html");
1627  ui_test_utils::NavigateToURL(browser(), url);
1628  PopulateForm("NAME_FIRST");
1629
1630  content::WindowedNotificationObserver load_stop_observer(
1631      content::NOTIFICATION_LOAD_STOP,
1632      content::Source<content::NavigationController>(
1633          &browser()->tab_strip_model()->GetActiveWebContents()->
1634              GetController()));
1635
1636  ASSERT_TRUE(content::ExecuteScript(
1637      render_view_host(),
1638      "document.getElementById('testform').submit();"));
1639  // This will ensure the test didn't hang.
1640  load_stop_observer.Wait();
1641}
1642
1643// http://crbug.com/150084
1644#if defined(OS_MACOSX)
1645#define MAYBE_DisableAutocompleteWhileFilling DisableAutocompleteWhileFilling
1646#else
1647#define MAYBE_DisableAutocompleteWhileFilling \
1648    DISABLED_DisableAutocompleteWhileFilling
1649#endif
1650// Test that Chrome doesn't crash when autocomplete is disabled while the user
1651// is interacting with the form.  This is a regression test for
1652// http://crbug.com/160476
1653IN_PROC_BROWSER_TEST_F(AutofillTest, MAYBE_DisableAutocompleteWhileFilling) {
1654  CreateTestProfile();
1655
1656  // Load the test page.
1657  ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
1658      GURL(std::string(kDataURIPrefix) + kTestFormString)));
1659
1660  // Invoke Autofill: Start filling the first name field with "M" and wait for
1661  // the popup to be shown.
1662  FocusFirstNameField();
1663  SendKeyToPageAndWait(ui::VKEY_M);
1664
1665  // Now that the popup with suggestions is showing, disable autocomplete for
1666  // the active field.
1667  ASSERT_TRUE(content::ExecuteScript(
1668      render_view_host(),
1669      "document.querySelector('input').autocomplete = 'off';"));
1670
1671  // Press the down arrow to select the suggestion and attempt to preview the
1672  // autofilled form.
1673  if (!external_delegate()) {
1674    content::SimulateKeyPress(
1675        browser()->tab_strip_model()->GetActiveWebContents(),
1676        ui::VKEY_DOWN, false, false, false, false);
1677  } else {
1678    content::NativeWebKeyboardEvent event;
1679    event.windowsKeyCode = ui::VKEY_DOWN;
1680    external_delegate()->keyboard_listener()->HandleKeyPressEvent(event);
1681  }
1682
1683  // Wait for any IPCs to complete by performing an action that generates an
1684  // IPC that's easy to wait for.  Chrome shouldn't crash.
1685  bool result = false;
1686  ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1687      render_view_host(),
1688      "var city = document.getElementById('city');"
1689      "city.onfocus = function() { domAutomationController.send(true); };"
1690      "city.focus()",
1691      &result));
1692  ASSERT_TRUE(result);
1693  SendKeyToPageAndWait(ui::VKEY_A);
1694}
1695
1696// Test that profiles merge for aggregated data with same address.
1697// The criterion for when two profiles are expected to be merged is when their
1698// 'Address Line 1' and 'City' data match. When two profiles are merged, any
1699// remaining address fields are expected to be overwritten. Any non-address
1700// fields should accumulate multi-valued data.
1701// DISABLED: http://crbug.com/150084
1702IN_PROC_BROWSER_TEST_F(AutofillTest,
1703                       DISABLED_MergeAggregatedProfilesWithSameAddress) {
1704  AggregateProfilesIntoAutofillPrefs("dataset_2.txt");
1705
1706  ASSERT_EQ(3u, personal_data_manager()->GetProfiles().size());
1707}
1708
1709// Test profiles are not merged without mininum address values.
1710// Mininum address values needed during aggregation are: address line 1, city,
1711// state, and zip code.
1712// Profiles are merged when data for address line 1 and city match.
1713// DISABLED: http://crbug.com/150084
1714IN_PROC_BROWSER_TEST_F(AutofillTest,
1715                       DISABLED_ProfilesNotMergedWhenNoMinAddressData) {
1716  AggregateProfilesIntoAutofillPrefs("dataset_no_address.txt");
1717
1718  ASSERT_EQ(0u, personal_data_manager()->GetProfiles().size());
1719}
1720
1721// Test Autofill ability to merge duplicate profiles and throw away junk.
1722// TODO(isherman): this looks redundant, consider removing.
1723// DISABLED: http://crbug.com/150084
1724IN_PROC_BROWSER_TEST_F(AutofillTest,
1725                       DISABLED_MergeAggregatedDuplicatedProfiles) {
1726  int num_of_profiles =
1727      AggregateProfilesIntoAutofillPrefs("dataset_no_address.txt");
1728
1729  ASSERT_GT(num_of_profiles,
1730            static_cast<int>(personal_data_manager()->GetProfiles().size()));
1731}
1732
1733}  // namespace autofill
1734