File: search_engine_choice_service_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 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 (1302 lines) | stat: -rw-r--r-- 56,411 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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/search_engines/search_engine_choice/search_engine_choice_service.h"

#include <memory>
#include <string_view>
#include <vector>

#include "base/check_deref.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/functional/callback_helpers.h"
#include "base/notreached.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/time/time.h"
#include "base/version.h"
#include "build/build_config.h"
#include "components/country_codes/country_codes.h"
#include "components/metrics/metrics_pref_names.h"
#include "components/policy/core/common/mock_policy_service.h"
#include "components/policy/core/common/policy_namespace.h"
#include "components/policy/core/common/policy_types.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/testing_pref_service.h"
#include "components/regional_capabilities/regional_capabilities_service.h"
#include "components/regional_capabilities/regional_capabilities_switches.h"
#include "components/regional_capabilities/regional_capabilities_test_utils.h"
#include "components/search_engines/choice_made_location.h"
#include "components/search_engines/default_search_manager.h"
#include "components/search_engines/search_engine_choice/search_engine_choice_metrics_service_accessor.h"
#include "components/search_engines/search_engine_choice/search_engine_choice_service_test_base.h"
#include "components/search_engines/search_engine_choice/search_engine_choice_utils.h"
#include "components/search_engines/search_engine_type.h"
#include "components/search_engines/search_engines_pref_names.h"
#include "components/search_engines/search_engines_switches.h"
#include "components/search_engines/search_engines_test_environment.h"
#include "components/search_engines/search_engines_test_util.h"
#include "components/search_engines/template_url_data.h"
#include "components/search_engines/template_url_data_util.h"
#include "components/search_engines/template_url_prepopulate_data.h"
#include "components/search_engines/template_url_prepopulate_data_resolver.h"
#include "components/search_engines/template_url_service.h"
#include "components/signin/public/base/signin_switches.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "components/version_info/version_info.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/search_engines_data/resources/definitions/prepopulated_engines.h"

using ::country_codes::CountryId;
using ::search_engines::RepromptResult;
using ::search_engines::SearchEngineChoiceWipeReason;
using ::testing::NiceMock;

namespace search_engines {
namespace {

const CountryId kBelgiumCountryId = CountryId("BE");
const CountryId kUsaCountryId = CountryId("US");

TemplateURL::OwnedTemplateURLVector
OwnedTemplateURLVectorFromPrepopulatedEngines(
    const std::vector<const TemplateURLPrepopulateData::PrepopulatedEngine*>&
        engines) {
  TemplateURL::OwnedTemplateURLVector result;
  for (const TemplateURLPrepopulateData::PrepopulatedEngine* engine : engines) {
    result.push_back(std::make_unique<TemplateURL>(
        *TemplateURLDataFromPrepopulatedEngine(*engine)));
  }
  return result;
}

}  // namespace

class SearchEngineChoiceServiceTest : public SearchEngineChoiceServiceTestBase {
};

#if !BUILDFLAG(IS_IOS) && !BUILDFLAG(IS_ANDROID)
TEST_F(SearchEngineChoiceServiceTest, GuestSessionDsePropagation) {
  InitService({.force_reset = true,
               .is_profile_eligible_for_dse_guest_propagation = true});

  EXPECT_FALSE(local_state().HasPrefPath(
      prefs::kDefaultSearchProviderGuestModePrepopulatedId));
  EXPECT_FALSE(search_engine_choice_service()
                   .GetSavedSearchEngineBetweenGuestSessions()
                   .has_value());

  constexpr int prepopulated_id = 1;
  search_engine_choice_service().SetSavedSearchEngineBetweenGuestSessions(
      prepopulated_id);
  EXPECT_EQ(local_state().GetInt64(
                prefs::kDefaultSearchProviderGuestModePrepopulatedId),
            prepopulated_id);
  EXPECT_EQ(
      search_engine_choice_service().GetSavedSearchEngineBetweenGuestSessions(),
      prepopulated_id);

  // The guest DSE is not propagated to services that are not guest profiles.
  InitService({.force_reset = true,
               .is_profile_eligible_for_dse_guest_propagation = false});
  EXPECT_FALSE(search_engine_choice_service()
                   .GetSavedSearchEngineBetweenGuestSessions()
                   .has_value());

  // A new guest service propagates the DSE.
  InitService({.force_reset = true,
               .is_profile_eligible_for_dse_guest_propagation = true});
  EXPECT_EQ(
      search_engine_choice_service().GetSavedSearchEngineBetweenGuestSessions(),
      prepopulated_id);
}

TEST_F(SearchEngineChoiceServiceTest,
       UpdatesDefaultSearchEngineManagerForGuestMode) {
  InitService({.force_reset = true,
               .is_profile_eligible_for_dse_guest_propagation = true});

  DefaultSearchManager manager(pref_service(), &search_engine_choice_service(),
                               prepopulate_data_resolver(),
                               base::NullCallback());
  DefaultSearchManager::Source source;
  EXPECT_EQ(manager.GetDefaultSearchEngine(&source)->prepopulate_id, 1);
  EXPECT_EQ(source, DefaultSearchManager::Source::FROM_FALLBACK);

  // Test the changes in the SearchEngineChoiceService propagate to the DSE
  // manager.
  search_engine_choice_service().SetSavedSearchEngineBetweenGuestSessions(2);
  EXPECT_EQ(manager.GetDefaultSearchEngine(&source)->prepopulate_id, 2);
  EXPECT_EQ(source, DefaultSearchManager::Source::FROM_FALLBACK);
}
#endif

TEST_F(SearchEngineChoiceServiceTest, RecordChoiceMade) {
  base::CommandLine::ForCurrentProcess()->RemoveSwitch(
      switches::kSearchEngineChoiceCountry);
  // Test that the choice is not recorded for countries outside the EEA region.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kSearchEngineChoiceCountry, "US");

  const TemplateURL* default_search_engine =
      template_url_service().GetDefaultSearchProvider();
  EXPECT_EQ(default_search_engine->prepopulate_id(),
            TemplateURLPrepopulateData::google.id);

  search_engine_choice_service().RecordChoiceMade(
      search_engines::ChoiceMadeLocation::kChoiceScreen,
      &template_url_service());

  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceScreenDefaultSearchEngineTypeHistogram,
      SearchEngineType::SEARCH_ENGINE_GOOGLE, 0);
  histogram_tester_.ExpectUniqueSample(
      search_engines::
          kSearchEngineChoiceScreenDefaultSearchEngineType2Histogram,
      SearchEngineType::SEARCH_ENGINE_GOOGLE, 0);
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));

  // Revert to an EEA region country.
  base::CommandLine::ForCurrentProcess()->RemoveSwitch(
      switches::kSearchEngineChoiceCountry);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kSearchEngineChoiceCountry, kBelgiumCountryId.CountryCode());

  // Test that the choice is recorded if it wasn't previously done.
  search_engine_choice_service().RecordChoiceMade(
      search_engines::ChoiceMadeLocation::kChoiceScreen,
      &template_url_service());
  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceScreenDefaultSearchEngineTypeHistogram,
      SearchEngineType::SEARCH_ENGINE_GOOGLE, 1);
  histogram_tester_.ExpectUniqueSample(
      search_engines::
          kSearchEngineChoiceScreenDefaultSearchEngineType2Histogram,
      SearchEngineType::SEARCH_ENGINE_GOOGLE, 1);

  EXPECT_NEAR(pref_service()->GetInt64(
                  prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp),
              base::Time::Now().ToDeltaSinceWindowsEpoch().InSeconds(),
              /*abs_error=*/2);
  EXPECT_EQ(pref_service()->GetString(
                prefs::kDefaultSearchProviderChoiceScreenCompletionVersion),
            version_info::GetVersionNumber());

  // Set the pref to 5 so that we can know if it gets modified.
  const int kModifiedTimestamp = 5;
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      kModifiedTimestamp);

  // Test that the choice is not recorded if it was previously done.
  search_engine_choice_service().RecordChoiceMade(
      search_engines::ChoiceMadeLocation::kChoiceScreen,
      &template_url_service());
  EXPECT_EQ(pref_service()->GetInt64(
                prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp),
            kModifiedTimestamp);

  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceScreenDefaultSearchEngineTypeHistogram,
      SearchEngineType::SEARCH_ENGINE_GOOGLE, 1);
  histogram_tester_.ExpectUniqueSample(
      search_engines::
          kSearchEngineChoiceScreenDefaultSearchEngineType2Histogram,
      SearchEngineType::SEARCH_ENGINE_GOOGLE, 1);
}

