File: iban_manager_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; 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 (781 lines) | stat: -rw-r--r-- 34,733 bytes parent folder | download | duplicates (2)
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
// Copyright 2022 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/payments/iban_manager.h"

#include <string_view>

#include "base/functional/callback_helpers.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/task_environment.h"
#include "base/uuid.h"
#include "components/autofill/core/browser/autofill_field.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/data_manager/payments/payments_data_manager.h"
#include "components/autofill/core/browser/data_manager/payments/test_payments_data_manager.h"
#include "components/autofill/core/browser/data_manager/test_personal_data_manager.h"
#include "components/autofill/core/browser/field_types.h"
#include "components/autofill/core/browser/form_structure_test_api.h"
#include "components/autofill/core/browser/foundations/test_autofill_client.h"
#include "components/autofill/core/browser/integrators/optimization_guide/mock_autofill_optimization_guide.h"
#include "components/autofill/core/browser/payments/iban_manager_test_api.h"
#include "components/autofill/core/browser/test_utils/autofill_test_utils.h"
#include "components/autofill/core/common/autofill_payments_features.h"
#include "components/grit/components_scaled_resources.h"
#include "components/strings/grit/components_strings.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/mock_resource_bundle_delegate.h"
#include "ui/gfx/image/image_unittest_util.h"

using testing::_;
using testing::Field;
using testing::IsEmpty;
using testing::Truly;
using testing::UnorderedElementsAre;

namespace autofill {
namespace {

constexpr char kNickname_0[] = "Nickname 0";
constexpr char kNickname_1[] = "Nickname 1";
constexpr char16_t kIbanValue[] = u"FR7630006000011234567890189";

using OnSuggestionsReturnedCallback =
    SingleFieldFillRouter::OnSuggestionsReturnedCallback;

// Extends base::MockCallback to get references to the underlying callback.
//
// This is convenient because the functions we test take mutable references to
// the callbacks, which can't bind to the result of
// base::MockCallback<T>::Get().
class MockSuggestionsReturnedCallback
    : public base::MockCallback<OnSuggestionsReturnedCallback> {
 public:
  OnSuggestionsReturnedCallback& GetNewRef() {
    callbacks_.push_back(Get());
    return callbacks_.back();
  }

 private:
  using base::MockCallback<OnSuggestionsReturnedCallback>::Get;

  std::list<OnSuggestionsReturnedCallback> callbacks_;
};

class IbanManagerTest : public testing::Test,
                        public testing::WithParamInterface<bool> {
 protected:
  IbanManagerTest() = default;

  void SetUp() override {
    feature_list_metadata_.InitWithFeatureStates(
        {{features::kAutofillEnableNewFopDisplayDesktop,
          IsNewFopDisplayEnabled()}});
    payments_data_manager().SetAutofillPaymentMethodsEnabled(true);
    original_resource_bundle_ =
        ui::ResourceBundle::SwapSharedInstanceForTesting(nullptr);
    form_structure_ = std::make_unique<FormStructure>(
        test::CreateTestIbanFormData(/*value=*/""));
    test_api(*form_structure_).SetFieldTypes({IBAN_VALUE});
    autofill_field_ = form_structure_->field(0);

    ui::ResourceBundle::InitSharedInstanceWithLocale(
        "en-US", &mock_resource_delegate_,
        ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);
    if (IsNewFopDisplayEnabled()) {
      ON_CALL(mock_resource_delegate_, GetImageNamed(IDR_AUTOFILL_IBAN))
          .WillByDefault(testing::Return(gfx::test::CreateImage(100, 50)));
    } else {
      ON_CALL(mock_resource_delegate_, GetImageNamed(IDR_AUTOFILL_IBAN_OLD))
          .WillByDefault(testing::Return(gfx::test::CreateImage(100, 50)));
    }

    ON_CALL(*autofill_client_.GetAutofillOptimizationGuide(),
            ShouldBlockSingleFieldSuggestions)
        .WillByDefault(testing::Return(false));
  }

  bool IsNewFopDisplayEnabled() const {
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_IOS)
    return false;
#else
    return GetParam();
#endif
  }

