File: password_generation_interactive_uitest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (584 lines) | stat: -rw-r--r-- 22,573 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "build/build_config.h"
#include "chrome/browser/password_manager/chrome_password_manager_client.h"
#include "chrome/browser/password_manager/password_manager_interactive_test_base.h"
#include "chrome/browser/password_manager/password_manager_uitest_util.h"
#include "chrome/browser/password_manager/passwords_navigation_observer.h"
#include "chrome/browser/password_manager/profile_password_store_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/passwords/password_generation_popup_observer.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/autofill/content/browser/content_autofill_client.h"
#include "components/autofill/content/browser/test_autofill_client_injector.h"
#include "components/autofill/core/browser/foundations/test_autofill_client.h"
#include "components/autofill/core/browser/test_utils/autofill_test_utils.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/password_manager/content/browser/content_password_manager_driver.h"
#include "components/password_manager/core/browser/features/password_features.h"
#include "components/password_manager/core/browser/password_form_manager.h"
#include "components/password_manager/core/browser/password_generation_frame_helper.h"
#include "components/password_manager/core/browser/password_manager_util.h"
#include "components/password_manager/core/browser/password_store/test_password_store.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/prerender_test_util.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/geometry/point_f.h"

namespace {

enum ReturnCodes {  // Possible results of the JavaScript code.
  RETURN_CODE_OK,
  RETURN_CODE_NO_ELEMENT,
  RETURN_CODE_INVALID,
};

}  // namespace