TEST_F(SearchEngineChoiceServiceTest, RecordChoiceMade_ByLocation) {
  // Configure to an EEA region country.
  base::CommandLine::ForCurrentProcess()->RemoveSwitch(
      switches::kSearchEngineChoiceCountry);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kSearchEngineChoiceCountry, kBelgiumCountryId.CountryCode());
  EXPECT_EQ(template_url_service().GetDefaultSearchProvider()->prepopulate_id(),
            TemplateURLPrepopulateData::google.id);

  auto locations = {ChoiceMadeLocation::kChoiceScreen,
                    ChoiceMadeLocation::kSearchSettings,
                    ChoiceMadeLocation::kSearchEngineSettings};
  int expected_v1_records = 0;
  int expected_v2_records = 0;
  for (const ChoiceMadeLocation& choice_location : locations) {
    switch (choice_location) {
      case ChoiceMadeLocation::kChoiceScreen:
        // For the choice screen, the choice should be recorded in the both
        // histograms.
        expected_v1_records += 1;
        expected_v2_records += 1;
        break;

      case ChoiceMadeLocation::kSearchSettings:
      case ChoiceMadeLocation::kSearchEngineSettings:
        // For other locations, the choice should be recorded only in the legacy
        // histogram.
        expected_v1_records += 1;
        break;
      case ChoiceMadeLocation::kOther:
        NOTREACHED();  // Not an allowed value for `RecordChoiceMade()`.
    }

    search_engine_choice_service().RecordChoiceMade(choice_location,
                                                    &template_url_service());
    histogram_tester_.ExpectBucketCount(
        search_engines::
            kSearchEngineChoiceScreenDefaultSearchEngineTypeHistogram,
        SearchEngineType::SEARCH_ENGINE_GOOGLE, expected_v1_records);
    histogram_tester_.ExpectUniqueSample(
        search_engines::
            kSearchEngineChoiceScreenDefaultSearchEngineType2Histogram,
        SearchEngineType::SEARCH_ENGINE_GOOGLE, expected_v2_records);
    WipeSearchEngineChoicePrefs(*pref_service(),
                                SearchEngineChoiceWipeReason::kCommandLineFlag);
  }
}

