File: autofill_suggestion_controller_test_base.h

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 (265 lines) | stat: -rw-r--r-- 11,118 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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_SUGGESTION_CONTROLLER_TEST_BASE_H_
#define CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_SUGGESTION_CONTROLLER_TEST_BASE_H_

#include <concepts>
#include <memory>
#include <optional>
#include <utility>

#include "base/functional/callback.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/ui/autofill/autofill_popup_view.h"
#include "chrome/browser/ui/autofill/mock_autofill_popup_view.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "components/autofill/content/browser/content_autofill_driver.h"
#include "components/autofill/content/browser/test_autofill_client_injector.h"
#include "components/autofill/content/browser/test_autofill_driver_injector.h"
#include "components/autofill/content/browser/test_autofill_manager_injector.h"
#include "components/autofill/content/browser/test_content_autofill_client.h"
#include "components/autofill/core/browser/foundations/browser_autofill_manager.h"
#include "components/autofill/core/browser/ui/autofill_external_delegate.h"
#include "components/autofill/core/browser/ui/autofill_suggestion_delegate.h"
#include "components/autofill/core/browser/ui/suggestion_button_action.h"
#include "components/autofill/core/common/autofill_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_ANDROID)
#include "chrome/browser/autofill/mock_manual_filling_view.h"
#include "chrome/browser/keyboard_accessory/android/manual_filling_controller_impl.h"
#include "chrome/browser/keyboard_accessory/test_utils/android/mock_address_accessory_controller.h"
#include "chrome/browser/keyboard_accessory/test_utils/android/mock_password_accessory_controller.h"
#include "chrome/browser/keyboard_accessory/test_utils/android/mock_payment_method_accessory_controller.h"
#include "chrome/browser/ui/autofill/autofill_keyboard_accessory_controller_impl.h"
#else
#include "chrome/browser/ui/autofill/autofill_popup_controller_impl.h"
#endif  // BUILDFLAG(IS_ANDROID)

namespace autofill {

class AutofillExternalDelegateForPopupTest;
class AutofillSuggestionControllerForTest;

// A `BrowserAutofillManager` with a modified `AutofillExternalDelegate` that
// allows verifying interactions with the popup.
class BrowserAutofillManagerForPopupTest : public BrowserAutofillManager {
 public:
  explicit BrowserAutofillManagerForPopupTest(AutofillDriver* driver);
  ~BrowserAutofillManagerForPopupTest() override;

