File: save_card_bubble_controller_impl_unittest.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 (1514 lines) | stat: -rw-r--r-- 58,355 bytes parent folder | download | duplicates (3)
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
// 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 "chrome/browser/ui/autofill/payments/save_card_bubble_controller_impl.h"

#include <stddef.h>

#include <string>
#include <tuple>
#include <utility>

#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/metrics/user_action_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/metrics/desktop_session_duration/desktop_session_duration_tracker.h"
#include "chrome/browser/ui/autofill/autofill_bubble_base.h"
#include "chrome/browser/ui/autofill/payments/save_card_ui.h"
#include "chrome/browser/ui/autofill/payments/save_payment_icon_controller.h"
#include "chrome/browser/ui/autofill/test/test_autofill_bubble_handler.h"
#include "chrome/browser/ui/hats/mock_trust_safety_sentiment_service.h"
#include "chrome/browser/ui/hats/trust_safety_sentiment_service_factory.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/browser_with_test_window_test.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "components/autofill/core/browser/data_manager/personal_data_manager.h"
#include "components/autofill/core/browser/data_manager/test_personal_data_manager.h"
#include "components/autofill/core/browser/data_model/payments/credit_card.h"
#include "components/autofill/core/browser/metrics/autofill_metrics.h"
#include "components/autofill/core/browser/metrics/payments/credit_card_save_metrics.h"
#include "components/autofill/core/browser/metrics/payments/manage_cards_prompt_metrics.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/common/autofill_features.h"
#include "components/autofill/core/common/autofill_payments_features.h"
#include "components/strings/grit/components_strings.h"
#include "components/tabs/public/tab_interface.h"
#include "content/public/test/mock_navigation_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"

using base::Bucket;
using testing::ElementsAre;

namespace autofill {
namespace {

using CardSaveType = payments::PaymentsAutofillClient::CardSaveType;
using SaveCreditCardOptions =
    payments::PaymentsAutofillClient::SaveCreditCardOptions;

std::unique_ptr<KeyedService> BuildTestPersonalDataManager(
    content::BrowserContext* context) {
  auto personal_data_manager =
      std::make_unique<autofill::TestPersonalDataManager>();
  personal_data_manager->test_payments_data_manager()
      .SetAutofillPaymentMethodsEnabled(true);
  return personal_data_manager;
}

// Test AutofillBubbleBase implementation which:
// - Notifies the controller when the bubble hides (to match prod).
// - Tracks the bubble's visibility.
class ObserveHideTestAutofillBubble : public AutofillBubbleBase {
 public:
  explicit ObserveHideTestAutofillBubble(content::WebContents* web_contents)
      : web_contents_(web_contents->GetWeakPtr()) {}
  ~ObserveHideTestAutofillBubble() override = default;

  void Show() { is_visible_ = true; }

  void Hide() override {
    // Call OnBubbleClosed() because the real implementation does so.
    if (web_contents_) {
      auto* controller = static_cast<SaveCardBubbleControllerImpl*>(
          SaveCardBubbleControllerImpl::FromWebContents(web_contents_.get()));
      controller->OnBubbleClosed(PaymentsUiClosedReason::kUnknown);
    }

    is_visible_ = false;
  }

  bool is_visible() { return is_visible_; }

 private:
  // WeakPtr because ObserveHideTestAutofillBubble outlives the WebContents in
  // tests.
  base::WeakPtr<content::WebContents> web_contents_;

  bool is_visible_;
};

// TestAutofillBubbleHandler which provides access to bubbles it creates.
class ExposeBubbleAutofillBubbleHandler : public TestAutofillBubbleHandler {
 public:
  ExposeBubbleAutofillBubbleHandler() = default;
  ExposeBubbleAutofillBubbleHandler(const ExposeBubbleAutofillBubbleHandler&) =
      delete;
  ExposeBubbleAutofillBubbleHandler& operator=(
      const ExposeBubbleAutofillBubbleHandler&) = delete;
  ~ExposeBubbleAutofillBubbleHandler() override = default;

  AutofillBubbleBase* ShowSaveCreditCardBubble(
      content::WebContents* web_contents,
      SaveCardBubbleController* controller,
      bool is_use_gesture) override {
    if (!save_card_bubble_) {
      save_card_bubble_ =
          std::make_unique<ObserveHideTestAutofillBubble>(web_contents);
    }
    save_card_bubble_->Show();
    return save_card_bubble_.get();
  }

  AutofillBubbleBase* ShowSaveCardConfirmationBubble(
      content::WebContents* web_contents,
      SaveCardBubbleController* controller) override {
    if (!confirmation_bubble_) {
      confirmation_bubble_ =
          std::make_unique<ObserveHideTestAutofillBubble>(web_contents);
    }
    confirmation_bubble_->Show();
    return confirmation_bubble_.get();
  }

  bool is_save_card_bubble_visible() {
    return save_card_bubble_ && save_card_bubble_->is_visible();
  }

  bool is_confirmation_bubble_visible() {
    return confirmation_bubble_ && confirmation_bubble_->is_visible();
  }

 private:
  std::unique_ptr<ObserveHideTestAutofillBubble> save_card_bubble_;
  std::unique_ptr<ObserveHideTestAutofillBubble> confirmation_bubble_;
};

class TestBrowserWindowWithAutofillHandler : public TestBrowserWindow {
 public:
  TestBrowserWindowWithAutofillHandler() = default;
  ~TestBrowserWindowWithAutofillHandler() override = default;
  TestBrowserWindowWithAutofillHandler(
      const TestBrowserWindowWithAutofillHandler&) = delete;
  TestBrowserWindowWithAutofillHandler& operator=(
      const TestBrowserWindowWithAutofillHandler&) = delete;

  autofill::AutofillBubbleHandler* GetAutofillBubbleHandler() override {
    return &handler_;
  }

 private:
  ExposeBubbleAutofillBubbleHandler handler_;
};

class TestSaveCardBubbleControllerImpl : public SaveCardBubbleControllerImpl {
 public:
  static void CreateForTesting(content::WebContents* web_contents) {
    web_contents->SetUserData(
        UserDataKey(),
        std::make_unique<TestSaveCardBubbleControllerImpl>(web_contents));
  }

  // Overriding because parent function requires a browser window to redirect
  // properly, which is not available in unit tests.
  void ShowPaymentsSettingsPage() override {}

  explicit TestSaveCardBubbleControllerImpl(content::WebContents* web_contents)
      : SaveCardBubbleControllerImpl(web_contents) {}

  void SimulateNavigation() {
    content::MockNavigationHandle handle;
    handle.set_has_committed(true);
    DidFinishNavigation(&handle);
  }

