File: card_unmask_prompt_view_browsertest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (301 lines) | stat: -rw-r--r-- 11,157 bytes parent folder | download | duplicates (5)
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
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/core/browser/ui/payments/card_unmask_prompt_view.h"

#include <string_view>

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "chrome/browser/ui/autofill/payments/card_unmask_prompt_view_tester.h"
#include "chrome/browser/ui/autofill/payments/create_card_unmask_prompt_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/test/test_browser_dialog.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "components/autofill/core/browser/payments/card_unmask_delegate.h"
#include "components/autofill/core/browser/payments/payments_autofill_client.h"
#include "components/autofill/core/browser/test_utils/autofill_test_utils.h"
#include "components/autofill/core/browser/ui/payments/card_unmask_prompt_controller_impl.h"
#include "components/autofill/core/browser/ui/payments/card_unmask_prompt_options.h"
#include "components/user_prefs/user_prefs.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_utils.h"

namespace autofill {

namespace {

// Forms of the dialog that can be invoked.
constexpr const char kExpiryExpired[] = "expired";
constexpr const char kExpiryValidTemporaryError[] = "valid_TemporaryError";
constexpr const char kExpiryValidPermanentError[] = "valid_PermanentError";

class TestCardUnmaskDelegate : public CardUnmaskDelegate {
 public:
  TestCardUnmaskDelegate() = default;

  TestCardUnmaskDelegate(const TestCardUnmaskDelegate&) = delete;
  TestCardUnmaskDelegate& operator=(const TestCardUnmaskDelegate&) = delete;

  ~TestCardUnmaskDelegate() override = default;

  // CardUnmaskDelegate:
  void OnUnmaskPromptAccepted(
      const UserProvidedUnmaskDetails& details) override {
    details_ = details;
  }
  void OnUnmaskPromptCancelled() override {}
  bool ShouldOfferFidoAuth() const override { return false; }

  base::WeakPtr<TestCardUnmaskDelegate> GetWeakPtr() {
    return weak_factory_.GetWeakPtr();
  }

  UserProvidedUnmaskDetails details() { return details_; }

 private:
  UserProvidedUnmaskDetails details_;

  base::WeakPtrFactory<TestCardUnmaskDelegate> weak_factory_{this};
};

class TestCardUnmaskPromptController : public CardUnmaskPromptControllerImpl {
 public:
  TestCardUnmaskPromptController(
      content::WebContents* contents,
      scoped_refptr<content::MessageLoopRunner> runner,
      const CreditCard& card,
      const CardUnmaskPromptOptions& card_unmask_prompt_options,
      base::WeakPtr<CardUnmaskDelegate> delegate)
      : CardUnmaskPromptControllerImpl(
            user_prefs::UserPrefs::Get(contents->GetBrowserContext()),
            card,
            card_unmask_prompt_options,
            delegate),
        runner_(runner) {}
  TestCardUnmaskPromptController(const TestCardUnmaskPromptController&) =
      delete;
  TestCardUnmaskPromptController& operator=(
      const TestCardUnmaskPromptController&) = delete;

  // CardUnmaskPromptControllerImpl:.
  // When the confirm button is clicked.
  void OnUnmaskPromptAccepted(std::u16string_view cvc,
                              const std::u16string& exp_month,
                              const std::u16string& exp_year,
                              bool enable_fido_auth,
                              bool was_checkbox_visible) override {
    // Call the original implementation.
    CardUnmaskPromptControllerImpl::OnUnmaskPromptAccepted(
        cvc, exp_month, exp_year, enable_fido_auth, was_checkbox_visible);

    // Wait some time and show verification result. An empty message means
    // success is shown.
    std::u16string verification_message;
    if (expected_failure_temporary_) {
      verification_message = u"Check your CVC and try again";
    } else if (expected_failure_permanent_) {
      verification_message = u"This card can't be verified right now.";
    }
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&TestCardUnmaskPromptController::ShowVerificationResult,
                       weak_factory_.GetWeakPtr(), verification_message,
                       /*allow_retry=*/expected_failure_temporary_),
        GetSuccessMessageDuration());
  }

  base::TimeDelta GetSuccessMessageDuration() const override {
    // Change this to ~4000 if you're in --test-launcher-interactive mode and
    // would like to see the progress/success overlay.
    return base::Milliseconds(10);
  }

  payments::PaymentsAutofillClient::PaymentsRpcResult GetVerificationResult()
      const override {
    if (expected_failure_temporary_) {
      return payments::PaymentsAutofillClient::PaymentsRpcResult::
          kTryAgainFailure;
    }
    if (expected_failure_permanent_) {
      return payments::PaymentsAutofillClient::PaymentsRpcResult::
          kPermanentFailure;
    }

    return payments::PaymentsAutofillClient::PaymentsRpcResult::kSuccess;
  }

  void set_expected_verification_failure(bool allow_retry) {
    if (allow_retry) {
      expected_failure_temporary_ = true;
    } else {
      expected_failure_permanent_ = true;
    }
  }

  using CardUnmaskPromptControllerImpl::view;

 private:
  void ShowVerificationResult(const std::u16string& verification_message,
                              bool allow_retry) {
    // It's possible the prompt has been closed.
    if (!view()) {
      return;
    }
    view()->GotVerificationResult(verification_message, allow_retry);
  }