  void TearDown() override {
    ui::ResourceBundle::CleanupSharedInstance();
    ui::ResourceBundle::SwapSharedInstanceForTesting(original_resource_bundle_);
  }

  // Sets up the TestPersonalDataManager with a local IBAN.
  Iban SetUpLocalIban(std::string_view value, std::string_view nickname) {
    Iban iban;
    iban.set_value(base::UTF8ToUTF16(std::string(value)));
    iban.set_nickname(base::UTF8ToUTF16(std::string(nickname)));
    payments_data_manager().AddAsLocalIban(iban);
    return iban;
  }

  // Sets up the TestPersonalDataManager with a server IBAN.
  Iban SetUpServerIban(int64_t instrument_id,
                       std::string_view prefix,
                       std::string_view suffix,
                       std::string_view nickname) {
    Iban iban{Iban::InstrumentId(instrument_id)};
    iban.set_prefix(base::UTF8ToUTF16(std::string(prefix)));
    iban.set_suffix(base::UTF8ToUTF16(std::string(suffix)));
    iban.set_nickname(base::UTF8ToUTF16(std::string(nickname)));
    payments_data_manager().AddServerIban(iban);
    return iban;
  }

  // Get an IBAN suggestion with the given `iban`.
  Suggestion GetSuggestionForIban(const Iban& iban) {
    Suggestion iban_suggestion;
    const std::u16string iban_identifier =
        iban.GetIdentifierStringForAutofillDisplay();
    if constexpr (BUILDFLAG(IS_ANDROID)) {
      if (!iban.nickname().empty()) {
        iban_suggestion.main_text.value = iban.nickname();
        iban_suggestion.minor_texts.emplace_back(iban_identifier);
      } else {
        iban_suggestion.main_text.value = iban_identifier;
      }
    } else {
      if (iban.nickname().empty()) {
        iban_suggestion.main_text = Suggestion::Text(
            iban_identifier, Suggestion::Text::IsPrimary(true));
      } else {
        iban_suggestion.main_text = Suggestion::Text(
            iban.nickname(), Suggestion::Text::IsPrimary(true));
        iban_suggestion.labels = {{Suggestion::Text(iban_identifier)}};
      }
    }

    iban_suggestion.type = SuggestionType::kIbanEntry;
    if (iban.record_type() == Iban::kServerIban) {
      iban_suggestion.payload = Suggestion::InstrumentId(iban.instrument_id());
    } else {
      iban_suggestion.payload = Suggestion::Guid(iban.guid());
    }
    return iban_suggestion;
  }

  Suggestion SetUpSeparator() {
    Suggestion separator;
    separator.type = SuggestionType::kSeparator;
    return separator;
  }

  Suggestion SetUpFooterManagePaymentMethods() {
    Suggestion footer_suggestion(
        l10n_util::GetStringUTF16(IDS_AUTOFILL_MANAGE_PAYMENT_METHODS));
    footer_suggestion.type = SuggestionType::kManageIban;
    footer_suggestion.icon = Suggestion::Icon::kSettings;
    return footer_suggestion;
  }

  TestPaymentsDataManager& payments_data_manager() {
    return autofill_client_.GetPersonalDataManager()
        .test_payments_data_manager();
  }