TEST_F(SearchEngineChoiceServiceTest, RecordChoiceMade_DistributionCustom) {
  // A distribution custom search engine will have a `prepopulate_id` > 1000.
  const int kDistributionCustomSearchEnginePrepopulateId = 1001;
  TemplateURLData template_url_data;
  template_url_data.prepopulate_id =
      kDistributionCustomSearchEnginePrepopulateId;
  template_url_data.SetURL("https://www.example.com/?q={searchTerms}");
  template_url_service().SetUserSelectedDefaultSearchProvider(
      template_url_service().Add(
          std::make_unique<TemplateURL>(template_url_data)));

  // Revert to an EEA region country.
  base::CommandLine::ForCurrentProcess()->RemoveSwitch(
      switches::kSearchEngineChoiceCountry);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kSearchEngineChoiceCountry, kBelgiumCountryId.CountryCode());

  // Test that the choice is recorded if it wasn't previously done.
  search_engine_choice_service().RecordChoiceMade(
      search_engines::ChoiceMadeLocation::kChoiceScreen,
      &template_url_service());
  histogram_tester_.ExpectBucketCount(
      search_engines::kSearchEngineChoiceScreenDefaultSearchEngineTypeHistogram,
      SearchEngineType::SEARCH_ENGINE_OTHER, 1);
  histogram_tester_.ExpectUniqueSample(
      search_engines::
          kSearchEngineChoiceScreenDefaultSearchEngineType2Histogram,
      SearchEngineType::SEARCH_ENGINE_OTHER, 1);

  EXPECT_NEAR(pref_service()->GetInt64(
                  prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp),
              base::Time::Now().ToDeltaSinceWindowsEpoch().InSeconds(),
              /*abs_error=*/2);
  EXPECT_EQ(pref_service()->GetString(
                prefs::kDefaultSearchProviderChoiceScreenCompletionVersion),
            version_info::GetVersionNumber());
}

TEST_F(SearchEngineChoiceServiceTest, RecordChoiceMade_RemovedPrepopulated) {
  // We don't have a prepopulated search engine with ID 20, but at some point
  // in the past, we did. So some profiles might still have it.
  const int kRemovedSearchEnginePrepopulateId = 20;
  TemplateURLData template_url_data;
  template_url_data.prepopulate_id = kRemovedSearchEnginePrepopulateId;
  template_url_data.SetURL("https://www.example.com/?q={searchTerms}");
  template_url_service().SetUserSelectedDefaultSearchProvider(
      template_url_service().Add(
          std::make_unique<TemplateURL>(template_url_data)));

  // Revert to an EEA region country.
  base::CommandLine::ForCurrentProcess()->RemoveSwitch(
      switches::kSearchEngineChoiceCountry);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kSearchEngineChoiceCountry, kBelgiumCountryId.CountryCode());

  // Test that the choice is recorded if it wasn't previously done.
  search_engine_choice_service().RecordChoiceMade(
      search_engines::ChoiceMadeLocation::kChoiceScreen,
      &template_url_service());
  histogram_tester_.ExpectBucketCount(
      search_engines::kSearchEngineChoiceScreenDefaultSearchEngineTypeHistogram,
      SearchEngineType::SEARCH_ENGINE_OTHER, 1);
  histogram_tester_.ExpectUniqueSample(
      search_engines::
          kSearchEngineChoiceScreenDefaultSearchEngineType2Histogram,
      SearchEngineType::SEARCH_ENGINE_OTHER, 1);

  EXPECT_NEAR(pref_service()->GetInt64(
                  prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp),
              base::Time::Now().ToDeltaSinceWindowsEpoch().InSeconds(),
              /*abs_error=*/2);
  EXPECT_EQ(pref_service()->GetString(
                prefs::kDefaultSearchProviderChoiceScreenCompletionVersion),
            version_info::GetVersionNumber());
}