 protected:
  bool IsPaymentsSyncTransportEnabledWithoutSyncFeature() const override {
    return false;
  }
};

class SaveCardBubbleControllerImplTest : public BrowserWithTestWindowTest {
 public:
  SaveCardBubbleControllerImplTest()
      : BrowserWithTestWindowTest(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        dependency_manager_subscription_(
            BrowserContextDependencyManager::GetInstance()
                ->RegisterCreateServicesCallbackForTesting(base::BindRepeating(
                    &SaveCardBubbleControllerImplTest::SetTestingFactories,
                    base::Unretained(this)))) {
    scoped_feature_list_.InitAndDisableFeature(
        features::kAutofillEnableCvcStorageAndFilling);
  }

  SaveCardBubbleControllerImplTest(SaveCardBubbleControllerImplTest&) = delete;
  SaveCardBubbleControllerImplTest& operator=(
      SaveCardBubbleControllerImplTest&) = delete;

  void SetUp() override {
    BrowserWithTestWindowTest::SetUp();
    AddTab(browser(), GURL("about:blank"));
    TestSaveCardBubbleControllerImpl::CreateForTesting(active_web_contents());

    // Initialize a tracker for TrustSafetySentimentService to work properly.
    metrics::DesktopSessionDurationTracker::Initialize();
    mock_sentiment_service_ = static_cast<MockTrustSafetySentimentService*>(
        TrustSafetySentimentServiceFactory::GetInstance()
            ->SetTestingFactoryAndUse(
                profile(),
                base::BindRepeating(&BuildMockTrustSafetySentimentService)));

    // Set the visibility to VISIBLE as the web contents are initially hidden.
    active_web_contents()->UpdateWebContentsVisibility(
        content::Visibility::VISIBLE);
  }

  void TearDown() override {
    mock_sentiment_service_ = nullptr;
    did_on_confirmation_closed_callback_run_ = false;
    personal_data_manager()->test_payments_data_manager().ClearCreditCards();
    BrowserWithTestWindowTest::TearDown();
    metrics::DesktopSessionDurationTracker::CleanupForTesting();
  }

  // BrowserWithTestWindowTest:
  std::unique_ptr<BrowserWindow> CreateBrowserWindow() override {
    std::unique_ptr<TestBrowserWindowWithAutofillHandler> window =
        std::make_unique<TestBrowserWindowWithAutofillHandler>();
    window->set_is_active(true);
    return std::move(window);
  }

  ExposeBubbleAutofillBubbleHandler* GetAutofillBubbleHandler() {
    return static_cast<ExposeBubbleAutofillBubbleHandler*>(
        window()->GetAutofillBubbleHandler());
  }

  bool IsSaveCardBubbleVisible() {
    return GetAutofillBubbleHandler()->is_save_card_bubble_visible();
  }

  bool IsConfirmationBubbleVisible() {
    return GetAutofillBubbleHandler()->is_confirmation_bubble_visible();
  }

  void SetLegalMessage(const std::string& message_json,
                       SaveCreditCardOptions options =
                           SaveCreditCardOptions().with_show_prompt()) {
    std::optional<base::Value> value(base::JSONReader::Read(message_json));
    ASSERT_TRUE(value);
    ASSERT_TRUE(value->is_dict());
    LegalMessageLines legal_message_lines;
    LegalMessageLine::Parse(value->GetDict(), &legal_message_lines,
                            /*escape_apostrophes=*/true);
    controller()->OfferUploadSave(CreditCard(), legal_message_lines, options,
                                  base::BindOnce(&UploadSaveCardCallback));
  }

  void ShowLocalBubble(const CreditCard* card = nullptr,
                       SaveCreditCardOptions options =
                           SaveCreditCardOptions().with_show_prompt()) {
    controller()->OfferLocalSave(
        card ? CreditCard(*card)
             : autofill::test::GetCreditCard(),  // Visa by default
        options, base::BindOnce(&LocalSaveCardCallback));
  }

  void ShowUploadBubble(SaveCreditCardOptions options =
                            SaveCreditCardOptions().with_show_prompt()) {
    if (options.card_save_type == CardSaveType::kCvcSaveOnly) {
      SetLegalMessage("{}", options);
      return;
    }
    SetLegalMessage(
        "{"
        "  \"line\" : [ {"
        "     \"template\": \"This is the entire message.\""
        "  } ]"
        "}",
        options);
  }

  void ShowConfirmationBubbleView(bool card_saved) {
    controller()->ShowConfirmationBubbleView(
        /*card_saved=*/card_saved,
        /*on_confirmation_closed_callback=*/base::BindOnce(
            &SaveCardBubbleControllerImplTest::OnConfirmationClosedCallback,
            weak_ptr_factory_.GetWeakPtr()));
  }

  void CloseBubble(PaymentsUiClosedReason closed_reason =
                       PaymentsUiClosedReason::kNotInteracted) {
    controller()->OnBubbleClosed(closed_reason);
  }

  void CloseAndReshowBubble() {
    CloseBubble();
    controller()->ReshowBubble(/*is_user_gesture=*/true);
  }

  void ClickSaveButton(bool is_upload = false) {
    controller()->OnSaveButton({});
    PaymentsUiClosedReason close_reason = PaymentsUiClosedReason::kAccepted;
    if (is_upload) {
      // The `Upload` dialog shows loading and doesn't close by itself. The
      // dialog needs to be closed and the reason recorded for closure is
      // `kClosed`.
      close_reason = PaymentsUiClosedReason::kClosed;
      CloseBubble(close_reason);
    }
    controller()->OnBubbleClosed(close_reason);
    if (controller()->ShouldShowPaymentSavedLabelAnimation()) {
      controller()->OnAnimationEnded();
    }
  }

  void AddCreditCard(const CreditCard& card) {
    personal_data_manager()->test_payments_data_manager().AddCreditCard(card);
  }

 protected:
  TestSaveCardBubbleControllerImpl* controller() {
    return static_cast<TestSaveCardBubbleControllerImpl*>(
        TestSaveCardBubbleControllerImpl::FromWebContents(
            active_web_contents()));
  }

  content::WebContents* active_web_contents() {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

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

  tabs::TabInterface* active_tab() {
    return browser()->tab_strip_model()->GetActiveTab();
  }

  raw_ptr<MockTrustSafetySentimentService> mock_sentiment_service_ = nullptr;
  bool did_on_confirmation_closed_callback_run_ = false;

 private:
  static void UploadSaveCardCallback(
      payments::PaymentsAutofillClient::SaveCardOfferUserDecision user_decision,
      const payments::PaymentsAutofillClient::UserProvidedCardDetails&
          user_provided_card_details) {}
  static void LocalSaveCardCallback(
      payments::PaymentsAutofillClient::SaveCardOfferUserDecision
          user_decision) {}
  void OnConfirmationClosedCallback() {
    did_on_confirmation_closed_callback_run_ = true;
  }
  void SetTestingFactories(content::BrowserContext* context) {
    autofill::PersonalDataManagerFactory::GetInstance()->SetTestingFactory(
        context, base::BindRepeating(&BuildTestPersonalDataManager));
  }

  base::CallbackListSubscription dependency_manager_subscription_;
  base::test::ScopedFeatureList scoped_feature_list_;

  base::WeakPtrFactory<SaveCardBubbleControllerImplTest> weak_ptr_factory_{
      this};
};

// Tests that the legal message lines vector is empty when doing a local save so
// that no legal messages will be shown to the user in that case.
TEST_F(SaveCardBubbleControllerImplTest, LegalMessageLinesEmptyOnLocalSave) {
  ShowUploadBubble();
  CloseBubble();
  ShowLocalBubble();
  EXPECT_TRUE(controller()->GetLegalMessageLines().empty());
}

TEST_F(SaveCardBubbleControllerImplTest,
       PropagateShouldRequestNameFromUserWhenFalse) {
  ShowUploadBubble();
  EXPECT_FALSE(controller()->ShouldRequestNameFromUser());
}

TEST_F(SaveCardBubbleControllerImplTest,
       PropagateShouldRequestNameFromUserWhenTrue) {
  ShowUploadBubble(SaveCreditCardOptions()
                       .with_should_request_name_from_user(true)
                       .with_show_prompt());
  EXPECT_TRUE(controller()->ShouldRequestNameFromUser());
}

TEST_F(SaveCardBubbleControllerImplTest,
       PropagateShouldRequestExpirationDateFromUserWhenFalse) {
  ShowUploadBubble(SaveCreditCardOptions()
                       .with_should_request_name_from_user(true)
                       .with_show_prompt());

  EXPECT_FALSE(controller()->ShouldRequestExpirationDateFromUser());
}

TEST_F(SaveCardBubbleControllerImplTest,
       PropagateShouldRequestExpirationDateFromUserWhenTrue) {
  ShowUploadBubble(SaveCreditCardOptions()
                       .with_should_request_name_from_user(true)
                       .with_should_request_expiration_date_from_user(true)
                       .with_show_prompt());

  EXPECT_TRUE(controller()->ShouldRequestExpirationDateFromUser());
}

using SaveCreditCardPromptResultMetricTestData =
    std::tuple<PaymentsUiClosedReason, autofill_metrics::SaveCardPromptResult>;

// Test fixture to ensure the correct reporting of UMA metric
// Autofill.SaveCreditCardPromptResult{SaveDestination}.{UserGroup}.
class SaveCreditCardPromptResultMetricTest
    : public SaveCardBubbleControllerImplTest,
      public testing::WithParamInterface<
          SaveCreditCardPromptResultMetricTestData> {
 public:
  SaveCreditCardPromptResultMetricTest()
      : closed_reason_(std::get<0>(GetParam())),
        prompt_result_(std::get<1>(GetParam())) {}
  ~SaveCreditCardPromptResultMetricTest() override = default;

 protected:
  const PaymentsUiClosedReason closed_reason_;
  const autofill_metrics::SaveCardPromptResult prompt_result_;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    SaveCreditCardPromptResultMetricTest,
    testing::Values(SaveCreditCardPromptResultMetricTestData(
                        PaymentsUiClosedReason::kAccepted,
                        autofill_metrics::SaveCardPromptResult::kAccepted),
                    SaveCreditCardPromptResultMetricTestData(
                        PaymentsUiClosedReason::kCancelled,
                        autofill_metrics::SaveCardPromptResult::kCancelled),
                    SaveCreditCardPromptResultMetricTestData(
                        PaymentsUiClosedReason::kClosed,
                        autofill_metrics::SaveCardPromptResult::kClosed),
                    SaveCreditCardPromptResultMetricTestData(
                        PaymentsUiClosedReason::kNotInteracted,
                        autofill_metrics::SaveCardPromptResult::kNotInteracted),
                    SaveCreditCardPromptResultMetricTestData(
                        PaymentsUiClosedReason::kLostFocus,
                        autofill_metrics::SaveCardPromptResult::kLostFocus)));

// Tests that after the user interacts with a "save *local* card" dialog and
// *does not* have any card data on file, metrics
// Autofill.SaveCreditCardPromptResult.Local.Aggregate and .UserHasNoCards are
// recorded.
TEST_P(SaveCreditCardPromptResultMetricTest,
       EmitsSavePromptResultLocalHasNoCards) {
  personal_data_manager()->test_payments_data_manager().ClearCreditCards();
  base::HistogramTester histogram_tester;
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions().with_show_prompt(true));
  if (closed_reason_ == PaymentsUiClosedReason::kAccepted) {
    controller()->OnSaveButton({});
  }
  CloseBubble(closed_reason_);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Local.Aggregate", prompt_result_, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Local.UserHasNoCards",
      prompt_result_, 1);
}

// Tests that after the user interacts with a "save *server* card" dialog and
// *does not* have any card data on file, metrics
// Autofill.SaveCreditCardPromptResult.Upload.Aggregate and .UserHasNoCards are
// recorded.
TEST_P(SaveCreditCardPromptResultMetricTest,
       EmitsSavePromptResultUploadHasNoCards) {
  personal_data_manager()->test_payments_data_manager().ClearCreditCards();
  base::HistogramTester histogram_tester;
  ShowUploadBubble(SaveCreditCardOptions().with_show_prompt(true));
  if (closed_reason_ == PaymentsUiClosedReason::kAccepted) {
    controller()->OnSaveButton({});
    // On Save button clicked, the dialog shows loading and doesn't close by
    // itself. The dialog needs to be closed and the reason recorded for
    // closure is `kClosed`.
    CloseBubble(PaymentsUiClosedReason::kClosed);
  } else {
    CloseBubble(closed_reason_);
  }

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Upload.Aggregate", prompt_result_,
      1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Upload.UserHasNoCards",
      prompt_result_, 1);
}

// Tests that after the user interacts with a "save *local* card" dialog and
// *does* have card data on file, metrics
// Autofill.SaveCreditCardPromptResult.Local.Aggregate and .UserHasSavedCards
// are recorded.
TEST_P(SaveCreditCardPromptResultMetricTest,
       EmitsSavePromptResultLocalHasSavedCards) {
  personal_data_manager()->test_payments_data_manager().ClearCreditCards();
  AddCreditCard(test::GetCreditCard());
  base::HistogramTester histogram_tester;
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions().with_show_prompt(true));
  if (closed_reason_ == PaymentsUiClosedReason::kAccepted) {
    controller()->OnSaveButton({});
  }
  CloseBubble(closed_reason_);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Local.Aggregate", prompt_result_, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Local.UserHasSavedCards",
      prompt_result_, 1);
}