  base::test::TaskEnvironment task_environment_;
  test::AutofillUnitTestEnvironment autofill_test_environment_;
  TestAutofillClient autofill_client_;
  std::unique_ptr<FormStructure> form_structure_;
  // Owned by `form_structure_`.
  raw_ptr<AutofillField> autofill_field_;
  IbanManager iban_manager_{
      &autofill_client_.GetPersonalDataManager().payments_data_manager()};
  testing::NiceMock<ui::MockResourceBundleDelegate> mock_resource_delegate_;
  raw_ptr<ui::ResourceBundle> original_resource_bundle_;
  base::test::ScopedFeatureList feature_list_metadata_;
};

INSTANTIATE_TEST_SUITE_P(IbanManagerTest, IbanManagerTest, ::testing::Bool());

MATCHER_P(MatchesTextAndSuggestionType, suggestion, "") {
  return arg.main_text == suggestion.main_text && arg.type == suggestion.type;
}

TEST_P(IbanManagerTest, ShowsAllIbanSuggestions) {
  payments_data_manager().SetAutofillWalletImportEnabled(true);
  Suggestion local_iban_suggestion_0 = GetSuggestionForIban(
      SetUpLocalIban("FR76 3000 6000 0112 3456 7890 189", kNickname_0));
  Suggestion local_iban_suggestion_1 = GetSuggestionForIban(
      SetUpLocalIban("CH56 0483 5012 3456 7800 9", kNickname_1));
  Suggestion server_iban_suggestion_0 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12345, /*prefix=*/"DE91", /*suffix=*/"6789",
      kNickname_0));
  Suggestion server_iban_suggestion_1 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12346, /*prefix=*/"BE71", /*suffix=*/"6769",
      kNickname_1));
  Suggestion separator_suggestion = SetUpSeparator();
  Suggestion footer_suggestion = SetUpFooterManagePaymentMethods();

  // Setting up mock to verify that the handler is returned a list of
  // IBAN-based suggestions.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(local_iban_suggestion_0),
                      MatchesTextAndSuggestionType(local_iban_suggestion_1),
                      MatchesTextAndSuggestionType(server_iban_suggestion_0),
                      MatchesTextAndSuggestionType(server_iban_suggestion_1),
                      MatchesTextAndSuggestionType(separator_suggestion),
                      MatchesTextAndSuggestionType(footer_suggestion))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

TEST_P(IbanManagerTest, PaymentsAutofillEnabledPrefOff_NoIbanSuggestionsShown) {
  payments_data_manager().SetAutofillPaymentMethodsEnabled(false);
  GetSuggestionForIban(SetUpLocalIban(test::kIbanValue, kNickname_0));
  GetSuggestionForIban(SetUpLocalIban(test::kIbanValue_1, kNickname_1));

  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);

  // Because the "Save and autofill payment methods" toggle is off, the
  // suggestion handler should not be triggered.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

TEST_P(IbanManagerTest, IbanSuggestions_SeparatorAndFooter) {
  Suggestion iban_suggestion_0 =
      GetSuggestionForIban(SetUpLocalIban(test::kIbanValue, kNickname_0));
  Suggestion iban_suggestion_1 = SetUpSeparator();
  Suggestion iban_suggestion_2 = SetUpFooterManagePaymentMethods();

  // Setting up mock to verify that the handler is returned IBAN-based
  // suggestions. A separator and the "Manage payment methods..." row should
  // also be returned.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(iban_suggestion_0),
                      MatchesTextAndSuggestionType(iban_suggestion_1),
                      MatchesTextAndSuggestionType(iban_suggestion_2))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