TEST_F(SearchEngineChoiceServiceTest, MaybeRecordChoiceScreenDisplayState) {
  InitService({.variation_country_id = kBelgiumCountryId,
               .client_country_id = kBelgiumCountryId,
               .force_reset = true});
  ChoiceScreenData choice_screen_data(
      OwnedTemplateURLVectorFromPrepopulatedEngines(
          {&TemplateURLPrepopulateData::google,
           &TemplateURLPrepopulateData::bing,
           &TemplateURLPrepopulateData::yahoo}),
      kBelgiumCountryId, SearchTermsData());
  ChoiceScreenDisplayState display_state = choice_screen_data.display_state();
  display_state.selected_engine_index = 2;

  base::HistogramTester histogram_tester;
  search_engine_choice_service().MaybeRecordChoiceScreenDisplayState(
      display_state);

  histogram_tester.ExpectUniqueSample(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 2, 1);
  histogram_tester.ExpectBucketCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, false,
      1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      SEARCH_ENGINE_GOOGLE, 1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 1),
      SEARCH_ENGINE_BING, 1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 2),
      SEARCH_ENGINE_YAHOO, 1);

  // There is no search engine shown at index 3, since we have only 3 options.
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 3),
      0);

  // We logged the display state, so we don't need to cache it.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_ProfileCountryMismatch) {
  // The actual profile of the country does not matter, we are checking the
  // `ChoiceScreenData` country against the variations country.
  InitService({.variation_country_id = kBelgiumCountryId,
               .client_country_id = kUsaCountryId,
               .force_reset = true});
  ChoiceScreenData choice_screen_data(
      OwnedTemplateURLVectorFromPrepopulatedEngines(
          {&TemplateURLPrepopulateData::google,
           &TemplateURLPrepopulateData::bing,
           &TemplateURLPrepopulateData::yahoo}),
      kBelgiumCountryId, SearchTermsData());
  ChoiceScreenDisplayState display_state = choice_screen_data.display_state();
  display_state.selected_engine_index = 2;

  base::HistogramTester histogram_tester;
  search_engine_choice_service().MaybeRecordChoiceScreenDisplayState(
      display_state);

  histogram_tester.ExpectUniqueSample(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 2, 1);
  histogram_tester.ExpectBucketCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, false,
      1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      SEARCH_ENGINE_GOOGLE, 1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 1),
      SEARCH_ENGINE_BING, 1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 2),
      SEARCH_ENGINE_YAHOO, 1);

  // There is no search engine shown at index 3, since we have only 3 options.
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 3),
      0);

  // We logged the display state, so we don't need to cache it.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_NoopUnsupportedCountry) {
  auto engines = {&TemplateURLPrepopulateData::google,
                  &TemplateURLPrepopulateData::bing,
                  &TemplateURLPrepopulateData::yahoo};
  base::HistogramTester histogram_tester;

  {
    // Unknown country.
    InitService({.force_reset = true});
    ChoiceScreenData choice_screen_data(
        OwnedTemplateURLVectorFromPrepopulatedEngines(engines), CountryId(),
        SearchTermsData());
    ChoiceScreenDisplayState display_state = choice_screen_data.display_state();
    display_state.selected_engine_index = 0;

    search_engine_choice_service().MaybeRecordChoiceScreenDisplayState(
        display_state);
  }

  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 0);
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, 0);

  // The choice is coming from a non-eea country and won't be logged, don't
  // cache it.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));

  {
    // Non-EEA variations country.
    InitService({.variation_country_id = kUsaCountryId, .force_reset = true});
    ChoiceScreenData choice_screen_data(
        OwnedTemplateURLVectorFromPrepopulatedEngines(engines), kUsaCountryId,
        SearchTermsData());
    ChoiceScreenDisplayState display_state = choice_screen_data.display_state();
    display_state.selected_engine_index = 0;
    search_engine_choice_service().MaybeRecordChoiceScreenDisplayState(
        display_state);
  }

  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 0);
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, 0);

  // The choice is coming from a non-eea country and won't be logged, don't
  // cache it.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_MismatchingCountry) {
  auto engines = {&TemplateURLPrepopulateData::google,
                  &TemplateURLPrepopulateData::bing,
                  &TemplateURLPrepopulateData::yahoo};
  base::HistogramTester histogram_tester;

  // Mismatch between the variations and choice screen data country.
  InitService({.variation_country_id = country_codes::CountryId("DE"),
               .force_reset = true});
  ChoiceScreenData choice_screen_data(
      OwnedTemplateURLVectorFromPrepopulatedEngines(engines), kBelgiumCountryId,
      SearchTermsData());
  ChoiceScreenDisplayState display_state = choice_screen_data.display_state();
  display_state.selected_engine_index = 0;
  search_engine_choice_service().MaybeRecordChoiceScreenDisplayState(
      display_state);

  histogram_tester.ExpectBucketCount(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 0, 1);
  histogram_tester.ExpectBucketCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, true, 1);

  // None of the above should have logged the full list of indices.
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 1),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 2),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 3),
      0);

  // The choice screen state should be cached for a next chance later.
  EXPECT_TRUE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));

  auto stored_display_state =
      ChoiceScreenDisplayState::FromDict(pref_service()->GetDict(
          prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
  EXPECT_EQ(stored_display_state->search_engines, display_state.search_engines);
  EXPECT_EQ(stored_display_state->country_id, display_state.country_id);
  EXPECT_EQ(stored_display_state->selected_engine_index,
            display_state.selected_engine_index);
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_OnServiceStartup) {
  ChoiceScreenDisplayState display_state(
      /*search_engines=*/{SEARCH_ENGINE_GOOGLE, SEARCH_ENGINE_BING,
                          SEARCH_ENGINE_YAHOO},
      /*country_id=*/kBelgiumCountryId,
      /*selected_engine_index=*/0);
  pref_service()->SetDict(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState,
      display_state.ToDict());
  search_engines::MarkSearchEngineChoiceCompletedForTesting(*pref_service());

  base::HistogramTester histogram_tester;
  InitService({.variation_country_id = kBelgiumCountryId, .force_reset = true});

  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      SEARCH_ENGINE_GOOGLE, 1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 1),
      SEARCH_ENGINE_BING, 1);
  histogram_tester.ExpectUniqueSample(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 2),
      SEARCH_ENGINE_YAHOO, 1);

  // These metrics are expected to have been already logged at the time we
  // cached the screen state.
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 0);
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, 0);

  // The choice screen state should now be cleared.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_OnServiceStartup_CountryMismatch) {
  ChoiceScreenDisplayState display_state(
      /*search_engines=*/{SEARCH_ENGINE_GOOGLE, SEARCH_ENGINE_BING,
                          SEARCH_ENGINE_YAHOO},
      /*country_id=*/kBelgiumCountryId,
      /*selected_engine_index=*/0);
  pref_service()->SetDict(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState,
      display_state.ToDict());
  search_engines::MarkSearchEngineChoiceCompletedForTesting(*pref_service());

  base::HistogramTester histogram_tester;
  InitService({.force_reset = true});

  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 1),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 2),
      0);

  // These metrics are expected to have been already logged at the time we
  // cached the screen state.
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenSelectedEngineIndexHistogram, 0);
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, 0);

  // The choice screen state should stay around.
  EXPECT_TRUE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_OnServiceStartup_ChoicePrefCleared) {
  ChoiceScreenDisplayState display_state(
      /*search_engines=*/{SEARCH_ENGINE_GOOGLE, SEARCH_ENGINE_BING,
                          SEARCH_ENGINE_YAHOO},
      /*country_id=*/kBelgiumCountryId,
      /*selected_engine_index=*/0);
  pref_service()->SetDict(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState,
      display_state.ToDict());

  base::HistogramTester histogram_tester;
  InitService({.force_reset = true});

  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, 0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 1),
      0);
  histogram_tester.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 2),
      0);

  // Choice not marked done, so the service also clear the pending state.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));
}

TEST_F(SearchEngineChoiceServiceTest,
       MaybeRecordChoiceScreenDisplayState_OnServiceStartup_UmaDisabled) {
  // Disable UMA reporting.
  SearchEngineChoiceMetricsServiceAccessor::
      SetForceIsMetricsReportingEnabledPrefLookup(false);

  ChoiceScreenDisplayState display_state(
      /*search_engines=*/{SEARCH_ENGINE_GOOGLE, SEARCH_ENGINE_BING,
                          SEARCH_ENGINE_YAHOO},
      /*country_id=*/kBelgiumCountryId,
      /*selected_engine_index=*/0);
  pref_service()->SetDict(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState,
      display_state.ToDict());
  EXPECT_TRUE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));

  InitService({.variation_country_id = kBelgiumCountryId, .force_reset = true});
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderPendingChoiceScreenDisplayState));

  histogram_tester_.ExpectTotalCount(
      base::StringPrintf(
          kSearchEngineChoiceScreenShowedEngineAtHistogramPattern, 0),
      0);
  histogram_tester_.ExpectTotalCount(
      kSearchEngineChoiceScreenShowedEngineAtCountryMismatchHistogram, 0);
}