// Tests that after the user interacts with a "save *server* card" dialog and
// *does* have card data on file, metrics
// Autofill.SaveCreditCardPromptResult.Upload.Aggregate and .UserHasSavedCards
// are recorded.
TEST_P(SaveCreditCardPromptResultMetricTest,
       EmitsSavePromptResultUploadHasSavedCards) {
  personal_data_manager()->test_payments_data_manager().ClearCreditCards();
  AddCreditCard(test::GetCreditCard());
  base::HistogramTester histogram_tester;
  ShowUploadBubble(SaveCreditCardOptions().with_show_prompt(true));
  if (closed_reason_ == PaymentsUiClosedReason::kAccepted) {
    // On Save button clicked, the dialog shows loading and doesn't close by
    // itself.
    controller()->OnSaveButton({});
  } else {
    CloseBubble(closed_reason_);
  }

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Upload.Aggregate", prompt_result_,
      1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Upload.UserHasSavedCards",
      prompt_result_, 1);
}

// Param of the SaveCardBubbleSingletonTestData:
// -- bool first_shown_is_local;
// -- bool second_and_third_shown_are_local;
typedef std::tuple<bool, bool> SaveCardBubbleSingletonTestData;

// One test case will be run several times till we cover all the param
// combinations of the |SaveCardBubbleSingletonTestData|. GetParam() will help
// get the specific param value for a particular run.
class SaveCardBubbleSingletonTest
    : public SaveCardBubbleControllerImplTest,
      public testing::WithParamInterface<SaveCardBubbleSingletonTestData> {
 public:
  SaveCardBubbleSingletonTest()
      : first_shown_is_local_(std::get<0>(GetParam())),
        second_and_third_shown_are_local_(std::get<1>(GetParam())) {}

  ~SaveCardBubbleSingletonTest() override = default;

  void ShowBubble(bool is_local) {
    is_local ? ShowLocalBubble() : ShowUploadBubble();
  }

  void TriggerFlow() {
    ShowBubble(first_shown_is_local_);
    ShowBubble(second_and_third_shown_are_local_);
    ShowBubble(second_and_third_shown_are_local_);
  }

  const bool first_shown_is_local_;
  const bool second_and_third_shown_are_local_;
};