TEST_P(IbanManagerTest,
       OnGetSingleFieldSuggestions_FieldEqualsLocalIban_NothingReturned) {
  Suggestion iban_suggestion_0 = GetSuggestionForIban(
      SetUpLocalIban("CH93 0076 2011 6238 5295 7", kNickname_0));
  Suggestion iban_suggestion_1 = GetSuggestionForIban(
      SetUpLocalIban("CH56 0483 5012 3456 7800 9", kNickname_1));

  autofill_field_->set_value(u"CH5604835012345678009");

  // The field contains value matches existing IBAN already, so check that we
  // do not return suggestions to the handler.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);

  // Simulate request for suggestions.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

TEST_P(IbanManagerTest,
       OnGetSingleFieldSuggestions_LocalIbansMatchingPrefix_Shows) {
  Suggestion iban_suggestion_0 =
      GetSuggestionForIban(SetUpLocalIban(test::kIbanValue_1, kNickname_0));
  Suggestion iban_suggestion_1 =
      GetSuggestionForIban(SetUpLocalIban(test::kIbanValue_2, kNickname_1));
  Suggestion iban_suggestion_2 = SetUpSeparator();
  Suggestion iban_suggestion_3 = SetUpFooterManagePaymentMethods();

  autofill_field_->set_value(u"CH");

  // Setting up mock to verify that the handler is returned a list of
  // IBAN-based suggestions whose prefixes match `prefix_`. Both values should
  // be returned because they both start with CH56. Other than that, there are
  // one separator and one footer suggestion displayed.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(iban_suggestion_0),
                      MatchesTextAndSuggestionType(iban_suggestion_1),
                      MatchesTextAndSuggestionType(iban_suggestion_2),
                      MatchesTextAndSuggestionType(iban_suggestion_3))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));

  autofill_field_->set_value(u"CH5604");

  // Setting up mock to verify that the handler is returned only one
  // IBAN-based suggestion whose prefix matches `prefix_`. Only one of the two
  // IBANs should stay because the other will be filtered out. Other than
  // that, there are one separator and one footer suggestion displayed.
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(iban_suggestion_0),
                      MatchesTextAndSuggestionType(iban_suggestion_2),
                      MatchesTextAndSuggestionType(iban_suggestion_3))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));

  autofill_field_->set_value(u"AB56");

  // Verify that the handler is not triggered because no IBAN suggestions
  // match the given prefix.
  EXPECT_CALL(mock_callback, Run).Times(0);

  // Simulate request for suggestions.
  // Verify that no IBAN suggestions match the given prefix.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

// Test that when the input text field is shorter than IBAN's prefix, all
// IBANs with matching prefixes should be returned.
TEST_P(IbanManagerTest,
       OnGetSingleFieldSuggestions_ServerIbansMatchingPrefix_Shows_All) {
  payments_data_manager().SetAutofillWalletImportEnabled(true);
  // Set up two server IBANs with different prefixes except for the first two
  // characters, and with same suffixes and lengths.
  Suggestion server_iban_suggestion_0 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12345, /*prefix=*/"CH56", /*suffix=*/"8009",
      /*nickname=*/"My IBAN"));
  Suggestion server_iban_suggestion_1 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12346, /*prefix=*/"CH78", /*suffix=*/"8009",
      /*nickname=*/"My doctor's IBAN"));
  Suggestion separator_suggestion = SetUpSeparator();
  Suggestion footer_suggestion = SetUpFooterManagePaymentMethods();

  autofill_field_->set_value(u"CH");

  // Expect that a list of IBAN suggestions whose prefixes match input field
  // is returned because they both start with "CH". Other than that, there is
  // one separator and one footer suggestion displayed.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(server_iban_suggestion_0),
                      MatchesTextAndSuggestionType(server_iban_suggestion_1),
                      MatchesTextAndSuggestionType(separator_suggestion),
                      MatchesTextAndSuggestionType(footer_suggestion))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

// Test that when the input text field is shorter than IBAN's prefix, only
// IBANs with matching prefixes should be returned.
TEST_P(IbanManagerTest,
       OnGetSingleFieldSuggestions_ServerIbansMatchingPrefix_Shows_Some) {
  payments_data_manager().SetAutofillWalletImportEnabled(true);
  // Set up two server IBANs with different prefixes except for the first two
  // characters, and with same suffixes and lengths.
  Suggestion server_iban_suggestion_0 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12345, /*prefix=*/"CH56", /*suffix=*/"8009",
      /*nickname=*/"My IBAN"));
  Suggestion server_iban_suggestion_1 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12346, /*prefix=*/"CH78", /*suffix=*/"8009",
      /*nickname=*/"My doctor's IBAN"));
  Suggestion separator_suggestion = SetUpSeparator();
  Suggestion footer_suggestion = SetUpFooterManagePaymentMethods();

  autofill_field_->set_value(u"CH567");

  // Expect that only one of the two IBANs should stay because the other will
  // be filtered out. Other than that, there is one separator and one footer
  // suggestion displayed.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(server_iban_suggestion_0),
                      MatchesTextAndSuggestionType(separator_suggestion),
                      MatchesTextAndSuggestionType(footer_suggestion))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

