1 // Copyright (c) 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.
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_manager.h"
35 #include "components/autofill/core/browser/autofill_manager_test_delegate.h"
36 #include "components/autofill/core/browser/autofill_profile.h"
37 #include "components/autofill/core/browser/personal_data_manager.h"
38 #include "components/autofill/core/browser/personal_data_manager_observer.h"
39 #include "components/autofill/core/browser/validation.h"
40 #include "content/public/browser/navigation_controller.h"
41 #include "content/public/browser/notification_observer.h"
42 #include "content/public/browser/notification_registrar.h"
43 #include "content/public/browser/notification_service.h"
44 #include "content/public/browser/render_view_host.h"
45 #include "content/public/browser/render_widget_host.h"
46 #include "content/public/browser/web_contents.h"
47 #include "content/public/test/browser_test_utils.h"
48 #include "content/public/test/test_renderer_host.h"
49 #include "content/public/test/test_utils.h"
50 #include "net/url_request/test_url_fetcher_factory.h"
51 #include "testing/gmock/include/gmock/gmock.h"
52 #include "testing/gtest/include/gtest/gtest.h"
53 #include "ui/events/keycodes/keyboard_codes.h"
58 static const char* kDataURIPrefix = "data:text/html;charset=utf-8,";
59 static 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>"
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>"
86 "<label for=\"phone\">Phone number:</label>"
87 " <input type=\"text\" id=\"phone\"><br>"
91 // AutofillManagerTestDelegateImpl --------------------------------------------
93 class AutofillManagerTestDelegateImpl
94 : public autofill::AutofillManagerTestDelegate {
96 AutofillManagerTestDelegateImpl() {}
97 virtual ~AutofillManagerTestDelegateImpl() {}
99 // autofill::AutofillManagerTestDelegate:
100 virtual void DidPreviewFormData() OVERRIDE {
101 loop_runner_->Quit();
104 virtual void DidFillFormData() OVERRIDE {
105 loop_runner_->Quit();
108 virtual void DidShowSuggestions() OVERRIDE {
109 loop_runner_->Quit();
113 loop_runner_ = new content::MessageLoopRunner();
121 scoped_refptr<content::MessageLoopRunner> loop_runner_;
123 DISALLOW_COPY_AND_ASSIGN(AutofillManagerTestDelegateImpl);
127 // WindowedPersonalDataManagerObserver ----------------------------------------
129 class WindowedPersonalDataManagerObserver
130 : public PersonalDataManagerObserver,
131 public content::NotificationObserver {
133 explicit WindowedPersonalDataManagerObserver(Browser* browser)
135 has_run_message_loop_(false),
137 infobar_service_(NULL) {
138 PersonalDataManagerFactory::GetForProfile(browser_->profile())->
140 registrar_.Add(this, chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
141 content::NotificationService::AllSources());
144 virtual ~WindowedPersonalDataManagerObserver() {
145 if (infobar_service_) {
146 while (infobar_service_->infobar_count() > 0) {
147 infobar_service_->RemoveInfoBar(infobar_service_->infobar_at(0));
152 // PersonalDataManagerObserver:
153 virtual void OnPersonalDataChanged() OVERRIDE {
154 if (has_run_message_loop_) {
155 base::MessageLoopForUI::current()->Quit();
156 has_run_message_loop_ = false;
161 virtual void OnInsufficientFormData() OVERRIDE {
162 OnPersonalDataChanged();
165 // content::NotificationObserver:
166 virtual void Observe(int type,
167 const content::NotificationSource& source,
168 const content::NotificationDetails& details) OVERRIDE {
169 infobar_service_ = InfoBarService::FromWebContents(
170 browser_->tab_strip_model()->GetActiveWebContents());
171 infobar_service_->infobar_at(0)->AsConfirmInfoBarDelegate()->Accept();
176 has_run_message_loop_ = true;
177 content::RunMessageLoop();
179 PersonalDataManagerFactory::GetForProfile(browser_->profile())->
180 RemoveObserver(this);
185 bool has_run_message_loop_;
187 content::NotificationRegistrar registrar_;
188 InfoBarService* infobar_service_;
190 DISALLOW_COPY_AND_ASSIGN(WindowedPersonalDataManagerObserver);
193 // AutofillInteractiveTest ----------------------------------------------------
195 class AutofillInteractiveTest : public InProcessBrowserTest {
197 AutofillInteractiveTest() :
198 key_press_event_sink_(
199 base::Bind(&AutofillInteractiveTest::HandleKeyPressEvent,
200 base::Unretained(this))) {}
201 virtual ~AutofillInteractiveTest() {}
203 // InProcessBrowserTest:
204 virtual void SetUpOnMainThread() OVERRIDE {
205 // Don't want Keychain coming up on Mac.
206 test::DisableSystemServices(browser()->profile());
208 // Inject the test delegate into the AutofillManager.
209 content::WebContents* web_contents = GetWebContents();
210 AutofillDriverImpl* autofill_driver =
211 AutofillDriverImpl::FromWebContents(web_contents);
212 AutofillManager* autofill_manager = autofill_driver->autofill_manager();
213 autofill_manager->SetTestDelegate(&test_delegate_);
216 virtual void CleanUpOnMainThread() OVERRIDE {
217 // Make sure to close any showing popups prior to tearing down the UI.
218 content::WebContents* web_contents = GetWebContents();
219 AutofillManager* autofill_manager =
220 AutofillDriverImpl::FromWebContents(web_contents)->autofill_manager();
221 autofill_manager->delegate()->HideAutofillPopup();
224 PersonalDataManager* GetPersonalDataManager() {
225 return PersonalDataManagerFactory::GetForProfile(browser()->profile());
228 content::WebContents* GetWebContents() {
229 return browser()->tab_strip_model()->GetActiveWebContents();
232 content::RenderViewHost* GetRenderViewHost() {
233 return GetWebContents()->GetRenderViewHost();
236 void CreateTestProfile() {
237 AutofillProfile profile;
238 test::SetProfileInfo(
239 &profile, "Milton", "C.", "Waddams",
240 "red.swingline@initech.com", "Initech", "4120 Freidrich Lane",
241 "Basement", "Austin", "Texas", "78744", "US", "5125551234");
243 WindowedPersonalDataManagerObserver observer(browser());
244 GetPersonalDataManager()->AddProfile(profile);
246 // AddProfile is asynchronous. Wait for it to finish before continuing the
251 void SetProfiles(std::vector<AutofillProfile>* profiles) {
252 WindowedPersonalDataManagerObserver observer(browser());
253 GetPersonalDataManager()->SetProfiles(profiles);
257 void SetProfile(const AutofillProfile& profile) {
258 std::vector<AutofillProfile> profiles;
259 profiles.push_back(profile);
260 SetProfiles(&profiles);
263 // Populates a webpage form using autofill data and keypress events.
264 // This function focuses the specified input field in the form, and then
265 // sends keypress events to the tab to cause the form to be populated.
266 void PopulateForm(const std::string& field_id) {
267 std::string js("document.getElementById('" + field_id + "').focus();");
268 ASSERT_TRUE(content::ExecuteScript(GetRenderViewHost(), js));
270 SendKeyToPageAndWait(ui::VKEY_DOWN);
271 SendKeyToPopupAndWait(ui::VKEY_DOWN);
272 SendKeyToPopupAndWait(ui::VKEY_RETURN);
275 void ExpectFieldValue(const std::string& field_name,
276 const std::string& expected_value) {
278 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
280 "window.domAutomationController.send("
281 " document.getElementById('" + field_name + "').value);",
283 EXPECT_EQ(expected_value, value);
286 void SimulateURLFetch(bool success) {
287 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
288 ASSERT_TRUE(fetcher);
289 net::URLRequestStatus status;
290 status.set_status(success ? net::URLRequestStatus::SUCCESS :
291 net::URLRequestStatus::FAILED);
293 std::string script = " var google = {};"
294 "google.translate = (function() {"
296 " TranslateService: function() {"
298 " isAvailable : function() {"
301 " restore : function() {"
304 " getDetectedLanguage : function() {"
307 " translatePage : function(originalLang, targetLang,"
308 " onTranslateProgress) {"
309 " document.getElementsByTagName(\"body\")[0].innerHTML = '" +
310 std::string(kTestFormString) +
312 " onTranslateProgress(100, true, false);"
318 "cr.googleTranslate.onTranslateElementLoad();";
320 fetcher->set_url(fetcher->GetOriginalURL());
321 fetcher->set_status(status);
322 fetcher->set_response_code(success ? 200 : 500);
323 fetcher->SetResponseString(script);
324 fetcher->delegate()->OnURLFetchComplete(fetcher);
327 void FocusFirstNameField() {
329 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
331 "if (document.readyState === 'complete')"
332 " document.getElementById('firstname').focus();"
334 " domAutomationController.send(false);",
339 void ExpectFilledTestForm() {
340 ExpectFieldValue("firstname", "Milton");
341 ExpectFieldValue("lastname", "Waddams");
342 ExpectFieldValue("address1", "4120 Freidrich Lane");
343 ExpectFieldValue("address2", "Basement");
344 ExpectFieldValue("city", "Austin");
345 ExpectFieldValue("state", "TX");
346 ExpectFieldValue("zip", "78744");
347 ExpectFieldValue("country", "US");
348 ExpectFieldValue("phone", "5125551234");
351 void SendKeyToPageAndWait(ui::KeyboardCode key) {
352 test_delegate_.Reset();
353 content::SimulateKeyPress(
354 GetWebContents(), key, false, false, false, false);
355 test_delegate_.Wait();
358 bool HandleKeyPressEvent(const content::NativeWebKeyboardEvent& event) {
362 void SendKeyToPopupAndWait(ui::KeyboardCode key) {
363 // Route popup-targeted key presses via the render view host.
364 content::NativeWebKeyboardEvent event;
365 event.windowsKeyCode = key;
366 event.type = WebKit::WebKeyboardEvent::RawKeyDown;
367 test_delegate_.Reset();
368 // Install the key press event sink to ensure that any events that are not
369 // handled by the installed callbacks do not end up crashing the test.
370 GetRenderViewHost()->AddKeyPressEventCallback(key_press_event_sink_);
371 GetRenderViewHost()->ForwardKeyboardEvent(event);
372 test_delegate_.Wait();
373 GetRenderViewHost()->RemoveKeyPressEventCallback(key_press_event_sink_);
376 void TryBasicFormFill() {
377 FocusFirstNameField();
379 // Start filling the first name field with "M" and wait for the popup to be
381 SendKeyToPageAndWait(ui::VKEY_M);
383 // Press the down arrow to select the suggestion and preview the autofilled
385 SendKeyToPopupAndWait(ui::VKEY_DOWN);
387 // The previewed values should not be accessible to JavaScript.
388 ExpectFieldValue("firstname", "M");
389 ExpectFieldValue("lastname", std::string());
390 ExpectFieldValue("address1", std::string());
391 ExpectFieldValue("address2", std::string());
392 ExpectFieldValue("city", std::string());
393 ExpectFieldValue("state", std::string());
394 ExpectFieldValue("zip", std::string());
395 ExpectFieldValue("country", std::string());
396 ExpectFieldValue("phone", std::string());
397 // TODO(isherman): It would be nice to test that the previewed values are
398 // displayed: http://crbug.com/57220
400 // Press Enter to accept the autofill suggestions.
401 SendKeyToPopupAndWait(ui::VKEY_RETURN);
403 // The form should be filled.
404 ExpectFilledTestForm();
408 AutofillManagerTestDelegateImpl test_delegate_;
410 net::TestURLFetcherFactory url_fetcher_factory_;
412 // KeyPressEventCallback that serves as a sink to ensure that every key press
413 // event the tests create and have the WebContents forward is handled by some
414 // key press event callback. It is necessary to have this sinkbecause if no
415 // key press event callback handles the event (at least on Mac), a DCHECK
416 // ends up going off that the |event| doesn't have an |os_event| associated
418 content::RenderWidgetHost::KeyPressEventCallback key_press_event_sink_;
420 DISALLOW_COPY_AND_ASSIGN(AutofillInteractiveTest);
423 // Test that basic form fill is working.
424 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, BasicFormFill) {
427 // Load the test page.
428 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
429 GURL(std::string(kDataURIPrefix) + kTestFormString)));
435 // Test that form filling can be initiated by pressing the down arrow.
436 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillViaDownArrow) {
439 // Load the test page.
440 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
441 GURL(std::string(kDataURIPrefix) + kTestFormString)));
443 // Focus a fillable field.
444 FocusFirstNameField();
446 // Press the down arrow to initiate Autofill and wait for the popup to be
448 SendKeyToPageAndWait(ui::VKEY_DOWN);
450 // Press the down arrow to select the suggestion and preview the autofilled
452 SendKeyToPopupAndWait(ui::VKEY_DOWN);
454 // Press Enter to accept the autofill suggestions.
455 SendKeyToPopupAndWait(ui::VKEY_RETURN);
457 // The form should be filled.
458 ExpectFilledTestForm();
461 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillSelectViaTab) {
464 // Load the test page.
465 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
466 GURL(std::string(kDataURIPrefix) + kTestFormString)));
468 // Focus a fillable field.
469 FocusFirstNameField();
471 // Press the down arrow to initiate Autofill and wait for the popup to be
473 SendKeyToPageAndWait(ui::VKEY_DOWN);
475 // Press the down arrow to select the suggestion and preview the autofilled
477 SendKeyToPopupAndWait(ui::VKEY_DOWN);
479 // Press tab to accept the autofill suggestions.
480 SendKeyToPopupAndWait(ui::VKEY_TAB);
482 // The form should be filled.
483 ExpectFilledTestForm();
486 // Test that a JavaScript onchange event is fired after auto-filling a form.
487 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, OnChangeAfterAutofill) {
490 const char* kOnChangeScript =
492 "focused_fired = false;"
493 "unfocused_fired = false;"
494 "changed_select_fired = false;"
495 "unchanged_select_fired = false;"
496 "document.getElementById('firstname').onchange = function() {"
497 " focused_fired = true;"
499 "document.getElementById('lastname').onchange = function() {"
500 " unfocused_fired = true;"
502 "document.getElementById('state').onchange = function() {"
503 " changed_select_fired = true;"
505 "document.getElementById('country').onchange = function() {"
506 " unchanged_select_fired = true;"
508 "document.getElementById('country').value = 'US';"
511 // Load the test page.
512 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
513 GURL(std::string(kDataURIPrefix) + kTestFormString + kOnChangeScript)));
516 FocusFirstNameField();
518 // Start filling the first name field with "M" and wait for the popup to be
520 SendKeyToPageAndWait(ui::VKEY_M);
522 // Press the down arrow to select the suggestion and preview the autofilled
524 SendKeyToPopupAndWait(ui::VKEY_DOWN);
526 // Press Enter to accept the autofill suggestions.
527 SendKeyToPopupAndWait(ui::VKEY_RETURN);
529 // The form should be filled.
530 ExpectFilledTestForm();
532 // The change event should have already fired for unfocused fields, both of
533 // <input> and of <select> type. However, it should not yet have fired for the
535 bool focused_fired = false;
536 bool unfocused_fired = false;
537 bool changed_select_fired = false;
538 bool unchanged_select_fired = false;
539 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
541 "domAutomationController.send(focused_fired);",
543 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
545 "domAutomationController.send(unfocused_fired);",
547 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
549 "domAutomationController.send(changed_select_fired);",
550 &changed_select_fired));
551 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
553 "domAutomationController.send(unchanged_select_fired);",
554 &unchanged_select_fired));
555 EXPECT_FALSE(focused_fired);
556 EXPECT_TRUE(unfocused_fired);
557 EXPECT_TRUE(changed_select_fired);
558 EXPECT_FALSE(unchanged_select_fired);
560 // Unfocus the first name field. Its change event should fire.
561 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
563 "document.getElementById('firstname').blur();"
564 "domAutomationController.send(focused_fired);", &focused_fired));
565 EXPECT_TRUE(focused_fired);
568 // Test that we can autofill forms distinguished only by their |id| attribute.
569 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
570 AutofillFormsDistinguishedById) {
573 // Load the test page.
574 const std::string kURL =
575 std::string(kDataURIPrefix) + kTestFormString +
577 "var mainForm = document.forms[0];"
578 "mainForm.id = 'mainForm';"
579 "var newForm = document.createElement('form');"
580 "newForm.action = mainForm.action;"
581 "newForm.method = mainForm.method;"
582 "newForm.id = 'newForm';"
583 "mainForm.parentNode.insertBefore(newForm, mainForm);"
585 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(), GURL(kURL)));
591 // Test that we properly autofill forms with repeated fields.
592 // In the wild, the repeated fields are typically either email fields
593 // (duplicated for "confirmation"); or variants that are hot-swapped via
594 // JavaScript, with only one actually visible at any given time.
595 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillFormWithRepeatedField) {
598 // Load the test page.
599 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
600 GURL(std::string(kDataURIPrefix) +
601 "<form action=\"http://www.example.com/\" method=\"POST\">"
602 "<label for=\"firstname\">First name:</label>"
603 " <input type=\"text\" id=\"firstname\""
604 " onFocus=\"domAutomationController.send(true)\"><br>"
605 "<label for=\"lastname\">Last name:</label>"
606 " <input type=\"text\" id=\"lastname\"><br>"
607 "<label for=\"address1\">Address line 1:</label>"
608 " <input type=\"text\" id=\"address1\"><br>"
609 "<label for=\"address2\">Address line 2:</label>"
610 " <input type=\"text\" id=\"address2\"><br>"
611 "<label for=\"city\">City:</label>"
612 " <input type=\"text\" id=\"city\"><br>"
613 "<label for=\"state\">State:</label>"
614 " <select id=\"state\">"
615 " <option value=\"\" selected=\"yes\">--</option>"
616 " <option value=\"CA\">California</option>"
617 " <option value=\"TX\">Texas</option>"
619 "<label for=\"state_freeform\" style=\"display:none\">State:</label>"
620 " <input type=\"text\" id=\"state_freeform\""
621 " style=\"display:none\"><br>"
622 "<label for=\"zip\">ZIP code:</label>"
623 " <input type=\"text\" id=\"zip\"><br>"
624 "<label for=\"country\">Country:</label>"
625 " <select id=\"country\">"
626 " <option value=\"\" selected=\"yes\">--</option>"
627 " <option value=\"CA\">Canada</option>"
628 " <option value=\"US\">United States</option>"
630 "<label for=\"phone\">Phone number:</label>"
631 " <input type=\"text\" id=\"phone\"><br>"
636 ExpectFieldValue("state_freeform", std::string());
639 // Test that we properly autofill forms with non-autofillable fields.
640 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
641 AutofillFormWithNonAutofillableField) {
644 // Load the test page.
645 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
646 GURL(std::string(kDataURIPrefix) +
647 "<form action=\"http://www.example.com/\" method=\"POST\">"
648 "<label for=\"firstname\">First name:</label>"
649 " <input type=\"text\" id=\"firstname\""
650 " onFocus=\"domAutomationController.send(true)\"><br>"
651 "<label for=\"middlename\">Middle name:</label>"
652 " <input type=\"text\" id=\"middlename\" autocomplete=\"off\" /><br>"
653 "<label for=\"lastname\">Last name:</label>"
654 " <input type=\"text\" id=\"lastname\"><br>"
655 "<label for=\"address1\">Address line 1:</label>"
656 " <input type=\"text\" id=\"address1\"><br>"
657 "<label for=\"address2\">Address line 2:</label>"
658 " <input type=\"text\" id=\"address2\"><br>"
659 "<label for=\"city\">City:</label>"
660 " <input type=\"text\" id=\"city\"><br>"
661 "<label for=\"state\">State:</label>"
662 " <select id=\"state\">"
663 " <option value=\"\" selected=\"yes\">--</option>"
664 " <option value=\"CA\">California</option>"
665 " <option value=\"TX\">Texas</option>"
667 "<label for=\"zip\">ZIP code:</label>"
668 " <input type=\"text\" id=\"zip\"><br>"
669 "<label for=\"country\">Country:</label>"
670 " <select id=\"country\">"
671 " <option value=\"\" selected=\"yes\">--</option>"
672 " <option value=\"CA\">Canada</option>"
673 " <option value=\"US\">United States</option>"
675 "<label for=\"phone\">Phone number:</label>"
676 " <input type=\"text\" id=\"phone\"><br>"
683 // Test that we can Autofill dynamically generated forms.
684 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, DynamicFormFill) {
687 // Load the test page.
688 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
689 GURL(std::string(kDataURIPrefix) +
690 "<form id=\"form\" action=\"http://www.example.com/\""
691 " method=\"POST\"></form>"
693 "function AddElement(name, label) {"
694 " var form = document.getElementById('form');"
696 " var label_text = document.createTextNode(label);"
697 " var label_element = document.createElement('label');"
698 " label_element.setAttribute('for', name);"
699 " label_element.appendChild(label_text);"
700 " form.appendChild(label_element);"
702 " if (name === 'state' || name === 'country') {"
703 " var select_element = document.createElement('select');"
704 " select_element.setAttribute('id', name);"
705 " select_element.setAttribute('name', name);"
707 " /* Add an empty selected option. */"
708 " var default_option = new Option('--', '', true);"
709 " select_element.appendChild(default_option);"
711 " /* Add the other options. */"
712 " if (name == 'state') {"
713 " var option1 = new Option('California', 'CA');"
714 " select_element.appendChild(option1);"
715 " var option2 = new Option('Texas', 'TX');"
716 " select_element.appendChild(option2);"
718 " var option1 = new Option('Canada', 'CA');"
719 " select_element.appendChild(option1);"
720 " var option2 = new Option('United States', 'US');"
721 " select_element.appendChild(option2);"
724 " form.appendChild(select_element);"
726 " var input_element = document.createElement('input');"
727 " input_element.setAttribute('id', name);"
728 " input_element.setAttribute('name', name);"
730 " /* Add the onFocus listener to the 'firstname' field. */"
731 " if (name === 'firstname') {"
732 " input_element.setAttribute("
733 " 'onFocus', 'domAutomationController.send(true)');"
736 " form.appendChild(input_element);"
739 " form.appendChild(document.createElement('br'));"
742 "function BuildForm() {"
744 " ['firstname', 'First name:'],"
745 " ['lastname', 'Last name:'],"
746 " ['address1', 'Address line 1:'],"
747 " ['address2', 'Address line 2:'],"
748 " ['city', 'City:'],"
749 " ['state', 'State:'],"
750 " ['zip', 'ZIP code:'],"
751 " ['country', 'Country:'],"
752 " ['phone', 'Phone number:'],"
755 " for (var i = 0; i < elements.length; i++) {"
756 " var name = elements[i][0];"
757 " var label = elements[i][1];"
758 " AddElement(name, label);"
763 // Dynamically construct the form.
764 ASSERT_TRUE(content::ExecuteScript(GetRenderViewHost(), "BuildForm();"));
770 // Test that form filling works after reloading the current page.
771 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillAfterReload) {
774 // Load the test page.
775 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
776 GURL(std::string(kDataURIPrefix) + kTestFormString)));
779 content::WebContents* web_contents = GetWebContents();
780 web_contents->GetController().Reload(false);
781 content::WaitForLoadStop(web_contents);
787 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillAfterTranslate) {
790 GURL url(std::string(kDataURIPrefix) +
791 "<form action=\"http://www.example.com/\" method=\"POST\">"
792 "<label for=\"fn\">なまえ</label>"
793 " <input type=\"text\" id=\"fn\""
794 " onFocus=\"domAutomationController.send(true)\""
796 "<label for=\"ln\">みょうじ</label>"
797 " <input type=\"text\" id=\"ln\"><br>"
798 "<label for=\"a1\">Address line 1:</label>"
799 " <input type=\"text\" id=\"a1\"><br>"
800 "<label for=\"a2\">Address line 2:</label>"
801 " <input type=\"text\" id=\"a2\"><br>"
802 "<label for=\"ci\">City:</label>"
803 " <input type=\"text\" id=\"ci\"><br>"
804 "<label for=\"st\">State:</label>"
805 " <select id=\"st\">"
806 " <option value=\"\" selected=\"yes\">--</option>"
807 " <option value=\"CA\">California</option>"
808 " <option value=\"TX\">Texas</option>"
810 "<label for=\"z\">ZIP code:</label>"
811 " <input type=\"text\" id=\"z\"><br>"
812 "<label for=\"co\">Country:</label>"
813 " <select id=\"co\">"
814 " <option value=\"\" selected=\"yes\">--</option>"
815 " <option value=\"CA\">Canada</option>"
816 " <option value=\"US\">United States</option>"
818 "<label for=\"ph\">Phone number:</label>"
819 " <input type=\"text\" id=\"ph\"><br>"
821 // Add additional Japanese characters to ensure the translate bar
823 "我々は重要な、興味深いものになるが、時折状況が発生するため苦労や痛みは"
824 "彼にいくつかの素晴らしいを調達することができます。それから、いくつかの利");
826 content::WindowedNotificationObserver infobar_observer(
827 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
828 content::NotificationService::AllSources());
829 ASSERT_NO_FATAL_FAILURE(
830 ui_test_utils::NavigateToURL(browser(), url));
832 // Wait for the translation bar to appear and get it.
833 infobar_observer.Wait();
834 TranslateInfoBarDelegate* delegate = InfoBarService::FromWebContents(
835 GetWebContents())->infobar_at(0)->AsTranslateInfoBarDelegate();
836 ASSERT_TRUE(delegate);
837 EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE,
838 delegate->infobar_type());
840 // Simulate translation button press.
841 delegate->Translate();
843 content::WindowedNotificationObserver translation_observer(
844 chrome::NOTIFICATION_PAGE_TRANSLATED,
845 content::NotificationService::AllSources());
847 // Simulate the translate script being retrieved.
848 // Pass fake google.translate lib as the translate script.
849 SimulateURLFetch(true);
851 // Simulate the render notifying the translation has been done.
852 translation_observer.Wait();
857 // Test phone fields parse correctly from a given profile.
858 // The high level key presses execute the following: Select the first text
859 // field, invoke the autofill popup list, select the first profile within the
860 // list, and commit to the profile to populate the form.
861 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, ComparePhoneNumbers) {
862 ASSERT_TRUE(test_server()->Start());
864 AutofillProfile profile;
865 profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
866 profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
867 profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 H St."));
868 profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
869 profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
870 profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
871 profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("1-408-555-4567"));
874 GURL url = test_server()->GetURL("files/autofill/form_phones.html");
875 ui_test_utils::NavigateToURL(browser(), url);
876 PopulateForm("NAME_FIRST");
878 ExpectFieldValue("NAME_FIRST", "Bob");
879 ExpectFieldValue("NAME_LAST", "Smith");
880 ExpectFieldValue("ADDRESS_HOME_LINE1", "1234 H St.");
881 ExpectFieldValue("ADDRESS_HOME_CITY", "San Jose");
882 ExpectFieldValue("ADDRESS_HOME_STATE", "CA");
883 ExpectFieldValue("ADDRESS_HOME_ZIP", "95110");
884 ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "14085554567");
885 ExpectFieldValue("PHONE_HOME_CITY_CODE-1", "408");
886 ExpectFieldValue("PHONE_HOME_CITY_CODE-2", "408");
887 ExpectFieldValue("PHONE_HOME_NUMBER", "5554567");
888 ExpectFieldValue("PHONE_HOME_NUMBER_3-1", "555");
889 ExpectFieldValue("PHONE_HOME_NUMBER_3-2", "555");
890 ExpectFieldValue("PHONE_HOME_NUMBER_4-1", "4567");
891 ExpectFieldValue("PHONE_HOME_NUMBER_4-2", "4567");
892 ExpectFieldValue("PHONE_HOME_EXT-1", std::string());
893 ExpectFieldValue("PHONE_HOME_EXT-2", std::string());
894 ExpectFieldValue("PHONE_HOME_COUNTRY_CODE-1", "1");
897 // Test that Autofill does not fill in read-only fields.
898 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, NoAutofillForReadOnlyFields) {
899 ASSERT_TRUE(test_server()->Start());
901 std::string addr_line1("1234 H St.");
903 AutofillProfile profile;
904 profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
905 profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
906 profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("bsmith@gmail.com"));
907 profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16(addr_line1));
908 profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
909 profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
910 profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
911 profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Company X"));
912 profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("408-871-4567"));
915 GURL url = test_server()->GetURL("files/autofill/read_only_field_test.html");
916 ui_test_utils::NavigateToURL(browser(), url);
917 PopulateForm("firstname");
919 ExpectFieldValue("email", std::string());
920 ExpectFieldValue("address", addr_line1);
923 // Test form is fillable from a profile after form was reset.
925 // 1. Fill form using a saved profile.
926 // 2. Reset the form.
927 // 3. Fill form using a saved profile.
928 // Flakily times out: http://crbug.com/270341
929 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, DISABLED_FormFillableOnReset) {
930 ASSERT_TRUE(test_server()->Start());
934 GURL url = test_server()->GetURL("files/autofill/autofill_test_form.html");
935 ui_test_utils::NavigateToURL(browser(), url);
936 PopulateForm("NAME_FIRST");
938 ASSERT_TRUE(content::ExecuteScript(
939 GetWebContents(), "document.getElementById('testform').reset()"));
941 PopulateForm("NAME_FIRST");
943 ExpectFieldValue("NAME_FIRST", "Milton");
944 ExpectFieldValue("NAME_LAST", "Waddams");
945 ExpectFieldValue("EMAIL_ADDRESS", "red.swingline@initech.com");
946 ExpectFieldValue("ADDRESS_HOME_LINE1", "4120 Freidrich Lane");
947 ExpectFieldValue("ADDRESS_HOME_CITY", "Austin");
948 ExpectFieldValue("ADDRESS_HOME_STATE", "Texas");
949 ExpectFieldValue("ADDRESS_HOME_ZIP", "78744");
950 ExpectFieldValue("ADDRESS_HOME_COUNTRY", "United States");
951 ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "5125551234");
954 // Test Autofill distinguishes a middle initial in a name.
955 // Flakily times out: http://crbug.com/270341
956 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
957 DISABLED_DistinguishMiddleInitialWithinName) {
958 ASSERT_TRUE(test_server()->Start());
962 GURL url = test_server()->GetURL(
963 "files/autofill/autofill_middleinit_form.html");
964 ui_test_utils::NavigateToURL(browser(), url);
965 PopulateForm("NAME_FIRST");
967 ExpectFieldValue("NAME_MIDDLE", "C");
970 // Test forms with multiple email addresses are filled properly.
971 // Entire form should be filled with one user gesture.
972 // Flakily times out: http://crbug.com/270341
973 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
974 DISABLED_MultipleEmailFilledByOneUserGesture) {
975 ASSERT_TRUE(test_server()->Start());
977 std::string email("bsmith@gmail.com");
979 AutofillProfile profile;
980 profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
981 profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
982 profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(email));
983 profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("4088714567"));
986 GURL url = test_server()->GetURL(
987 "files/autofill/autofill_confirmemail_form.html");
988 ui_test_utils::NavigateToURL(browser(), url);
989 PopulateForm("NAME_FIRST");
991 ExpectFieldValue("EMAIL_CONFIRM", email);
992 // TODO(isherman): verify entire form.
995 // http://crbug.com/281527
996 #if defined(OS_MACOSX)
997 #define MAYBE_FormFillLatencyAfterSubmit FormFillLatencyAfterSubmit
999 #define MAYBE_FormFillLatencyAfterSubmit DISABLED_FormFillLatencyAfterSubmit
1001 // Test latency time on form submit with lots of stored Autofill profiles.
1002 // This test verifies when a profile is selected from the Autofill dictionary
1003 // that consists of thousands of profiles, the form does not hang after being
1005 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
1006 MAYBE_FormFillLatencyAfterSubmit) {
1007 ASSERT_TRUE(test_server()->Start());
1009 std::vector<std::string> cities;
1010 cities.push_back("San Jose");
1011 cities.push_back("San Francisco");
1012 cities.push_back("Sacramento");
1013 cities.push_back("Los Angeles");
1015 std::vector<std::string> streets;
1016 streets.push_back("St");
1017 streets.push_back("Ave");
1018 streets.push_back("Ln");
1019 streets.push_back("Ct");
1021 const int kNumProfiles = 1500;
1022 base::Time start_time = base::Time::Now();
1023 std::vector<AutofillProfile> profiles;
1024 for (int i = 0; i < kNumProfiles; i++) {
1025 AutofillProfile profile;
1026 string16 name(base::IntToString16(i));
1027 string16 email(name + ASCIIToUTF16("@example.com"));
1028 string16 street = ASCIIToUTF16(
1029 base::IntToString(base::RandInt(0, 10000)) + " " +
1030 streets[base::RandInt(0, streets.size() - 1)]);
1031 string16 city = ASCIIToUTF16(cities[base::RandInt(0, cities.size() - 1)]);
1032 string16 zip(base::IntToString16(base::RandInt(0, 10000)));
1033 profile.SetRawInfo(NAME_FIRST, name);
1034 profile.SetRawInfo(EMAIL_ADDRESS, email);
1035 profile.SetRawInfo(ADDRESS_HOME_LINE1, street);
1036 profile.SetRawInfo(ADDRESS_HOME_CITY, city);
1037 profile.SetRawInfo(ADDRESS_HOME_STATE, WideToUTF16(L"CA"));
1038 profile.SetRawInfo(ADDRESS_HOME_ZIP, zip);
1039 profile.SetRawInfo(ADDRESS_HOME_COUNTRY, WideToUTF16(L"US"));
1040 profiles.push_back(profile);
1042 SetProfiles(&profiles);
1043 // TODO(isherman): once we're sure this test doesn't timeout on any bots, this
1045 LOG(INFO) << "Created " << kNumProfiles << " profiles in " <<
1046 (base::Time::Now() - start_time).InSeconds() << " seconds.";
1048 GURL url = test_server()->GetURL(
1049 "files/autofill/latency_after_submit_test.html");
1050 ui_test_utils::NavigateToURL(browser(), url);
1051 PopulateForm("NAME_FIRST");
1053 content::WindowedNotificationObserver load_stop_observer(
1054 content::NOTIFICATION_LOAD_STOP,
1055 content::Source<content::NavigationController>(
1056 &GetWebContents()->GetController()));
1058 ASSERT_TRUE(content::ExecuteScript(
1059 GetRenderViewHost(),
1060 "document.getElementById('testform').submit();"));
1061 // This will ensure the test didn't hang.
1062 load_stop_observer.Wait();
1065 // Test that Chrome doesn't crash when autocomplete is disabled while the user
1066 // is interacting with the form. This is a regression test for
1067 // http://crbug.com/160476
1068 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
1069 DisableAutocompleteWhileFilling) {
1070 CreateTestProfile();
1072 // Load the test page.
1073 ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
1074 GURL(std::string(kDataURIPrefix) + kTestFormString)));
1076 // Invoke Autofill: Start filling the first name field with "M" and wait for
1077 // the popup to be shown.
1078 FocusFirstNameField();
1079 SendKeyToPageAndWait(ui::VKEY_M);
1081 // Now that the popup with suggestions is showing, disable autocomplete for
1082 // the active field.
1083 ASSERT_TRUE(content::ExecuteScript(
1084 GetRenderViewHost(),
1085 "document.querySelector('input').autocomplete = 'off';"));
1087 // Press the down arrow to select the suggestion and attempt to preview the
1089 SendKeyToPopupAndWait(ui::VKEY_DOWN);
1092 } // namespace autofill