Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / autofill / autofill_interactive_uitest.cc
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.
4
5 #include <string>
6
7 #include "base/basictypes.h"
8 #include "base/command_line.h"
9 #include "base/files/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/infobar_service.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/translate/chrome_translate_client.h"
23 #include "chrome/browser/translate/translate_service.h"
24 #include "chrome/browser/ui/browser.h"
25 #include "chrome/browser/ui/browser_window.h"
26 #include "chrome/browser/ui/tabs/tab_strip_model.h"
27 #include "chrome/common/render_messages.h"
28 #include "chrome/test/base/in_process_browser_test.h"
29 #include "chrome/test/base/interactive_test_utils.h"
30 #include "chrome/test/base/test_switches.h"
31 #include "chrome/test/base/ui_test_utils.h"
32 #include "components/autofill/content/browser/content_autofill_driver.h"
33 #include "components/autofill/core/browser/autofill_manager.h"
34 #include "components/autofill/core/browser/autofill_manager_test_delegate.h"
35 #include "components/autofill/core/browser/autofill_profile.h"
36 #include "components/autofill/core/browser/autofill_test_utils.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 "components/infobars/core/confirm_infobar_delegate.h"
41 #include "components/infobars/core/infobar.h"
42 #include "components/infobars/core/infobar_manager.h"
43 #include "components/translate/core/browser/translate_infobar_delegate.h"
44 #include "content/public/browser/navigation_controller.h"
45 #include "content/public/browser/notification_observer.h"
46 #include "content/public/browser/notification_registrar.h"
47 #include "content/public/browser/notification_service.h"
48 #include "content/public/browser/render_view_host.h"
49 #include "content/public/browser/render_widget_host.h"
50 #include "content/public/browser/web_contents.h"
51 #include "content/public/test/browser_test_utils.h"
52 #include "content/public/test/test_renderer_host.h"
53 #include "content/public/test/test_utils.h"
54 #include "net/url_request/test_url_fetcher_factory.h"
55 #include "testing/gmock/include/gmock/gmock.h"
56 #include "testing/gtest/include/gtest/gtest.h"
57 #include "ui/events/keycodes/keyboard_codes.h"
58
59 using base::ASCIIToUTF16;
60
61 namespace autofill {
62
63 static const char kDataURIPrefix[] = "data:text/html;charset=utf-8,";
64 static const char kTestFormString[] =
65     "<form action=\"http://www.example.com/\" method=\"POST\">"
66     "<label for=\"firstname\">First name:</label>"
67     " <input type=\"text\" id=\"firstname\""
68     "        onfocus=\"domAutomationController.send(true)\"><br>"
69     "<label for=\"lastname\">Last name:</label>"
70     " <input type=\"text\" id=\"lastname\"><br>"
71     "<label for=\"address1\">Address line 1:</label>"
72     " <input type=\"text\" id=\"address1\"><br>"
73     "<label for=\"address2\">Address line 2:</label>"
74     " <input type=\"text\" id=\"address2\"><br>"
75     "<label for=\"city\">City:</label>"
76     " <input type=\"text\" id=\"city\"><br>"
77     "<label for=\"state\">State:</label>"
78     " <select id=\"state\">"
79     " <option value=\"\" selected=\"yes\">--</option>"
80     " <option value=\"CA\">California</option>"
81     " <option value=\"TX\">Texas</option>"
82     " </select><br>"
83     "<label for=\"zip\">ZIP code:</label>"
84     " <input type=\"text\" id=\"zip\"><br>"
85     "<label for=\"country\">Country:</label>"
86     " <select id=\"country\">"
87     " <option value=\"\" selected=\"yes\">--</option>"
88     " <option value=\"CA\">Canada</option>"
89     " <option value=\"US\">United States</option>"
90     " </select><br>"
91     "<label for=\"phone\">Phone number:</label>"
92     " <input type=\"text\" id=\"phone\"><br>"
93     "</form>";
94
95
96 // AutofillManagerTestDelegateImpl --------------------------------------------
97
98 class AutofillManagerTestDelegateImpl
99     : public autofill::AutofillManagerTestDelegate {
100  public:
101   AutofillManagerTestDelegateImpl() {}
102   ~AutofillManagerTestDelegateImpl() override {}
103
104   // autofill::AutofillManagerTestDelegate:
105   void DidPreviewFormData() override {
106     ASSERT_TRUE(loop_runner_->loop_running());
107     loop_runner_->Quit();
108   }
109
110   void DidFillFormData() override {
111     ASSERT_TRUE(loop_runner_->loop_running());
112     loop_runner_->Quit();
113   }
114
115   void DidShowSuggestions() override {
116     ASSERT_TRUE(loop_runner_->loop_running());
117     loop_runner_->Quit();
118   }
119
120   void Reset() {
121     loop_runner_ = new content::MessageLoopRunner();
122   }
123
124   void Wait() {
125     loop_runner_->Run();
126   }
127
128  private:
129   scoped_refptr<content::MessageLoopRunner> loop_runner_;
130
131   DISALLOW_COPY_AND_ASSIGN(AutofillManagerTestDelegateImpl);
132 };
133
134
135 // WindowedPersonalDataManagerObserver ----------------------------------------
136
137 class WindowedPersonalDataManagerObserver
138     : public PersonalDataManagerObserver,
139       public infobars::InfoBarManager::Observer {
140  public:
141   explicit WindowedPersonalDataManagerObserver(Browser* browser)
142       : alerted_(false),
143         has_run_message_loop_(false),
144         browser_(browser),
145         infobar_service_(InfoBarService::FromWebContents(
146             browser_->tab_strip_model()->GetActiveWebContents())) {
147     PersonalDataManagerFactory::GetForProfile(browser_->profile())->
148         AddObserver(this);
149     infobar_service_->AddObserver(this);
150   }
151
152   ~WindowedPersonalDataManagerObserver() override {
153     while (infobar_service_->infobar_count() > 0) {
154       infobar_service_->RemoveInfoBar(infobar_service_->infobar_at(0));
155     }
156     infobar_service_->RemoveObserver(this);
157   }
158
159   // PersonalDataManagerObserver:
160   void OnPersonalDataChanged() override {
161     if (has_run_message_loop_) {
162       base::MessageLoopForUI::current()->Quit();
163       has_run_message_loop_ = false;
164     }
165     alerted_ = true;
166   }
167
168   void OnInsufficientFormData() override { OnPersonalDataChanged(); }
169
170
171   void Wait() {
172     if (!alerted_) {
173       has_run_message_loop_ = true;
174       content::RunMessageLoop();
175     }
176     PersonalDataManagerFactory::GetForProfile(browser_->profile())->
177         RemoveObserver(this);
178   }
179
180  private:
181   // infobars::InfoBarManager::Observer:
182   void OnInfoBarAdded(infobars::InfoBar* infobar) override {
183     infobar_service_->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate()->
184         Accept();
185   }
186
187   bool alerted_;
188   bool has_run_message_loop_;
189   Browser* browser_;
190   InfoBarService* infobar_service_;
191
192   DISALLOW_COPY_AND_ASSIGN(WindowedPersonalDataManagerObserver);
193 };
194
195 // AutofillInteractiveTest ----------------------------------------------------
196
197 class AutofillInteractiveTest : public InProcessBrowserTest {
198  protected:
199   AutofillInteractiveTest() :
200       key_press_event_sink_(
201           base::Bind(&AutofillInteractiveTest::HandleKeyPressEvent,
202                      base::Unretained(this))) {}
203   ~AutofillInteractiveTest() override {}
204
205   // InProcessBrowserTest:
206   void SetUpOnMainThread() override {
207     // Don't want Keychain coming up on Mac.
208     test::DisableSystemServices(browser()->profile()->GetPrefs());
209
210     // Inject the test delegate into the AutofillManager.
211     content::WebContents* web_contents = GetWebContents();
212     ContentAutofillDriver* autofill_driver =
213         ContentAutofillDriver::FromWebContents(web_contents);
214     AutofillManager* autofill_manager = autofill_driver->autofill_manager();
215     autofill_manager->SetTestDelegate(&test_delegate_);
216
217     // If the mouse happened to be over where the suggestions are shown, then
218     // the preview will show up and will fail the tests. We need to give it a
219     // point that's within the browser frame, or else the method hangs.
220     gfx::Point reset_mouse(GetWebContents()->GetContainerBounds().origin());
221     reset_mouse = gfx::Point(reset_mouse.x() + 5, reset_mouse.y() + 5);
222     ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(reset_mouse));
223   }
224
225   void TearDownOnMainThread() override {
226     // Make sure to close any showing popups prior to tearing down the UI.
227     content::WebContents* web_contents = GetWebContents();
228     AutofillManager* autofill_manager = ContentAutofillDriver::FromWebContents(
229                                             web_contents)->autofill_manager();
230     autofill_manager->client()->HideAutofillPopup();
231   }
232
233   PersonalDataManager* GetPersonalDataManager() {
234     return PersonalDataManagerFactory::GetForProfile(browser()->profile());
235   }
236
237   content::WebContents* GetWebContents() {
238     return browser()->tab_strip_model()->GetActiveWebContents();
239   }
240
241   content::RenderViewHost* GetRenderViewHost() {
242     return GetWebContents()->GetRenderViewHost();
243   }
244
245   void CreateTestProfile() {
246     AutofillProfile profile;
247     test::SetProfileInfo(
248         &profile, "Milton", "C.", "Waddams",
249         "red.swingline@initech.com", "Initech", "4120 Freidrich Lane",
250         "Basement", "Austin", "Texas", "78744", "US", "5125551234");
251
252     WindowedPersonalDataManagerObserver observer(browser());
253     GetPersonalDataManager()->AddProfile(profile);
254
255     // AddProfile is asynchronous. Wait for it to finish before continuing the
256     // tests.
257     observer.Wait();
258   }
259
260   void SetProfiles(std::vector<AutofillProfile>* profiles) {
261     WindowedPersonalDataManagerObserver observer(browser());
262     GetPersonalDataManager()->SetProfiles(profiles);
263     observer.Wait();
264   }
265
266   void SetProfile(const AutofillProfile& profile) {
267     std::vector<AutofillProfile> profiles;
268     profiles.push_back(profile);
269     SetProfiles(&profiles);
270   }
271
272   // Populates a webpage form using autofill data and keypress events.
273   // This function focuses the specified input field in the form, and then
274   // sends keypress events to the tab to cause the form to be populated.
275   void PopulateForm(const std::string& field_id) {
276     std::string js("document.getElementById('" + field_id + "').focus();");
277     ASSERT_TRUE(content::ExecuteScript(GetRenderViewHost(), js));
278
279     SendKeyToPageAndWait(ui::VKEY_DOWN);
280     SendKeyToPopupAndWait(ui::VKEY_DOWN);
281     SendKeyToPopupAndWait(ui::VKEY_RETURN);
282   }
283
284   void ExpectFieldValue(const std::string& field_name,
285                         const std::string& expected_value) {
286     std::string value;
287     ASSERT_TRUE(content::ExecuteScriptAndExtractString(
288         GetWebContents(),
289         "window.domAutomationController.send("
290         "    document.getElementById('" + field_name + "').value);",
291         &value));
292     EXPECT_EQ(expected_value, value);
293   }
294
295   void GetFieldBackgroundColor(const std::string& field_name,
296                                std::string* color) {
297     ASSERT_TRUE(content::ExecuteScriptAndExtractString(
298         GetWebContents(),
299         "window.domAutomationController.send("
300         "    document.defaultView.getComputedStyle(document.getElementById('" +
301         field_name + "')).backgroundColor);",
302         color));
303   }
304
305   void SimulateURLFetch(bool success) {
306     net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
307     ASSERT_TRUE(fetcher);
308     net::URLRequestStatus status;
309     status.set_status(success ? net::URLRequestStatus::SUCCESS :
310                                 net::URLRequestStatus::FAILED);
311
312     std::string script = " var google = {};"
313         "google.translate = (function() {"
314         "  return {"
315         "    TranslateService: function() {"
316         "      return {"
317         "        isAvailable : function() {"
318         "          return true;"
319         "        },"
320         "        restore : function() {"
321         "          return;"
322         "        },"
323         "        getDetectedLanguage : function() {"
324         "          return \"ja\";"
325         "        },"
326         "        translatePage : function(originalLang, targetLang,"
327         "                                 onTranslateProgress) {"
328         "          document.getElementsByTagName(\"body\")[0].innerHTML = '" +
329         std::string(kTestFormString) +
330         "              ';"
331         "          onTranslateProgress(100, true, false);"
332         "        }"
333         "      };"
334         "    }"
335         "  };"
336         "})();"
337         "cr.googleTranslate.onTranslateElementLoad();";
338
339     fetcher->set_url(fetcher->GetOriginalURL());
340     fetcher->set_status(status);
341     fetcher->set_response_code(success ? 200 : 500);
342     fetcher->SetResponseString(script);
343     fetcher->delegate()->OnURLFetchComplete(fetcher);
344   }
345
346   void FocusFirstNameField() {
347     bool result = false;
348     ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
349         GetRenderViewHost(),
350         "if (document.readyState === 'complete')"
351         "  document.getElementById('firstname').focus();"
352         "else"
353         "  domAutomationController.send(false);",
354         &result));
355     ASSERT_TRUE(result);
356   }
357
358   // Simulates a click on the middle of the DOM element with the given |id|.
359   void ClickElementWithId(const std::string& id) {
360     int x;
361     ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
362         GetRenderViewHost(),
363         "var bounds = document.getElementById('" +
364             id +
365             "').getBoundingClientRect();"
366             "domAutomationController.send("
367             "    Math.floor(bounds.left + bounds.width / 2));",
368         &x));
369     int y;
370     ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
371         GetRenderViewHost(),
372         "var bounds = document.getElementById('" +
373             id +
374             "').getBoundingClientRect();"
375             "domAutomationController.send("
376             "    Math.floor(bounds.top + bounds.height / 2));",
377         &y));
378     content::SimulateMouseClickAt(GetWebContents(),
379                                   0,
380                                   blink::WebMouseEvent::ButtonLeft,
381                                   gfx::Point(x, y));
382   }
383
384   void ClickFirstNameField() {
385     ASSERT_NO_FATAL_FAILURE(ClickElementWithId("firstname"));
386   }
387
388   // Make a pointless round trip to the renderer, giving the popup a chance to
389   // show if it's going to. If it does show, an assert in
390   // AutofillManagerTestDelegateImpl will trigger.
391   void MakeSurePopupDoesntAppear() {
392     int unused;
393     ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
394         GetRenderViewHost(), "domAutomationController.send(42)", &unused));
395   }
396
397   void ExpectFilledTestForm() {
398     ExpectFieldValue("firstname", "Milton");
399     ExpectFieldValue("lastname", "Waddams");
400     ExpectFieldValue("address1", "4120 Freidrich Lane");
401     ExpectFieldValue("address2", "Basement");
402     ExpectFieldValue("city", "Austin");
403     ExpectFieldValue("state", "TX");
404     ExpectFieldValue("zip", "78744");
405     ExpectFieldValue("country", "US");
406     ExpectFieldValue("phone", "5125551234");
407   }
408
409   void SendKeyToPageAndWait(ui::KeyboardCode key) {
410     test_delegate_.Reset();
411     content::SimulateKeyPress(
412         GetWebContents(), key, false, false, false, false);
413     test_delegate_.Wait();
414   }
415
416   bool HandleKeyPressEvent(const content::NativeWebKeyboardEvent& event) {
417     return true;
418   }
419
420   void SendKeyToPopupAndWait(ui::KeyboardCode key) {
421     // Route popup-targeted key presses via the render view host.
422     content::NativeWebKeyboardEvent event;
423     event.windowsKeyCode = key;
424     event.type = blink::WebKeyboardEvent::RawKeyDown;
425     test_delegate_.Reset();
426     // Install the key press event sink to ensure that any events that are not
427     // handled by the installed callbacks do not end up crashing the test.
428     GetRenderViewHost()->AddKeyPressEventCallback(key_press_event_sink_);
429     GetRenderViewHost()->ForwardKeyboardEvent(event);
430     test_delegate_.Wait();
431     GetRenderViewHost()->RemoveKeyPressEventCallback(key_press_event_sink_);
432   }
433
434   // Datalist does not support autofill preview. There is no need to start
435   // message loop for Datalist.
436   void SendKeyToDataListPopup(ui::KeyboardCode key) {
437     // Route popup-targeted key presses via the render view host.
438     content::NativeWebKeyboardEvent event;
439     event.windowsKeyCode = key;
440     event.type = blink::WebKeyboardEvent::RawKeyDown;
441     // Install the key press event sink to ensure that any events that are not
442     // handled by the installed callbacks do not end up crashing the test.
443     GetRenderViewHost()->AddKeyPressEventCallback(key_press_event_sink_);
444     GetRenderViewHost()->ForwardKeyboardEvent(event);
445     GetRenderViewHost()->RemoveKeyPressEventCallback(key_press_event_sink_);
446   }
447
448   void TryBasicFormFill() {
449     FocusFirstNameField();
450
451     // Start filling the first name field with "M" and wait for the popup to be
452     // shown.
453     SendKeyToPageAndWait(ui::VKEY_M);
454
455     // Press the down arrow to select the suggestion and preview the autofilled
456     // form.
457     SendKeyToPopupAndWait(ui::VKEY_DOWN);
458
459     // The previewed values should not be accessible to JavaScript.
460     ExpectFieldValue("firstname", "M");
461     ExpectFieldValue("lastname", std::string());
462     ExpectFieldValue("address1", std::string());
463     ExpectFieldValue("address2", std::string());
464     ExpectFieldValue("city", std::string());
465     ExpectFieldValue("state", std::string());
466     ExpectFieldValue("zip", std::string());
467     ExpectFieldValue("country", std::string());
468     ExpectFieldValue("phone", std::string());
469     // TODO(isherman): It would be nice to test that the previewed values are
470     // displayed: http://crbug.com/57220
471
472     // Press Enter to accept the autofill suggestions.
473     SendKeyToPopupAndWait(ui::VKEY_RETURN);
474
475     // The form should be filled.
476     ExpectFilledTestForm();
477   }
478
479   AutofillManagerTestDelegateImpl* test_delegate() { return &test_delegate_; }
480
481  private:
482   AutofillManagerTestDelegateImpl test_delegate_;
483
484   net::TestURLFetcherFactory url_fetcher_factory_;
485
486   // KeyPressEventCallback that serves as a sink to ensure that every key press
487   // event the tests create and have the WebContents forward is handled by some
488   // key press event callback. It is necessary to have this sinkbecause if no
489   // key press event callback handles the event (at least on Mac), a DCHECK
490   // ends up going off that the |event| doesn't have an |os_event| associated
491   // with it.
492   content::RenderWidgetHost::KeyPressEventCallback key_press_event_sink_;
493
494   DISALLOW_COPY_AND_ASSIGN(AutofillInteractiveTest);
495 };
496
497 // Test that basic form fill is working.
498 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, BasicFormFill) {
499   CreateTestProfile();
500
501   // Load the test page.
502   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
503       GURL(std::string(kDataURIPrefix) + kTestFormString)));
504
505   // Invoke Autofill.
506   TryBasicFormFill();
507 }
508
509 // Test that form filling can be initiated by pressing the down arrow.
510 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillViaDownArrow) {
511   CreateTestProfile();
512
513   // Load the test page.
514   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
515       GURL(std::string(kDataURIPrefix) + kTestFormString)));
516
517   // Focus a fillable field.
518   FocusFirstNameField();
519
520   // Press the down arrow to initiate Autofill and wait for the popup to be
521   // shown.
522   SendKeyToPageAndWait(ui::VKEY_DOWN);
523
524   // Press the down arrow to select the suggestion and preview the autofilled
525   // form.
526   SendKeyToPopupAndWait(ui::VKEY_DOWN);
527
528   // Press Enter to accept the autofill suggestions.
529   SendKeyToPopupAndWait(ui::VKEY_RETURN);
530
531   // The form should be filled.
532   ExpectFilledTestForm();
533 }
534
535 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillSelectViaTab) {
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   // Focus a fillable field.
543   FocusFirstNameField();
544
545   // Press the down arrow to initiate Autofill and wait for the popup to be
546   // shown.
547   SendKeyToPageAndWait(ui::VKEY_DOWN);
548
549   // Press the down arrow to select the suggestion and preview the autofilled
550   // form.
551   SendKeyToPopupAndWait(ui::VKEY_DOWN);
552
553   // Press tab to accept the autofill suggestions.
554   SendKeyToPopupAndWait(ui::VKEY_TAB);
555
556   // The form should be filled.
557   ExpectFilledTestForm();
558 }
559
560 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillViaClick) {
561   CreateTestProfile();
562
563   // Load the test page.
564   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
565       browser(), GURL(std::string(kDataURIPrefix) + kTestFormString)));
566   // Focus a fillable field.
567   ASSERT_NO_FATAL_FAILURE(FocusFirstNameField());
568
569   // Now click it.
570   test_delegate()->Reset();
571   ASSERT_NO_FATAL_FAILURE(ClickFirstNameField());
572   test_delegate()->Wait();
573
574   // Press the down arrow to select the suggestion and preview the autofilled
575   // form.
576   SendKeyToPopupAndWait(ui::VKEY_DOWN);
577
578   // Press Enter to accept the autofill suggestions.
579   SendKeyToPopupAndWait(ui::VKEY_RETURN);
580
581   // The form should be filled.
582   ExpectFilledTestForm();
583 }
584
585 // Makes sure that the first click does *not* activate the popup.
586 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, DontAutofillForFirstClick) {
587   CreateTestProfile();
588
589   // Load the test page.
590   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
591       browser(), GURL(std::string(kDataURIPrefix) + kTestFormString)));
592
593   // Click the first name field while it's out of focus, then twiddle our thumbs
594   // a bit. If a popup were to show, it would hit the asserts in
595   // AutofillManagerTestDelegateImpl while we're wasting time.
596   ASSERT_NO_FATAL_FAILURE(ClickFirstNameField());
597   ASSERT_NO_FATAL_FAILURE(MakeSurePopupDoesntAppear());
598
599   // The second click should activate the popup since the first click focused
600   // the field.
601   test_delegate()->Reset();
602   ASSERT_NO_FATAL_FAILURE(ClickFirstNameField());
603   test_delegate()->Wait();
604 }
605
606 // Makes sure that clicking outside the focused field doesn't activate
607 // the popup.
608 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, DontAutofillForOutsideClick) {
609   CreateTestProfile();
610
611   // Load the test page.
612   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
613       browser(),
614       GURL(std::string(kDataURIPrefix) + kTestFormString +
615            "<button disabled id='disabled-button'>Cant click this</button>")));
616
617   ASSERT_NO_FATAL_FAILURE(FocusFirstNameField());
618
619   // Clicking a disabled button will generate a mouse event but focus doesn't
620   // change. This tests that autofill can handle a mouse event outside a focused
621   // input *without* showing the popup.
622   ASSERT_NO_FATAL_FAILURE(ClickElementWithId("disabled-button"));
623   ASSERT_NO_FATAL_FAILURE(MakeSurePopupDoesntAppear());
624
625   test_delegate()->Reset();
626   ASSERT_NO_FATAL_FAILURE(ClickFirstNameField());
627   test_delegate()->Wait();
628 }
629
630 // Test that a field is still autofillable after the previously autofilled
631 // value is deleted.
632 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, OnDeleteValueAfterAutofill) {
633   CreateTestProfile();
634
635   // Load the test page.
636   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
637       GURL(std::string(kDataURIPrefix) + kTestFormString)));
638
639   // Invoke and accept the Autofill popup and verify the form was filled.
640   FocusFirstNameField();
641   SendKeyToPageAndWait(ui::VKEY_M);
642   SendKeyToPopupAndWait(ui::VKEY_DOWN);
643   SendKeyToPopupAndWait(ui::VKEY_RETURN);
644   ExpectFilledTestForm();
645
646   // Delete the value of a filled field.
647   ASSERT_TRUE(content::ExecuteScript(
648       GetRenderViewHost(),
649       "document.getElementById('firstname').value = '';"));
650   ExpectFieldValue("firstname", "");
651
652   // Invoke and accept the Autofill popup and verify the field was filled.
653   SendKeyToPageAndWait(ui::VKEY_M);
654   SendKeyToPopupAndWait(ui::VKEY_DOWN);
655   SendKeyToPopupAndWait(ui::VKEY_RETURN);
656   ExpectFieldValue("firstname", "Milton");
657 }
658
659 // Test that an input field is not rendered with the yellow autofilled
660 // background color when choosing an option from the datalist suggestion list.
661 #if defined(OS_MACOSX)
662 // Flakily triggers and assert on Mac.
663 // http://crbug.com/419868
664 #define MAYBE_OnSelectOptionFromDatalist DISABLED_OnSelectOptionFromDatalist
665 #else
666 #define MAYBE_OnSelectOptionFromDatalist OnSelectOptionFromDatalist
667 #endif
668 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
669                        MAYBE_OnSelectOptionFromDatalist) {
670   // Load the test page.
671   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(
672       browser(),
673       GURL(std::string(kDataURIPrefix) +
674            "<form action=\"http://www.example.com/\" method=\"POST\">"
675            "  <input list=\"dl\" type=\"search\" id=\"firstname\""
676            "         onfocus=\"domAutomationController.send(true)\"><br>"
677            "  <datalist id=\"dl\">"
678            "  <option value=\"Adam\"></option>"
679            "  <option value=\"Bob\"></option>"
680            "  <option value=\"Carl\"></option>"
681            "  </datalist>"
682            "</form>")));
683   std::string orginalcolor;
684   GetFieldBackgroundColor("firstname", &orginalcolor);
685
686   FocusFirstNameField();
687   SendKeyToPageAndWait(ui::VKEY_DOWN);
688   SendKeyToDataListPopup(ui::VKEY_DOWN);
689   SendKeyToDataListPopup(ui::VKEY_RETURN);
690   ExpectFieldValue("firstname", "Adam");
691   std::string color;
692   GetFieldBackgroundColor("firstname", &color);
693   EXPECT_EQ(color, orginalcolor);
694 }
695
696 // Test that a JavaScript oninput event is fired after auto-filling a form.
697 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, OnInputAfterAutofill) {
698   CreateTestProfile();
699
700   const char kOnInputScript[] =
701       "<script>"
702       "focused_fired = false;"
703       "unfocused_fired = false;"
704       "changed_select_fired = false;"
705       "unchanged_select_fired = false;"
706       "document.getElementById('firstname').oninput = function() {"
707       "  focused_fired = true;"
708       "};"
709       "document.getElementById('lastname').oninput = function() {"
710       "  unfocused_fired = true;"
711       "};"
712       "document.getElementById('state').oninput = function() {"
713       "  changed_select_fired = true;"
714       "};"
715       "document.getElementById('country').oninput = function() {"
716       "  unchanged_select_fired = true;"
717       "};"
718       "document.getElementById('country').value = 'US';"
719       "</script>";
720
721   // Load the test page.
722   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
723       GURL(std::string(kDataURIPrefix) + kTestFormString + kOnInputScript)));
724
725   // Invoke Autofill.
726   FocusFirstNameField();
727
728   // Start filling the first name field with "M" and wait for the popup to be
729   // shown.
730   SendKeyToPageAndWait(ui::VKEY_M);
731
732   // Press the down arrow to select the suggestion and preview the autofilled
733   // form.
734   SendKeyToPopupAndWait(ui::VKEY_DOWN);
735
736   // Press Enter to accept the autofill suggestions.
737   SendKeyToPopupAndWait(ui::VKEY_RETURN);
738
739   // The form should be filled.
740   ExpectFilledTestForm();
741
742   bool focused_fired = false;
743   bool unfocused_fired = false;
744   bool changed_select_fired = false;
745   bool unchanged_select_fired = false;
746   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
747       GetRenderViewHost(),
748       "domAutomationController.send(focused_fired);",
749       &focused_fired));
750   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
751       GetRenderViewHost(),
752       "domAutomationController.send(unfocused_fired);",
753       &unfocused_fired));
754   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
755       GetRenderViewHost(),
756       "domAutomationController.send(changed_select_fired);",
757       &changed_select_fired));
758   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
759       GetRenderViewHost(),
760       "domAutomationController.send(unchanged_select_fired);",
761       &unchanged_select_fired));
762   EXPECT_TRUE(focused_fired);
763   EXPECT_TRUE(unfocused_fired);
764   EXPECT_TRUE(changed_select_fired);
765   EXPECT_FALSE(unchanged_select_fired);
766 }
767
768 // Test that a JavaScript onchange event is fired after auto-filling a form.
769 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, OnChangeAfterAutofill) {
770   CreateTestProfile();
771
772   const char kOnChangeScript[] =
773       "<script>"
774       "focused_fired = false;"
775       "unfocused_fired = false;"
776       "changed_select_fired = false;"
777       "unchanged_select_fired = false;"
778       "document.getElementById('firstname').onchange = function() {"
779       "  focused_fired = true;"
780       "};"
781       "document.getElementById('lastname').onchange = function() {"
782       "  unfocused_fired = true;"
783       "};"
784       "document.getElementById('state').onchange = function() {"
785       "  changed_select_fired = true;"
786       "};"
787       "document.getElementById('country').onchange = function() {"
788       "  unchanged_select_fired = true;"
789       "};"
790       "document.getElementById('country').value = 'US';"
791       "</script>";
792
793   // Load the test page.
794   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
795       GURL(std::string(kDataURIPrefix) + kTestFormString + kOnChangeScript)));
796
797   // Invoke Autofill.
798   FocusFirstNameField();
799
800   // Start filling the first name field with "M" and wait for the popup to be
801   // shown.
802   SendKeyToPageAndWait(ui::VKEY_M);
803
804   // Press the down arrow to select the suggestion and preview the autofilled
805   // form.
806   SendKeyToPopupAndWait(ui::VKEY_DOWN);
807
808   // Press Enter to accept the autofill suggestions.
809   SendKeyToPopupAndWait(ui::VKEY_RETURN);
810
811   // The form should be filled.
812   ExpectFilledTestForm();
813
814   bool focused_fired = false;
815   bool unfocused_fired = false;
816   bool changed_select_fired = false;
817   bool unchanged_select_fired = false;
818   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
819       GetRenderViewHost(),
820       "domAutomationController.send(focused_fired);",
821       &focused_fired));
822   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
823       GetRenderViewHost(),
824       "domAutomationController.send(unfocused_fired);",
825       &unfocused_fired));
826   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
827       GetRenderViewHost(),
828       "domAutomationController.send(changed_select_fired);",
829       &changed_select_fired));
830   ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
831       GetRenderViewHost(),
832       "domAutomationController.send(unchanged_select_fired);",
833       &unchanged_select_fired));
834   EXPECT_TRUE(focused_fired);
835   EXPECT_TRUE(unfocused_fired);
836   EXPECT_TRUE(changed_select_fired);
837   EXPECT_FALSE(unchanged_select_fired);
838 }
839
840 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, InputFiresBeforeChange) {
841   CreateTestProfile();
842
843   const char kInputFiresBeforeChangeScript[] =
844       "<script>"
845       "inputElementEvents = [];"
846       "function recordInputElementEvent(e) {"
847       "  if (e.target.tagName != 'INPUT') throw 'only <input> tags allowed';"
848       "  inputElementEvents.push(e.type);"
849       "}"
850       "selectElementEvents = [];"
851       "function recordSelectElementEvent(e) {"
852       "  if (e.target.tagName != 'SELECT') throw 'only <select> tags allowed';"
853       "  selectElementEvents.push(e.type);"
854       "}"
855       "document.getElementById('lastname').oninput = recordInputElementEvent;"
856       "document.getElementById('lastname').onchange = recordInputElementEvent;"
857       "document.getElementById('country').oninput = recordSelectElementEvent;"
858       "document.getElementById('country').onchange = recordSelectElementEvent;"
859       "</script>";
860
861   // Load the test page.
862   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
863       GURL(std::string(kDataURIPrefix) + kTestFormString +
864            kInputFiresBeforeChangeScript)));
865
866   // Invoke and accept the Autofill popup and verify the form was filled.
867   FocusFirstNameField();
868   SendKeyToPageAndWait(ui::VKEY_M);
869   SendKeyToPopupAndWait(ui::VKEY_DOWN);
870   SendKeyToPopupAndWait(ui::VKEY_RETURN);
871   ExpectFilledTestForm();
872
873   int num_input_element_events = -1;
874   ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
875       GetRenderViewHost(),
876       "domAutomationController.send(inputElementEvents.length);",
877       &num_input_element_events));
878   EXPECT_EQ(2, num_input_element_events);
879
880   std::vector<std::string> input_element_events;
881   input_element_events.resize(2);
882
883   ASSERT_TRUE(content::ExecuteScriptAndExtractString(
884       GetRenderViewHost(),
885       "domAutomationController.send(inputElementEvents[0]);",
886       &input_element_events[0]));
887   ASSERT_TRUE(content::ExecuteScriptAndExtractString(
888       GetRenderViewHost(),
889       "domAutomationController.send(inputElementEvents[1]);",
890       &input_element_events[1]));
891
892   EXPECT_EQ("input", input_element_events[0]);
893   EXPECT_EQ("change", input_element_events[1]);
894
895   int num_select_element_events = -1;
896   ASSERT_TRUE(content::ExecuteScriptAndExtractInt(
897       GetRenderViewHost(),
898       "domAutomationController.send(selectElementEvents.length);",
899       &num_select_element_events));
900   EXPECT_EQ(2, num_select_element_events);
901
902   std::vector<std::string> select_element_events;
903   select_element_events.resize(2);
904
905   ASSERT_TRUE(content::ExecuteScriptAndExtractString(
906       GetRenderViewHost(),
907       "domAutomationController.send(selectElementEvents[0]);",
908       &select_element_events[0]));
909   ASSERT_TRUE(content::ExecuteScriptAndExtractString(
910       GetRenderViewHost(),
911       "domAutomationController.send(selectElementEvents[1]);",
912       &select_element_events[1]));
913
914   EXPECT_EQ("input", select_element_events[0]);
915   EXPECT_EQ("change", select_element_events[1]);
916 }
917
918 // Test that we can autofill forms distinguished only by their |id| attribute.
919 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
920                        AutofillFormsDistinguishedById) {
921   CreateTestProfile();
922
923   // Load the test page.
924   const std::string kURL =
925       std::string(kDataURIPrefix) + kTestFormString +
926       "<script>"
927       "var mainForm = document.forms[0];"
928       "mainForm.id = 'mainForm';"
929       "var newForm = document.createElement('form');"
930       "newForm.action = mainForm.action;"
931       "newForm.method = mainForm.method;"
932       "newForm.id = 'newForm';"
933       "mainForm.parentNode.insertBefore(newForm, mainForm);"
934       "</script>";
935   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(), GURL(kURL)));
936
937   // Invoke Autofill.
938   TryBasicFormFill();
939 }
940
941 // Test that we properly autofill forms with repeated fields.
942 // In the wild, the repeated fields are typically either email fields
943 // (duplicated for "confirmation"); or variants that are hot-swapped via
944 // JavaScript, with only one actually visible at any given time.
945 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillFormWithRepeatedField) {
946   CreateTestProfile();
947
948   // Load the test page.
949   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
950       GURL(std::string(kDataURIPrefix) +
951            "<form action=\"http://www.example.com/\" method=\"POST\">"
952            "<label for=\"firstname\">First name:</label>"
953            " <input type=\"text\" id=\"firstname\""
954            "        onfocus=\"domAutomationController.send(true)\"><br>"
955            "<label for=\"lastname\">Last name:</label>"
956            " <input type=\"text\" id=\"lastname\"><br>"
957            "<label for=\"address1\">Address line 1:</label>"
958            " <input type=\"text\" id=\"address1\"><br>"
959            "<label for=\"address2\">Address line 2:</label>"
960            " <input type=\"text\" id=\"address2\"><br>"
961            "<label for=\"city\">City:</label>"
962            " <input type=\"text\" id=\"city\"><br>"
963            "<label for=\"state\">State:</label>"
964            " <select id=\"state\">"
965            " <option value=\"\" selected=\"yes\">--</option>"
966            " <option value=\"CA\">California</option>"
967            " <option value=\"TX\">Texas</option>"
968            " </select><br>"
969            "<label for=\"state_freeform\" style=\"display:none\">State:</label>"
970            " <input type=\"text\" id=\"state_freeform\""
971            "        style=\"display:none\"><br>"
972            "<label for=\"zip\">ZIP code:</label>"
973            " <input type=\"text\" id=\"zip\"><br>"
974            "<label for=\"country\">Country:</label>"
975            " <select id=\"country\">"
976            " <option value=\"\" selected=\"yes\">--</option>"
977            " <option value=\"CA\">Canada</option>"
978            " <option value=\"US\">United States</option>"
979            " </select><br>"
980            "<label for=\"phone\">Phone number:</label>"
981            " <input type=\"text\" id=\"phone\"><br>"
982            "</form>")));
983
984   // Invoke Autofill.
985   TryBasicFormFill();
986   ExpectFieldValue("state_freeform", std::string());
987 }
988
989 // Test that we properly autofill forms with non-autofillable fields.
990 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
991                        AutofillFormWithNonAutofillableField) {
992   CreateTestProfile();
993
994   // Load the test page.
995   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
996       GURL(std::string(kDataURIPrefix) +
997            "<form action=\"http://www.example.com/\" method=\"POST\">"
998            "<label for=\"firstname\">First name:</label>"
999            " <input type=\"text\" id=\"firstname\""
1000            "        onfocus=\"domAutomationController.send(true)\"><br>"
1001            "<label for=\"middlename\">Middle name:</label>"
1002            " <input type=\"text\" id=\"middlename\" autocomplete=\"off\" /><br>"
1003            "<label for=\"lastname\">Last name:</label>"
1004            " <input type=\"text\" id=\"lastname\"><br>"
1005            "<label for=\"address1\">Address line 1:</label>"
1006            " <input type=\"text\" id=\"address1\"><br>"
1007            "<label for=\"address2\">Address line 2:</label>"
1008            " <input type=\"text\" id=\"address2\"><br>"
1009            "<label for=\"city\">City:</label>"
1010            " <input type=\"text\" id=\"city\"><br>"
1011            "<label for=\"state\">State:</label>"
1012            " <select id=\"state\">"
1013            " <option value=\"\" selected=\"yes\">--</option>"
1014            " <option value=\"CA\">California</option>"
1015            " <option value=\"TX\">Texas</option>"
1016            " </select><br>"
1017            "<label for=\"zip\">ZIP code:</label>"
1018            " <input type=\"text\" id=\"zip\"><br>"
1019            "<label for=\"country\">Country:</label>"
1020            " <select id=\"country\">"
1021            " <option value=\"\" selected=\"yes\">--</option>"
1022            " <option value=\"CA\">Canada</option>"
1023            " <option value=\"US\">United States</option>"
1024            " </select><br>"
1025            "<label for=\"phone\">Phone number:</label>"
1026            " <input type=\"text\" id=\"phone\"><br>"
1027            "</form>")));
1028
1029   // Invoke Autofill.
1030   TryBasicFormFill();
1031 }
1032
1033 // Test that we can Autofill dynamically generated forms.
1034 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, DynamicFormFill) {
1035   CreateTestProfile();
1036
1037   // Load the test page.
1038   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
1039       GURL(std::string(kDataURIPrefix) +
1040            "<form id=\"form\" action=\"http://www.example.com/\""
1041            "      method=\"POST\"></form>"
1042            "<script>"
1043            "function AddElement(name, label) {"
1044            "  var form = document.getElementById('form');"
1045            ""
1046            "  var label_text = document.createTextNode(label);"
1047            "  var label_element = document.createElement('label');"
1048            "  label_element.setAttribute('for', name);"
1049            "  label_element.appendChild(label_text);"
1050            "  form.appendChild(label_element);"
1051            ""
1052            "  if (name === 'state' || name === 'country') {"
1053            "    var select_element = document.createElement('select');"
1054            "    select_element.setAttribute('id', name);"
1055            "    select_element.setAttribute('name', name);"
1056            ""
1057            "    /* Add an empty selected option. */"
1058            "    var default_option = new Option('--', '', true);"
1059            "    select_element.appendChild(default_option);"
1060            ""
1061            "    /* Add the other options. */"
1062            "    if (name == 'state') {"
1063            "      var option1 = new Option('California', 'CA');"
1064            "      select_element.appendChild(option1);"
1065            "      var option2 = new Option('Texas', 'TX');"
1066            "      select_element.appendChild(option2);"
1067            "    } else {"
1068            "      var option1 = new Option('Canada', 'CA');"
1069            "      select_element.appendChild(option1);"
1070            "      var option2 = new Option('United States', 'US');"
1071            "      select_element.appendChild(option2);"
1072            "    }"
1073            ""
1074            "    form.appendChild(select_element);"
1075            "  } else {"
1076            "    var input_element = document.createElement('input');"
1077            "    input_element.setAttribute('id', name);"
1078            "    input_element.setAttribute('name', name);"
1079            ""
1080            "    /* Add the onfocus listener to the 'firstname' field. */"
1081            "    if (name === 'firstname') {"
1082            "      input_element.onfocus = function() {"
1083            "        domAutomationController.send(true);"
1084            "      };"
1085            "    }"
1086            ""
1087            "    form.appendChild(input_element);"
1088            "  }"
1089            ""
1090            "  form.appendChild(document.createElement('br'));"
1091            "};"
1092            ""
1093            "function BuildForm() {"
1094            "  var elements = ["
1095            "    ['firstname', 'First name:'],"
1096            "    ['lastname', 'Last name:'],"
1097            "    ['address1', 'Address line 1:'],"
1098            "    ['address2', 'Address line 2:'],"
1099            "    ['city', 'City:'],"
1100            "    ['state', 'State:'],"
1101            "    ['zip', 'ZIP code:'],"
1102            "    ['country', 'Country:'],"
1103            "    ['phone', 'Phone number:'],"
1104            "  ];"
1105            ""
1106            "  for (var i = 0; i < elements.length; i++) {"
1107            "    var name = elements[i][0];"
1108            "    var label = elements[i][1];"
1109            "    AddElement(name, label);"
1110            "  }"
1111            "};"
1112            "</script>")));
1113
1114   // Dynamically construct the form.
1115   ASSERT_TRUE(content::ExecuteScript(GetRenderViewHost(), "BuildForm();"));
1116
1117   // Invoke Autofill.
1118   TryBasicFormFill();
1119 }
1120
1121 // Test that form filling works after reloading the current page.
1122 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillAfterReload) {
1123   CreateTestProfile();
1124
1125   // Load the test page.
1126   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
1127       GURL(std::string(kDataURIPrefix) + kTestFormString)));
1128
1129   // Reload the page.
1130   content::WebContents* web_contents = GetWebContents();
1131   web_contents->GetController().Reload(false);
1132   content::WaitForLoadStop(web_contents);
1133
1134   // Invoke Autofill.
1135   TryBasicFormFill();
1136 }
1137
1138 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, AutofillAfterTranslate) {
1139   // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
1140   if (TranslateService::IsTranslateBubbleEnabled())
1141     return;
1142
1143   CreateTestProfile();
1144
1145   GURL url(std::string(kDataURIPrefix) +
1146                "<form action=\"http://www.example.com/\" method=\"POST\">"
1147                "<label for=\"fn\">なまえ</label>"
1148                " <input type=\"text\" id=\"fn\""
1149                "        onfocus=\"domAutomationController.send(true)\""
1150                "><br>"
1151                "<label for=\"ln\">みょうじ</label>"
1152                " <input type=\"text\" id=\"ln\"><br>"
1153                "<label for=\"a1\">Address line 1:</label>"
1154                " <input type=\"text\" id=\"a1\"><br>"
1155                "<label for=\"a2\">Address line 2:</label>"
1156                " <input type=\"text\" id=\"a2\"><br>"
1157                "<label for=\"ci\">City:</label>"
1158                " <input type=\"text\" id=\"ci\"><br>"
1159                "<label for=\"st\">State:</label>"
1160                " <select id=\"st\">"
1161                " <option value=\"\" selected=\"yes\">--</option>"
1162                " <option value=\"CA\">California</option>"
1163                " <option value=\"TX\">Texas</option>"
1164                " </select><br>"
1165                "<label for=\"z\">ZIP code:</label>"
1166                " <input type=\"text\" id=\"z\"><br>"
1167                "<label for=\"co\">Country:</label>"
1168                " <select id=\"co\">"
1169                " <option value=\"\" selected=\"yes\">--</option>"
1170                " <option value=\"CA\">Canada</option>"
1171                " <option value=\"US\">United States</option>"
1172                " </select><br>"
1173                "<label for=\"ph\">Phone number:</label>"
1174                " <input type=\"text\" id=\"ph\"><br>"
1175                "</form>"
1176                // Add additional Japanese characters to ensure the translate bar
1177                // will appear.
1178                "我々は重要な、興味深いものになるが、時折状況が発生するため苦労や痛みは"
1179                "彼にいくつかの素晴らしいを調達することができます。それから、いくつかの利");
1180
1181   content::WindowedNotificationObserver infobar_observer(
1182       chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
1183       content::NotificationService::AllSources());
1184   ASSERT_NO_FATAL_FAILURE(
1185       ui_test_utils::NavigateToURL(browser(), url));
1186
1187   // Wait for the translation bar to appear and get it.
1188   infobar_observer.Wait();
1189   InfoBarService* infobar_service =
1190       InfoBarService::FromWebContents(GetWebContents());
1191   translate::TranslateInfoBarDelegate* delegate =
1192       infobar_service->infobar_at(0)->delegate()->AsTranslateInfoBarDelegate();
1193   ASSERT_TRUE(delegate);
1194   EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
1195             delegate->translate_step());
1196
1197   // Simulate translation button press.
1198   delegate->Translate();
1199
1200   content::WindowedNotificationObserver translation_observer(
1201       chrome::NOTIFICATION_PAGE_TRANSLATED,
1202       content::NotificationService::AllSources());
1203
1204   // Simulate the translate script being retrieved.
1205   // Pass fake google.translate lib as the translate script.
1206   SimulateURLFetch(true);
1207
1208   // Simulate the render notifying the translation has been done.
1209   translation_observer.Wait();
1210
1211   TryBasicFormFill();
1212 }
1213
1214 // Test phone fields parse correctly from a given profile.
1215 // The high level key presses execute the following: Select the first text
1216 // field, invoke the autofill popup list, select the first profile within the
1217 // list, and commit to the profile to populate the form.
1218 // Flakily times out on windows. http://crbug.com/390564
1219 #if defined(OS_WIN)
1220 #define MAYBE_ComparePhoneNumbers DISABLED_ComparePhoneNumbers
1221 #else
1222 #define MAYBE_ComparePhoneNumbers ComparePhoneNumbers
1223 #endif
1224 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, MAYBE_ComparePhoneNumbers) {
1225   ASSERT_TRUE(test_server()->Start());
1226
1227   AutofillProfile profile;
1228   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
1229   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1230   profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16("1234 H St."));
1231   profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
1232   profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1233   profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
1234   profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("1-408-555-4567"));
1235   SetProfile(profile);
1236
1237   GURL url = test_server()->GetURL("files/autofill/form_phones.html");
1238   ui_test_utils::NavigateToURL(browser(), url);
1239   PopulateForm("NAME_FIRST");
1240
1241   ExpectFieldValue("NAME_FIRST", "Bob");
1242   ExpectFieldValue("NAME_LAST", "Smith");
1243   ExpectFieldValue("ADDRESS_HOME_LINE1", "1234 H St.");
1244   ExpectFieldValue("ADDRESS_HOME_CITY", "San Jose");
1245   ExpectFieldValue("ADDRESS_HOME_STATE", "CA");
1246   ExpectFieldValue("ADDRESS_HOME_ZIP", "95110");
1247   ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "14085554567");
1248   ExpectFieldValue("PHONE_HOME_CITY_CODE-1", "408");
1249   ExpectFieldValue("PHONE_HOME_CITY_CODE-2", "408");
1250   ExpectFieldValue("PHONE_HOME_NUMBER", "5554567");
1251   ExpectFieldValue("PHONE_HOME_NUMBER_3-1", "555");
1252   ExpectFieldValue("PHONE_HOME_NUMBER_3-2", "555");
1253   ExpectFieldValue("PHONE_HOME_NUMBER_4-1", "4567");
1254   ExpectFieldValue("PHONE_HOME_NUMBER_4-2", "4567");
1255   ExpectFieldValue("PHONE_HOME_EXT-1", std::string());
1256   ExpectFieldValue("PHONE_HOME_EXT-2", std::string());
1257   ExpectFieldValue("PHONE_HOME_COUNTRY_CODE-1", "1");
1258 }
1259
1260 // Test that Autofill does not fill in read-only fields.
1261 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, NoAutofillForReadOnlyFields) {
1262   ASSERT_TRUE(test_server()->Start());
1263
1264   std::string addr_line1("1234 H St.");
1265
1266   AutofillProfile profile;
1267   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
1268   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1269   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16("bsmith@gmail.com"));
1270   profile.SetRawInfo(ADDRESS_HOME_LINE1, ASCIIToUTF16(addr_line1));
1271   profile.SetRawInfo(ADDRESS_HOME_CITY, ASCIIToUTF16("San Jose"));
1272   profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1273   profile.SetRawInfo(ADDRESS_HOME_ZIP, ASCIIToUTF16("95110"));
1274   profile.SetRawInfo(COMPANY_NAME, ASCIIToUTF16("Company X"));
1275   profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("408-871-4567"));
1276   SetProfile(profile);
1277
1278   GURL url = test_server()->GetURL("files/autofill/read_only_field_test.html");
1279   ui_test_utils::NavigateToURL(browser(), url);
1280   PopulateForm("firstname");
1281
1282   ExpectFieldValue("email", std::string());
1283   ExpectFieldValue("address", addr_line1);
1284 }
1285
1286 // Test form is fillable from a profile after form was reset.
1287 // Steps:
1288 //   1. Fill form using a saved profile.
1289 //   2. Reset the form.
1290 //   3. Fill form using a saved profile.
1291 // Flakily times out: http://crbug.com/270341
1292 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest, DISABLED_FormFillableOnReset) {
1293   ASSERT_TRUE(test_server()->Start());
1294
1295   CreateTestProfile();
1296
1297   GURL url = test_server()->GetURL("files/autofill/autofill_test_form.html");
1298   ui_test_utils::NavigateToURL(browser(), url);
1299   PopulateForm("NAME_FIRST");
1300
1301   ASSERT_TRUE(content::ExecuteScript(
1302        GetWebContents(), "document.getElementById('testform').reset()"));
1303
1304   PopulateForm("NAME_FIRST");
1305
1306   ExpectFieldValue("NAME_FIRST", "Milton");
1307   ExpectFieldValue("NAME_LAST", "Waddams");
1308   ExpectFieldValue("EMAIL_ADDRESS", "red.swingline@initech.com");
1309   ExpectFieldValue("ADDRESS_HOME_LINE1", "4120 Freidrich Lane");
1310   ExpectFieldValue("ADDRESS_HOME_CITY", "Austin");
1311   ExpectFieldValue("ADDRESS_HOME_STATE", "Texas");
1312   ExpectFieldValue("ADDRESS_HOME_ZIP", "78744");
1313   ExpectFieldValue("ADDRESS_HOME_COUNTRY", "United States");
1314   ExpectFieldValue("PHONE_HOME_WHOLE_NUMBER", "5125551234");
1315 }
1316
1317 // Test Autofill distinguishes a middle initial in a name.
1318 // Flakily times out: http://crbug.com/270341
1319 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
1320                        DISABLED_DistinguishMiddleInitialWithinName) {
1321   ASSERT_TRUE(test_server()->Start());
1322
1323   CreateTestProfile();
1324
1325   GURL url = test_server()->GetURL(
1326       "files/autofill/autofill_middleinit_form.html");
1327   ui_test_utils::NavigateToURL(browser(), url);
1328   PopulateForm("NAME_FIRST");
1329
1330   ExpectFieldValue("NAME_MIDDLE", "C");
1331 }
1332
1333 // Test forms with multiple email addresses are filled properly.
1334 // Entire form should be filled with one user gesture.
1335 // Flakily times out: http://crbug.com/270341
1336 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
1337                        DISABLED_MultipleEmailFilledByOneUserGesture) {
1338   ASSERT_TRUE(test_server()->Start());
1339
1340   std::string email("bsmith@gmail.com");
1341
1342   AutofillProfile profile;
1343   profile.SetRawInfo(NAME_FIRST, ASCIIToUTF16("Bob"));
1344   profile.SetRawInfo(NAME_LAST, ASCIIToUTF16("Smith"));
1345   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(email));
1346   profile.SetRawInfo(PHONE_HOME_WHOLE_NUMBER, ASCIIToUTF16("4088714567"));
1347   SetProfile(profile);
1348
1349   GURL url = test_server()->GetURL(
1350       "files/autofill/autofill_confirmemail_form.html");
1351   ui_test_utils::NavigateToURL(browser(), url);
1352   PopulateForm("NAME_FIRST");
1353
1354   ExpectFieldValue("EMAIL_CONFIRM", email);
1355   // TODO(isherman): verify entire form.
1356 }
1357
1358 // http://crbug.com/281527
1359 #if defined(OS_MACOSX)
1360 #define MAYBE_FormFillLatencyAfterSubmit FormFillLatencyAfterSubmit
1361 #else
1362 #define MAYBE_FormFillLatencyAfterSubmit DISABLED_FormFillLatencyAfterSubmit
1363 #endif
1364 // Test latency time on form submit with lots of stored Autofill profiles.
1365 // This test verifies when a profile is selected from the Autofill dictionary
1366 // that consists of thousands of profiles, the form does not hang after being
1367 // submitted.
1368 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
1369                        MAYBE_FormFillLatencyAfterSubmit) {
1370   ASSERT_TRUE(test_server()->Start());
1371
1372   std::vector<std::string> cities;
1373   cities.push_back("San Jose");
1374   cities.push_back("San Francisco");
1375   cities.push_back("Sacramento");
1376   cities.push_back("Los Angeles");
1377
1378   std::vector<std::string> streets;
1379   streets.push_back("St");
1380   streets.push_back("Ave");
1381   streets.push_back("Ln");
1382   streets.push_back("Ct");
1383
1384   const int kNumProfiles = 1500;
1385   base::Time start_time = base::Time::Now();
1386   std::vector<AutofillProfile> profiles;
1387   for (int i = 0; i < kNumProfiles; i++) {
1388     AutofillProfile profile;
1389     base::string16 name(base::IntToString16(i));
1390     base::string16 email(name + ASCIIToUTF16("@example.com"));
1391     base::string16 street = ASCIIToUTF16(
1392         base::IntToString(base::RandInt(0, 10000)) + " " +
1393         streets[base::RandInt(0, streets.size() - 1)]);
1394     base::string16 city =
1395         ASCIIToUTF16(cities[base::RandInt(0, cities.size() - 1)]);
1396     base::string16 zip(base::IntToString16(base::RandInt(0, 10000)));
1397     profile.SetRawInfo(NAME_FIRST, name);
1398     profile.SetRawInfo(EMAIL_ADDRESS, email);
1399     profile.SetRawInfo(ADDRESS_HOME_LINE1, street);
1400     profile.SetRawInfo(ADDRESS_HOME_CITY, city);
1401     profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("CA"));
1402     profile.SetRawInfo(ADDRESS_HOME_ZIP, zip);
1403     profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
1404     profiles.push_back(profile);
1405   }
1406   SetProfiles(&profiles);
1407   // TODO(isherman): once we're sure this test doesn't timeout on any bots, this
1408   // can be removd.
1409   LOG(INFO) << "Created " << kNumProfiles << " profiles in " <<
1410                (base::Time::Now() - start_time).InSeconds() << " seconds.";
1411
1412   GURL url = test_server()->GetURL(
1413       "files/autofill/latency_after_submit_test.html");
1414   ui_test_utils::NavigateToURL(browser(), url);
1415   PopulateForm("NAME_FIRST");
1416
1417   content::WindowedNotificationObserver load_stop_observer(
1418       content::NOTIFICATION_LOAD_STOP,
1419       content::Source<content::NavigationController>(
1420           &GetWebContents()->GetController()));
1421
1422   ASSERT_TRUE(content::ExecuteScript(
1423       GetRenderViewHost(),
1424       "document.getElementById('testform').submit();"));
1425   // This will ensure the test didn't hang.
1426   load_stop_observer.Wait();
1427 }
1428
1429 // Test that Chrome doesn't crash when autocomplete is disabled while the user
1430 // is interacting with the form.  This is a regression test for
1431 // http://crbug.com/160476
1432 IN_PROC_BROWSER_TEST_F(AutofillInteractiveTest,
1433                        DisableAutocompleteWhileFilling) {
1434   CreateTestProfile();
1435
1436   // Load the test page.
1437   ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL(browser(),
1438       GURL(std::string(kDataURIPrefix) + kTestFormString)));
1439
1440   // Invoke Autofill: Start filling the first name field with "M" and wait for
1441   // the popup to be shown.
1442   FocusFirstNameField();
1443   SendKeyToPageAndWait(ui::VKEY_M);
1444
1445   // Now that the popup with suggestions is showing, disable autocomplete for
1446   // the active field.
1447   ASSERT_TRUE(content::ExecuteScript(
1448       GetRenderViewHost(),
1449       "document.querySelector('input').autocomplete = 'off';"));
1450
1451   // Press the down arrow to select the suggestion and attempt to preview the
1452   // autofilled form.
1453   SendKeyToPopupAndWait(ui::VKEY_DOWN);
1454 }
1455
1456 }  // namespace autofill