// Test that when there is no prefix present, all server IBANs should be
// recommended when the character count of the input text is less than
// `kFieldLengthLimitOnServerIbanSuggestion`.
TEST_P(
    IbanManagerTest,
    OnGetSingleFieldSuggestions_ServerIbansLackingPrefix_ShowsIfFewCharsInField) {
  payments_data_manager().SetAutofillWalletImportEnabled(true);
  // Set up three server IBANs with empty `prefix`.
  Suggestion server_iban_suggestion_0 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12345, /*prefix=*/"", /*suffix=*/"8009",
      /*nickname=*/"My IBAN"));
  Suggestion server_iban_suggestion_1 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12346, /*prefix=*/"", /*suffix=*/"8009",
      /*nickname=*/"My doctor's IBAN"));
  Suggestion server_iban_suggestion_2 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12347, /*prefix=*/"", /*suffix=*/"9123",
      /*nickname=*/"My sister's IBAN"));
  Suggestion separator_suggestion = SetUpSeparator();
  Suggestion footer_suggestion = SetUpFooterManagePaymentMethods();

  // Expect that all server IBANs are returned.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(server_iban_suggestion_0),
                      MatchesTextAndSuggestionType(server_iban_suggestion_1),
                      MatchesTextAndSuggestionType(server_iban_suggestion_2),
                      MatchesTextAndSuggestionType(separator_suggestion),
                      MatchesTextAndSuggestionType(footer_suggestion))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));

  autofill_field_->set_value(u"AB567");

  // Expect that all server IBANs are returned because the count of input
  // character is less than `kFieldLengthLimitOnServerIbanSuggestion`.
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::UnorderedElementsAre(
                      MatchesTextAndSuggestionType(server_iban_suggestion_0),
                      MatchesTextAndSuggestionType(server_iban_suggestion_1),
                      MatchesTextAndSuggestionType(server_iban_suggestion_2),
                      MatchesTextAndSuggestionType(separator_suggestion),
                      MatchesTextAndSuggestionType(footer_suggestion))));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

// Test that when there is no prefix present, no server IBANs should be
// recommended if the length equals or exceeds
// `kFieldLengthLimitOnServerIbanSuggestion`.
TEST_P(
    IbanManagerTest,
    OnGetSingleFieldSuggestions_ServerIbansLackingPrefix_HidesIfManyCharsInField) {
  payments_data_manager().SetAutofillWalletImportEnabled(true);
  // Set up three server IBANs with empty `prefix`.
  Suggestion server_iban_suggestion_0 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12345, /*prefix=*/"", /*suffix=*/"8009",
      /*nickname=*/"My IBAN"));
  Suggestion server_iban_suggestion_1 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12346, /*prefix=*/"", /*suffix=*/"8009",
      /*nickname=*/"My doctor's IBAN"));
  Suggestion server_iban_suggestion_2 = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12347, /*prefix=*/"", /*suffix=*/"9123",
      /*nickname=*/"My sister's IBAN"));
  Suggestion separator_suggestion = SetUpSeparator();
  Suggestion footer_suggestion = SetUpFooterManagePaymentMethods();

  autofill_field_->set_value(u"AB5678");

  // Expect that no suggestions are returned because length of input field
  // exceeds `kFieldLengthLimitOnServerIbanSuggestion`.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);

  // Simulate request for suggestions.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