INSTANTIATE_TEST_SUITE_P(,
                         SaveCardBubbleSingletonTest,
                         testing::Combine(testing::Bool(), testing::Bool()));

TEST_P(SaveCardBubbleSingletonTest, OnlyOneActiveBubble) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  std::string suffix =
      first_shown_is_local_ ? ".Local.FirstShow" : ".Upload.FirstShow";

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer" + suffix,
      autofill_metrics::SaveCardPromptOffer::kShown, 1);
}

// Note that even though in prod the four options in the SaveCreditCardOptions
// struct can be true at the same time, we don't support that in the test case
// (by the way we create histogram name suffixes).
struct SaveCardOptionParam {
  bool should_request_name_from_user;
  bool should_request_expiration_date_from_user;
  bool has_multiple_legal_lines;
  bool has_same_last_four_as_server_card_but_different_expiration_date;
  CardSaveType card_save_type;
};

const SaveCardOptionParam kSaveCardOptionParam[] = {
    {false, false, false, false, CardSaveType::kCardSaveOnly},
    {true, false, false, false, CardSaveType::kCardSaveOnly},
    {false, true, false, false, CardSaveType::kCardSaveOnly},
    {false, false, true, false, CardSaveType::kCardSaveOnly},
    {false, false, false, true, CardSaveType::kCardSaveOnly},
    {false, false, false, false, CardSaveType::kCardSaveWithCvc}};

// Param of the SaveCardBubbleSingletonTestData:
// -- std::string save_destination
// -- std::string show_type
// -- SaveCardOptionParam save_card_option_param
typedef std::tuple<std::string, std::string, SaveCardOptionParam>
    SaveCardBubbleLoggingTestData;

// Test class to ensure the save card bubble events are logged correctly.
class SaveCardBubbleLoggingTest
    : public SaveCardBubbleControllerImplTest,
      public ::testing::WithParamInterface<SaveCardBubbleLoggingTestData> {
 public:
  SaveCardBubbleLoggingTest()
      : save_destination_(std::get<0>(GetParam())),
        show_type_(std::get<1>(GetParam())) {
    SaveCardOptionParam save_card_option_param = std::get<2>(GetParam());
    save_credit_card_options_ =
        SaveCreditCardOptions()
            .with_should_request_name_from_user(
                save_card_option_param.should_request_name_from_user)
            .with_should_request_expiration_date_from_user(
                save_card_option_param.should_request_expiration_date_from_user)
            .with_has_multiple_legal_lines(
                save_card_option_param.has_multiple_legal_lines)
            .with_same_last_four_as_server_card_but_different_expiration_date(
                save_card_option_param
                    .has_same_last_four_as_server_card_but_different_expiration_date)
            .with_card_save_type(save_card_option_param.card_save_type);
  }

  ~SaveCardBubbleLoggingTest() override = default;

  void TriggerFlow(bool show_prompt = true) {
    if (save_destination_ == "Local") {
      if (show_type_ == "FirstShow") {
        ShowLocalBubble(/*card=*/nullptr,
                        /*options=*/GetSaveCreditCardOptions().with_show_prompt(
                            show_prompt));
      } else {
        ASSERT_EQ(show_type_, "Reshows");
        ShowLocalBubble(/*card=*/nullptr,
                        /*options=*/GetSaveCreditCardOptions().with_show_prompt(
                            show_prompt));
        CloseAndReshowBubble();
      }
    } else {
      ASSERT_EQ(save_destination_, "Upload");
      if (show_type_ == "FirstShow") {
        ShowUploadBubble(
            GetSaveCreditCardOptions().with_show_prompt(show_prompt));
      } else {
        ASSERT_EQ(show_type_, "Reshows");
        ShowUploadBubble(
            GetSaveCreditCardOptions().with_show_prompt(show_prompt));
        CloseAndReshowBubble();
      }
    }
  }

  SaveCreditCardOptions GetSaveCreditCardOptions() {
    return save_credit_card_options_;
  }

  std::string GetHistogramNameSuffix() {
    std::string result = "." + save_destination_ + "." + show_type_;

    if (GetSaveCreditCardOptions().should_request_name_from_user) {
      result += ".RequestingCardholderName";
    }

    if (GetSaveCreditCardOptions().should_request_expiration_date_from_user) {
      result += ".RequestingExpirationDate";
    }

    if (GetSaveCreditCardOptions().has_multiple_legal_lines) {
      result += ".WithMultipleLegalLines";
    }

    if (GetSaveCreditCardOptions()
            .has_same_last_four_as_server_card_but_different_expiration_date) {
      result += ".WithSameLastFourButDifferentExpiration";
    }
    if (GetSaveCreditCardOptions().card_save_type ==
        CardSaveType::kCardSaveWithCvc) {
      result += ".SavingWithCvc";
    }

    return result;
  }

  const std::string save_destination_;
  const std::string show_type_;

 private:
  SaveCreditCardOptions save_credit_card_options_;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    SaveCardBubbleLoggingTest,
    testing::Combine(testing::Values("Local", "Upload"),
                     testing::Values("FirstShow", "Reshows"),
                     testing::ValuesIn(kSaveCardOptionParam)));