class PasswordGenerationInteractiveTest
    : public PasswordManagerInteractiveTestBase {
 public:
  void SetUpOnMainThread() override {
    PasswordManagerBrowserTestBase::SetUpOnMainThread();

    // Set observer for popup.
    ChromePasswordManagerClient* client =
        ChromePasswordManagerClient::FromWebContents(WebContents());
    client->SetTestObserver(&observer_);

    password_manager::PasswordFormManager::
        set_wait_for_server_predictions_for_filling(false);

    NavigateToFile("/password/signup_form_new_password.html");
  }

  void TearDownOnMainThread() override {
    // RunUntilIdle() is necessary because otherwise, under the hood
    // PasswordFormManager::OnFetchComplete() callback is run after this test is
    // destroyed meaning that OsCryptImpl will be used instead of OsCryptMocker,
    // causing this test to fail.
    base::RunLoop().RunUntilIdle();
    PasswordManagerBrowserTestBase::TearDownOnMainThread();
  }

  // Waits until the value of the field with id |field_id| becomes non-empty.
  void WaitForNonEmptyFieldValue(const std::string& field_id) {
    const std::string script = base::StringPrintf(
        "element = document.getElementById('%s');"
        "new Promise(resolve => {"
        "  if (!element) {"
        "    setTimeout(() => resolve(%d), 0);"
        "  }"
        "  if (element.value) {"
        "    setTimeout(() => resolve(%d), 0); "
        "  } else {"
        "    element.onchange = function() {"
        "      if (element.value) {"
        "        resove(%d);"
        "      }"
        "    }"
        "  }"
        "});",
        field_id.c_str(), RETURN_CODE_NO_ELEMENT, RETURN_CODE_OK,
        RETURN_CODE_OK);
    EXPECT_EQ(RETURN_CODE_OK,
              content::EvalJs(RenderFrameHost(), script,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  }

  void WaitForFieldFocused(const std::string& field_id) {
    const std::string script = base::StringPrintf(
        "element = document.getElementById('%s');"
        "new Promise(resolve => {"
        "  if (!element) {"
        "    resolve(%d);"
        "  }"
        "  if (document.activeElement && element.id == "
        "document.activeElement.id) {"
        "    resolve(%d);"
        "  } else {"
        "    element.onfocus = function() {"
        "      resolve(%d);"
        "      element.onfocus = undefined;"
        "    }"
        "  }"
        "});",
        field_id.c_str(), RETURN_CODE_NO_ELEMENT, RETURN_CODE_OK,
        RETURN_CODE_OK);
    EXPECT_EQ(RETURN_CODE_OK,
              content::EvalJs(RenderFrameHost(), script,
                              content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  }

  void WaitForPasswordFieldFocused() { WaitForFieldFocused("password_field"); }

  std::string GetFocusedElement() {
    return content::EvalJs(WebContents(), "document.activeElement.id")
        .ExtractString();
  }

  void SimulateMouseClickOrTapAt(content::RenderWidgetHost* rwh,
                                 gfx::PointF point) {
    blink::WebMouseEvent mouse_event(
        blink::WebInputEvent::Type::kMouseDown,
        blink::WebInputEvent::kNoModifiers,
        blink::WebInputEvent::GetStaticTimeStampForTests());
    mouse_event.button = blink::WebPointerProperties::Button::kLeft;
    mouse_event.SetPositionInWidget(point.x(), point.y());
    rwh->ForwardMouseEvent(mouse_event);
  }

  void FocusPasswordField() {
    content::SimulateMouseClickOrTapElementWithId(WebContents(),
                                                  "password_field");
    WaitForPasswordFieldFocused();
  }

  void FocusUsernameField() {
    ASSERT_TRUE(content::ExecJs(
        WebContents(), "document.getElementById('username_field').focus();"));
  }

  void SendKeyToPopup(ui::KeyboardCode key) {
    input::NativeWebKeyboardEvent event(
        blink::WebKeyboardEvent::Type::kRawKeyDown,
        blink::WebInputEvent::kNoModifiers,
        blink::WebInputEvent::GetStaticTimeStampForTests());
    event.windows_key_code = key;
    WebContents()
        ->GetPrimaryMainFrame()
        ->GetRenderViewHost()
        ->GetWidget()
        ->ForwardKeyboardEvent(event);
  }

  void NavigateToAndAcceptSuggestedPassword() {
    // Cancel button is the first focusable element, hence two down button
    // presses to reach the accept button.
    SendKeyToPopup(ui::VKEY_DOWN);
    SendKeyToPopup(ui::VKEY_DOWN);
    SendKeyToPopup(ui::VKEY_RETURN);
  }

  bool GenerationPopupShowing() {
    return observer_.popup_showing() &&
           observer_.state() ==
               PasswordGenerationPopupController::kOfferGeneration;
  }

  bool EditingPopupShowing() {
    return observer_.popup_showing() &&
           observer_.state() ==
               PasswordGenerationPopupController::kEditGeneratedPassword;
  }

  void WaitForStatus(TestGenerationPopupObserver::GenerationPopup status) {
    observer_.WaitForStatus(status);
  }

  void WaitForGenerationPopupShowing() {
    if (GenerationPopupShowing()) {
      return;
    }
    observer_.WaitForStatusChange();
    EXPECT_TRUE(GenerationPopupShowing());
  }

  void WaitForEditingPopupShowing() {
    if (EditingPopupShowing()) {
      return;
    }
    observer_.WaitForStatusChange();
    EXPECT_TRUE(EditingPopupShowing());
  }

 private:
  TestGenerationPopupObserver observer_;
};

// A test fixture that injects an `ObservingAutofillClient` into newly created
// tabs to allow waiting for an Autofill popup to open.
class PasswordGenerationAutofillPopupInteractiveTest
    : public PasswordGenerationInteractiveTest {
 protected:
  ObservingAutofillClient& autofill_client() {
    return *autofill_client_injector_[WebContents()];
  }

 private:
  autofill::TestAutofillClientInjector<ObservingAutofillClient>
      autofill_client_injector_;
};

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       PopupShownAndPasswordSelected) {
  FocusPasswordField();
  WaitForGenerationPopupShowing();
  base::HistogramTester histogram_tester;
  NavigateToAndAcceptSuggestedPassword();

  // Selecting the password should fill the field and move focus to the
  // submit button.
  WaitForNonEmptyFieldValue("password_field");
  EXPECT_FALSE(GenerationPopupShowing());
  EXPECT_FALSE(EditingPopupShowing());
  EXPECT_EQ("input_submit_button", GetFocusedElement());

  // Re-focusing the password field should show the editing popup.
  FocusPasswordField();
  WaitForEditingPopupShowing();

  // The metrics are recorded when the form manager is destroyed. Closing the
  // tab enforces it.
  ClearWebContentsPtr();
  CloseAllBrowsers();
  histogram_tester.ExpectUniqueSample(
      "PasswordGeneration.UserDecision",
      password_manager::PasswordFormMetricsRecorder::GeneratedPasswordStatus::
          kPasswordAccepted,
      1);
}

// TODO(http://crbug.com/382272011): Re-enable this test after flakiness is
// resolved.
IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       DISABLED_PopupShownAutomaticallyAndPasswordErased) {
  FocusPasswordField();
  WaitForGenerationPopupShowing();
  NavigateToAndAcceptSuggestedPassword();

  // Wait until the password is filled.
  WaitForNonEmptyFieldValue("password_field");

  // Re-focusing the password field should show the editing popup.
  FocusPasswordField();
  WaitForEditingPopupShowing();

  // Delete the password. The generation prompt should be visible.
  base::HistogramTester histogram_tester;
  SimulateUserDeletingFieldContent("password_field");
  WaitForGenerationPopupShowing();

  // The metrics are recorded on navigation when the frame is destroyed.
  NavigateToFile("/password/done.html");
  histogram_tester.ExpectUniqueSample(
      "PasswordGeneration.UserDecision",
      password_manager::PasswordFormMetricsRecorder::GeneratedPasswordStatus::
          kPasswordDeleted,
      1);
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       PopupShownManuallyAndPasswordErased) {
  NavigateToFile("/password/password_form.html");
  FocusPasswordField();
  EXPECT_FALSE(GenerationPopupShowing());
  // The same flow happens when user generates a password from the context menu.
  password_manager_util::UserTriggeredManualGenerationFromContextMenu(
      ChromePasswordManagerClient::FromWebContents(WebContents()),
      autofill::ContentAutofillClient::FromWebContents(WebContents()));
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kShown);
  EXPECT_TRUE(GenerationPopupShowing());
  NavigateToAndAcceptSuggestedPassword();

  // Wait until the password is filled.
  WaitForNonEmptyFieldValue("password_field");

  // Re-focusing the password field should show the editing popup.
  FocusPasswordField();
  WaitForEditingPopupShowing();

  // Delete the password. The generation prompt should not be visible.
  SimulateUserDeletingFieldContent("password_field");
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kHidden);
  EXPECT_FALSE(EditingPopupShowing());
  EXPECT_FALSE(GenerationPopupShowing());
}