// Tests if choice screen completion date is not recorded if last choice date is
// unknown.
TEST_F(SearchEngineChoiceServiceTest, IgnoresChoiceScreenCompletionDateRecord) {
  base::HistogramTester histogram_tester;
  search_engine_choice_service();
  histogram_tester.ExpectTotalCount(
      kSearchEngineChoiceCompletedOnMonthHistogram, 0);
}

// Tests if choice screen completion date is recorded.
TEST_F(SearchEngineChoiceServiceTest,
       RecordsChoiceScreenCompletionDateHistogram) {
  base::HistogramTester histogram_tester;

  // April 18, 2025, 13:30 Europe/Warsaw. What is specific about this timestamp
  // (in windows epoch seconds) is that in every known timezone,
  // this was April 2025.
  int64_t windows_epoch_timestamp = 13388103000;

  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion, "1.0.0.0");
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      windows_epoch_timestamp);

  search_engine_choice_service();
  histogram_tester.ExpectUniqueSample(
      kSearchEngineChoiceCompletedOnMonthHistogram, 202504, 1);
}

// Tests if choice screen completion date is recorded.
TEST_F(SearchEngineChoiceServiceTest,
       RecordsChoiceScreenCompletionDateBefore2022Histogram) {
  base::HistogramTester histogram_tester;

  // July 1993. What is specific about this timestamp (in windows epoch seconds)
  // is that it is before 2022.
  int64_t windows_epoch_timestamp = 12388103000;

  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion, "1.0.0.0");
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      windows_epoch_timestamp);

  search_engine_choice_service();
  histogram_tester.ExpectUniqueSample(
      kSearchEngineChoiceCompletedOnMonthHistogram, 100001, 1);
}

// Tests if choice screen completion date is recorded.
TEST_F(SearchEngineChoiceServiceTest,
       RecordsChoiceScreenCompletionDateAfter2050Histogram) {
  base::HistogramTester histogram_tester;

  // December 2056. What is specific about this timestamp (in windows epoch
  // seconds) is that it is after 2050.
  int64_t windows_epoch_timestamp = 14388103000;

  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion, "1.0.0.0");
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      windows_epoch_timestamp);

  search_engine_choice_service();
  histogram_tester.ExpectUniqueSample(
      kSearchEngineChoiceCompletedOnMonthHistogram, 300001, 1);
}

// Test that the user is not reprompted if the reprompt parameter is not a valid
// JSON string.
TEST_F(SearchEngineChoiceServiceTest, NoRepromptForSyntaxError) {
  // Set the reprompt parameters with invalid syntax.
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      switches::kSearchEngineChoiceTrigger,
      {{switches::kSearchEngineChoiceTriggerRepromptParams.name, "Foo"}});
  ASSERT_EQ("Foo", switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  // Initialize the preference with some previous choice.
  int64_t kPreviousTimestamp = 1;
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      kPreviousTimestamp);
  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion, "1.0.0.0");

  // Trigger the creation of the service, which should check for the reprompt.
  search_engine_choice_service();

  // The user should not be reprompted.
  EXPECT_EQ(kPreviousTimestamp,
            pref_service()->GetInt64(
                prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceWipeReasonHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceRepromptHistogram,
      RepromptResult::kInvalidDictionary, 1);
}

// Test that the user is not reprompted when no persisted metadata indicates any
// choice-related activity took place.
TEST_F(SearchEngineChoiceServiceTest, NoOpWhenNoChoiceMetadataPresent) {
  ASSERT_EQ(switches::kSearchEngineChoiceNoRepromptString,
            switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  // Trigger the creation of the service, which should check for the reprompt.
  search_engine_choice_service();

  // The user should not be reprompted, no associated histogram recorded.
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceWipeReasonHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptHistogram, 0);
}

// Test that the user is not reprompted by default.
TEST_F(SearchEngineChoiceServiceTest, NoRepromptByDefault) {
  ASSERT_EQ(switches::kSearchEngineChoiceNoRepromptString,
            switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  // Initialize the preference with some previous choice.
  int64_t kPreviousTimestamp = 1;
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      kPreviousTimestamp);
  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion, "1.0.0.0");

  // Trigger the creation of the service, which should check for the reprompt.
  search_engine_choice_service();

  // The user should not be reprompted.
  EXPECT_EQ(kPreviousTimestamp,
            pref_service()->GetInt64(
                prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceWipeReasonHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceRepromptHistogram,
      RepromptResult::kNoReprompt, 1);
  histogram_tester_.ExpectBucketCount(
      search_engines::kSearchEngineChoiceRepromptHistogram,
      RepromptResult::kInvalidDictionary, 0);
}

// The user is reprompted if the version preference is missing.
TEST_F(SearchEngineChoiceServiceTest, RepromptForMissingChoiceVersion) {
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      switches::kSearchEngineChoiceTrigger,
      {{switches::kSearchEngineChoiceTriggerRepromptParams.name, "{}"}});
  ASSERT_EQ("{}", switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  // Initialize the timestamp, but not the version.
  int64_t kPreviousTimestamp = 1;
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      kPreviousTimestamp);

  // Trigger the creation of the service, which should check for the reprompt.
  search_engine_choice_service();

  // The user should be reprompted.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceWipeReasonHistogram,
      SearchEngineChoiceWipeReason::kMissingMetadataVersion, 1);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptHistogram, 0);
}