TEST_P(SaveCardBubbleLoggingTest, Metrics_ShowBubble) {
  base::HistogramTester histogram_tester;
  TriggerFlow();

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptOffer::kShown, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_ShowIconOnly) {
  // This case does not happen when it is a reshow.
  if (show_type_ == "Reshows") {
    return;
  }

  base::HistogramTester histogram_tester;
  TriggerFlow(/*show_prompt=*/false);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptOffer::kNotShownMaxStrikesReached, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_SaveButton) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  controller()->OnSaveButton({});
  // On Save button clicked, the `Upload` dialog shows loading and doesn't close
  // by itself. The `Upload` dialog needs to be closed and the reason recorded
  // for closure is `kClosed`.
  PaymentsUiClosedReason closed_reason =
      save_destination_ == "Upload" ? PaymentsUiClosedReason::kClosed
                                    : PaymentsUiClosedReason::kAccepted;
  CloseBubble(closed_reason);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptResult::kAccepted, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_CancelButton) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kCancelled);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptResult::kCancelled, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_Closed) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kClosed);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptResult::kClosed, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_NotInteracted) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kNotInteracted);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptResult::kNotInteracted, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_LostFocus) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kLostFocus);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptResult::kLostFocus, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_Unknown) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kUnknown);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult" + GetHistogramNameSuffix(),
      autofill_metrics::SaveCardPromptResult::kUnknown, 1);
}

TEST_P(SaveCardBubbleLoggingTest, Metrics_LegalMessageLinkedClicked) {
  if (save_destination_ == "Local") {
    return;
  }

  TriggerFlow();
  base::HistogramTester histogram_tester;
  base::UserActionTester user_action_tester;
  controller()->OnLegalMessageLinkClicked(GURL("http://www.example.com"));

  EXPECT_EQ(1, user_action_tester.GetActionCount(
                   "Autofill_CreditCardUpload_LegalMessageLinkClicked"));
}

// Param of the SaveCvcBubbleLoggingTest:
// -- std::string show_type: decides if the view is shown first time or
// re-shown.
// -- std::string save_destination decides if card or CVC will be saved locally
// or to the server.
class SaveCvcBubbleLoggingTest
    : public SaveCardBubbleControllerImplTest,
      public testing::WithParamInterface<std::tuple<std::string, std::string>> {
 public:
  SaveCvcBubbleLoggingTest()
      : show_type_(std::get<0>(GetParam())),
        save_destination_(std::get<1>(GetParam())) {}
  ~SaveCvcBubbleLoggingTest() override = default;

  void TriggerFlow(bool show_prompt = true) {
    ASSERT_TRUE(show_type_ == "FirstShow" || show_type_ == "Reshows");
    if (save_destination_ == "Upload") {
      ShowUploadBubble(
          /*options=*/SaveCreditCardOptions()
              .with_card_save_type(CardSaveType::kCvcSaveOnly)
              .with_show_prompt(show_prompt));
    } else {
      ASSERT_EQ(save_destination_, "Local");
      ShowLocalBubble(
          /*card=*/nullptr,
          /*options=*/SaveCreditCardOptions()
              .with_card_save_type(CardSaveType::kCvcSaveOnly)
              .with_show_prompt(show_prompt));
    }

    if (show_type_ == "Reshows") {
      CloseAndReshowBubble();
    }
  }

  const std::string show_type_;
  const std::string save_destination_;
};

INSTANTIATE_TEST_SUITE_P(,
                         SaveCvcBubbleLoggingTest,
                         testing::Combine(testing::Values("FirstShow",
                                                          "Reshows"),
                                          testing::Values("Upload", "Local")));

TEST_P(SaveCvcBubbleLoggingTest, Metrics_ShowBubble) {
  base::HistogramTester histogram_tester;
  TriggerFlow();

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptOffer." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptOffer::kShown, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_ShowIconOnly) {
  // This case does not happen when it is a reshow.
  if (show_type_ == "Reshows") {
    return;
  }

  base::HistogramTester histogram_tester;
  TriggerFlow(/*show_prompt=*/false);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptOffer." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptOffer::kNotShownMaxStrikesReached, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_SaveButton) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  controller()->OnSaveButton({});
  CloseBubble(PaymentsUiClosedReason::kAccepted);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptResult." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptResult::kAccepted, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_CancelButton) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kCancelled);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptResult." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptResult::kCancelled, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_Closed) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kClosed);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptResult." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptResult::kClosed, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_NotInteracted) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kNotInteracted);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptResult." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptResult::kNotInteracted, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_LostFocus) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kLostFocus);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptResult." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptResult::kLostFocus, 1);
}

TEST_P(SaveCvcBubbleLoggingTest, Metrics_Unknown) {
  base::HistogramTester histogram_tester;
  TriggerFlow();
  CloseBubble(PaymentsUiClosedReason::kUnknown);

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCvcPromptResult." + save_destination_ + "." + show_type_,
      autofill_metrics::SaveCardPromptResult::kUnknown, 1);
}

TEST_F(SaveCardBubbleControllerImplTest, LocalCvcOnlySaveDialogContent) {
  // Show the local CVC save bubble.
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions()
          .with_card_save_type(CardSaveType::kCvcSaveOnly)
          .with_show_prompt(true));

  ASSERT_EQ(BubbleType::LOCAL_CVC_SAVE, controller()->GetBubbleType());
  ASSERT_NE(nullptr, controller()->GetPaymentBubbleView());
  EXPECT_EQ(controller()->GetWindowTitle(), u"Save security code?");
  EXPECT_EQ(controller()->GetExplanatoryMessage(),
            u"This card's CVC will be encrypted and saved to your device for "
            u"faster checkout");
}

TEST_F(SaveCardBubbleControllerImplTest, UploadCvcOnlySaveDialogContent) {
  // Show the server CVC save bubble.
  ShowUploadBubble(
      /*options=*/SaveCreditCardOptions()
          .with_card_save_type(CardSaveType::kCvcSaveOnly)
          .with_show_prompt(true));

  ASSERT_EQ(BubbleType::UPLOAD_CVC_SAVE, controller()->GetBubbleType());
  ASSERT_NE(nullptr, controller()->GetPaymentBubbleView());
  EXPECT_EQ(controller()->GetWindowTitle(), u"Save security code?");
  EXPECT_EQ(controller()->GetExplanatoryMessage(),
            u"This card's CVC will be encrypted and saved in your Google "
            u"Account for faster checkout");
  EXPECT_TRUE(controller()->GetLegalMessageLines().empty());
}