  bool expected_failure_temporary_ = false;
  bool expected_failure_permanent_ = false;
  const scoped_refptr<content::MessageLoopRunner> runner_;
  base::WeakPtrFactory<TestCardUnmaskPromptController> weak_factory_{this};
};

class CardUnmaskPromptViewBrowserTest : public DialogBrowserTest {
 public:
  CardUnmaskPromptViewBrowserTest() = default;

  CardUnmaskPromptViewBrowserTest(const CardUnmaskPromptViewBrowserTest&) =
      delete;
  CardUnmaskPromptViewBrowserTest& operator=(
      const CardUnmaskPromptViewBrowserTest&) = delete;

  ~CardUnmaskPromptViewBrowserTest() override = default;

  // DialogBrowserTest:
  void SetUpOnMainThread() override {
    runner_ = new content::MessageLoopRunner;

    delegate_ = std::make_unique<TestCardUnmaskDelegate>();
  }

  void TearDownOnMainThread() override {
    controller_.reset();
    DialogBrowserTest::TearDownOnMainThread();
  }

  void ShowUi(const std::string& name) override {
    CreditCard card = test::GetMaskedServerCard();
    if (name == kExpiryExpired) {
      card.SetExpirationYear(2016);
    }

    CardUnmaskPromptOptions card_unmask_prompt_options =
        CardUnmaskPromptOptions(
            /*challenge_option=*/
            std::nullopt,
            payments::PaymentsAutofillClient::UnmaskCardReason::kAutofill);
    controller_ = std::make_unique<TestCardUnmaskPromptController>(
        contents(), runner_, card, card_unmask_prompt_options,
        delegate_->GetWeakPtr());
    controller_->ShowPrompt(base::BindOnce(&CreateCardUnmaskPromptView,
                                           base::Unretained(controller()),
                                           base::Unretained(contents())));
    // Setting error expectations and confirming the dialogs for some test
    // cases.
    if (name == kExpiryValidPermanentError ||
        name == kExpiryValidTemporaryError) {
      controller_->set_expected_verification_failure(
          /*allow_retry*/ name == kExpiryValidTemporaryError);
      CardUnmaskPromptViewTester::For(controller()->view())
          ->EnterCVCAndAccept(u"123");
    }
  }

  void FreeDelegate() { delegate_.reset(); }

  content::WebContents* contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }
  TestCardUnmaskPromptController* controller() { return controller_.get(); }
  TestCardUnmaskDelegate* delegate() { return delegate_.get(); }

 protected:
  // This member must outlive the controller.
  scoped_refptr<content::MessageLoopRunner> runner_;

 private:
  std::unique_ptr<TestCardUnmaskPromptController> controller_;
  std::unique_ptr<TestCardUnmaskDelegate> delegate_;
};

IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest, InvokeUi_expired) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest, InvokeUi_valid) {
  ShowAndVerifyUi();
}

// This dialog will show a temporary error when Confirm is clicked.
IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest,
                       InvokeUi_valid_TemporaryError) {
  ShowAndVerifyUi();
}

// This dialog will show a permanent error when Confirm is clicked.
IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest,
                       InvokeUi_valid_PermanentError) {
  ShowAndVerifyUi();
}

IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest, DisplayUI) {
  ShowUi(kExpiryExpired);
}

// Makes sure the user can close the dialog while the verification success
// message is showing.
IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest,
                       EarlyCloseAfterSuccess) {
  ShowUi(kExpiryExpired);
  controller()->OnUnmaskPromptAccepted(u"123", u"10",
                                       base::ASCIIToUTF16(test::NextYear()),
                                       /*enable_fido_auth=*/false,
                                       /*was_checkbox_visible=*/false);
  EXPECT_EQ(u"123", delegate()->details().cvc);
  controller()->OnVerificationResult(
      payments::PaymentsAutofillClient::PaymentsRpcResult::kSuccess);

  // Simulate the user clicking [x] before the "Success!" message disappears.
  CardUnmaskPromptViewTester::For(controller()->view())->Close();
  // Wait a little while; there should be no crash.
  base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE,
      base::BindOnce(&content::MessageLoopRunner::Quit,
                     base::Unretained(runner_.get())),
      2 * controller()->GetSuccessMessageDuration());
  runner_->Run();
}

// Makes sure the tab can be closed while the dialog is showing.
// https://crbug.com/484376
// TODO(crbug.com/409069597): Re-enable this test on Mac.
#if BUILDFLAG(IS_MAC)
#define MAYBE_CloseTabWhileDialogShowing DISABLED_CloseTabWhileDialogShowing
#else
#define MAYBE_CloseTabWhileDialogShowing CloseTabWhileDialogShowing
#endif
IN_PROC_BROWSER_TEST_F(CardUnmaskPromptViewBrowserTest,
                       MAYBE_CloseTabWhileDialogShowing) {
  ShowUi(kExpiryExpired);
  // Simulate BrowserAutofillManager (the delegate in production code) being
  // destroyed before CardUnmaskPromptViewBridge::OnConstrainedWindowClosed() is
  // called.
  FreeDelegate();
  contents()->Close();

  content::RunAllPendingInMessageLoop();
}

}  // namespace

}  // namespace autofill