Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / chrome / renderer / autofill / password_autofill_agent_browsertest.cc
blob59532e8bcb42683aadf364ff51429c5594266cce
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/strings/string_util.h"
6 #include "base/strings/utf_string_conversions.h"
7 #include "chrome/test/base/chrome_render_view_test.h"
8 #include "components/autofill/content/common/autofill_messages.h"
9 #include "components/autofill/content/renderer/autofill_agent.h"
10 #include "components/autofill/content/renderer/form_autofill_util.h"
11 #include "components/autofill/content/renderer/password_autofill_agent.h"
12 #include "components/autofill/content/renderer/test_password_autofill_agent.h"
13 #include "components/autofill/core/common/autofill_constants.h"
14 #include "components/autofill/core/common/autofill_switches.h"
15 #include "components/autofill/core/common/form_data.h"
16 #include "components/autofill/core/common/form_field_data.h"
17 #include "content/public/renderer/render_frame.h"
18 #include "testing/gtest/include/gtest/gtest.h"
19 #include "third_party/WebKit/public/platform/WebString.h"
20 #include "third_party/WebKit/public/platform/WebVector.h"
21 #include "third_party/WebKit/public/web/WebDocument.h"
22 #include "third_party/WebKit/public/web/WebElement.h"
23 #include "third_party/WebKit/public/web/WebFormElement.h"
24 #include "third_party/WebKit/public/web/WebInputElement.h"
25 #include "third_party/WebKit/public/web/WebLocalFrame.h"
26 #include "third_party/WebKit/public/web/WebNode.h"
27 #include "third_party/WebKit/public/web/WebView.h"
28 #include "ui/events/keycodes/keyboard_codes.h"
30 using autofill::PasswordForm;
31 using base::ASCIIToUTF16;
32 using base::UTF16ToUTF8;
33 using blink::WebDocument;
34 using blink::WebElement;
35 using blink::WebFrame;
36 using blink::WebInputElement;
37 using blink::WebString;
38 using blink::WebView;
40 namespace {
42 const int kPasswordFillFormDataId = 1234;
44 // The name of the username/password element in the form.
45 const char kUsernameName[] = "username";
46 const char kPasswordName[] = "password";
48 const char kAliceUsername[] = "alice";
49 const char kAlicePassword[] = "password";
50 const char kBobUsername[] = "bob";
51 const char kBobPassword[] = "secret";
52 const char kCarolUsername[] = "Carol";
53 const char kCarolPassword[] = "test";
54 const char kCarolAlternateUsername[] = "RealCarolUsername";
56 const char kFormHTML[] =
57 "<FORM name='LoginTestForm' action='http://www.bidule.com'>"
58 " <INPUT type='text' id='username'/>"
59 " <INPUT type='password' id='password'/>"
60 " <INPUT type='submit' value='Login'/>"
61 "</FORM>";
63 const char kVisibleFormWithNoUsernameHTML[] =
64 "<head> <style> form {display: inline;} </style> </head>"
65 "<body>"
66 " <form name='LoginTestForm' action='http://www.bidule.com'>"
67 " <div>"
68 " <input type='password' id='password'/>"
69 " </div>"
70 " </form>"
71 "</body>";
73 const char kEmptyFormHTML[] =
74 "<head> <style> form {display: inline;} </style> </head>"
75 "<body> <form> </form> </body>";
77 const char kNonVisibleFormHTML[] =
78 "<head> <style> form {display: none;} </style> </head>"
79 "<body>"
80 " <form>"
81 " <div>"
82 " <input type='password' id='password'/>"
83 " </div>"
84 " </form>"
85 "</body>";
87 const char kEmptyWebpage[] =
88 "<html>"
89 " <head>"
90 " </head>"
91 " <body>"
92 " </body>"
93 "</html>";
95 const char kRedirectionWebpage[] =
96 "<html>"
97 " <head>"
98 " <meta http-equiv='Content-Type' content='text/html'>"
99 " <title>Redirection page</title>"
100 " <script></script>"
101 " </head>"
102 " <body>"
103 " <script type='text/javascript'>"
104 " function test(){}"
105 " </script>"
106 " </body>"
107 "</html>";
109 const char kSimpleWebpage[] =
110 "<html>"
111 " <head>"
112 " <meta charset='utf-8' />"
113 " <title>Title</title>"
114 " </head>"
115 " <body>"
116 " <form name='LoginTestForm'>"
117 " <input type='text' id='username'/>"
118 " <input type='password' id='password'/>"
119 " <input type='submit' value='Login'/>"
120 " </form>"
121 " </body>"
122 "</html>";
124 const char kWebpageWithDynamicContent[] =
125 "<html>"
126 " <head>"
127 " <meta charset='utf-8' />"
128 " <title>Title</title>"
129 " </head>"
130 " <body>"
131 " <script type='text/javascript'>"
132 " function addParagraph() {"
133 " var p = document.createElement('p');"
134 " document.body.appendChild(p);"
135 " }"
136 " window.onload = addParagraph;"
137 " </script>"
138 " </body>"
139 "</html>";
141 const char kJavaScriptClick[] =
142 "var event = new MouseEvent('click', {"
143 " 'view': window,"
144 " 'bubbles': true,"
145 " 'cancelable': true"
146 "});"
147 "var form = document.getElementById('myform1');"
148 "form.dispatchEvent(event);"
149 "console.log('clicked!');";
151 const char kOnChangeDetectionScript[] =
152 "<script>"
153 " usernameOnchangeCalled = false;"
154 " passwordOnchangeCalled = false;"
155 " document.getElementById('username').onchange = function() {"
156 " usernameOnchangeCalled = true;"
157 " };"
158 " document.getElementById('password').onchange = function() {"
159 " passwordOnchangeCalled = true;"
160 " };"
161 "</script>";
163 // Sets the "readonly" attribute of |element| to the value given by |read_only|.
164 void SetElementReadOnly(WebInputElement& element, bool read_only) {
165 element.setAttribute(WebString::fromUTF8("readonly"),
166 read_only ? WebString::fromUTF8("true") : WebString());
169 } // namespace
171 namespace autofill {
173 class PasswordAutofillAgentTest : public ChromeRenderViewTest {
174 public:
175 PasswordAutofillAgentTest() {
178 // Simulates the fill password form message being sent to the renderer.
179 // We use that so we don't have to make RenderView::OnFillPasswordForm()
180 // protected.
181 void SimulateOnFillPasswordForm(
182 const PasswordFormFillData& fill_data) {
183 AutofillMsg_FillPasswordForm msg(0, kPasswordFillFormDataId, fill_data);
184 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
185 ->OnMessageReceived(msg);
188 // As above, but fills for an iframe.
189 void SimulateOnFillPasswordFormForFrame(
190 WebFrame* frame,
191 const PasswordFormFillData& fill_data) {
192 AutofillMsg_FillPasswordForm msg(0, kPasswordFillFormDataId, fill_data);
193 content::RenderFrame::FromWebFrame(frame)->OnMessageReceived(msg);
196 void SendVisiblePasswordForms() {
197 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
198 ->DidFinishLoad();
201 void SetUp() override {
202 ChromeRenderViewTest::SetUp();
204 // Add a preferred login and an additional login to the FillData.
205 username1_ = ASCIIToUTF16(kAliceUsername);
206 password1_ = ASCIIToUTF16(kAlicePassword);
207 username2_ = ASCIIToUTF16(kBobUsername);
208 password2_ = ASCIIToUTF16(kBobPassword);
209 username3_ = ASCIIToUTF16(kCarolUsername);
210 password3_ = ASCIIToUTF16(kCarolPassword);
211 alternate_username3_ = ASCIIToUTF16(kCarolAlternateUsername);
213 FormFieldData username_field;
214 username_field.name = ASCIIToUTF16(kUsernameName);
215 username_field.value = username1_;
216 fill_data_.username_field = username_field;
218 FormFieldData password_field;
219 password_field.name = ASCIIToUTF16(kPasswordName);
220 password_field.value = password1_;
221 password_field.form_control_type = "password";
222 fill_data_.password_field = password_field;
224 PasswordAndRealm password2;
225 password2.password = password2_;
226 fill_data_.additional_logins[username2_] = password2;
227 PasswordAndRealm password3;
228 password3.password = password3_;
229 fill_data_.additional_logins[username3_] = password3;
231 UsernamesCollectionKey key;
232 key.username = username3_;
233 key.password = password3_;
234 key.realm = "google.com";
235 fill_data_.other_possible_usernames[key].push_back(alternate_username3_);
237 // We need to set the origin so it matches the frame URL and the action so
238 // it matches the form action, otherwise we won't autocomplete.
239 UpdateOriginForHTML(kFormHTML);
240 fill_data_.action = GURL("http://www.bidule.com");
242 LoadHTML(kFormHTML);
244 // Now retrieve the input elements so the test can access them.
245 UpdateUsernameAndPasswordElements();
248 void TearDown() override {
249 username_element_.reset();
250 password_element_.reset();
251 ChromeRenderViewTest::TearDown();
254 void UpdateOriginForHTML(const std::string& html) {
255 std::string origin = "data:text/html;charset=utf-8," + html;
256 fill_data_.origin = GURL(origin);
259 void UpdateUsernameAndPasswordElements() {
260 WebDocument document = GetMainFrame()->document();
261 WebElement element =
262 document.getElementById(WebString::fromUTF8(kUsernameName));
263 ASSERT_FALSE(element.isNull());
264 username_element_ = element.to<blink::WebInputElement>();
265 element = document.getElementById(WebString::fromUTF8(kPasswordName));
266 ASSERT_FALSE(element.isNull());
267 password_element_ = element.to<blink::WebInputElement>();
270 void ClearUsernameAndPasswordFields() {
271 username_element_.setValue("");
272 username_element_.setAutofilled(false);
273 password_element_.setValue("");
274 password_element_.setAutofilled(false);
277 void SimulateDidEndEditing(WebFrame* input_frame, WebInputElement& input) {
278 static_cast<blink::WebAutofillClient*>(autofill_agent_)
279 ->textFieldDidEndEditing(input);
282 void SimulateInputChangeForElement(const std::string& new_value,
283 bool move_caret_to_end,
284 WebFrame* input_frame,
285 WebInputElement& input,
286 bool is_user_input) {
287 input.setValue(WebString::fromUTF8(new_value), is_user_input);
288 // The field must have focus or AutofillAgent will think the
289 // change should be ignored.
290 while (!input.focused())
291 input_frame->document().frame()->view()->advanceFocus(false);
292 if (move_caret_to_end)
293 input.setSelectionRange(new_value.length(), new_value.length());
294 if (is_user_input) {
295 AutofillMsg_FirstUserGestureObservedInTab msg(0);
296 content::RenderFrame::FromWebFrame(input_frame)->OnMessageReceived(msg);
298 // Also pass the message to the testing object.
299 if (input_frame == GetMainFrame())
300 password_autofill_agent_->FirstUserGestureObserved();
302 input_frame->toWebLocalFrame()->autofillClient()->textFieldDidChange(input);
303 // Processing is delayed because of a Blink bug:
304 // https://bugs.webkit.org/show_bug.cgi?id=16976
305 // See PasswordAutofillAgent::TextDidChangeInTextField() for details.
307 // Autocomplete will trigger a style recalculation when we put up the next
308 // frame, but we don't want to wait that long. Instead, trigger a style
309 // recalcuation manually after TextFieldDidChangeImpl runs.
310 base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
311 &PasswordAutofillAgentTest::LayoutMainFrame, base::Unretained(this)));
313 base::MessageLoop::current()->RunUntilIdle();
316 void SimulateSuggestionChoice(WebInputElement& username_input) {
317 base::string16 username(base::ASCIIToUTF16(kAliceUsername));
318 base::string16 password(base::ASCIIToUTF16(kAlicePassword));
319 SimulateSuggestionChoiceOfUsernameAndPassword(username_input, username,
320 password);
323 void SimulateSuggestionChoiceOfUsernameAndPassword(
324 WebInputElement& input,
325 const base::string16& username,
326 const base::string16& password) {
327 // This call is necessary to setup the autofill agent appropriate for the
328 // user selection; simulates the menu actually popping up.
329 render_thread_->sink().ClearMessages();
330 static_cast<autofill::PageClickListener*>(autofill_agent_)
331 ->FormControlElementClicked(input, false);
333 AutofillMsg_FillPasswordSuggestion msg(0, username, password);
334 static_cast<content::RenderFrameObserver*>(autofill_agent_)
335 ->OnMessageReceived(msg);
338 void LayoutMainFrame() {
339 GetMainFrame()->view()->layout();
342 void SimulateUsernameChange(const std::string& username,
343 bool move_caret_to_end,
344 bool is_user_input = false) {
345 SimulateInputChangeForElement(username,
346 move_caret_to_end,
347 GetMainFrame(),
348 username_element_,
349 is_user_input);
352 void SimulateKeyDownEvent(const WebInputElement& element,
353 ui::KeyboardCode key_code) {
354 blink::WebKeyboardEvent key_event;
355 key_event.windowsKeyCode = key_code;
356 static_cast<blink::WebAutofillClient*>(autofill_agent_)
357 ->textFieldDidReceiveKeyDown(element, key_event);
360 void CheckTextFieldsStateForElements(const WebInputElement& username_element,
361 const std::string& username,
362 bool username_autofilled,
363 const WebInputElement& password_element,
364 const std::string& password,
365 bool password_autofilled,
366 bool checkSuggestedValue) {
367 EXPECT_EQ(username,
368 static_cast<std::string>(username_element.value().utf8()));
369 EXPECT_EQ(username_autofilled, username_element.isAutofilled());
370 EXPECT_EQ(password,
371 static_cast<std::string>(
372 checkSuggestedValue ? password_element.suggestedValue().utf8()
373 : password_element.value().utf8()))
374 << "checkSuggestedValue == " << checkSuggestedValue;
375 EXPECT_EQ(password_autofilled, password_element.isAutofilled());
378 // Checks the DOM-accessible value of the username element and the
379 // *suggested* value of the password element.
380 void CheckTextFieldsState(const std::string& username,
381 bool username_autofilled,
382 const std::string& password,
383 bool password_autofilled) {
384 CheckTextFieldsStateForElements(username_element_,
385 username,
386 username_autofilled,
387 password_element_,
388 password,
389 password_autofilled,
390 true);
393 // Checks the DOM-accessible value of the username element and the
394 // DOM-accessible value of the password element.
395 void CheckTextFieldsDOMState(const std::string& username,
396 bool username_autofilled,
397 const std::string& password,
398 bool password_autofilled) {
399 CheckTextFieldsStateForElements(username_element_,
400 username,
401 username_autofilled,
402 password_element_,
403 password,
404 password_autofilled,
405 false);
408 void CheckUsernameSelection(int start, int end) {
409 EXPECT_EQ(start, username_element_.selectionStart());
410 EXPECT_EQ(end, username_element_.selectionEnd());
413 // Checks the message sent to PasswordAutofillManager to build the suggestion
414 // list. |username| is the expected username field value, and |show_all| is
415 // the expected flag for the PasswordAutofillManager, whether to show all
416 // suggestions, or only those starting with |username|.
417 void CheckSuggestions(const std::string& username, bool show_all) {
418 const IPC::Message* message =
419 render_thread_->sink().GetFirstMessageMatching(
420 AutofillHostMsg_ShowPasswordSuggestions::ID);
421 EXPECT_TRUE(message);
422 Tuple<int, base::i18n::TextDirection, base::string16, int, gfx::RectF>
423 args;
424 AutofillHostMsg_ShowPasswordSuggestions::Read(message, &args);
425 EXPECT_EQ(kPasswordFillFormDataId, get<0>(args));
426 EXPECT_EQ(ASCIIToUTF16(username), get<2>(args));
427 EXPECT_EQ(show_all, static_cast<bool>(get<3>(args) & autofill::SHOW_ALL));
429 render_thread_->sink().ClearMessages();
432 void ExpectFormSubmittedWithUsernameAndPasswords(
433 const std::string& username_value,
434 const std::string& password_value,
435 const std::string& new_password_value) {
436 const IPC::Message* message =
437 render_thread_->sink().GetFirstMessageMatching(
438 AutofillHostMsg_PasswordFormSubmitted::ID);
439 ASSERT_TRUE(message);
440 Tuple<autofill::PasswordForm> args;
441 AutofillHostMsg_PasswordFormSubmitted::Read(message, &args);
442 EXPECT_EQ(ASCIIToUTF16(username_value), get<0>(args).username_value);
443 EXPECT_EQ(ASCIIToUTF16(password_value), get<0>(args).password_value);
444 EXPECT_EQ(ASCIIToUTF16(new_password_value),
445 get<0>(args).new_password_value);
448 base::string16 username1_;
449 base::string16 username2_;
450 base::string16 username3_;
451 base::string16 password1_;
452 base::string16 password2_;
453 base::string16 password3_;
454 base::string16 alternate_username3_;
455 PasswordFormFillData fill_data_;
457 WebInputElement username_element_;
458 WebInputElement password_element_;
460 private:
461 DISALLOW_COPY_AND_ASSIGN(PasswordAutofillAgentTest);
464 // Tests that the password login is autocompleted as expected when the browser
465 // sends back the password info.
466 TEST_F(PasswordAutofillAgentTest, InitialAutocomplete) {
468 * Right now we are not sending the message to the browser because we are
469 * loading a data URL and the security origin canAccessPasswordManager()
470 * returns false. May be we should mock URL loading to cirmcuvent this?
471 TODO(jcivelli): find a way to make the security origin not deny access to the
472 password manager and then reenable this code.
474 // The form has been loaded, we should have sent the browser a message about
475 // the form.
476 const IPC::Message* msg = render_thread_.sink().GetFirstMessageMatching(
477 AutofillHostMsg_PasswordFormsParsed::ID);
478 ASSERT_TRUE(msg != NULL);
480 Tuple1<std::vector<PasswordForm> > forms;
481 AutofillHostMsg_PasswordFormsParsed::Read(msg, &forms);
482 ASSERT_EQ(1U, forms.a.size());
483 PasswordForm password_form = forms.a[0];
484 EXPECT_EQ(PasswordForm::SCHEME_HTML, password_form.scheme);
485 EXPECT_EQ(ASCIIToUTF16(kUsernameName), password_form.username_element);
486 EXPECT_EQ(ASCIIToUTF16(kPasswordName), password_form.password_element);
489 // Simulate the browser sending back the login info, it triggers the
490 // autocomplete.
491 SimulateOnFillPasswordForm(fill_data_);
493 // The username and password should have been autocompleted.
494 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
497 // Tests that we correctly fill forms having an empty 'action' attribute.
498 TEST_F(PasswordAutofillAgentTest, InitialAutocompleteForEmptyAction) {
499 const char kEmptyActionFormHTML[] =
500 "<FORM name='LoginTestForm'>"
501 " <INPUT type='text' id='username'/>"
502 " <INPUT type='password' id='password'/>"
503 " <INPUT type='submit' value='Login'/>"
504 "</FORM>";
505 LoadHTML(kEmptyActionFormHTML);
507 // Retrieve the input elements so the test can access them.
508 WebDocument document = GetMainFrame()->document();
509 WebElement element =
510 document.getElementById(WebString::fromUTF8(kUsernameName));
511 ASSERT_FALSE(element.isNull());
512 username_element_ = element.to<blink::WebInputElement>();
513 element = document.getElementById(WebString::fromUTF8(kPasswordName));
514 ASSERT_FALSE(element.isNull());
515 password_element_ = element.to<blink::WebInputElement>();
517 // Set the expected form origin and action URLs.
518 UpdateOriginForHTML(kEmptyActionFormHTML);
519 fill_data_.action = fill_data_.origin;
521 // Simulate the browser sending back the login info, it triggers the
522 // autocomplete.
523 SimulateOnFillPasswordForm(fill_data_);
525 // The username and password should have been autocompleted.
526 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
529 // Tests that if a password is marked as readonly, neither field is autofilled
530 // on page load.
531 TEST_F(PasswordAutofillAgentTest, NoInitialAutocompleteForReadOnlyPassword) {
532 SetElementReadOnly(password_element_, true);
534 // Simulate the browser sending back the login info, it triggers the
535 // autocomplete.
536 SimulateOnFillPasswordForm(fill_data_);
538 CheckTextFieldsState(std::string(), false, std::string(), false);
541 // Can still fill a password field if the username is set to a value that
542 // matches.
543 TEST_F(PasswordAutofillAgentTest,
544 AutocompletePasswordForReadonlyUsernameMatched) {
545 username_element_.setValue(username3_);
546 SetElementReadOnly(username_element_, true);
548 // Filled even though username is not the preferred match.
549 SimulateOnFillPasswordForm(fill_data_);
550 CheckTextFieldsState(UTF16ToUTF8(username3_), false,
551 UTF16ToUTF8(password3_), true);
554 // If a username field is empty and readonly, don't autofill.
555 TEST_F(PasswordAutofillAgentTest,
556 NoAutocompletePasswordForReadonlyUsernameUnmatched) {
557 username_element_.setValue(WebString::fromUTF8(""));
558 SetElementReadOnly(username_element_, true);
560 SimulateOnFillPasswordForm(fill_data_);
561 CheckTextFieldsState(std::string(), false, std::string(), false);
564 // Tests that having a non-matching username precludes the autocomplete.
565 TEST_F(PasswordAutofillAgentTest, NoAutocompleteForFilledFieldUnmatched) {
566 username_element_.setValue(WebString::fromUTF8("bogus"));
568 // Simulate the browser sending back the login info, it triggers the
569 // autocomplete.
570 SimulateOnFillPasswordForm(fill_data_);
572 // Neither field should be autocompleted.
573 CheckTextFieldsState("bogus", false, std::string(), false);
576 // Don't try to complete a prefilled value even if it's a partial match
577 // to a username.
578 TEST_F(PasswordAutofillAgentTest, NoPartialMatchForPrefilledUsername) {
579 username_element_.setValue(WebString::fromUTF8("ali"));
581 SimulateOnFillPasswordForm(fill_data_);
583 CheckTextFieldsState("ali", false, std::string(), false);
586 TEST_F(PasswordAutofillAgentTest, InputWithNoForms) {
587 const char kNoFormInputs[] =
588 "<input type='text' id='username'/>"
589 "<input type='password' id='password'/>";
590 LoadHTML(kNoFormInputs);
592 SimulateOnFillPasswordForm(fill_data_);
594 // Input elements that aren't in a <form> won't autofill.
595 CheckTextFieldsState(std::string(), false, std::string(), false);
598 TEST_F(PasswordAutofillAgentTest, NoAutocompleteForTextFieldPasswords) {
599 const char kTextFieldPasswordFormHTML[] =
600 "<FORM name='LoginTestForm' action='http://www.bidule.com'>"
601 " <INPUT type='text' id='username'/>"
602 " <INPUT type='text' id='password'/>"
603 " <INPUT type='submit' value='Login'/>"
604 "</FORM>";
605 LoadHTML(kTextFieldPasswordFormHTML);
607 // Retrieve the input elements so the test can access them.
608 WebDocument document = GetMainFrame()->document();
609 WebElement element =
610 document.getElementById(WebString::fromUTF8(kUsernameName));
611 ASSERT_FALSE(element.isNull());
612 username_element_ = element.to<blink::WebInputElement>();
613 element = document.getElementById(WebString::fromUTF8(kPasswordName));
614 ASSERT_FALSE(element.isNull());
615 password_element_ = element.to<blink::WebInputElement>();
617 // Set the expected form origin URL.
618 UpdateOriginForHTML(kTextFieldPasswordFormHTML);
620 SimulateOnFillPasswordForm(fill_data_);
622 // Fields should still be empty.
623 CheckTextFieldsState(std::string(), false, std::string(), false);
626 TEST_F(PasswordAutofillAgentTest, NoAutocompleteForPasswordFieldUsernames) {
627 const char kPasswordFieldUsernameFormHTML[] =
628 "<FORM name='LoginTestForm' action='http://www.bidule.com'>"
629 " <INPUT type='password' id='username'/>"
630 " <INPUT type='password' id='password'/>"
631 " <INPUT type='submit' value='Login'/>"
632 "</FORM>";
633 LoadHTML(kPasswordFieldUsernameFormHTML);
635 // Retrieve the input elements so the test can access them.
636 WebDocument document = GetMainFrame()->document();
637 WebElement element =
638 document.getElementById(WebString::fromUTF8(kUsernameName));
639 ASSERT_FALSE(element.isNull());
640 username_element_ = element.to<blink::WebInputElement>();
641 element = document.getElementById(WebString::fromUTF8(kPasswordName));
642 ASSERT_FALSE(element.isNull());
643 password_element_ = element.to<blink::WebInputElement>();
645 // Set the expected form origin URL.
646 UpdateOriginForHTML(kPasswordFieldUsernameFormHTML);
648 SimulateOnFillPasswordForm(fill_data_);
650 // Fields should still be empty.
651 CheckTextFieldsState(std::string(), false, std::string(), false);
654 // Tests that having a matching username does not preclude the autocomplete.
655 TEST_F(PasswordAutofillAgentTest, InitialAutocompleteForMatchingFilledField) {
656 username_element_.setValue(WebString::fromUTF8(kAliceUsername));
658 // Simulate the browser sending back the login info, it triggers the
659 // autocomplete.
660 SimulateOnFillPasswordForm(fill_data_);
662 // The username and password should have been autocompleted.
663 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
666 // Tests that editing the password clears the autocompleted password field.
667 TEST_F(PasswordAutofillAgentTest, PasswordClearOnEdit) {
668 // Simulate the browser sending back the login info, it triggers the
669 // autocomplete.
670 SimulateOnFillPasswordForm(fill_data_);
672 // Simulate the user changing the username to some unknown username.
673 SimulateUsernameChange("alicia", true);
675 // The password should have been cleared.
676 CheckTextFieldsState("alicia", false, std::string(), false);
679 // Tests that we only autocomplete on focus lost and with a full username match
680 // when |wait_for_username| is true.
681 TEST_F(PasswordAutofillAgentTest, WaitUsername) {
682 // Simulate the browser sending back the login info.
683 fill_data_.wait_for_username = true;
684 SimulateOnFillPasswordForm(fill_data_);
686 // No auto-fill should have taken place.
687 CheckTextFieldsState(std::string(), false, std::string(), false);
689 // No autocomplete should happen when text is entered in the username.
690 SimulateUsernameChange("a", true);
691 CheckTextFieldsState("a", false, std::string(), false);
692 SimulateUsernameChange("al", true);
693 CheckTextFieldsState("al", false, std::string(), false);
694 SimulateUsernameChange(kAliceUsername, true);
695 CheckTextFieldsState(kAliceUsername, false, std::string(), false);
697 // Autocomplete should happen only when the username textfield is blurred with
698 // a full match.
699 username_element_.setValue("a");
700 static_cast<blink::WebAutofillClient*>(autofill_agent_)
701 ->textFieldDidEndEditing(username_element_);
702 CheckTextFieldsState("a", false, std::string(), false);
703 username_element_.setValue("al");
704 static_cast<blink::WebAutofillClient*>(autofill_agent_)
705 ->textFieldDidEndEditing(username_element_);
706 CheckTextFieldsState("al", false, std::string(), false);
707 username_element_.setValue("alices");
708 static_cast<blink::WebAutofillClient*>(autofill_agent_)
709 ->textFieldDidEndEditing(username_element_);
710 CheckTextFieldsState("alices", false, std::string(), false);
711 username_element_.setValue(ASCIIToUTF16(kAliceUsername));
712 static_cast<blink::WebAutofillClient*>(autofill_agent_)
713 ->textFieldDidEndEditing(username_element_);
714 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
717 // Tests that inline autocompletion works properly.
718 TEST_F(PasswordAutofillAgentTest, InlineAutocomplete) {
719 // Simulate the browser sending back the login info.
720 SimulateOnFillPasswordForm(fill_data_);
722 ClearUsernameAndPasswordFields();
724 // Simulate the user typing in the first letter of 'alice', a stored
725 // username.
726 SimulateUsernameChange("a", true);
727 // Both the username and password text fields should reflect selection of the
728 // stored login.
729 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
730 // And the selection should have been set to 'lice', the last 4 letters.
731 CheckUsernameSelection(1, 5);
733 // Now the user types the next letter of the same username, 'l'.
734 SimulateUsernameChange("al", true);
735 // Now the fields should have the same value, but the selection should have a
736 // different start value.
737 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
738 CheckUsernameSelection(2, 5);
740 // Test that deleting does not trigger autocomplete.
741 SimulateKeyDownEvent(username_element_, ui::VKEY_BACK);
742 SimulateUsernameChange("alic", true);
743 CheckTextFieldsState("alic", false, std::string(), false);
744 CheckUsernameSelection(4, 4); // No selection.
745 // Reset the last pressed key to something other than backspace.
746 SimulateKeyDownEvent(username_element_, ui::VKEY_A);
748 // Now lets say the user goes astray from the stored username and types the
749 // letter 'f', spelling 'alf'. We don't know alf (that's just sad), so in
750 // practice the username should no longer be 'alice' and the selected range
751 // should be empty.
752 SimulateUsernameChange("alf", true);
753 CheckTextFieldsState("alf", false, std::string(), false);
754 CheckUsernameSelection(3, 3); // No selection.
756 // Ok, so now the user removes all the text and enters the letter 'b'.
757 SimulateUsernameChange("b", true);
758 // The username and password fields should match the 'bob' entry.
759 CheckTextFieldsState(kBobUsername, true, kBobPassword, true);
760 CheckUsernameSelection(1, 3);
762 // Then, the user again removes all the text and types an uppercase 'C'.
763 SimulateUsernameChange("C", true);
764 // The username and password fields should match the 'Carol' entry.
765 CheckTextFieldsState(kCarolUsername, true, kCarolPassword, true);
766 CheckUsernameSelection(1, 5);
767 // The user removes all the text and types a lowercase 'c'. We only
768 // want case-sensitive autocompletion, so the username and the selected range
769 // should be empty.
770 SimulateUsernameChange("c", true);
771 CheckTextFieldsState("c", false, std::string(), false);
772 CheckUsernameSelection(1, 1);
774 // Check that we complete other_possible_usernames as well.
775 SimulateUsernameChange("R", true);
776 CheckTextFieldsState(kCarolAlternateUsername, true, kCarolPassword, true);
777 CheckUsernameSelection(1, 17);
780 TEST_F(PasswordAutofillAgentTest, IsWebNodeVisibleTest) {
781 blink::WebVector<blink::WebFormElement> forms1, forms2, forms3;
782 blink::WebFrame* frame;
784 LoadHTML(kVisibleFormWithNoUsernameHTML);
785 frame = GetMainFrame();
786 frame->document().forms(forms1);
787 ASSERT_EQ(1u, forms1.size());
788 EXPECT_TRUE(IsWebNodeVisible(forms1[0]));
790 LoadHTML(kEmptyFormHTML);
791 frame = GetMainFrame();
792 frame->document().forms(forms2);
793 ASSERT_EQ(1u, forms2.size());
794 EXPECT_FALSE(IsWebNodeVisible(forms2[0]));
796 LoadHTML(kNonVisibleFormHTML);
797 frame = GetMainFrame();
798 frame->document().forms(forms3);
799 ASSERT_EQ(1u, forms3.size());
800 EXPECT_FALSE(IsWebNodeVisible(forms3[0]));
803 TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest) {
804 render_thread_->sink().ClearMessages();
805 LoadHTML(kVisibleFormWithNoUsernameHTML);
806 const IPC::Message* message = render_thread_->sink()
807 .GetFirstMessageMatching(AutofillHostMsg_PasswordFormsRendered::ID);
808 EXPECT_TRUE(message);
809 Tuple<std::vector<autofill::PasswordForm>, bool> param;
810 AutofillHostMsg_PasswordFormsRendered::Read(message, &param);
811 EXPECT_TRUE(get<0>(param).size());
813 render_thread_->sink().ClearMessages();
814 LoadHTML(kEmptyFormHTML);
815 message = render_thread_->sink().GetFirstMessageMatching(
816 AutofillHostMsg_PasswordFormsRendered::ID);
817 EXPECT_TRUE(message);
818 AutofillHostMsg_PasswordFormsRendered::Read(message, &param);
819 EXPECT_FALSE(get<0>(param).size());
821 render_thread_->sink().ClearMessages();
822 LoadHTML(kNonVisibleFormHTML);
823 message = render_thread_->sink().GetFirstMessageMatching(
824 AutofillHostMsg_PasswordFormsRendered::ID);
825 EXPECT_TRUE(message);
826 AutofillHostMsg_PasswordFormsRendered::Read(message, &param);
827 EXPECT_FALSE(get<0>(param).size());
830 TEST_F(PasswordAutofillAgentTest, SendPasswordFormsTest_Redirection) {
831 render_thread_->sink().ClearMessages();
832 LoadHTML(kEmptyWebpage);
833 EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching(
834 AutofillHostMsg_PasswordFormsRendered::ID));
836 render_thread_->sink().ClearMessages();
837 LoadHTML(kRedirectionWebpage);
838 EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching(
839 AutofillHostMsg_PasswordFormsRendered::ID));
841 render_thread_->sink().ClearMessages();
842 LoadHTML(kSimpleWebpage);
843 EXPECT_TRUE(render_thread_->sink().GetFirstMessageMatching(
844 AutofillHostMsg_PasswordFormsRendered::ID));
846 render_thread_->sink().ClearMessages();
847 LoadHTML(kWebpageWithDynamicContent);
848 EXPECT_TRUE(render_thread_->sink().GetFirstMessageMatching(
849 AutofillHostMsg_PasswordFormsRendered::ID));
852 // Tests that a password form in an iframe will not be filled in until a user
853 // interaction with the form.
854 TEST_F(PasswordAutofillAgentTest, IframeNoFillTest) {
855 const char kIframeName[] = "iframe";
856 const char kWebpageWithIframeStart[] =
857 "<html>"
858 " <head>"
859 " <meta charset='utf-8' />"
860 " <title>Title</title>"
861 " </head>"
862 " <body>"
863 " <iframe name='iframe' src=\"";
864 const char kWebpageWithIframeEnd[] =
865 "\"></iframe>"
866 " </body>"
867 "</html>";
869 std::string origin("data:text/html;charset=utf-8,");
870 origin += kSimpleWebpage;
872 std::string page_html(kWebpageWithIframeStart);
873 page_html += origin;
874 page_html += kWebpageWithIframeEnd;
876 LoadHTML(page_html.c_str());
878 // Set the expected form origin and action URLs.
879 fill_data_.origin = GURL(origin);
880 fill_data_.action = GURL(origin);
882 // Retrieve the input elements from the iframe since that is where we want to
883 // test the autofill.
884 WebFrame* iframe = GetMainFrame()->findChildByName(kIframeName);
885 ASSERT_TRUE(iframe);
887 SimulateOnFillPasswordFormForFrame(iframe, fill_data_);
889 WebDocument document = iframe->document();
891 WebElement username_element = document.getElementById(kUsernameName);
892 WebElement password_element = document.getElementById(kPasswordName);
893 ASSERT_FALSE(username_element.isNull());
894 ASSERT_FALSE(password_element.isNull());
896 WebInputElement username_input = username_element.to<WebInputElement>();
897 WebInputElement password_input = password_element.to<WebInputElement>();
898 ASSERT_FALSE(username_element.isNull());
900 CheckTextFieldsStateForElements(
901 username_input, "", false, password_input, "", false, false);
903 // Simulate the user typing in the username in the iframe which should cause
904 // an autofill.
905 SimulateInputChangeForElement(
906 kAliceUsername, true, iframe, username_input, true);
908 CheckTextFieldsStateForElements(username_input,
909 kAliceUsername,
910 true,
911 password_input,
912 kAlicePassword,
913 true,
914 false);
917 // Tests that a password will only be filled as a suggested and will not be
918 // accessible by the DOM until a user gesture has occurred.
919 TEST_F(PasswordAutofillAgentTest, GestureRequiredTest) {
920 // Trigger the initial autocomplete.
921 SimulateOnFillPasswordForm(fill_data_);
923 // The username and password should have been autocompleted.
924 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
926 // However, it should only have completed with the suggested value, as tested
927 // above, and it should not have completed into the DOM accessible value for
928 // the password field.
929 CheckTextFieldsDOMState(kAliceUsername, true, std::string(), true);
931 // Simulate a user click so that the password field's real value is filled.
932 SimulateElementClick(kUsernameName);
933 CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
936 // Verfies that a DOM-activated UI event will not cause an autofill.
937 TEST_F(PasswordAutofillAgentTest, NoDOMActivationTest) {
938 // Trigger the initial autocomplete.
939 SimulateOnFillPasswordForm(fill_data_);
941 ExecuteJavaScript(kJavaScriptClick);
942 CheckTextFieldsDOMState(kAliceUsername, true, "", true);
945 // Verifies that password autofill triggers onChange events in JavaScript for
946 // forms that are filled on page load.
947 TEST_F(PasswordAutofillAgentTest,
948 PasswordAutofillTriggersOnChangeEventsOnLoad) {
949 std::string html = std::string(kFormHTML) + kOnChangeDetectionScript;
950 LoadHTML(html.c_str());
951 UpdateOriginForHTML(html);
952 UpdateUsernameAndPasswordElements();
954 // Simulate the browser sending back the login info, it triggers the
955 // autocomplete.
956 SimulateOnFillPasswordForm(fill_data_);
958 // The username and password should have been autocompleted...
959 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
960 // ... but since there hasn't been a user gesture yet, the autocompleted
961 // password should only be visible to the user.
962 CheckTextFieldsDOMState(kAliceUsername, true, std::string(), true);
964 // A JavaScript onChange event should have been triggered for the username,
965 // but not yet for the password.
966 int username_onchange_called = -1;
967 int password_onchange_called = -1;
968 ASSERT_TRUE(
969 ExecuteJavaScriptAndReturnIntValue(
970 ASCIIToUTF16("usernameOnchangeCalled ? 1 : 0"),
971 &username_onchange_called));
972 EXPECT_EQ(1, username_onchange_called);
973 ASSERT_TRUE(
974 ExecuteJavaScriptAndReturnIntValue(
975 ASCIIToUTF16("passwordOnchangeCalled ? 1 : 0"),
976 &password_onchange_called));
977 // TODO(isherman): Re-enable this check once http://crbug.com/333144 is fixed.
978 // EXPECT_EQ(0, password_onchange_called);
980 // Simulate a user click so that the password field's real value is filled.
981 SimulateElementClick(kUsernameName);
982 CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
984 // Now, a JavaScript onChange event should have been triggered for the
985 // password as well.
986 ASSERT_TRUE(
987 ExecuteJavaScriptAndReturnIntValue(
988 ASCIIToUTF16("passwordOnchangeCalled ? 1 : 0"),
989 &password_onchange_called));
990 EXPECT_EQ(1, password_onchange_called);
993 // Verifies that password autofill triggers onChange events in JavaScript for
994 // forms that are filled after page load.
995 TEST_F(PasswordAutofillAgentTest,
996 PasswordAutofillTriggersOnChangeEventsWaitForUsername) {
997 std::string html = std::string(kFormHTML) + kOnChangeDetectionScript;
998 LoadHTML(html.c_str());
999 UpdateOriginForHTML(html);
1000 UpdateUsernameAndPasswordElements();
1002 // Simulate the browser sending back the login info, it triggers the
1003 // autocomplete.
1004 fill_data_.wait_for_username = true;
1005 SimulateOnFillPasswordForm(fill_data_);
1007 // The username and password should not yet have been autocompleted.
1008 CheckTextFieldsState(std::string(), false, std::string(), false);
1010 // Simulate a click just to force a user gesture, since the username value is
1011 // set directly.
1012 SimulateElementClick(kUsernameName);
1014 // Simulate the user entering her username and selecting the matching autofill
1015 // from the dropdown.
1016 SimulateUsernameChange(kAliceUsername, true, true);
1017 SimulateSuggestionChoice(username_element_);
1019 // The username and password should now have been autocompleted.
1020 CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
1022 // JavaScript onChange events should have been triggered both for the username
1023 // and for the password.
1024 int username_onchange_called = -1;
1025 int password_onchange_called = -1;
1026 ASSERT_TRUE(
1027 ExecuteJavaScriptAndReturnIntValue(
1028 ASCIIToUTF16("usernameOnchangeCalled ? 1 : 0"),
1029 &username_onchange_called));
1030 EXPECT_EQ(1, username_onchange_called);
1031 ASSERT_TRUE(
1032 ExecuteJavaScriptAndReturnIntValue(
1033 ASCIIToUTF16("passwordOnchangeCalled ? 1 : 0"),
1034 &password_onchange_called));
1035 EXPECT_EQ(1, password_onchange_called);
1038 // Tests that |FillSuggestion| properly fills the username and password.
1039 TEST_F(PasswordAutofillAgentTest, FillSuggestion) {
1040 // Simulate the browser sending the login info, but set |wait_for_username|
1041 // to prevent the form from being immediately filled.
1042 fill_data_.wait_for_username = true;
1043 SimulateOnFillPasswordForm(fill_data_);
1045 // Neither field should have been autocompleted.
1046 CheckTextFieldsDOMState(std::string(), false, std::string(), false);
1048 // If the password field is not autocompletable, it should not be affected.
1049 SetElementReadOnly(password_element_, true);
1050 EXPECT_FALSE(password_autofill_agent_->FillSuggestion(
1051 username_element_, kAliceUsername, kAlicePassword));
1052 CheckTextFieldsDOMState(std::string(), false, std::string(), false);
1053 SetElementReadOnly(password_element_, false);
1055 // After filling with the suggestion, both fields should be autocompleted.
1056 EXPECT_TRUE(password_autofill_agent_->FillSuggestion(
1057 username_element_, kAliceUsername, kAlicePassword));
1058 CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
1059 int username_length = strlen(kAliceUsername);
1060 CheckUsernameSelection(username_length, username_length);
1062 // Try Filling with a suggestion with password different from the one that was
1063 // initially sent to the renderer.
1064 EXPECT_TRUE(password_autofill_agent_->FillSuggestion(
1065 username_element_, kBobUsername, kCarolPassword));
1066 CheckTextFieldsDOMState(kBobUsername, true, kCarolPassword, true);
1067 username_length = strlen(kBobUsername);
1068 CheckUsernameSelection(username_length, username_length);
1071 // Tests that |PreviewSuggestion| properly previews the username and password.
1072 TEST_F(PasswordAutofillAgentTest, PreviewSuggestion) {
1073 // Simulate the browser sending the login info, but set |wait_for_username|
1074 // to prevent the form from being immediately filled.
1075 fill_data_.wait_for_username = true;
1076 SimulateOnFillPasswordForm(fill_data_);
1078 // Neither field should have been autocompleted.
1079 CheckTextFieldsDOMState(std::string(), false, std::string(), false);
1081 // If the password field is not autocompletable, it should not be affected.
1082 SetElementReadOnly(password_element_, true);
1083 EXPECT_FALSE(password_autofill_agent_->PreviewSuggestion(
1084 username_element_, kAliceUsername, kAlicePassword));
1085 EXPECT_EQ(std::string(), username_element_.suggestedValue().utf8());
1086 EXPECT_FALSE(username_element_.isAutofilled());
1087 EXPECT_EQ(std::string(), password_element_.suggestedValue().utf8());
1088 EXPECT_FALSE(password_element_.isAutofilled());
1089 SetElementReadOnly(password_element_, false);
1091 // After selecting the suggestion, both fields should be previewed
1092 // with suggested values.
1093 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1094 username_element_, kAliceUsername, kAlicePassword));
1095 EXPECT_EQ(
1096 kAliceUsername,
1097 static_cast<std::string>(username_element_.suggestedValue().utf8()));
1098 EXPECT_TRUE(username_element_.isAutofilled());
1099 EXPECT_EQ(
1100 kAlicePassword,
1101 static_cast<std::string>(password_element_.suggestedValue().utf8()));
1102 EXPECT_TRUE(password_element_.isAutofilled());
1103 int username_length = strlen(kAliceUsername);
1104 CheckUsernameSelection(0, username_length);
1106 // Try previewing with a password different from the one that was initially
1107 // sent to the renderer.
1108 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1109 username_element_, kBobUsername, kCarolPassword));
1110 EXPECT_EQ(
1111 kBobUsername,
1112 static_cast<std::string>(username_element_.suggestedValue().utf8()));
1113 EXPECT_TRUE(username_element_.isAutofilled());
1114 EXPECT_EQ(
1115 kCarolPassword,
1116 static_cast<std::string>(password_element_.suggestedValue().utf8()));
1117 EXPECT_TRUE(password_element_.isAutofilled());
1118 username_length = strlen(kBobUsername);
1119 CheckUsernameSelection(0, username_length);
1122 // Tests that |PreviewSuggestion| properly sets the username selection range.
1123 TEST_F(PasswordAutofillAgentTest, PreviewSuggestionSelectionRange) {
1124 username_element_.setValue(WebString::fromUTF8("ali"));
1125 username_element_.setSelectionRange(3, 3);
1126 username_element_.setAutofilled(true);
1128 CheckTextFieldsDOMState("ali", true, std::string(), false);
1130 // Simulate the browser sending the login info, but set |wait_for_username|
1131 // to prevent the form from being immediately filled.
1132 fill_data_.wait_for_username = true;
1133 SimulateOnFillPasswordForm(fill_data_);
1135 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1136 username_element_, kAliceUsername, kAlicePassword));
1137 EXPECT_EQ(
1138 kAliceUsername,
1139 static_cast<std::string>(username_element_.suggestedValue().utf8()));
1140 EXPECT_TRUE(username_element_.isAutofilled());
1141 EXPECT_EQ(
1142 kAlicePassword,
1143 static_cast<std::string>(password_element_.suggestedValue().utf8()));
1144 EXPECT_TRUE(password_element_.isAutofilled());
1145 int username_length = strlen(kAliceUsername);
1146 CheckUsernameSelection(3, username_length);
1149 // Tests that |ClearPreview| properly clears previewed username and password
1150 // with password being previously autofilled.
1151 TEST_F(PasswordAutofillAgentTest, ClearPreviewWithPasswordAutofilled) {
1152 password_element_.setValue(WebString::fromUTF8("sec"));
1153 password_element_.setAutofilled(true);
1155 // Simulate the browser sending the login info, but set |wait_for_username|
1156 // to prevent the form from being immediately filled.
1157 fill_data_.wait_for_username = true;
1158 SimulateOnFillPasswordForm(fill_data_);
1160 CheckTextFieldsDOMState(std::string(), false, "sec", true);
1162 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1163 username_element_, kAliceUsername, kAlicePassword));
1165 EXPECT_TRUE(
1166 password_autofill_agent_->DidClearAutofillSelection(username_element_));
1168 EXPECT_TRUE(username_element_.value().isEmpty());
1169 EXPECT_TRUE(username_element_.suggestedValue().isEmpty());
1170 EXPECT_FALSE(username_element_.isAutofilled());
1171 EXPECT_EQ(ASCIIToUTF16("sec"), password_element_.value());
1172 EXPECT_TRUE(password_element_.suggestedValue().isEmpty());
1173 EXPECT_TRUE(password_element_.isAutofilled());
1174 CheckUsernameSelection(0, 0);
1177 // Tests that |ClearPreview| properly clears previewed username and password
1178 // with username being previously autofilled.
1179 TEST_F(PasswordAutofillAgentTest, ClearPreviewWithUsernameAutofilled) {
1180 username_element_.setValue(WebString::fromUTF8("ali"));
1181 username_element_.setSelectionRange(3, 3);
1182 username_element_.setAutofilled(true);
1184 // Simulate the browser sending the login info, but set |wait_for_username|
1185 // to prevent the form from being immediately filled.
1186 fill_data_.wait_for_username = true;
1187 SimulateOnFillPasswordForm(fill_data_);
1189 CheckTextFieldsDOMState("ali", true, std::string(), false);
1191 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1192 username_element_, kAliceUsername, kAlicePassword));
1194 EXPECT_TRUE(
1195 password_autofill_agent_->DidClearAutofillSelection(username_element_));
1197 EXPECT_EQ(ASCIIToUTF16("ali"), username_element_.value());
1198 EXPECT_TRUE(username_element_.suggestedValue().isEmpty());
1199 EXPECT_TRUE(username_element_.isAutofilled());
1200 EXPECT_TRUE(password_element_.value().isEmpty());
1201 EXPECT_TRUE(password_element_.suggestedValue().isEmpty());
1202 EXPECT_FALSE(password_element_.isAutofilled());
1203 CheckUsernameSelection(3, 3);
1206 // Tests that |ClearPreview| properly clears previewed username and password
1207 // with username and password being previously autofilled.
1208 TEST_F(PasswordAutofillAgentTest,
1209 ClearPreviewWithAutofilledUsernameAndPassword) {
1210 username_element_.setValue(WebString::fromUTF8("ali"));
1211 username_element_.setSelectionRange(3, 3);
1212 username_element_.setAutofilled(true);
1213 password_element_.setValue(WebString::fromUTF8("sec"));
1214 password_element_.setAutofilled(true);
1216 // Simulate the browser sending the login info, but set |wait_for_username|
1217 // to prevent the form from being immediately filled.
1218 fill_data_.wait_for_username = true;
1219 SimulateOnFillPasswordForm(fill_data_);
1221 CheckTextFieldsDOMState("ali", true, "sec", true);
1223 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1224 username_element_, kAliceUsername, kAlicePassword));
1226 EXPECT_TRUE(
1227 password_autofill_agent_->DidClearAutofillSelection(username_element_));
1229 EXPECT_EQ(ASCIIToUTF16("ali"), username_element_.value());
1230 EXPECT_TRUE(username_element_.suggestedValue().isEmpty());
1231 EXPECT_TRUE(username_element_.isAutofilled());
1232 EXPECT_EQ(ASCIIToUTF16("sec"), password_element_.value());
1233 EXPECT_TRUE(password_element_.suggestedValue().isEmpty());
1234 EXPECT_TRUE(password_element_.isAutofilled());
1235 CheckUsernameSelection(3, 3);
1238 // Tests that |ClearPreview| properly clears previewed username and password
1239 // with neither username nor password being previously autofilled.
1240 TEST_F(PasswordAutofillAgentTest,
1241 ClearPreviewWithNotAutofilledUsernameAndPassword) {
1242 // Simulate the browser sending the login info, but set |wait_for_username|
1243 // to prevent the form from being immediately filled.
1244 fill_data_.wait_for_username = true;
1245 SimulateOnFillPasswordForm(fill_data_);
1247 CheckTextFieldsDOMState(std::string(), false, std::string(), false);
1249 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1250 username_element_, kAliceUsername, kAlicePassword));
1252 EXPECT_TRUE(
1253 password_autofill_agent_->DidClearAutofillSelection(username_element_));
1255 EXPECT_TRUE(username_element_.value().isEmpty());
1256 EXPECT_TRUE(username_element_.suggestedValue().isEmpty());
1257 EXPECT_FALSE(username_element_.isAutofilled());
1258 EXPECT_TRUE(password_element_.value().isEmpty());
1259 EXPECT_TRUE(password_element_.suggestedValue().isEmpty());
1260 EXPECT_FALSE(password_element_.isAutofilled());
1261 CheckUsernameSelection(0, 0);
1264 // Tests that |ClearPreview| properly restores the original selection range of
1265 // username field that has initially been filled by inline autocomplete.
1266 TEST_F(PasswordAutofillAgentTest, ClearPreviewWithInlineAutocompletedUsername) {
1267 // Simulate the browser sending back the login info.
1268 SimulateOnFillPasswordForm(fill_data_);
1270 // Clear the text fields to start fresh.
1271 ClearUsernameAndPasswordFields();
1273 // Simulate the user typing in the first letter of 'alice', a stored username.
1274 SimulateUsernameChange("a", true);
1275 // Both the username and password text fields should reflect selection of the
1276 // stored login.
1277 CheckTextFieldsState(kAliceUsername, true, kAlicePassword, true);
1278 // The selection should have been set to 'lice', the last 4 letters.
1279 CheckUsernameSelection(1, 5);
1281 EXPECT_TRUE(password_autofill_agent_->PreviewSuggestion(
1282 username_element_, "alicia", "secret"));
1283 EXPECT_EQ(
1284 "alicia",
1285 static_cast<std::string>(username_element_.suggestedValue().utf8()));
1286 EXPECT_TRUE(username_element_.isAutofilled());
1287 EXPECT_EQ(
1288 "secret",
1289 static_cast<std::string>(password_element_.suggestedValue().utf8()));
1290 EXPECT_TRUE(password_element_.isAutofilled());
1291 CheckUsernameSelection(1, 6);
1293 EXPECT_TRUE(
1294 password_autofill_agent_->DidClearAutofillSelection(username_element_));
1296 EXPECT_EQ(kAliceUsername, username_element_.value().utf8());
1297 EXPECT_TRUE(username_element_.suggestedValue().isEmpty());
1298 EXPECT_TRUE(username_element_.isAutofilled());
1299 EXPECT_TRUE(password_element_.value().isEmpty());
1300 EXPECT_TRUE(password_element_.suggestedValue().isEmpty());
1301 EXPECT_TRUE(password_element_.isAutofilled());
1302 CheckUsernameSelection(1, 5);
1305 // Tests that logging is off by default.
1306 TEST_F(PasswordAutofillAgentTest, OnChangeLoggingState_NoMessage) {
1307 render_thread_->sink().ClearMessages();
1308 SendVisiblePasswordForms();
1309 const IPC::Message* message = render_thread_->sink().GetFirstMessageMatching(
1310 AutofillHostMsg_RecordSavePasswordProgress::ID);
1311 EXPECT_FALSE(message);
1314 // Test that logging can be turned on by a message.
1315 TEST_F(PasswordAutofillAgentTest, OnChangeLoggingState_Activated) {
1316 // Turn the logging on.
1317 AutofillMsg_SetLoggingState msg_activate(0, true);
1318 // Up-cast to access OnMessageReceived, which is private in the agent.
1319 EXPECT_TRUE(static_cast<IPC::Listener*>(password_autofill_agent_)
1320 ->OnMessageReceived(msg_activate));
1322 render_thread_->sink().ClearMessages();
1323 SendVisiblePasswordForms();
1324 const IPC::Message* message = render_thread_->sink().GetFirstMessageMatching(
1325 AutofillHostMsg_RecordSavePasswordProgress::ID);
1326 EXPECT_TRUE(message);
1329 // Test that logging can be turned off by a message.
1330 TEST_F(PasswordAutofillAgentTest, OnChangeLoggingState_Deactivated) {
1331 // Turn the logging on and then off.
1332 AutofillMsg_SetLoggingState msg_activate(0, /*active=*/true);
1333 // Up-cast to access OnMessageReceived, which is private in the agent.
1334 EXPECT_TRUE(static_cast<IPC::Listener*>(password_autofill_agent_)
1335 ->OnMessageReceived(msg_activate));
1336 AutofillMsg_SetLoggingState msg_deactivate(0, /*active=*/false);
1337 EXPECT_TRUE(static_cast<IPC::Listener*>(password_autofill_agent_)
1338 ->OnMessageReceived(msg_deactivate));
1340 render_thread_->sink().ClearMessages();
1341 SendVisiblePasswordForms();
1342 const IPC::Message* message = render_thread_->sink().GetFirstMessageMatching(
1343 AutofillHostMsg_RecordSavePasswordProgress::ID);
1344 EXPECT_FALSE(message);
1347 // Test that the agent sends an IPC call to get the current activity state of
1348 // password saving logging soon after construction.
1349 TEST_F(PasswordAutofillAgentTest, SendsLoggingStateUpdatePingOnConstruction) {
1350 const IPC::Message* message = render_thread_->sink().GetFirstMessageMatching(
1351 AutofillHostMsg_PasswordAutofillAgentConstructed::ID);
1352 EXPECT_TRUE(message);
1355 // TODO(gcasto): Re-enabled these tests after crbug.com/430318 has been fixed.
1356 #if !defined(OS_ANDROID)
1358 // Tests that one user click on a username field is sufficient to bring up a
1359 // credential suggestion popup, and the user can autocomplete the password by
1360 // selecting the credential from the popup.
1361 TEST_F(PasswordAutofillAgentTest, ClickAndSelect) {
1362 // SimulateElementClick() is called so that a user gesture is actually made
1363 // and the password can be filled. However, SimulateElementClick() does not
1364 // actually lead to the AutofillAgent's InputElementClicked() method being
1365 // called, so SimulateSuggestionChoice has to manually call
1366 // InputElementClicked().
1367 ClearUsernameAndPasswordFields();
1368 SimulateOnFillPasswordForm(fill_data_);
1369 SimulateElementClick(kUsernameName);
1370 SimulateSuggestionChoice(username_element_);
1371 CheckSuggestions(kAliceUsername, true);
1373 CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
1376 // Tests the autosuggestions that are given when the element is clicked.
1377 // Specifically, tests when the user clicks on the username element after page
1378 // load and the element is autofilled, when the user clicks on an element that
1379 // has a non-matching username, and when the user clicks on an element that's
1380 // already been autofilled and they've already modified.
1381 TEST_F(PasswordAutofillAgentTest, CredentialsOnClick) {
1382 // Simulate the browser sending back the login info.
1383 SimulateOnFillPasswordForm(fill_data_);
1385 // Clear the text fields to start fresh.
1386 ClearUsernameAndPasswordFields();
1388 // Call SimulateElementClick() to produce a user gesture on the page so
1389 // autofill will actually fill.
1390 SimulateElementClick(kUsernameName);
1392 // Simulate a user clicking on the username element. This should produce a
1393 // message with all the usernames.
1394 render_thread_->sink().ClearMessages();
1395 static_cast<PageClickListener*>(autofill_agent_)
1396 ->FormControlElementClicked(username_element_, false);
1397 CheckSuggestions(std::string(), false);
1399 // Now simulate a user typing in an unrecognized username and then
1400 // clicking on the username element. This should also produce a message with
1401 // all the usernames.
1402 SimulateUsernameChange("baz", true);
1403 render_thread_->sink().ClearMessages();
1404 static_cast<PageClickListener*>(autofill_agent_)
1405 ->FormControlElementClicked(username_element_, true);
1406 CheckSuggestions("baz", true);
1408 // Now simulate a user typing in the first letter of the username and then
1409 // clicking on the username element. While the typing of the first letter will
1410 // inline autocomplete, clicking on the element should still produce a full
1411 // suggestion list.
1412 SimulateUsernameChange("a", true);
1413 render_thread_->sink().ClearMessages();
1414 static_cast<PageClickListener*>(autofill_agent_)
1415 ->FormControlElementClicked(username_element_, true);
1416 CheckSuggestions(kAliceUsername, true);
1419 // Tests that there are no autosuggestions from the password manager when the
1420 // user clicks on the password field and the username field is editable when
1421 // FillOnAccountSelect is enabled.
1422 TEST_F(PasswordAutofillAgentTest,
1423 FillOnAccountSelectOnlyNoCredentialsOnPasswordClick) {
1424 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1425 autofill::switches::kEnableFillOnAccountSelect);
1427 // Simulate the browser sending back the login info.
1428 SimulateOnFillPasswordForm(fill_data_);
1430 // Clear the text fields to start fresh.
1431 ClearUsernameAndPasswordFields();
1433 // Call SimulateElementClick() to produce a user gesture on the page so
1434 // autofill will actually fill.
1435 SimulateElementClick(kUsernameName);
1437 // Simulate a user clicking on the password element. This should produce no
1438 // message.
1439 render_thread_->sink().ClearMessages();
1440 static_cast<PageClickListener*>(autofill_agent_)
1441 ->FormControlElementClicked(password_element_, false);
1442 EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching(
1443 AutofillHostMsg_ShowPasswordSuggestions::ID));
1446 // Tests the autosuggestions that are given when a password element is clicked,
1447 // the username element is not editable, and FillOnAccountSelect is enabled.
1448 // Specifically, tests when the user clicks on the password element after page
1449 // load, and the corresponding username element is readonly (and thus
1450 // uneditable), that the credentials for the already-filled username are
1451 // suggested.
1452 TEST_F(PasswordAutofillAgentTest,
1453 FillOnAccountSelectOnlyCredentialsOnPasswordClick) {
1454 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1455 autofill::switches::kEnableFillOnAccountSelect);
1457 // Simulate the browser sending back the login info.
1458 SimulateOnFillPasswordForm(fill_data_);
1460 // Clear the text fields to start fresh.
1461 ClearUsernameAndPasswordFields();
1463 // Simulate the page loading with a prefilled username element that is
1464 // uneditable.
1465 username_element_.setValue("alicia");
1466 SetElementReadOnly(username_element_, true);
1468 // Call SimulateElementClick() to produce a user gesture on the page so
1469 // autofill will actually fill.
1470 SimulateElementClick(kUsernameName);
1472 // Simulate a user clicking on the password element. This should produce a
1473 // message with "alicia" suggested as the credential.
1474 render_thread_->sink().ClearMessages();
1475 static_cast<PageClickListener*>(autofill_agent_)
1476 ->FormControlElementClicked(password_element_, false);
1477 CheckSuggestions("alicia", false);
1480 // Tests that there are no autosuggestions from the password manager when the
1481 // user clicks on the password field (not the username field).
1482 TEST_F(PasswordAutofillAgentTest, NoCredentialsOnPasswordClick) {
1483 // Simulate the browser sending back the login info.
1484 SimulateOnFillPasswordForm(fill_data_);
1486 // Clear the text fields to start fresh.
1487 ClearUsernameAndPasswordFields();
1489 // Call SimulateElementClick() to produce a user gesture on the page so
1490 // autofill will actually fill.
1491 SimulateElementClick(kUsernameName);
1493 // Simulate a user clicking on the password element. This should produce no
1494 // message.
1495 render_thread_->sink().ClearMessages();
1496 static_cast<PageClickListener*>(autofill_agent_)
1497 ->FormControlElementClicked(password_element_, false);
1498 EXPECT_FALSE(render_thread_->sink().GetFirstMessageMatching(
1499 AutofillHostMsg_ShowPasswordSuggestions::ID));
1502 #endif // !defined(OS_ANDROID)
1504 // The user types in a username and a password, but then just before sending
1505 // the form off, a script clears them. This test checks that
1506 // PasswordAutofillAgent can still remember the username and the password
1507 // typed by the user.
1508 TEST_F(PasswordAutofillAgentTest,
1509 RememberLastNonEmptyUsernameAndPasswordOnSubmit_ScriptCleared) {
1510 SimulateInputChangeForElement(
1511 "temp", true, GetMainFrame(), username_element_, true);
1512 SimulateInputChangeForElement(
1513 "random", true, GetMainFrame(), password_element_, true);
1515 // Simulate that the username and the password value was cleared by the
1516 // site's JavaScript before submit.
1517 username_element_.setValue(WebString());
1518 password_element_.setValue(WebString());
1519 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1520 ->WillSubmitForm(username_element_.form());
1522 // Observe that the PasswordAutofillAgent still remembered the last non-empty
1523 // username and password and sent that to the browser.
1524 ExpectFormSubmittedWithUsernameAndPasswords("temp", "random", "");
1527 // Similar to RememberLastNonEmptyPasswordOnSubmit_ScriptCleared, but this time
1528 // it's the user who clears the username and the password. This test checks
1529 // that in that case, the last non-empty username and password are not
1530 // remembered.
1531 TEST_F(PasswordAutofillAgentTest,
1532 RememberLastNonEmptyUsernameAndPasswordOnSubmit_UserCleared) {
1533 SimulateInputChangeForElement(
1534 "temp", true, GetMainFrame(), username_element_, true);
1535 SimulateInputChangeForElement(
1536 "random", true, GetMainFrame(), password_element_, true);
1538 // Simulate that the user actually cleared the username and password again.
1539 SimulateInputChangeForElement("", true, GetMainFrame(), username_element_,
1540 true);
1541 SimulateInputChangeForElement(
1542 "", true, GetMainFrame(), password_element_, true);
1543 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1544 ->WillSubmitForm(username_element_.form());
1546 // Observe that the PasswordAutofillAgent respects the user having cleared the
1547 // password.
1548 ExpectFormSubmittedWithUsernameAndPasswords("", "", "");
1551 // Similar to RememberLastNonEmptyPasswordOnSubmit_ScriptCleared, but uses the
1552 // new password instead of the current password.
1553 TEST_F(PasswordAutofillAgentTest,
1554 RememberLastNonEmptyUsernameAndPasswordOnSubmit_New) {
1555 const char kNewPasswordFormHTML[] =
1556 "<FORM name='LoginTestForm'>"
1557 " <INPUT type='text' id='username' autocomplete='username'/>"
1558 " <INPUT type='password' id='password' autocomplete='new-password'/>"
1559 " <INPUT type='submit' value='Login'/>"
1560 "</FORM>";
1561 LoadHTML(kNewPasswordFormHTML);
1562 UpdateUsernameAndPasswordElements();
1564 SimulateInputChangeForElement(
1565 "temp", true, GetMainFrame(), username_element_, true);
1566 SimulateInputChangeForElement(
1567 "random", true, GetMainFrame(), password_element_, true);
1569 // Simulate that the username and the password value was cleared by
1570 // the site's JavaScript before submit.
1571 username_element_.setValue(WebString());
1572 password_element_.setValue(WebString());
1573 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1574 ->WillSubmitForm(username_element_.form());
1576 // Observe that the PasswordAutofillAgent still remembered the last non-empty
1577 // password and sent that to the browser.
1578 ExpectFormSubmittedWithUsernameAndPasswords("temp", "", "random");
1581 // The user first accepts a suggestion, but then overwrites the password. This
1582 // test checks that the overwritten password is not reverted back if the user
1583 // triggers autofill through focusing (but not changing) the username again.
1584 TEST_F(PasswordAutofillAgentTest,
1585 NoopEditingDoesNotOverwriteManuallyEditedPassword) {
1586 // Simulate having credentials which needed to wait until the user starts
1587 // typing the username to be filled (e.g., PSL-matched credentials). Those are
1588 // the ones which can be filled as a result of TextFieldDidEndEditing.
1589 fill_data_.wait_for_username = true;
1590 SimulateOnFillPasswordForm(fill_data_);
1591 // Simulate that the user typed her name to make the autofill work.
1592 SimulateInputChangeForElement(kAliceUsername,
1593 /*move_caret_to_end=*/true,
1594 GetMainFrame(),
1595 username_element_,
1596 /*is_user_input=*/true);
1597 SimulateDidEndEditing(GetMainFrame(), username_element_);
1598 const std::string old_username(username_element_.value().utf8());
1599 const std::string old_password(password_element_.value().utf8());
1600 const std::string new_password(old_password + "modify");
1602 // The user changes the password.
1603 SimulateInputChangeForElement(new_password,
1604 /*move_caret_to_end=*/true,
1605 GetMainFrame(),
1606 password_element_,
1607 /*is_user_input=*/true);
1609 // The user switches back into the username field, but leaves that without
1610 // changes.
1611 SimulateDidEndEditing(GetMainFrame(), username_element_);
1613 // The password should have stayed as the user changed it.
1614 CheckTextFieldsDOMState(old_username, true, new_password, false);
1615 // The password should not have a suggested value.
1616 CheckTextFieldsState(old_username, true, std::string(), false);
1619 TEST_F(PasswordAutofillAgentTest,
1620 InlineAutocompleteOverwritesManuallyEditedPassword) {
1621 // Simulate the browser sending back the login info.
1622 SimulateOnFillPasswordForm(fill_data_);
1624 ClearUsernameAndPasswordFields();
1626 // The user enters a password
1627 SimulateInputChangeForElement("someOtherPassword",
1628 /*move_caret_to_end=*/true,
1629 GetMainFrame(),
1630 password_element_,
1631 /*is_user_input=*/true);
1633 // Simulate the user typing a stored username.
1634 SimulateUsernameChange(kAliceUsername, true);
1635 // The autofileld password should replace the typed one.
1636 CheckTextFieldsDOMState(kAliceUsername, true, kAlicePassword, true);
1639 // The user types in a username and a password, but then just before sending
1640 // the form off, a script changes them. This test checks that
1641 // PasswordAutofillAgent can still remember the username and the password
1642 // typed by the user.
1643 TEST_F(PasswordAutofillAgentTest,
1644 RememberLastTypedUsernameAndPasswordOnSubmit_ScriptChanged) {
1645 SimulateInputChangeForElement("temp", true, GetMainFrame(), username_element_,
1646 true);
1647 SimulateInputChangeForElement("random", true, GetMainFrame(),
1648 password_element_, true);
1650 // Simulate that the username and the password value was changed by the
1651 // site's JavaScript before submit.
1652 username_element_.setValue(WebString("new username"));
1653 password_element_.setValue(WebString("new password"));
1654 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1655 ->WillSendSubmitEvent(username_element_.form());
1656 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1657 ->WillSubmitForm(username_element_.form());
1659 // Observe that the PasswordAutofillAgent still remembered the last typed
1660 // username and password and sent that to the browser.
1661 ExpectFormSubmittedWithUsernameAndPasswords("temp", "random", "");
1664 // The user starts typing username then it is autofilled.
1665 // PasswordAutofillAgent should remember the username that was autofilled,
1666 // not last typed.
1667 TEST_F(PasswordAutofillAgentTest, RememberAutofilledUsername) {
1668 SimulateInputChangeForElement("Te", true, GetMainFrame(), username_element_,
1669 true);
1670 // Simulate that the username was changed by autofilling.
1671 username_element_.setValue(WebString("temp"));
1672 SimulateInputChangeForElement("random", true, GetMainFrame(),
1673 password_element_, true);
1675 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1676 ->WillSendSubmitEvent(username_element_.form());
1677 static_cast<content::RenderFrameObserver*>(password_autofill_agent_)
1678 ->WillSubmitForm(username_element_.form());
1680 // Observe that the PasswordAutofillAgent still remembered the last typed
1681 // username and password and sent that to the browser.
1682 ExpectFormSubmittedWithUsernameAndPasswords("temp", "random", "");
1685 TEST_F(PasswordAutofillAgentTest, FormFillDataMustHaveUsername) {
1686 ClearUsernameAndPasswordFields();
1688 PasswordFormFillData no_username_fill_data = fill_data_;
1689 no_username_fill_data.username_field.name = base::string16();
1690 SimulateOnFillPasswordForm(no_username_fill_data);
1692 // The username and password should not have been autocompleted.
1693 CheckTextFieldsState("", false, "", false);
1696 TEST_F(PasswordAutofillAgentTest, FillOnAccountSelectOnly) {
1697 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1698 autofill::switches::kEnableFillOnAccountSelect);
1700 ClearUsernameAndPasswordFields();
1702 // Simulate the browser sending back the login info for an initial page load.
1703 SimulateOnFillPasswordForm(fill_data_);
1705 CheckTextFieldsState(std::string(), true, std::string(), false);
1708 TEST_F(PasswordAutofillAgentTest, FillOnAccountSelectOnlyReadonlyUsername) {
1709 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1710 autofill::switches::kEnableFillOnAccountSelect);
1712 ClearUsernameAndPasswordFields();
1714 username_element_.setValue("alice");
1715 SetElementReadOnly(username_element_, true);
1717 // Simulate the browser sending back the login info for an initial page load.
1718 SimulateOnFillPasswordForm(fill_data_);
1720 CheckTextFieldsState(std::string("alice"), false, std::string(), true);
1723 TEST_F(PasswordAutofillAgentTest,
1724 FillOnAccountSelectOnlyReadonlyNotPreferredUsername) {
1725 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1726 autofill::switches::kEnableFillOnAccountSelect);
1728 ClearUsernameAndPasswordFields();
1730 username_element_.setValue("Carol");
1731 SetElementReadOnly(username_element_, true);
1733 // Simulate the browser sending back the login info for an initial page load.
1734 SimulateOnFillPasswordForm(fill_data_);
1736 CheckTextFieldsState(std::string("Carol"), false, std::string(), true);
1739 TEST_F(PasswordAutofillAgentTest, FillOnAccountSelectOnlyNoUsername) {
1740 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1741 autofill::switches::kEnableFillOnAccountSelect);
1743 // Load a form with no username and update test data.
1744 LoadHTML(kVisibleFormWithNoUsernameHTML);
1745 username_element_.reset();
1746 WebDocument document = GetMainFrame()->document();
1747 WebElement element =
1748 document.getElementById(WebString::fromUTF8(kPasswordName));
1749 ASSERT_FALSE(element.isNull());
1750 password_element_ = element.to<blink::WebInputElement>();
1751 fill_data_.username_field = FormFieldData();
1752 UpdateOriginForHTML(kVisibleFormWithNoUsernameHTML);
1753 fill_data_.additional_logins.clear();
1754 fill_data_.other_possible_usernames.clear();
1756 password_element_.setValue("");
1757 password_element_.setAutofilled(false);
1759 // Simulate the browser sending back the login info for an initial page load.
1760 SimulateOnFillPasswordForm(fill_data_);
1762 EXPECT_TRUE(password_element_.suggestedValue().isEmpty());
1763 EXPECT_TRUE(password_element_.isAutofilled());
1766 TEST_F(PasswordAutofillAgentTest, ShowPopupNoUsername) {
1767 // Load a form with no username and update test data.
1768 LoadHTML(kVisibleFormWithNoUsernameHTML);
1769 username_element_.reset();
1770 WebDocument document = GetMainFrame()->document();
1771 WebElement element =
1772 document.getElementById(WebString::fromUTF8(kPasswordName));
1773 ASSERT_FALSE(element.isNull());
1774 password_element_ = element.to<blink::WebInputElement>();
1775 fill_data_.username_field = FormFieldData();
1776 UpdateOriginForHTML(kVisibleFormWithNoUsernameHTML);
1777 fill_data_.additional_logins.clear();
1778 fill_data_.other_possible_usernames.clear();
1780 password_element_.setValue("");
1781 password_element_.setAutofilled(false);
1783 // Simulate the browser sending back the login info for an initial page load.
1784 SimulateOnFillPasswordForm(fill_data_);
1786 password_element_.setValue("");
1787 password_element_.setAutofilled(false);
1789 SimulateSuggestionChoiceOfUsernameAndPassword(
1790 password_element_, base::string16(), ASCIIToUTF16(kAlicePassword));
1791 CheckSuggestions(std::string(), false);
1792 EXPECT_EQ(ASCIIToUTF16(kAlicePassword), password_element_.value());
1793 EXPECT_TRUE(password_element_.isAutofilled());
1796 // Tests with fill-on-account-select enabled that if the username element is
1797 // read-only and filled with an unknown username, then the password field is not
1798 // highlighted as autofillable (regression test for https://crbug.com/442564).
1799 TEST_F(PasswordAutofillAgentTest,
1800 FillOnAccountSelectOnlyReadonlyUnknownUsername) {
1801 base::CommandLine::ForCurrentProcess()->AppendSwitch(
1802 autofill::switches::kEnableFillOnAccountSelect);
1804 ClearUsernameAndPasswordFields();
1806 username_element_.setValue("foobar");
1807 SetElementReadOnly(username_element_, true);
1809 CheckTextFieldsState(std::string("foobar"), false, std::string(), false);
1812 } // namespace autofill