TEST_F(SaveCardBubbleControllerImplTest,
       LocalCard_FirstShow_SaveButton_SigninPromo_Close_Reshow_ManageCards) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);

  // Show the local card save bubble.
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions().with_card_save_type(
          CardSaveType::kCardSaveOnly));
  ClickSaveButton();
  CloseAndReshowBubble();
  // After closing the sign-in promo, clicking the icon should bring up the
  // Manage cards bubble. Verify that the icon tooltip, the title for the
  // bubble, and the save animation reflect the correct info.
  ASSERT_EQ(BubbleType::MANAGE_CARDS, controller()->GetBubbleType());
  ASSERT_NE(nullptr, controller()->GetPaymentBubbleView());
  EXPECT_EQ(controller()->GetWindowTitle(), u"Card saved");
  EXPECT_EQ(controller()->GetSavePaymentIconTooltipText(), u"Save card");
  EXPECT_EQ(controller()->GetSaveSuccessAnimationStringId(),
            IDS_AUTOFILL_CARD_SAVED);
}

TEST_F(SaveCardBubbleControllerImplTest,
       LocalCvc_FirstShow_SaveButton_SigninPromo_Close_Reshow_ManageCards) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);

  // Show the local CVC save bubble.
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions().with_card_save_type(
          CardSaveType::kCvcSaveOnly));
  ClickSaveButton();
  CloseAndReshowBubble();
  // After closing the sign-in promo, clicking the icon should bring up the
  // Manage cards bubble. Verify that the icon tooltip, the title for the
  // bubble, and the save animation reflect the correct info.
  ASSERT_EQ(BubbleType::MANAGE_CARDS, controller()->GetBubbleType());
  ASSERT_NE(nullptr, controller()->GetPaymentBubbleView());
  EXPECT_EQ(controller()->GetWindowTitle(), u"CVC saved");
  EXPECT_EQ(controller()->GetSavePaymentIconTooltipText(), u"Save CVC");
  EXPECT_EQ(controller()->GetSaveSuccessAnimationStringId(),
            IDS_AUTOFILL_CVC_SAVED);
}

TEST_F(SaveCardBubbleControllerImplTest,
       Metrics_Local_ClickManageCardsDoneButton) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);
  base::HistogramTester histogram_tester;
  ShowLocalBubble();
  ClickSaveButton();
  CloseAndReshowBubble();
  ASSERT_EQ(BubbleType::MANAGE_CARDS, controller()->GetBubbleType());

  ClickSaveButton();
  EXPECT_THAT(
      histogram_tester.GetAllSamples("Autofill.ManageCardsPrompt"),
      ElementsAre(Bucket(ManageCardsPromptMetric::kManageCardsShown, 1),
                  Bucket(ManageCardsPromptMetric::kManageCardsDone, 1)));
}

TEST_F(SaveCardBubbleControllerImplTest,
       Metrics_Local_ClickManageCardsManageCardsButton) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);
  base::HistogramTester histogram_tester;
  ShowLocalBubble();
  ClickSaveButton();
  CloseAndReshowBubble();
  controller()->OnManageCardsClicked();
  EXPECT_THAT(
      histogram_tester.GetAllSamples("Autofill.ManageCardsPrompt"),
      ElementsAre(Bucket(ManageCardsPromptMetric::kManageCardsShown, 1),
                  Bucket(ManageCardsPromptMetric::kManageCardsManageCards, 1)));
}

TEST_F(
    SaveCardBubbleControllerImplTest,
    Metrics_Local_FirstShow_SaveButton_Close_Reshow_Close_Reshow_ManageCards) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);
  base::HistogramTester histogram_tester;
  ShowLocalBubble();
  ClickSaveButton();
  CloseAndReshowBubble();
  CloseAndReshowBubble();
  // After closing the sign-in promo, clicking the icon should bring
  // up the Manage cards bubble.
  EXPECT_THAT(
      histogram_tester.GetAllSamples("Autofill.ManageCardsPrompt"),
      ElementsAre(Bucket(ManageCardsPromptMetric::kManageCardsShown, 2)));
}

TEST_F(
    SaveCardBubbleControllerImplTest,
    Metrics_Local_FirstShow_SaveButton_SigninPromo_Close_Reshow_ManageCards) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);
  base::HistogramTester histogram_tester;
  ShowLocalBubble();
  ClickSaveButton();
  CloseAndReshowBubble();
  // After closing the sign-in promo, clicking the icon should bring
  // up the Manage cards bubble.
  EXPECT_THAT(
      histogram_tester.GetAllSamples("Autofill.ManageCardsPrompt"),
      ElementsAre(Bucket(ManageCardsPromptMetric::kManageCardsShown, 1)));
}

TEST_F(SaveCardBubbleControllerImplTest,
       Upload_FirstShow_SaveButton_NoSigninPromo) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);
  ShowUploadBubble();
  ClickSaveButton(/*is_upload=*/true);

  EXPECT_FALSE(controller()->IsIconVisible());
  EXPECT_EQ(nullptr, controller()->GetPaymentBubbleView());
}

TEST_F(SaveCardBubbleControllerImplTest,
       Metrics_Upload_FirstShow_SaveButton_NoSigninPromo) {
  EXPECT_CALL(*mock_sentiment_service_, SavedCard()).Times(1);
  base::HistogramTester histogram_tester;
  ShowUploadBubble();
  ClickSaveButton(/*is_upload=*/true);
  // No other bubbles should have popped up.
  histogram_tester.ExpectTotalCount("Autofill.SignInPromo", 0);
  histogram_tester.ExpectTotalCount("Autofill.ManageCardsPrompt", 0);
}

// Test the entire upload save flow with the ShowConfirmationBubbleView()
// callback.
TEST_F(SaveCardBubbleControllerImplTest,
       Upload_OnSave_ShowConfirmationBubbleView) {
  ShowUploadBubble();
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_SAVE);
  EXPECT_TRUE(controller()->IsIconVisible());
  EXPECT_TRUE(IsSaveCardBubbleVisible());

  controller()->OnSaveButton({});
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_IN_PROGRESS);
  EXPECT_TRUE(IsSaveCardBubbleVisible());
  EXPECT_FALSE(IsConfirmationBubbleVisible());

  ShowConfirmationBubbleView(/*card_saved=*/true);
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_COMPLETED);
  EXPECT_FALSE(IsSaveCardBubbleVisible());
  EXPECT_TRUE(IsConfirmationBubbleVisible());
  EXPECT_TRUE(controller()->GetConfirmationUiParams().is_success);

  controller()->HideSaveCardBubble();
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::INACTIVE);
  EXPECT_FALSE(IsConfirmationBubbleVisible());
  EXPECT_FALSE(controller()->IsIconVisible());
}

// Test that when passing in "card_saved=false" for ShowConfirmationBubbleView()
// the confirmation UI model has "is_success" set to false.
TEST_F(SaveCardBubbleControllerImplTest,
       Upload_OnShowConfirmation_ShowFailureUIModel) {
  ShowConfirmationBubbleView(/*card_saved=*/false);
  EXPECT_FALSE(IsSaveCardBubbleVisible());
  EXPECT_TRUE(IsConfirmationBubbleVisible());
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_COMPLETED);
  EXPECT_FALSE(controller()->GetConfirmationUiParams().is_success);
}