TEST_P(IbanManagerTest, DoesNotShowIbansForBlockedWebsite) {
  SetUpLocalIban(test::kIbanValue, kNickname_0);

  // Setting up mock to verify that suggestions returning is not triggered if
  // the website is blocked.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);
  ON_CALL(*autofill_client_.GetAutofillOptimizationGuide(),
          ShouldBlockSingleFieldSuggestions)
      .WillByDefault(testing::Return(true));

  // Simulate request for suggestions.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

// Test that suggestions are returned on platforms that don't have an
// AutofillOptimizationGuide. Having no AutofillOptimizationGuide means that
// suggestions cannot and will not be blocked.
TEST_P(IbanManagerTest, ShowsIbanSuggestions_OptimizationGuideNotPresent) {
  Suggestion iban_suggestion_0 =
      GetSuggestionForIban(SetUpLocalIban(test::kIbanValue, kNickname_0));

  // Delete the AutofillOptimizationGuide.
  autofill_client_.ResetAutofillOptimizationGuide();

  // Setting up mock to verify that the handler is returned a list of
  // IBAN-based suggestions.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback,
              Run(autofill_field_->global_id(),
                  testing::IsSupersetOf(
                      {MatchesTextAndSuggestionType(iban_suggestion_0)})));

  // Simulate request for suggestions.
  // Because all criteria are met to trigger returning to the handler,
  // the handler should be triggered and this should return true.
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

TEST_P(IbanManagerTest, NotIbanFieldFocused_NoSuggestionsShown) {
  SetUpLocalIban(test::kIbanValue, kNickname_0);

  autofill_field_->set_value(std::u16string(test::kIbanValue16));
  // Set the field type to any type than "IBAN_VALUE".
  autofill_field_->SetTypeTo(AutofillType(CREDIT_CARD_VERIFICATION_CODE),
                             AutofillPredictionSource::kHeuristics);

  // Setting up mock to verify that suggestions returning is not triggered if
  // we are not focused on an IBAN field.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);

  // Simulate request for suggestions.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
}

// Tests that when showing IBAN suggestions is allowed by the site-specific
// blocklist, appropriate metrics are logged.
TEST_P(IbanManagerTest, Metrics_Suggestions_Allowed) {
  base::HistogramTester histogram_tester;
  SetUpLocalIban(test::kIbanValue, kNickname_0);

  autofill_field_->set_renderer_id(test::MakeFieldRendererId());
  // Simulate request for suggestions.
  // TODO: handle return value.
  OnSuggestionsReturnedCallback do_nothing = base::DoNothing();
  std::ignore = iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_, do_nothing);

  histogram_tester.ExpectUniqueSample(
      "Autofill.Iban.ShowSuggestionsBlocklistDecision",
      autofill_metrics::IbanSuggestionBlockListStatus::kAllowed, 1);
}

// Tests that when showing IBAN suggestions is blocked by the site-specific
// blocklist, appropriate metrics are logged.
TEST_P(IbanManagerTest, Metrics_Suggestions_Blocked) {
  base::HistogramTester histogram_tester;
  SetUpLocalIban(test::kIbanValue, kNickname_0);

  // Setting up mock to verify that suggestions returning is not triggered if
  // the website is blocked.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);
  ON_CALL(*autofill_client_.GetAutofillOptimizationGuide(),
          ShouldBlockSingleFieldSuggestions)
      .WillByDefault(testing::Return(true));
  // Simulate request for suggestions.
  // TODO: handle return value.
  std::ignore = iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef());

  histogram_tester.ExpectUniqueSample(
      "Autofill.Iban.ShowSuggestionsBlocklistDecision",
      autofill_metrics::IbanSuggestionBlockListStatus::kBlocked, 1);
}

// Tests that when showing IBAN suggestions and the site-specific blocklist is
// not available, appropriate metrics are logged.
TEST_P(IbanManagerTest, Metrics_Suggestions_BlocklistNotAccessible) {
  base::HistogramTester histogram_tester;
  SetUpLocalIban(test::kIbanValue, kNickname_0);
  // Delete the AutofillOptimizationGuide.
  autofill_client_.ResetAutofillOptimizationGuide();

  // Simulate request for suggestions.
  // TODO: handle return value.
  OnSuggestionsReturnedCallback do_nothing = base::DoNothing();
  std::ignore = iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_, do_nothing);

  histogram_tester.ExpectUniqueSample(
      "Autofill.Iban.ShowSuggestionsBlocklistDecision",
      autofill_metrics::IbanSuggestionBlockListStatus::kBlocklistIsNotAvailable,
      1);
}