// Verify that tapping the password field does not trigger the suggestion popup
// when user triggered the generation popup first (either by choosing it from
// suggestions popup with generation or context menu).
IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       SuggestionsPopupIsNotShownWhenGenerationPopupVisible) {
  // Save the credentials since the autofill popup with generation and
  // password suggestion would not appear without stored passwords.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"random123";
  password_store->AddLogin(signin_form);
  WaitForPasswordStore();
  NavigateToFile("/password/signup_form_new_password.html");

  FocusPasswordField();
  // The user generates a password from the context menu.
  password_manager_util::UserTriggeredManualGenerationFromContextMenu(
      ChromePasswordManagerClient::FromWebContents(WebContents()),
      autofill::ContentAutofillClient::FromWebContents(WebContents()));
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kShown);
  WaitForGenerationPopupShowing();
  EXPECT_TRUE(GenerationPopupShowing());

  // Click on the password field and check that generation popup is still shown.
  content::SimulateMouseClickOrTapElementWithId(WebContents(),
                                                "password_field");
  EXPECT_TRUE(GenerationPopupShowing());
}

// Verify that password suggestions popup is still showing up even after
// user rejected password generation.
IN_PROC_BROWSER_TEST_F(
    PasswordGenerationAutofillPopupInteractiveTest,
    PopupWithSuggestionsShowingUpAfterUserRejectedGeneration) {
  // Save a credential since the autofill popup with generation and
  // password suggestion would not appear otherwise.
  password_manager::PasswordStoreInterface* password_store =
      ProfilePasswordStoreFactory::GetForProfile(
          browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
          .get();
  password_manager::PasswordForm signin_form;
  signin_form.signon_realm = embedded_test_server()->base_url().spec();
  signin_form.username_value = u"temp";
  signin_form.password_value = u"random123";
  password_store->AddLogin(signin_form);
  WaitForPasswordStore();

  NavigateToFile("/password/signup_form_new_password.html");

  // Trigger password generation and reject by navigating to "Cancel" button.
  password_manager_util::UserTriggeredManualGenerationFromContextMenu(
      ChromePasswordManagerClient::FromWebContents(WebContents()),
      autofill::ContentAutofillClient::FromWebContents(WebContents()));
  SendKeyToPopup(ui::VKEY_DOWN);
  SendKeyToPopup(ui::VKEY_RETURN);
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kHidden);

  // Check that the suggestions popup still shows up on password field tap.
  content::SimulateMouseClickOrTapElementWithId(WebContents(),
                                                "password_field");
  autofill_client().WaitForAutofillPopup();
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       PopupShownAndDismissed) {
  FocusPasswordField();
  WaitForGenerationPopupShowing();

  FocusUsernameField();

  // Popup is dismissed.
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kHidden);
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       PopupShownAndDismissedByKeyPress) {
  FocusPasswordField();
  WaitForGenerationPopupShowing();

  SendKeyToPopup(ui::VKEY_ESCAPE);

  // Popup is dismissed.
  EXPECT_FALSE(GenerationPopupShowing());
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       PopupShownAndDismissedByScrolling) {
  FocusPasswordField();
  WaitForGenerationPopupShowing();

  ASSERT_TRUE(content::ExecJs(WebContents(), "window.scrollTo(100, 0);"));

  EXPECT_FALSE(GenerationPopupShowing());
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       GenerationTriggeredInIFrame) {
  NavigateToFile("/password/framed_signup_form.html");

  // Execute the script in the context of the iframe so that it kinda receives a
  // user gesture.
  content::RenderFrameHost* child_frame = ChildFrameAt(WebContents(), 0);
  gfx::PointF click_point =
      GetCenterCoordinatesOfElementWithId(child_frame, "password_field");
  SimulateMouseClickOrTapAt(child_frame->GetRenderWidgetHost(), click_point);

  WaitForGenerationPopupShowing();
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       GenerationTriggeredOnTap) {
  ASSERT_TRUE(content::ExecJs(
      RenderFrameHost(),
      "var submitRect = document.getElementById('password_field')"
      ".getBoundingClientRect();",
      content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  double y = content::EvalJs(RenderFrameHost(),
                             "(submitRect.top + submitRect.bottom) / 2;",
                             content::EXECUTE_SCRIPT_NO_USER_GESTURE)
                 .ExtractDouble();
  double x = content::EvalJs(RenderFrameHost(),
                             "(submitRect.left + submitRect.right) / 2;",
                             content::EXECUTE_SCRIPT_NO_USER_GESTURE)
                 .ExtractDouble();

  // Tap in the middle of the field.
  content::SimulateTapAt(WebContents(),
                         gfx::Point(static_cast<int>(x), static_cast<int>(y)));
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kShown);
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       GenerationTriggeredOnClick) {
  ASSERT_TRUE(content::ExecJs(
      RenderFrameHost(),
      "var submitRect = document.getElementById('password_field')"
      ".getBoundingClientRect();",
      content::EXECUTE_SCRIPT_NO_USER_GESTURE));
  double y = content::EvalJs(RenderFrameHost(),
                             "(submitRect.top + submitRect.bottom) / 2;",
                             content::EXECUTE_SCRIPT_NO_USER_GESTURE)
                 .ExtractDouble();
  double x = content::EvalJs(RenderFrameHost(),
                             "(submitRect.left + submitRect.right) / 2;",
                             content::EXECUTE_SCRIPT_NO_USER_GESTURE)
                 .ExtractDouble();

  // Click in the middle of the field.
  content::SimulateMouseClickAt(
      WebContents(), 0, blink::WebMouseEvent::Button::kLeft,
      gfx::Point(static_cast<int>(x), static_cast<int>(y)));
  WaitForStatus(TestGenerationPopupObserver::GenerationPopup::kShown);
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       AutoSavingGeneratedPassword) {
  scoped_refptr<password_manager::TestPasswordStore> password_store =
      static_cast<password_manager::TestPasswordStore*>(
          ProfilePasswordStoreFactory::GetForProfile(
              browser()->profile(), ServiceAccessType::IMPLICIT_ACCESS)
              .get());

  FocusPasswordField();
  WaitForGenerationPopupShowing();
  NavigateToAndAcceptSuggestedPassword();

  // Change username.
  FocusUsernameField();
  content::SimulateKeyPress(WebContents(), ui::DomKey::FromCharacter('U'),
                            ui::DomCode::US_U, ui::VKEY_U, false, false, false,
                            false);
  content::SimulateKeyPress(WebContents(), ui::DomKey::FromCharacter('N'),
                            ui::DomCode::US_N, ui::VKEY_N, false, false, false,
                            false);

  // Submit form.
  PasswordsNavigationObserver observer(WebContents());
  std::string submit_script =
      "document.getElementById('input_submit_button').click()";
  ASSERT_TRUE(content::ExecJs(WebContents(), submit_script));
  ASSERT_TRUE(observer.Wait());

  WaitForPasswordStore();
  EXPECT_FALSE(password_store->IsEmpty());

  // Make sure the username is correct.
  password_manager::TestPasswordStore::PasswordMap stored_passwords =
      password_store->stored_passwords();
  EXPECT_EQ(1u, stored_passwords.size());
  EXPECT_EQ(1u, stored_passwords.begin()->second.size());
  EXPECT_EQ(u"UN", (stored_passwords.begin()->second)[0].username_value);
}

// Verify that navigating away closes the popup.
IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       NavigatingAwayClosesPopup) {
  // Open popup.
  FocusPasswordField();
  WaitForGenerationPopupShowing();

  // Simulate navigating to a different page.
  NavigateToFile("/password/signup_form.html");

  // Check that popup is dismissed.
  EXPECT_FALSE(GenerationPopupShowing());
}