// Test that when showing the upload bubble when the confirmation bubble view is
// still up, the confirmation bubble view is closed and the upload bubble view
// is still shown.
TEST_F(SaveCardBubbleControllerImplTest,
       Upload_OnShowConfirmationBubbleView_ThenShowUploadView) {
  ShowConfirmationBubbleView(/*card_saved=*/true);
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_COMPLETED);
  EXPECT_TRUE(IsConfirmationBubbleVisible());
  EXPECT_TRUE(controller()->GetConfirmationUiParams().is_success);

  ShowUploadBubble();
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_SAVE);
  EXPECT_TRUE(IsSaveCardBubbleVisible());
  EXPECT_FALSE(IsConfirmationBubbleVisible());
  EXPECT_TRUE(controller()->IsIconVisible());
}

// Test that the `Accepted` upload result metric is recorded on upload card save
// and that upload result metrics are not recorded but the confirmation shown &
// result metrics are recorded when the save card bubble is closed after the
// save card upload completes.
TEST_F(SaveCardBubbleControllerImplTest, Metrics_Upload_AfterSave_OnClose) {
  base::HistogramTester histogram_tester;

  ShowUploadBubble();
  controller()->OnSaveButton({});

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow",
      autofill_metrics::SaveCardPromptResult::kAccepted, 1);

  ShowConfirmationBubbleView(/*card_saved=*/true);
  CloseBubble();

  histogram_tester.ExpectUniqueSample(
      "Autofill.CreditCardUpload.ConfirmationShown.CardUploaded", true, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.CreditCardUpload.ConfirmationResult.CardUploaded",
      autofill_metrics::SaveCardPromptResult::kNotInteracted, 1);
  // Expect the metric not to change from the save button interaction.
  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow", 1);
}

// Test that the `CardNotUploaded` confirmation shown & result metrics are
// recorded when the save card bubble is closed after the save card upload
// completes without the card being saved.
TEST_F(SaveCardBubbleControllerImplTest,
       Metrics_Upload_AfterFailedSave_OnClose) {
  base::HistogramTester histogram_tester;

  ShowUploadBubble();
  controller()->OnSaveButton({});
  ShowConfirmationBubbleView(/*card_saved=*/false);
  CloseBubble();

  histogram_tester.ExpectUniqueSample(
      "Autofill.CreditCardUpload.ConfirmationShown.CardNotUploaded", true, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.CreditCardUpload.ConfirmationResult.CardNotUploaded",
      autofill_metrics::SaveCardPromptResult::kNotInteracted, 1);
}

// Test that the `Accepted` upload result metric is not recorded and the loading
// view shown & closed metrics are recorded when the save card bubble is closed
// before the save card upload completes.
TEST_F(SaveCardBubbleControllerImplTest, Metrics_Upload_DuringSave_OnClose) {
  base::HistogramTester histogram_tester;

  ShowUploadBubble();
  controller()->OnSaveButton({});

  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow",
      autofill_metrics::SaveCardPromptResult::kAccepted, 1);

  CloseBubble();

  histogram_tester.ExpectUniqueSample("Autofill.CreditCardUpload.LoadingShown",
                                      true, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.CreditCardUpload.LoadingResult",
      autofill_metrics::SaveCardPromptResult::kNotInteracted, 1);
  // Expect the upload result metric not to change from the save button
  // interaction.
  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow", 1);
}

// Test that metrics are not recorded in
// SaveCardBubbleController::OnSaveButton() on local card save.
TEST_F(SaveCardBubbleControllerImplTest, Metrics_Local_OnSave) {
  base::HistogramTester histogram_tester;

  ShowLocalBubble();
  controller()->OnSaveButton({});

  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow", 0);
}

// Test that after changing tabs, when returning to the tab with the save card,
// the bubble view is no longer showing but can be accessed through the icon.
TEST_F(SaveCardBubbleControllerImplTest, VisibilityChange_Upload_HideBubble) {
  base::HistogramTester histogram_tester;

  ShowUploadBubble();
  EXPECT_TRUE(IsSaveCardBubbleVisible());

  // Simulate switching to a different tab.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);
  EXPECT_FALSE(IsSaveCardBubbleVisible());

  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow", 1);

  // Simulate returning to tab where bubble was previously shown.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::VISIBLE);

  EXPECT_FALSE(IsSaveCardBubbleVisible());
  EXPECT_TRUE(controller()->IsIconVisible());
}

// Test that after a link is clicked in the save card bubble view; and one
// returns to the tab with the save card, the bubble view is automatically
// re-shown without user prompt.
TEST_F(SaveCardBubbleControllerImplTest,
       VisibilityChange_Upload_ReshowAfterLinkClick) {
  tabs::TabInterface* tab = active_tab();

  ShowUploadBubble();
  EXPECT_TRUE(IsSaveCardBubbleVisible());

  controller()->OnLegalMessageLinkClicked(GURL("about:blank"));
  // Change active web contents back to previous tab so that
  // active_web_contents() and controller() return the correct object.
  browser()->tab_strip_model()->ActivateTabAt(
      browser()->tab_strip_model()->GetIndexOfTab(tab));

  // Usually, the visibility changes when changing tabs but it doesn't in the
  // test so it needs to be simulated.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);
  EXPECT_FALSE(IsSaveCardBubbleVisible());

  // Check that the bubble is shown when returning to the tab which previously
  // showed the bubble.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::VISIBLE);
  EXPECT_TRUE(IsSaveCardBubbleVisible());
  EXPECT_TRUE(controller()->IsIconVisible());

  // Check that the WebContents showing a subsequent time does not show the
  // bubble view.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);
  EXPECT_FALSE(IsSaveCardBubbleVisible());

  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::VISIBLE);

  EXPECT_FALSE(IsSaveCardBubbleVisible());
  EXPECT_TRUE(controller()->IsIconVisible());
}

// Test that while in the UPLOAD_IN_PROGRESS state, after changing tabs and
// returning to the tab with the save card, the state will remain as
// UPLOAD_IN_PROGRESS.
TEST_F(SaveCardBubbleControllerImplTest,
       VisibilityChange_Upload_InProgressState_Retained) {
  ShowUploadBubble();
  controller()->OnSaveButton({});
  EXPECT_TRUE(IsSaveCardBubbleVisible());
  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_IN_PROGRESS);

  // Simulate switching to a different tab and back to the original tab.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);
  EXPECT_FALSE(IsSaveCardBubbleVisible());
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::VISIBLE);

  EXPECT_EQ(controller()->GetBubbleType(), BubbleType::UPLOAD_IN_PROGRESS);
}