  AutofillExternalDelegateForPopupTest& external_delegate();
};

// This text fixture is intended for unit tests of the Autofill popup
// controller, which controls the Autofill popup on Desktop and the Keyboard
// Accessory on Clank. It has two template parameters that allow customizing the
// test fixture's behavior:
// - The class of the `AutofillSuggestionController` to test. The use of this
//   parameter is to be able to test different implementations of the
//   `AutofillSuggestionController` interface.
// - The class of the `AutofillDriver` to inject, used, e.g., in a11y-specific
//   tests.
//
// The main reason for the complexity of the test fixture is that there is
// little value in testing an `AutofillSuggestionController` just by itself:
// Most of its behavior depends on interactions with the `WebContents`, the
// `AutofillClient`, or the `AutofillPopupView`. This test fixture sets these up
// in a way that allows for controller testing.
//
// Once setup, the test fixture should allow writing suggestion controller unit
// tests (on both Desktop and Android) that closely mirror the production setup.
// Example for Desktop:
//
// using SampleTest = AutofillSuggestionControllerTestBase<
//     TestAutofillPopupControllerAutofillClient<>>;
//
// TEST_F(SampleTest, AcceptSuggestionWorksAfter500Ms) {
//   ShowSuggestions(manager(), {SuggestionType::kAddressEntry});
//   EXPECT_CALL(manager().external_delegate(), DidAcceptSuggestion);
//   task_environment()->FastForwardBy(base::Milliseconds(500));
//   client().popup_controller(manager()).AcceptSuggestion(/*index=*/0);
// }
//
// The same test can be run on for the Keyboard Accessory on Android by simply
// changing the test fixture template parameter:
//
// using SampleTest = AutofillSuggestionControllerTestBase<
//     TestAutofillKeyboardAccessoryControllerAutofillClient<>>;
template <typename Client, typename Driver = ContentAutofillDriver>
  requires(std::derived_from<Client, ContentAutofillClient> &&
           std::derived_from<Driver, ContentAutofillDriver>)
class AutofillSuggestionControllerTestBase
    : public ChromeRenderViewHostTestHarness {
 public:
  AutofillSuggestionControllerTestBase()
      : ChromeRenderViewHostTestHarness(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
  ~AutofillSuggestionControllerTestBase() override = default;

  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
    PersonalDataManagerFactory::GetInstance()->SetTestingFactory(
        profile(), base::BindRepeating([](content::BrowserContext* context)
                                           -> std::unique_ptr<KeyedService> {
          return std::make_unique<TestPersonalDataManager>();
        }));
    NavigateAndCommit(GURL("https://foo.com/"));
    FocusWebContentsOnMainFrame();
    ASSERT_TRUE(web_contents()->GetFocusedFrame());

#if BUILDFLAG(IS_ANDROID)
    ManualFillingControllerImpl::CreateForWebContentsForTesting(
        web_contents(), mock_pwd_controller_.AsWeakPtr(),
        mock_address_controller_.AsWeakPtr(),
        mock_payment_method_controller_.AsWeakPtr(),
        std::make_unique<::testing::NiceMock<MockManualFillingView>>());
#endif  // BUILDFLAG(IS_ANDROID)
  }

  void TearDown() override {
    // Wait for the pending deletion of the controllers. Otherwise, the
    // controllers are destroyed after the WebContents, and each of them
    // receives a final Hide() call for which we'd need to add explicit
    // expectations.
    task_environment()->RunUntilIdle();
    ChromeRenderViewHostTestHarness::TearDown();
  }

  using Manager = BrowserAutofillManagerForPopupTest;

  content::RenderFrameHost* main_frame() {
    return web_contents()->GetPrimaryMainFrame();
  }

  Client& client() { return *autofill_client_injector_[web_contents()]; }

  Driver& driver(content::RenderFrameHost* rfh = nullptr) {
    return *autofill_driver_injector_[rfh ? rfh : main_frame()];
  }

  Manager& manager(content::RenderFrameHost* rfh = nullptr) {
    return *autofill_manager_injector_[rfh ? rfh : main_frame()];
  }

  TestPersonalDataManager& personal_data() {
    return static_cast<TestPersonalDataManager&>(
        *PersonalDataManagerFactory::GetForBrowserContext(profile()));
  }

  // Shows empty suggestions with the type ids passed as
  // `types`.
  void ShowSuggestions(
      Manager& manager,
      const std::vector<SuggestionType>& types,
      AutofillSuggestionTriggerSource trigger_source =
          AutofillSuggestionTriggerSource::kFormControlElementClicked) {
    std::vector<Suggestion> suggestions;
    suggestions.reserve(types.size());
    for (SuggestionType type : types) {
      suggestions.emplace_back(u"", type);
    }
    ShowSuggestions(manager, std::move(suggestions), trigger_source);
  }

  void ShowSuggestions(
      Manager& manager,
      std::vector<Suggestion> suggestions,
      AutofillSuggestionTriggerSource trigger_source =
          AutofillSuggestionTriggerSource::kFormControlElementClicked) {
    FocusWebContentsOnFrame(
        static_cast<ContentAutofillDriver&>(manager.driver())
            .render_frame_host());
    client().popup_controller(manager).Show(
        AutofillSuggestionController::GenerateSuggestionUiSessionId(),
        std::move(suggestions), trigger_source,
        AutoselectFirstSuggestion(false));
  }

  input::NativeWebKeyboardEvent CreateKeyPressEvent(int windows_key_code) {
    input::NativeWebKeyboardEvent event(
        blink::WebInputEvent::Type::kRawKeyDown,
        blink::WebInputEvent::kNoModifiers,
        blink::WebInputEvent::GetStaticTimeStampForTests());
    event.windows_key_code = windows_key_code;
    return event;
  }

 private:
  ::autofill::test::AutofillUnitTestEnvironment autofill_test_environment_;

  TestAutofillClientInjector<Client> autofill_client_injector_;
  TestAutofillDriverInjector<Driver> autofill_driver_injector_;
  TestAutofillManagerInjector<Manager> autofill_manager_injector_;

#if BUILDFLAG(IS_ANDROID)
  ::testing::NiceMock<MockPasswordAccessoryController> mock_pwd_controller_;
  ::testing::NiceMock<MockAddressAccessoryController> mock_address_controller_;
  ::testing::NiceMock<MockPaymentMethodAccessoryController>
      mock_payment_method_controller_;
#endif  // BUILDFLAG(IS_ANDROID)
};

// Below are test versions of `AutofillClient`, `BrowserAutofillManager`,
// `AutofillExternalDelegate` and `AutofillSuggestionController` that are used
// in the fixture above.

class AutofillExternalDelegateForPopupTest : public AutofillExternalDelegate {
 public:
  explicit AutofillExternalDelegateForPopupTest(
      BrowserAutofillManager* autofill_manager);
  ~AutofillExternalDelegateForPopupTest() override;

  MOCK_METHOD(void, ClearPreviewedForm, (), (override));
  MOCK_METHOD(void,
              OnSuggestionsShown,
              (base::span<const Suggestion>),
              (override));
  MOCK_METHOD(void, OnSuggestionsHidden, (), (override));
  MOCK_METHOD(void, DidSelectSuggestion, (const Suggestion&), (override));
  MOCK_METHOD(void,
              DidAcceptSuggestion,
              (const Suggestion&,
               const AutofillSuggestionDelegate::SuggestionMetadata&),
              (override));
  MOCK_METHOD(void,
              DidPerformButtonActionForSuggestion,
              (const Suggestion&, const SuggestionButtonAction&),
              (override));
  MOCK_METHOD(bool, RemoveSuggestion, (const Suggestion&), (override));
};

using AutofillSuggestionControllerForTestBase =
#if BUILDFLAG(IS_ANDROID)
    AutofillKeyboardAccessoryControllerImpl;
#else
    AutofillPopupControllerImpl;
#endif

class AutofillSuggestionControllerForTest
    : public AutofillSuggestionControllerForTestBase {
 public:
  AutofillSuggestionControllerForTest(
      base::WeakPtr<AutofillExternalDelegate> external_delegate,
      content::WebContents* web_contents,
      const gfx::RectF& element_bounds
  );
  ~AutofillSuggestionControllerForTest() override;

  // Making protected functions public for testing
  using AutofillSuggestionControllerForTestBase::element_bounds;
  MOCK_METHOD(void, Hide, (SuggestionHidingReason reason), (override));

  void DoHide(
      SuggestionHidingReason reason = SuggestionHidingReason::kTabGone) {
    AutofillSuggestionControllerForTestBase::Hide(reason);
  }
};

}  // namespace autofill

#endif  // CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_SUGGESTION_CONTROLLER_TEST_BASE_H_