IN_PROC_BROWSER_TEST_F(PasswordGenerationInteractiveTest,
                       GenerationPopupNotShownAfterUserRejected) {
  FocusPasswordField();
  WaitForGenerationPopupShowing();

  // Reject generation by navigating to "Cancel" button.
  SendKeyToPopup(ui::VKEY_DOWN);
  SendKeyToPopup(ui::VKEY_RETURN);

  FocusPasswordField();
  EXPECT_FALSE(GenerationPopupShowing());
}

class PasswordGenerationPopupViewPrerenderingTest
    : public PasswordGenerationInteractiveTest {
 public:
  PasswordGenerationPopupViewPrerenderingTest()
      : prerender_helper_(base::BindRepeating(
            &PasswordGenerationPopupViewPrerenderingTest::WebContents,
            base::Unretained(this))) {}
  ~PasswordGenerationPopupViewPrerenderingTest() override = default;

  void SetUp() override {
    prerender_helper_.RegisterServerRequestMonitor(embedded_test_server());
    PasswordGenerationInteractiveTest::SetUp();
  }

  content::test::PrerenderTestHelper* prerender_helper() {
    return &prerender_helper_;
  }

 protected:
  content::test::PrerenderTestHelper prerender_helper_;
};

IN_PROC_BROWSER_TEST_F(PasswordGenerationPopupViewPrerenderingTest,
                       PasswordGenerationPopupControllerInPrerendering) {
  // Open popup.
  FocusPasswordField();
  WaitForGenerationPopupShowing();

  auto prerender_url = embedded_test_server()->GetURL("/empty.html");
  // Loads a page in the prerender.
  content::FrameTreeNodeId host_id =
      prerender_helper()->AddPrerender(prerender_url);
  content::test::PrerenderHostObserver host_observer(*WebContents(), host_id);
  // It should keep the current popup controller since the prerenedering should
  // not affect the current page.
  EXPECT_TRUE(GenerationPopupShowing());

  // Navigates the primary page to the URL.
  prerender_helper()->NavigatePrimaryPage(prerender_url);
  // Makes sure that the page is activated from the prerendering.
  EXPECT_TRUE(host_observer.was_activated());
  // It should clear the current popup controller since the page loading deletes
  // the popup controller from the previous page.
  EXPECT_FALSE(GenerationPopupShowing());
}