// Test that while in the UPLOAD_IN_PROGRESS state, if the tab is changed and
// the upload is completed, upon returning to the original tab with the save
// card, the confirmation bubble will be showing.
TEST_F(SaveCardBubbleControllerImplTest,
       VisibilityChange_Upload_InProgressStateTransitionIntoCompletedState) {
  tabs::TabInterface* tab = active_tab();

  ShowUploadBubble();
  controller()->OnSaveButton({});
  EXPECT_TRUE(IsSaveCardBubbleVisible());

  // Need to save a reference to the controller to call while on a different tab
  // because controller() grabs the controller from active_web_contents()
  // which is based on the active tab.
  TestSaveCardBubbleControllerImpl* save_card_controller = controller();

  // Switch to a different tab.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);
  AddTab(browser(), GURL("about:blank"));
  EXPECT_FALSE(IsSaveCardBubbleVisible());

  // Simulate that the upload is completed.
  save_card_controller->ShowConfirmationBubbleView(
      /*card_saved=*/true,
      /*on_confirmation_closed_callback=*/std::nullopt);

  // Expect that the confirmation bubble doesn't show up on the other tab.
  EXPECT_FALSE(IsConfirmationBubbleVisible());

  // Return to the original tab.
  browser()->tab_strip_model()->ActivateTabAt(
      browser()->tab_strip_model()->GetIndexOfTab(tab));
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::VISIBLE);

  // Expect that the confirmation bubble is visible.
  EXPECT_TRUE(IsConfirmationBubbleVisible());
}

// Test the metrics for reshowing the bubble view after a link is clicked.
TEST_F(SaveCardBubbleControllerImplTest,
       Metrics_VisibilityChange_Upload_ReshowAfterLinkClick) {
  base::HistogramTester histogram_tester;
  tabs::TabInterface* tab = active_tab();

  ShowUploadBubble();
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer.Upload.FirstShow",
      autofill_metrics::SaveCardPromptOffer::kShown, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer.Upload.Reshows",
      autofill_metrics::SaveCardPromptOffer::kShown, 0);

  controller()->OnLegalMessageLinkClicked(GURL("about:blank"));
  browser()->tab_strip_model()->ActivateTabAt(
      browser()->tab_strip_model()->GetIndexOfTab(tab));

  // Usually, the visibility changes when changing tabs but it doesn't in the
  // test so it needs to be simulated.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);

  // Ensure that closing the bubble through clicking a link does not get logged
  // to the metrics.
  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow", 0);
  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.Reshows", 0);

  // Reshow bubble view.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::VISIBLE);

  // Expect the prompt metric not to change from the initial bubble showing
  // because this is a reshowing after returning to the original tab after a
  // link click.
  // TODO(crbug.com/316391673): Determine if a different metric (or the re-show
  // metric) should be tracking this re-show.
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer.Upload.FirstShow",
      autofill_metrics::SaveCardPromptOffer::kShown, 1);
  histogram_tester.ExpectUniqueSample(
      "Autofill.SaveCreditCardPromptOffer.Upload.Reshows",
      autofill_metrics::SaveCardPromptOffer::kShown, 0);

  // Ensure that metrics are recorded on a subsequent bubble close.
  active_web_contents()->UpdateWebContentsVisibility(
      content::Visibility::HIDDEN);
  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.FirstShow", 0);
  histogram_tester.ExpectTotalCount(
      "Autofill.SaveCreditCardPromptResult.Upload.Reshows", 1);
}

// Test that `HideSaveCardBubble()` hides save card offer and confirmation
// bubble.
TEST_F(SaveCardBubbleControllerImplTest, HideSaveCardBubble) {
  ShowUploadBubble();
  EXPECT_NE(controller()->GetPaymentBubbleView(), nullptr);

  controller()->HideSaveCardBubble();
  EXPECT_EQ(controller()->GetPaymentBubbleView(), nullptr);

  ShowConfirmationBubbleView(/*card_saved=*/true);
  EXPECT_NE(controller()->GetPaymentBubbleView(), nullptr);

  controller()->HideSaveCardBubble();
  EXPECT_EQ(controller()->GetPaymentBubbleView(), nullptr);
}

// Test that `OnConfirmationClosedCallback` runs when confirmation prompt
// is closed by user.
TEST_F(SaveCardBubbleControllerImplTest,
       OnConfirmationPromptClosedByUser_RunCallback) {
  ShowConfirmationBubbleView(/*card_saved=*/true);
  CloseBubble();
  EXPECT_TRUE(did_on_confirmation_closed_callback_run_);
  EXPECT_EQ(controller()->GetPaymentBubbleView(), nullptr);
}

// Test that `OnConfirmationClosedCallback` runs when confirmation prompt is
// auto-closed in 3 sec.
TEST_F(SaveCardBubbleControllerImplTest,
       OnConfirmationPromptAutoClosed_RunCallback) {
  ShowConfirmationBubbleView(/*card_saved=*/true);
  task_environment()->FastForwardBy(
      SaveCardBubbleControllerImpl::kAutoCloseConfirmationBubbleWaitSec);
  EXPECT_TRUE(did_on_confirmation_closed_callback_run_);
  EXPECT_EQ(controller()->GetPaymentBubbleView(), nullptr);
}

class SaveCardBubbleControllerImplTestWithCvCStorageAndFilling
    : public SaveCardBubbleControllerImplTest {
  base::test::ScopedFeatureList scoped_feature_list_{
      features::kAutofillEnableCvcStorageAndFilling};
};

TEST_F(SaveCardBubbleControllerImplTestWithCvCStorageAndFilling,
       LocalCardSaveOnlyDialogContent) {
  // Show the local card save bubble.
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions()
          .with_card_save_type(CardSaveType::kCardSaveOnly)
          .with_show_prompt(true));

  ASSERT_EQ(BubbleType::LOCAL_SAVE, controller()->GetBubbleType());
  ASSERT_NE(nullptr, controller()->GetPaymentBubbleView());
  EXPECT_EQ(controller()->GetWindowTitle(), u"Save card?");
  EXPECT_EQ(controller()->GetExplanatoryMessage(),
            u"To pay faster next time, save your card to your device");
}

TEST_F(SaveCardBubbleControllerImplTestWithCvCStorageAndFilling,
       LocalCardSaveWithCvcDialogContent) {
  // Show the local card save with CVC bubble.
  ShowLocalBubble(
      /*card=*/nullptr,
      /*options=*/SaveCreditCardOptions()
          .with_card_save_type(CardSaveType::kCardSaveWithCvc)
          .with_show_prompt(true));

  ASSERT_EQ(BubbleType::LOCAL_SAVE, controller()->GetBubbleType());
  ASSERT_NE(nullptr, controller()->GetPaymentBubbleView());
  EXPECT_EQ(controller()->GetWindowTitle(), u"Save card?");
  EXPECT_EQ(controller()->GetExplanatoryMessage(),
            u"To pay faster next time, save your card and encrypted security "
            u"code to your device");
}

}  // namespace
}  // namespace autofill