// The user is reprompted if the timestamp preference is missing.
TEST_F(SearchEngineChoiceServiceTest, RepromptForMissingTimestamp) {
  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      switches::kSearchEngineChoiceTrigger,
      {{switches::kSearchEngineChoiceTriggerRepromptParams.name, "{}"}});
  ASSERT_EQ("{}", switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  // Initialize the version, but not the timestamp.
  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion, "1.0.0.0");

  // Trigger the creation of the service, which should check for the reprompt.
  search_engine_choice_service();

  // The user should be reprompted.
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
  EXPECT_FALSE(pref_service()->HasPrefPath(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
  histogram_tester_.ExpectUniqueSample(
      search_engines::kSearchEngineChoiceWipeReasonHistogram,
      SearchEngineChoiceWipeReason::kInvalidMetadata, 1);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptHistogram, 0);
}

class SearchEngineChoiceServiceWipeOnMissingDSETest
    : public SearchEngineChoiceServiceTest,
      public testing::WithParamInterface<bool> {
 public:
  SearchEngineChoiceServiceWipeOnMissingDSETest() {
    scoped_feature_list_.InitWithFeatureState(
        switches::kWipeChoicePrefsOnMissingDefaultSearchEngine,
        IsFeatureEnabled());
  }

  bool IsFeatureEnabled() const { return GetParam(); }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

TEST_P(SearchEngineChoiceServiceWipeOnMissingDSETest, WipeOnMissingDSE) {
  {
    // Set up services and make some DSE choice.
    std::unique_ptr<TemplateURLData> data =
        TemplateURLDataFromPrepopulatedEngine(
            TemplateURLPrepopulateData::google);
    auto template_url = std::make_unique<TemplateURL>(*data);
    template_url_service().SetUserSelectedDefaultSearchProvider(
        template_url.get(), ChoiceMadeLocation::kChoiceScreen);

    // Check that choice prefs are present.
    EXPECT_TRUE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    EXPECT_TRUE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
    EXPECT_TRUE(pref_service()->HasPrefPath(
        DefaultSearchManager::kDefaultSearchProviderDataPrefName));

    ResetServices();
  }

  // Remove the DSE pref.
  pref_service()->ClearPref(
      DefaultSearchManager::kDefaultSearchProviderDataPrefName);

  // Instantiating the service should wipe the choice prefs when the feature is
  // enabled.
  search_engine_choice_service();

  if (IsFeatureEnabled()) {
    EXPECT_FALSE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    EXPECT_FALSE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
    histogram_tester_.ExpectUniqueSample(
        search_engines::kSearchEngineChoiceWipeReasonHistogram,
        SearchEngineChoiceWipeReason::kMissingDefaultSearchEngine, 1);
    histogram_tester_.ExpectUniqueSample(
        "Search.ChoicePrefsCheck.WipeOnMissingDse", true, 1);
  } else {
    EXPECT_TRUE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    EXPECT_TRUE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
    histogram_tester_.ExpectTotalCount(
        search_engines::kSearchEngineChoiceWipeReasonHistogram, 0);
    histogram_tester_.ExpectUniqueSample(
        "Search.ChoicePrefsCheck.WipeOnMissingDse", false, 1);
  }
}

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

struct DeviceRestoreTestParam {
  std::string test_suffix;
  bool restore_detected_in_current_session;
  bool choice_predates_restore;
  bool is_feature_enabled;
  bool is_invalidation_retroactive;
  bool expect_choice_info_wipe;
};

class SearchEngineChoiceServiceDeviceRestoreTest
    : public SearchEngineChoiceServiceTest,
      public testing::WithParamInterface<DeviceRestoreTestParam> {
 public:
  SearchEngineChoiceServiceDeviceRestoreTest() {
    if (GetParam().is_feature_enabled) {
      scoped_feature_list_.InitAndEnableFeatureWithParameters(
          switches::kInvalidateSearchEngineChoiceOnDeviceRestoreDetection,
          {{switches::kInvalidateChoiceOnRestoreIsRetroactive.name,
            GetParam().is_invalidation_retroactive ? "true" : "false"}});
    } else {
      scoped_feature_list_.InitAndDisableFeature(
          switches::kInvalidateSearchEngineChoiceOnDeviceRestoreDetection);
    }
  }

  static std::string GetTestSuffix(
      const testing::TestParamInfo<DeviceRestoreTestParam>& info) {
    return info.param.test_suffix;
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    SearchEngineChoiceServiceDeviceRestoreTest,
    ::testing::ValuesIn({
        DeviceRestoreTestParam{.test_suffix = "WipeForPreexistingChoice",
                               .restore_detected_in_current_session = true,
                               .choice_predates_restore = true,
                               .is_feature_enabled = true,
                               .is_invalidation_retroactive = false,
                               .expect_choice_info_wipe = true},
        DeviceRestoreTestParam{.test_suffix = "WipeForRetroactiveDetection",
                               .restore_detected_in_current_session = false,
                               .choice_predates_restore = true,
                               .is_feature_enabled = true,
                               .is_invalidation_retroactive = true,
                               .expect_choice_info_wipe = true},
        DeviceRestoreTestParam{.test_suffix = "NoWipeForLateDetection",
                               .restore_detected_in_current_session = false,
                               .choice_predates_restore = true,
                               .is_feature_enabled = true,
                               .is_invalidation_retroactive = false,
                               .expect_choice_info_wipe = false},
        DeviceRestoreTestParam{.test_suffix = "NoWipeForNewChoice",
                               .restore_detected_in_current_session = true,
                               .choice_predates_restore = false,
                               .is_feature_enabled = true,
                               .is_invalidation_retroactive = false,
                               .expect_choice_info_wipe = false},
        DeviceRestoreTestParam{.test_suffix = "NoWipeForFeatureDisabled",
                               .restore_detected_in_current_session = true,
                               .choice_predates_restore = true,
                               .is_feature_enabled = false,
                               .is_invalidation_retroactive = false,
                               .expect_choice_info_wipe = false},
    }),
    &SearchEngineChoiceServiceDeviceRestoreTest::GetTestSuffix);

TEST_P(SearchEngineChoiceServiceDeviceRestoreTest, RepromptOnRestoreDetection) {
  ASSERT_EQ(switches::kSearchEngineChoiceNoRepromptString,
            switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  SetChoiceCompletionMetadata(*pref_service(),
                              {base::Time::Now(), base::Version("1.0.0.0")});

  // Trigger the creation of the service, which should check for the reprompt.
  InitService({
      .force_reset = true,
      .restore_detected_in_current_session =
          GetParam().restore_detected_in_current_session,
      .choice_predates_restore = GetParam().choice_predates_restore,
  });

  if (GetParam().expect_choice_info_wipe) {
    EXPECT_FALSE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    histogram_tester_.ExpectUniqueSample(
        search_engines::kSearchEngineChoiceWipeReasonHistogram,
        SearchEngineChoiceWipeReason::kDeviceRestored, 1);
    histogram_tester_.ExpectTotalCount(
        search_engines::kSearchEngineChoiceRepromptHistogram, 0);
  } else {
    EXPECT_TRUE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    histogram_tester_.ExpectTotalCount(
        search_engines::kSearchEngineChoiceWipeReasonHistogram, 0);
    histogram_tester_.ExpectBucketCount(
        search_engines::kSearchEngineChoiceRepromptHistogram,
        RepromptResult::kNoReprompt, 1);
  }

  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  histogram_tester_.ExpectBucketCount(
      search_engines::kSearchEngineChoiceRepromptHistogram,
      RepromptResult::kInvalidDictionary, 0);
}

struct RepromptTestParam {
  // Whether the user should be reprompted or not.
  std::optional<SearchEngineChoiceWipeReason> wipe_reason;
  // Internal results of the reprompt computation.
  std::optional<RepromptResult> wildcard_result;
  std::optional<RepromptResult> country_result;
  // Version of the choice.
  const std::string_view choice_version;
  // The reprompt params, as sent by the server.  Use `CURRENT_VERSION` for the
  // current Chrome version, and `FUTURE_VERSION` for a future version.
  const char* param_dict;
};

class SearchEngineChoiceUtilsParamTest
    : public SearchEngineChoiceServiceTest,
      public testing::WithParamInterface<RepromptTestParam> {};

TEST_P(SearchEngineChoiceUtilsParamTest, Reprompt) {
  // Set the reprompt parameters.
  std::string param_dict = base::CollapseWhitespaceASCII(
      GetParam().param_dict, /*trim_sequences_with_line_breaks=*/true);
  base::ReplaceFirstSubstringAfterOffset(&param_dict, /*start_offset=*/0,
                                         "CURRENT_VERSION",
                                         version_info::GetVersionNumber());
  base::Version future_version(
      {version_info::GetMajorVersionNumberAsInt() + 5u, 2, 3, 4});
  ASSERT_TRUE(future_version.IsValid());
  base::ReplaceFirstSubstringAfterOffset(&param_dict, /*start_offset=*/0,
                                         "FUTURE_VERSION",
                                         future_version.GetString());

  std::string feature_param_value = param_dict.empty() ? "{}" : param_dict;

  base::test::ScopedFeatureList scoped_feature_list;
  scoped_feature_list.InitAndEnableFeatureWithParameters(
      switches::kSearchEngineChoiceTrigger,
      {{switches::kSearchEngineChoiceTriggerRepromptParams.name,
        feature_param_value}});
  ASSERT_EQ(feature_param_value,
            switches::kSearchEngineChoiceTriggerRepromptParams.Get());

  // Initialize the preference with some previous choice.
  int64_t kPreviousTimestamp = 1;
  pref_service()->SetInt64(
      prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp,
      kPreviousTimestamp);
  pref_service()->SetString(
      prefs::kDefaultSearchProviderChoiceScreenCompletionVersion,
      GetParam().choice_version);

  // Trigger the creation of the service, which should check for the reprompt.
  search_engine_choice_service();

  if (GetParam().wipe_reason) {
    // User is reprompted, prefs were wiped.
    EXPECT_FALSE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    EXPECT_FALSE(pref_service()->HasPrefPath(
        prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
    histogram_tester_.ExpectUniqueSample(
        search_engines::kSearchEngineChoiceWipeReasonHistogram,
        *GetParam().wipe_reason, 1);
  } else {
    // User is not reprompted, prefs were not wiped.
    EXPECT_EQ(
        kPreviousTimestamp,
        pref_service()->GetInt64(
            prefs::kDefaultSearchProviderChoiceScreenCompletionTimestamp));
    EXPECT_EQ(GetParam().choice_version,
              pref_service()->GetString(
                  prefs::kDefaultSearchProviderChoiceScreenCompletionVersion));
    histogram_tester_.ExpectTotalCount(
        search_engines::kSearchEngineChoiceWipeReasonHistogram, 0);
  }

  int total_reprompt_record_count = 0;
  if (GetParam().wildcard_result) {
    ++total_reprompt_record_count;
    histogram_tester_.ExpectUniqueSample(
        search_engines::kSearchEngineChoiceRepromptWildcardHistogram,
        *GetParam().wildcard_result, 1);
    EXPECT_GE(histogram_tester_.GetBucketCount(
                  search_engines::kSearchEngineChoiceRepromptHistogram,
                  *GetParam().wildcard_result),
              1);
  } else {
    histogram_tester_.ExpectTotalCount(
        search_engines::kSearchEngineChoiceRepromptWildcardHistogram, 0);
  }
  if (GetParam().country_result) {
    ++total_reprompt_record_count;
    histogram_tester_.ExpectUniqueSample(
        search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram,
        *GetParam().country_result, 1);
    EXPECT_GE(histogram_tester_.GetBucketCount(
                  search_engines::kSearchEngineChoiceRepromptHistogram,
                  *GetParam().country_result),
              1);
  } else {
    histogram_tester_.ExpectTotalCount(
        search_engines::kSearchEngineChoiceRepromptSpecificCountryHistogram, 0);
  }
  histogram_tester_.ExpectTotalCount(
      search_engines::kSearchEngineChoiceRepromptHistogram,
      total_reprompt_record_count);
}

constexpr RepromptTestParam kRepromptTestParams[] = {
    // Reprompt all countries with the wildcard.
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt,
     RepromptResult::kReprompt, RepromptResult::kNoDictionaryKey, "1.0.0.0",
     R"( {"*":"1.0.0.1"} )"},
    // Reprompt works with all version components.
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt,
     RepromptResult::kReprompt, RepromptResult::kNoDictionaryKey, "1.0.0.100",
     R"( {"*":"1.0.1.0"} )"},
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt,
     RepromptResult::kReprompt, RepromptResult::kNoDictionaryKey, "1.0.200.0",
     R"( {"*":"1.1.0.0"} )"},
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt,
     RepromptResult::kReprompt, RepromptResult::kNoDictionaryKey, "1.300.0.0",
     R"( {"*":"2.0.0.0"} )"},
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt,
     RepromptResult::kReprompt, RepromptResult::kNoDictionaryKey, "10.10.1.1",
     R"( {"*":"30.45.678.9100"} )"},
    // Reprompt a specific country.
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt, std::nullopt,
     RepromptResult::kReprompt, "1.0.0.0", R"( {"BE":"1.0.0.1"} )"},
    // Reprompt for params inclusive of current version
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt, std::nullopt,
     RepromptResult::kReprompt, "1.0.0.0", R"( {"BE":"CURRENT_VERSION"} )"},
    // Reprompt when the choice version is malformed.
    {SearchEngineChoiceWipeReason::kInvalidMetadataVersion, std::nullopt,
     std::nullopt, "Blah", ""},
    // Reprompt when both the country and the wild card are specified, as long
    // as one of them qualifies.
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt, std::nullopt,
     RepromptResult::kReprompt, "1.0.0.0",
     R"( {"*":"1.0.0.1","BE":"1.0.0.1"} )"},
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt, std::nullopt,
     RepromptResult::kReprompt, "1.0.0.0",
     R"( {"*":"FUTURE_VERSION","BE":"1.0.0.1"} )"},
    // Still works with irrelevant parameters for other countries.
    {SearchEngineChoiceWipeReason::kFinchBasedReprompt, std::nullopt,
     RepromptResult::kReprompt, "1.0.0.0",
     R"(
       {
         "FR":"FUTURE_VERSION",
         "INVALID_COUNTRY":"INVALID_VERSION",
         "US":"FUTURE_VERSION",
         "BE":"1.0.0.1"
       } )"},

    // Don't reprompt when the choice was made in the current version.
    {std::nullopt, RepromptResult::kRecentChoice,
     RepromptResult::kNoDictionaryKey, version_info::GetVersionNumber(),
     "{\"*\":\"CURRENT_VERSION\"}"},
    // Don't reprompt when the choice was recent enough.
    {std::nullopt, RepromptResult::kRecentChoice,
     RepromptResult::kNoDictionaryKey, "2.0.0.0", R"( {"*":"1.0.0.1"} )"},
    // Don't reprompt for another country.
    {std::nullopt, RepromptResult::kNoDictionaryKey,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", R"( {"FR":"1.0.0.1"} )"},
    {std::nullopt, RepromptResult::kNoDictionaryKey,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", R"( {"US":"1.0.0.1"} )"},
    {std::nullopt, RepromptResult::kNoDictionaryKey,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", R"( {"XX":"1.0.0.1"} )"},
    {std::nullopt, RepromptResult::kNoDictionaryKey,
     RepromptResult::kNoDictionaryKey, "1.0.0.0",
     R"( {"INVALID_COUNTRY":"1.0.0.1"} )"},
    {std::nullopt, std::nullopt, RepromptResult::kChromeTooOld, "1.0.0.0",
     R"( {"FR":"1.0.0.1","BE":"FUTURE_VERSION"} )"},
    // Don't reprompt for future versions.
    {std::nullopt, RepromptResult::kChromeTooOld,
     RepromptResult::kNoDictionaryKey, "1.0.0.0",
     R"( {"*":"FUTURE_VERSION"} )"},
    // Wildcard is overridden by specific country.
    {std::nullopt, std::nullopt, RepromptResult::kChromeTooOld, "1.0.0.0",
     R"( {"*":"1.0.0.1","BE":"FUTURE_VERSION"} )"},
    // Combination of right version for wrong country and wrong version for
    // right country.
    {std::nullopt, std::nullopt, RepromptResult::kChromeTooOld, "2.0.0.0",
     R"(
       {
          "*":"1.1.0.0",
          "BE":"FUTURE_VERSION",
          "FR":"2.0.0.1"
        } )"},
    // Empty dictionary.
    {std::nullopt, RepromptResult::kNoDictionaryKey,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", "{}"},
    // Empty parameter.
    {std::nullopt, RepromptResult::kNoDictionaryKey,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", ""},
    // Wrong number of components.
    {std::nullopt, RepromptResult::kInvalidVersion,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", R"( {"*":"2.0"} )"},
    // Wildcard in version.
    {std::nullopt, RepromptResult::kInvalidVersion,
     RepromptResult::kNoDictionaryKey, "1.0.0.0", R"( {"*":"2.0.0.*"} )"},
};

INSTANTIATE_TEST_SUITE_P(,
                         SearchEngineChoiceUtilsParamTest,
                         ::testing::ValuesIn(kRepromptTestParams));

}  // namespace search_engines