// Test that the metrics for local IBAN suggestion selected (once and total
// count) are logged correctly.
TEST_P(IbanManagerTest, Metrics_LocalIbanSuggestionSelected) {
  base::HistogramTester histogram_tester;
  SetUpLocalIban(test::kIbanValue, kNickname_0);
  SetUpLocalIban(test::kIbanValue_1, kNickname_1);
  SetUpLocalIban(test::kIbanValue_2, "");

  autofill_field_->set_renderer_id(test::MakeFieldRendererId());
  test_api(iban_manager_).set_most_recent_suggestions_shown_field_global_id(
      autofill_field_->global_id());

  // Simulate request for suggestions and select one suggested IBAN.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
  Suggestion suggestion(kIbanValue, SuggestionType::kIbanEntry);
  iban_manager_.OnSingleFieldSuggestionSelected(suggestion);

  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kLocalIbanSuggestionSelected, 1);
  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kLocalIbanSuggestionSelectedOnce,
      1);

  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
  iban_manager_.OnSingleFieldSuggestionSelected(suggestion);

  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kLocalIbanSuggestionSelected, 2);
  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kLocalIbanSuggestionSelectedOnce,
      1);
}

// Test that the metrics for server IBAN suggestion selected (once and total
// count) is logged correctly.
TEST_P(IbanManagerTest, Metrics_ServerIbanSuggestionSelected) {
  base::HistogramTester histogram_tester;
  payments_data_manager().SetAutofillWalletImportEnabled(true);
  Suggestion suggestion = GetSuggestionForIban(SetUpServerIban(
      /*instrument_id=*/12345, /*prefix=*/"DE", /*suffix=*/"6789",
      kNickname_0));

  autofill_field_->set_renderer_id(test::MakeFieldRendererId());
  test_api(iban_manager_).set_most_recent_suggestions_shown_field_global_id(
    autofill_field_->global_id());

  // Simulate request for suggestions and select one suggested IBAN.
  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
  iban_manager_.OnSingleFieldSuggestionSelected(suggestion);

  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kServerIbanSuggestionSelected, 1);
  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kServerIbanSuggestionSelectedOnce,
      1);

  EXPECT_TRUE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
  iban_manager_.OnSingleFieldSuggestionSelected(suggestion);

  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kServerIbanSuggestionSelected, 2);
  histogram_tester.ExpectBucketCount(
      "Autofill.Iban.Suggestions",
      autofill_metrics::IbanSuggestionsEvent::kServerIbanSuggestionSelectedOnce,
      1);
}

TEST_P(IbanManagerTest, Metrics_SuggestionSelected_CountryOfSelectedIban) {
  base::HistogramTester histogram_tester;
  // Simulate selecting one suggested IBAN.
  Suggestion suggestion(kIbanValue, SuggestionType::kIbanEntry);
  iban_manager_.OnSingleFieldSuggestionSelected(suggestion);

  histogram_tester.ExpectUniqueSample("Autofill.Iban.CountryOfSelectedIban",
                                      Iban::IbanSupportedCountry::kFR, 1);
}

TEST_P(IbanManagerTest, Metrics_NoSuggestionShown) {
  base::HistogramTester histogram_tester;
  SetUpLocalIban(test::kIbanValue, kNickname_0);
  SetUpLocalIban(test::kIbanValue_1, kNickname_1);
  // Input a prefix that does not have any matching IBAN value so that no IBAN
  // suggestions will be shown.
  autofill_field_->set_value(u"XY");
  test_api(iban_manager_).set_most_recent_suggestions_shown_field_global_id(
    autofill_field_->global_id());

  MockSuggestionsReturnedCallback mock_callback;
  EXPECT_CALL(mock_callback, Run).Times(0);

  // No suggestions are returned due to the prefix match requirement.
  EXPECT_FALSE(iban_manager_.OnGetSingleFieldSuggestions(*form_structure_,
      *autofill_field_, *autofill_field_, autofill_client_,
      mock_callback.GetNewRef()));
  EXPECT_THAT(
      histogram_tester.GetAllSamples("Autofill.Iban.Suggestions"),
      BucketsAre(
          base::Bucket(
              autofill_metrics::IbanSuggestionsEvent::kIbanSuggestionsShown, 0),
          base::Bucket(
              autofill_metrics::IbanSuggestionsEvent::kIbanSuggestionsShownOnce,
              0)));
}

}  // namespace
}  // namespace autofill