File: variations_field_trial_creator_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 (1817 lines) | stat: -rw-r--r-- 78,647 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
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif

#include "components/variations/service/variations_field_trial_creator.h"

#include <stddef.h>

#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/base_switches.h"
#include "base/build_time.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/json/json_string_value_serializer.h"
#include "base/memory/raw_ptr.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_entropy_provider.h"
#include "base/test/scoped_command_line.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/scoped_mock_clock_override.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "base/version.h"
#include "base/version_info/channel.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "components/metrics/clean_exit_beacon.h"
#include "components/metrics/client_info.h"
#include "components/metrics/metrics_service.h"
#include "components/metrics/metrics_state_manager.h"
#include "components/metrics/test/test_enabled_state_provider.h"
#include "components/prefs/testing_pref_service.h"
#include "components/variations/field_trial_config/field_trial_util.h"
#include "components/variations/platform_field_trials.h"
#include "components/variations/pref_names.h"
#include "components/variations/proto/variations_seed.pb.h"
#include "components/variations/scoped_variations_ids_provider.h"
#include "components/variations/service/buildflags.h"
#include "components/variations/service/safe_seed_manager.h"
#include "components/variations/service/variations_field_trial_creator_base.h"
#include "components/variations/service/variations_service.h"
#include "components/variations/service/variations_service_client.h"
#include "components/variations/variations_safe_seed_store_local_state.h"
#include "components/variations/variations_seed_store.h"
#include "components/variations/variations_switches.h"
#include "components/variations/variations_test_utils.h"
#include "components/version_info/channel.h"
#include "components/version_info/version_info.h"
#include "components/web_resource/resource_request_allowed_notifier_test_util.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_ANDROID)
#include "components/variations/seed_response.h"
#endif

namespace variations {
namespace {

using ::testing::_;
using ::testing::Ge;
using ::testing::NiceMock;
using ::testing::Return;

// Constants used to create the test seeds.
const char kTestSeedStudyName[] = "test";
const char kTestLimitedLayerStudyName[] = "test_study_in_limited_layer";
const char kTestSeedExperimentName[] = "abc";
const char kTestSafeSeedExperimentName[] = "abc.safe";
const int kTestSeedExperimentProbability = 100;
const char kTestSeedSerialNumber[] = "123";

// Constants used to mock the serialized seed state.
const char kTestSeedSerializedData[] = "a serialized seed, 100% realistic";
const char kTestSeedSignature[] = "a totally valid signature, I swear!";
const int kTestSeedMilestone = 90;

struct FetchAndLaunchTimeTestParams {
  // Inputs in relation to the current build time.
  const base::TimeDelta fetch_time;
  const base::TimeDelta launch_time;
};

std::unique_ptr<VariationsSeedStore> CreateSeedStore(
    PrefService* local_state,
    const base::FilePath& seed_file_dir) {
  return std::make_unique<VariationsSeedStore>(
      local_state, /*initial_seed=*/nullptr,
      /*signature_verification_enabled=*/true,
      std::make_unique<VariationsSafeSeedStoreLocalState>(
          local_state, seed_file_dir, version_info::Channel::UNKNOWN,
          /*entropy_providers=*/nullptr),
      version_info::Channel::UNKNOWN, seed_file_dir);
}

// Returns a seed with simple test data. The seed has a single study,
// "UMA-Uniformity-Trial-10-Percent", which has a single experiment, "abc", with
// probability weight 100.
VariationsSeed CreateTestSeed() {
  VariationsSeed seed;
  Study* study = seed.add_study();
  study->set_name(kTestSeedStudyName);
  study->set_default_experiment_name(kTestSeedExperimentName);
  Study_Experiment* experiment = study->add_experiment();
  experiment->set_name(kTestSeedExperimentName);
  experiment->set_probability_weight(kTestSeedExperimentProbability);
  seed.set_serial_number(kTestSeedSerialNumber);
  return seed;
}

// Returns a test seed that contains a single study,
// "UMA-Uniformity-Trial-10-Percent", which has a single experiment, "abc", with
// probability weight 100. The study references the 100% slot of a LIMITED
// entropy layer. The LIMITED layer created will use 0 bit of entropy.
VariationsSeed CreateTestSeedWithLimitedEntropyLayer() {
  VariationsSeed seed;
  seed.set_serial_number(kTestSeedSerialNumber);

  auto* layer = seed.add_layers();
  layer->set_id(1);
  layer->set_num_slots(100);
  layer->set_entropy_mode(Layer::LIMITED);

  auto* layer_member = layer->add_members();
  layer_member->set_id(1);
  auto* slot = layer_member->add_slots();
  slot->set_start(0);
  slot->set_end(99);

  auto* study = seed.add_study();
  study->set_name(kTestLimitedLayerStudyName);

  auto* experiment = study->add_experiment();
  experiment->set_name(kTestSeedExperimentName);
  experiment->set_probability_weight(kTestSeedExperimentProbability);

  auto* layer_member_reference = study->mutable_layer();
  layer_member_reference->set_layer_id(1);
  layer_member_reference->add_layer_member_ids(1);

  return seed;
}

VariationsSeed CreateTestSeedWithLimitedEntropyLayerUsingExcessiveEntropy() {
  VariationsSeed seed;
  seed.set_serial_number(kTestSeedSerialNumber);

  auto* layer = seed.add_layers();
  layer->set_id(1);
  layer->set_num_slots(100);
  layer->set_entropy_mode(Layer::LIMITED);

  auto* layer_member = layer->add_members();
  layer_member->set_id(1);
  auto* slot = layer_member->add_slots();
  slot->set_start(0);
  slot->set_end(99);

  Study* study = seed.add_study();
  study->set_name(kTestLimitedLayerStudyName);

  auto* experiment_1 = study->add_experiment();
  experiment_1->set_name("experiment_very_small");
  experiment_1->set_probability_weight(1);
  experiment_1->set_google_web_experiment_id(100001);

  auto* experiment_2 = study->add_experiment();
  experiment_2->set_name("experiment");
  experiment_2->set_probability_weight(999999);
  experiment_1->set_google_web_experiment_id(100002);

  auto* layer_member_reference = study->mutable_layer();
  layer_member_reference->set_layer_id(1);
  layer_member_reference->add_layer_member_ids(1);

  return seed;
}

// Returns a seed with simple test data. The seed has a single study,
// "UMA-Uniformity-Trial-10-Percent", which has a single experiment,
// "abc.safe", with probability weight 100.
//
// Intended to be used when a "safe" seed is needed so that test expectations
// can distinguish between a regular and safe seeds.
VariationsSeed CreateTestSafeSeed() {
  VariationsSeed seed = CreateTestSeed();
  Study* study = seed.mutable_study(0);
  study->set_default_experiment_name(kTestSafeSeedExperimentName);
  study->mutable_experiment(0)->set_name(kTestSafeSeedExperimentName);
  return seed;
}

// A base::Time instance representing a time in the distant past. Here, it would
// return the start for epoch in Unix-like system (Jan 1, 1970).
base::Time DistantPast() {
  return base::Time::UnixEpoch();
}

// Converts |list| to a string, to make it easier for debugging.
std::string ListToString(const base::Value::List& list) {
  std::string json;
  JSONStringValueSerializer serializer(&json);
  serializer.set_pretty_print(true);
  serializer.Serialize(list);
  return json;
}

#if BUILDFLAG(IS_ANDROID)
const char kTestSeedCountry[] = "in";

// Populates |seed| with simple test data, targetting only users in a specific
// country. The resulting seed will contain one study called "test", which
// contains one experiment called "abc" with probability weight 100, restricted
// just to users in |kTestSeedCountry|.
VariationsSeed CreateTestSeedWithCountryFilter() {
  VariationsSeed seed = CreateTestSeed();
  Study* study = seed.mutable_study(0);
  Study::Filter* filter = study->mutable_filter();
  filter->add_country(kTestSeedCountry);
  filter->add_platform(Study::PLATFORM_ANDROID);
  return seed;
}

// Serializes |seed| to protobuf binary format.
std::string SerializeSeed(const VariationsSeed& seed) {
  std::string serialized_seed;
  seed.SerializeToString(&serialized_seed);
  return serialized_seed;
}
#endif  // BUILDFLAG(IS_ANDROID)

class MockSafeSeedManager : public SafeSeedManager {
 public:
  explicit MockSafeSeedManager(PrefService* local_state)
      : SafeSeedManager(local_state) {}

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

  ~MockSafeSeedManager() override = default;

  MOCK_CONST_METHOD0(GetSeedType, SeedType());
  MOCK_METHOD5(DoSetActiveSeedState,
               void(const std::string& seed_data,
                    const std::string& base64_seed_signature,
                    int seed_milestone,
                    ClientFilterableState* client_filterable_state,
                    base::Time seed_fetch_time));

  void SetActiveSeedState(
      const std::string& seed_data,
      const std::string& base64_seed_signature,
      int seed_milestone,
      std::unique_ptr<ClientFilterableState> client_filterable_state,
      base::Time seed_fetch_time) override {
    DoSetActiveSeedState(seed_data, base64_seed_signature, seed_milestone,
                         client_filterable_state.get(), seed_fetch_time);
  }
};

// TODO(crbug.com/40742801): Remove when fake VariationsServiceClient created.
class TestVariationsServiceClient : public VariationsServiceClient {
 public:
  TestVariationsServiceClient() = default;

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

  ~TestVariationsServiceClient() override = default;

  // VariationsServiceClient:
  base::Version GetVersionForSimulation() override { return base::Version(); }
  scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory()
      override {
    return nullptr;
  }
  network_time::NetworkTimeTracker* GetNetworkTimeTracker() override {
    return nullptr;
  }
  bool OverridesRestrictParameter(std::string* parameter) override {
    if (restrict_parameter_.empty()) {
      return false;
    }
    *parameter = restrict_parameter_;
    return true;
  }
  bool IsEnterprise() override { return false; }
  void RemoveGoogleGroupsFromPrefsForDeletedProfiles(
      PrefService* local_state) override {}

 private:
  // VariationsServiceClient:
  version_info::Channel GetChannel() override {
    return version_info::Channel::UNKNOWN;
  }

  std::string restrict_parameter_;
};

class MockVariationsServiceClient : public TestVariationsServiceClient {
 public:
  MOCK_METHOD(void,
              RemoveGoogleGroupsFromPrefsForDeletedProfiles,
              (PrefService*),
              (override));
  MOCK_METHOD(Study::FormFactor, GetCurrentFormFactor, (), (override));
};

class TestVariationsSeedStore : public VariationsSeedStore {
 public:
  explicit TestVariationsSeedStore(PrefService* local_state)
      : VariationsSeedStore(local_state,
                            /*initial_seed=*/nullptr,
                            /*signature_verification_enabled=*/true,
                            std::make_unique<VariationsSafeSeedStoreLocalState>(
                                local_state,
                                /*seed_file_dir=*/base::FilePath(),
                                version_info::Channel::UNKNOWN,
                                /*entropy_providers=*/nullptr),
                            version_info::Channel::UNKNOWN,
                            /*seed_file_dir=*/base::FilePath()) {}

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

  ~TestVariationsSeedStore() override = default;

  bool LoadSeed(VariationsSeed* seed,
                std::string* seed_data,
                std::string* base64_signature) override {
    *seed = CreateTestSeed();
    *seed_data = kTestSeedSerializedData;
    *base64_signature = kTestSeedSignature;
    return true;
  }

  bool LoadSafeSeed(VariationsSeed* seed,
                    ClientFilterableState* client_state) override {
    if (has_unloadable_safe_seed_) {
      return false;
    }

    *seed = CreateTestSafeSeed();
    return true;
  }

  void set_has_unloadable_safe_seed(bool is_unloadable) {
    has_unloadable_safe_seed_ = is_unloadable;
  }

 private:
  // Whether to simulate having an unloadable (e.g. corrupted, empty, etc.) safe
  // seed.
  bool has_unloadable_safe_seed_ = false;
};

class TestVariationsFieldTrialCreator : public VariationsFieldTrialCreator {
 public:
  TestVariationsFieldTrialCreator(
      PrefService* local_state,
      TestVariationsServiceClient* client,
      SafeSeedManager* safe_seed_manager,
      const base::FilePath user_data_dir = base::FilePath(),
      metrics::StartupVisibility startup_visibility =
          metrics::StartupVisibility::kUnknown)
      : VariationsFieldTrialCreator(
            client,
            // Pass a VariationsSeedStore to base class.
            CreateSeedStore(local_state,
                            user_data_dir.AppendASCII("VariationsSeedV1")),
            UIStringOverrider()),
        enabled_state_provider_(/*consent=*/true, /*enabled=*/true),
        // Instead, use a TestVariationsSeedStore as the member variable.
        seed_store_(local_state),
        safe_seed_manager_(safe_seed_manager) {
    metrics_state_manager_ = metrics::MetricsStateManager::Create(
        local_state, &enabled_state_provider_, std::wstring(), user_data_dir,
        startup_visibility);
    metrics_state_manager_->InstantiateFieldTrialList();
  }

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

  ~TestVariationsFieldTrialCreator() override = default;

  // A convenience wrapper around SetUpFieldTrials() which passes default values
  // for uninteresting params.
  bool SetUpFieldTrials() {
    PlatformFieldTrials platform_field_trials;
    return VariationsFieldTrialCreator::SetUpFieldTrials(
        /*variation_ids=*/std::vector<std::string>(),
        base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
            switches::kForceVariationIds),
        std::vector<base::FeatureList::FeatureOverrideInfo>(),
        std::make_unique<base::FeatureList>(), metrics_state_manager_.get(),
        &platform_field_trials, safe_seed_manager_,
        /*add_entropy_source_to_variations_ids=*/true,
        *metrics_state_manager_->CreateEntropyProviders(
            /*enable_limited_entropy_mode=*/false));
  }

  // Passthrough, to expose the underlying method to tests without making it
  // public.
  base::flat_set<uint64_t> GetGoogleGroupsFromPrefs() {
    return VariationsFieldTrialCreator::GetGoogleGroupsFromPrefs();
  }

  TestVariationsSeedStore* seed_store() { return &seed_store_; }

 protected:
#if BUILDFLAG(FIELDTRIAL_TESTING_ENABLED)
  // We override this method so that a mock testing config is used instead of
  // the one defined in fieldtrial_testing_config.json.
  void ApplyFieldTrialTestingConfig(base::FeatureList* feature_list) override {
    AssociateParamsFromFieldTrialConfig(
        kTestingConfig,
        base::BindRepeating(&TestVariationsFieldTrialCreator::OverrideUIString,
                            base::Unretained(this)),
        GetPlatform(), GetCurrentFormFactor(), feature_list);
  }
#endif  // BUILDFLAG(FIELDTRIAL_TESTING_ENABLED)

 private:
  VariationsSeedStore* GetSeedStore() override { return &seed_store_; }

  metrics::TestEnabledStateProvider enabled_state_provider_;
  TestVariationsSeedStore seed_store_;
  const raw_ptr<SafeSeedManager> safe_seed_manager_;
  std::unique_ptr<metrics::MetricsStateManager> metrics_state_manager_;
};

}  // namespace

class FieldTrialCreatorTest : public ::testing::Test {
 public:
  FieldTrialCreatorTest() = default;
  FieldTrialCreatorTest(const FieldTrialCreatorTest&) = delete;
  FieldTrialCreatorTest& operator=(const FieldTrialCreatorTest&) = delete;
  ~FieldTrialCreatorTest() override = default;

  void SetUp() override {
    // Register the prefs used by the metrics and variations services.
    metrics::MetricsService::RegisterPrefs(local_state_.registry());
    VariationsService::RegisterPrefs(local_state_.registry());

    // Create a new temp dir for each test, to avoid cross test contamination.
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    // These tests validate the setup features and field trials: initialize
    // them to null on each test to mimic fresh startup.
    scoped_feature_list_.InitWithNullFeatureAndFieldTrialLists();

    // Do not use the static field trial testing config data. Perform the
    // "real" feature and field trial setup.
    DisableTestingConfig();
  }

  PrefService* local_state() { return &local_state_; }

  const base::FilePath user_data_dir_path() const {
    return temp_dir_.GetPath();
  }

  const base::FilePath seed_file_path() const {
    return user_data_dir_path().AppendASCII("TestSeedFile");
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
  base::test::TaskEnvironment task_environment_;
  base::test::ScopedCommandLine scoped_command_line_;
  TestingPrefServiceSimple local_state_;
  base::ScopedTempDir temp_dir_;
  variations::ScopedVariationsIdsProvider scoped_variations_ids_provider_{
      variations::VariationsIdsProvider::Mode::kUseSignedInState};
};

namespace {

class FieldTrialCreatorFetchAndLaunchTimeTest
    : public FieldTrialCreatorTest,
      public ::testing::WithParamInterface<FetchAndLaunchTimeTestParams> {};

constexpr FetchAndLaunchTimeTestParams kAllFetchAndLaunchTimes[] = {
    // Verify that when the binary is newer than the most recent seed, the
    // seed is applied as long as it was downloaded within the last 30 days.
    {.fetch_time = -base::Days(29), .launch_time = base::Days(1)},
    // Verify that when the binary is older than the most recent seed, the
    // seed is applied even though it was downloaded more than 30 days ago.
    {.fetch_time = base::Days(1), .launch_time = base::Days(32)},
};

}  // namespace

INSTANTIATE_TEST_SUITE_P(All,
                         FieldTrialCreatorFetchAndLaunchTimeTest,
                         ::testing::ValuesIn(kAllFetchAndLaunchTimes));

// Verify that unexpired seeds are used.
TEST_P(FieldTrialCreatorFetchAndLaunchTimeTest,
       SetUpFieldTrials_ValidSeed_NotExpired) {
  const auto& test_case = GetParam();
  // Fast forward the clock to build time.
  base::ScopedMockClockOverride mock_clock;
  base::Time build_time = base::GetBuildTime();
  mock_clock.Advance(build_time - base::Time::Now());

  // The seed should be used, so the safe seed manager should be informed of
  // the active seed state.
  const base::Time seed_fetch_time = build_time + test_case.fetch_time;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  EXPECT_CALL(safe_seed_manager,
              DoSetActiveSeedState(kTestSeedSerializedData, kTestSeedSignature,
                                   kTestSeedMilestone, _, seed_fetch_time))
      .Times(1);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Simulate the seed being stored.
  field_trial_creator.seed_store()
      ->GetSeedReaderWriterForTesting()
      ->SetFetchTime(seed_fetch_time);

  // Simulate a seed from an earlier (i.e. valid) milestone.
  local_state()->SetInteger(prefs::kVariationsSeedMilestone,
                            kTestSeedMilestone);

  // Fast forward the clock to launch_time and check that field trials are
  // created from the seed at launch_time. Since the test study has only one
  // experiment with 100% probability weight, we must be part of it.
  mock_clock.Advance(test_case.launch_time);
  base::HistogramTester histogram_tester;
  ASSERT_TRUE(field_trial_creator.SetUpFieldTrials());
  EXPECT_EQ(kTestSeedExperimentName,
            base::FieldTrialList::FindFullName(kTestSeedStudyName));

  // Verify metrics.
  histogram_tester.ExpectUniqueSample("Variations.CreateTrials.SeedExpiry",
                                      VariationsSeedExpiry::kNotExpired, 1);
  int freshness_in_minutes =
      (test_case.launch_time - test_case.fetch_time).InDays() * 24 * 60;
  histogram_tester.ExpectUniqueSample("Variations.SeedFreshness",
                                      freshness_in_minutes, 1);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kRegularSeedUsed, 1);
  histogram_tester.ExpectUniqueSample("Variations.AppliedSeed.Size",
                                      strlen(kTestSeedSerializedData), 1);
}

TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_ValidSeed_NoLastFetchTime) {
  // With a valid seed on first run, the safe seed manager should be informed of
  // the active seed state. The last fetch time in this case is expected to be
  // inferred to be recent.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  const base::Time start_time = base::Time::Now();
  EXPECT_CALL(safe_seed_manager,
              DoSetActiveSeedState(kTestSeedSerializedData, kTestSeedSignature,
                                   _, _, Ge(start_time)))
      .Times(1);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Simulate a first run by leaving fetch time empty.
  EXPECT_EQ(base::Time(), field_trial_creator.GetLatestSeedFetchTime());

  // Check that field trials are created from the seed. Since the test study has
  // only one experiment with 100% probability weight, we must be part of it.
  base::HistogramTester histogram_tester;
  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials());
  EXPECT_EQ(base::FieldTrialList::FindFullName(kTestSeedStudyName),
            kTestSeedExperimentName);

  // Verify metrics. The seed freshness metric should be recorded with a value
  // of 0 on first run.
  histogram_tester.ExpectUniqueSample("Variations.CreateTrials.SeedExpiry",
                                      VariationsSeedExpiry::kFetchTimeMissing,
                                      1);
  histogram_tester.ExpectUniqueSample("Variations.SeedFreshness", 0, 1);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kRegularSeedUsed, 1);
}

// Verify that a regular seed can be used when the milestone with which the seed
// was fetched is unknown. This can happen if the seed was fetched before the
// milestone pref was added.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_ValidSeed_NoMilestone) {
  // The regular seed should be used, so the safe seed manager should be
  // informed of the active seed state.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  const int minutes = 45;
  const base::Time seed_fetch_time = base::Time::Now() - base::Minutes(minutes);
  EXPECT_CALL(safe_seed_manager,
              DoSetActiveSeedState(kTestSeedSerializedData, kTestSeedSignature,
                                   0, _, seed_fetch_time))
      .Times(1);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Simulate the seed being stored.
  field_trial_creator.seed_store()
      ->GetSeedReaderWriterForTesting()
      ->SetFetchTime(seed_fetch_time);

  // Simulate the absence of a milestone by leaving
  // |prefs::kVariationsSeedMilestone| empty.
  EXPECT_EQ(0, local_state()->GetInteger(prefs::kVariationsSeedMilestone));

  // Check that field trials are created from the seed. Since the test study has
  // only one experiment with 100% probability weight, we must be part of it.
  base::HistogramTester histogram_tester;
  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials());
  EXPECT_EQ(base::FieldTrialList::FindFullName(kTestSeedStudyName),
            kTestSeedExperimentName);

  // Verify metrics.
  histogram_tester.ExpectUniqueSample("Variations.CreateTrials.SeedExpiry",
                                      VariationsSeedExpiry::kNotExpired, 1);
  histogram_tester.ExpectUniqueSample("Variations.SeedFreshness", minutes, 1);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kRegularSeedUsed, 1);
}

// Verify that no seed is applied when the seed has expired.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_ExpiredSeed) {
  // When the seed is has expired, no field trials should be created from the
  // seed. Hence, no active state should be passed to the safe seed manager.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);
  // Simulate a seed that is fetched a long time ago and should definitely
  // have expired.
  field_trial_creator.seed_store()
      ->GetSeedReaderWriterForTesting()
      ->SetFetchTime(DistantPast());

  // Check that field trials are not created from the expired seed.
  base::HistogramTester histogram_tester;
  EXPECT_FALSE(field_trial_creator.SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify metrics. The seed freshness metric should not be recorded for an
  // expired seed.
  histogram_tester.ExpectUniqueSample("Variations.CreateTrials.SeedExpiry",
                                      VariationsSeedExpiry::kExpired, 1);
  histogram_tester.ExpectTotalCount("Variations.SeedFreshness", 0);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kExpiredRegularSeedNotUsed, 1);
}

// Verify that a regular seed is not used when the milestone with which it was
// fetched is greater than the client's milestone.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_FutureMilestone) {
  const int future_seed_milestone = 7890;

  // When the seed is associated with a future milestone (relative to the
  // client's milestone), no field trials should be created from the seed.
  // Hence, no active state should be passed to the safe seed manager.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Simulate a seed from a future milestone.
  local_state()->SetInteger(prefs::kVariationsSeedMilestone,
                            future_seed_milestone);

  // Check that field trials are not created from the seed.
  base::HistogramTester histogram_tester;
  EXPECT_FALSE(field_trial_creator.SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify metrics.
  histogram_tester.ExpectUniqueSample(
      "Variations.SeedUsage", SeedUsage::kRegularSeedForFutureMilestoneNotUsed,
      1);
}

// Verify that unexpired safe seeds are used.
TEST_P(FieldTrialCreatorFetchAndLaunchTimeTest,
       SetUpFieldTrials_ValidSafeSeed_NewBinaryUsesSeed) {
  const auto& test_case = GetParam();
  // Fast forward the clock to build time.
  base::ScopedMockClockOverride mock_clock;
  base::Time build_time = base::GetBuildTime();
  mock_clock.Advance(build_time - base::Time::Now());

  // With a valid safe seed, the safe seed manager should not be informed of
  // the active seed state. This is an optimization to avoid saving a safe
  // seed when already running in safe mode.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  ON_CALL(safe_seed_manager, GetSeedType())
      .WillByDefault(Return(SeedType::kSafeSeed));
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Simulate the safe seed being stored.
  local_state()->SetTime(prefs::kVariationsSafeSeedFetchTime,
                         build_time + test_case.fetch_time);

  // Fast forward the clock to launch_time and check that field trials are
  // created from the safe seed. Since the test study has only one experiment
  // with 100% probability weight, we must be part of it.
  mock_clock.Advance(test_case.launch_time);
  base::HistogramTester histogram_tester;
  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials());
  EXPECT_EQ(kTestSafeSeedExperimentName,
            base::FieldTrialList::FindFullName(kTestSeedStudyName));

  // Verify metrics.
  histogram_tester.ExpectUniqueSample(
      "Variations.SafeMode.CreateTrials.SeedExpiry",
      VariationsSeedExpiry::kNotExpired, 1);
  int freshness_in_minutes =
      (test_case.launch_time - test_case.fetch_time).InDays() * 24 * 60;
  histogram_tester.ExpectUniqueSample("Variations.SeedFreshness",
                                      freshness_in_minutes, 1);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kSafeSeedUsed, 1);
}

// Verify that Chrome does not apply a variations seed when Chrome should run in
// Variations Safe Mode but the safe seed is unloadable.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_UnloadableSafeSeedNotUsed) {
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  ON_CALL(safe_seed_manager, GetSeedType())
      .WillByDefault(Return(SeedType::kSafeSeed));

  // When falling back to client-side defaults, the safe seed manager should not
  // be informed of the active seed state.
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);
  field_trial_creator.seed_store()->set_has_unloadable_safe_seed(true);

  base::HistogramTester histogram_tester;

  // Verify that field trials were not set up.
  EXPECT_FALSE(field_trial_creator.SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that Chrome did not apply the safe seed.
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kUnloadableSafeSeedNotUsed, 1);
}

// Verify that valid safe seeds with missing download times are applied.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_ValidSafeSeed_NoLastFetchTime) {
  // With a valid safe seed, the safe seed manager should not be informed of the
  // active seed state. This is an optimization to avoid saving a safe seed when
  // already running in safe mode.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  ON_CALL(safe_seed_manager, GetSeedType())
      .WillByDefault(Return(SeedType::kSafeSeed));
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that the safe seed does not have a fetch time.
  EXPECT_EQ(0, local_state()->GetInt64(prefs::kVariationsSafeSeedFetchTime));

  // Check that field trials are created from the safe seed. Since the test
  // study has only one experiment with 100% probability weight, we must be part
  // of it.
  base::HistogramTester histogram_tester;
  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials());
  EXPECT_EQ(kTestSafeSeedExperimentName,
            base::FieldTrialList::FindFullName(kTestSeedStudyName));

  // Verify metrics. The freshness should not be recorded when the fetch time is
  // missing.
  histogram_tester.ExpectUniqueSample(
      "Variations.SafeMode.CreateTrials.SeedExpiry",
      VariationsSeedExpiry::kFetchTimeMissing, 1);
  histogram_tester.ExpectTotalCount("Variations.SeedFreshness", 0);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kSafeSeedUsed, 1);
}

// Verify that no seed is applied when (i) safe mode is triggered and (ii) the
// loaded safe seed has expired.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_ExpiredSafeSeed) {
  // The safe seed manager should not be informed of the active seed state.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  ON_CALL(safe_seed_manager, GetSeedType())
      .WillByDefault(Return(SeedType::kSafeSeed));
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);
  // Simulate a safe seed that is fetched a long time ago and should definitely
  // have expired.
  local_state()->SetTime(prefs::kVariationsSafeSeedFetchTime, DistantPast());

  // Check that field trials are not created from the expired seed.
  base::HistogramTester histogram_tester;
  EXPECT_FALSE(field_trial_creator.SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify metrics. The seed freshness metric should not be recorded for an
  // expired seed.
  histogram_tester.ExpectUniqueSample(
      "Variations.SafeMode.CreateTrials.SeedExpiry",
      VariationsSeedExpiry::kExpired, 1);
  histogram_tester.ExpectTotalCount("Variations.SeedFreshness", 0);
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kExpiredSafeSeedNotUsed, 1);
}

// Verify that no seed is applied when (i) safe mode is triggered and (ii) the
// loaded safe seed was fetched with a future milestone.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_SafeSeedForFutureMilestone) {
  const int future_seed_milestone = 7890;

  // The safe seed manager should not be informed of the active seed state.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  ON_CALL(safe_seed_manager, GetSeedType())
      .WillByDefault(Return(SeedType::kSafeSeed));
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Simulate a safe seed that was fetched with a future milestone.
  local_state()->SetInteger(prefs::kVariationsSafeSeedMilestone,
                            future_seed_milestone);

  // Check that field trials are not created from the safe seed.
  base::HistogramTester histogram_tester;
  EXPECT_FALSE(field_trial_creator.SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify metrics.
  histogram_tester.ExpectUniqueSample(
      "Variations.SeedUsage", SeedUsage::kSafeSeedForFutureMilestoneNotUsed, 1);
}

// Verify that no seed is applied when null seed is triggered.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_NullSeed) {
  // The safe seed manager should not be informed of the active seed state.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  ON_CALL(safe_seed_manager, GetSeedType())
      .WillByDefault(Return(SeedType::kNullSeed));
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Check that field trials are not created from the null seed.
  base::HistogramTester histogram_tester;
  EXPECT_FALSE(field_trial_creator.SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify metrics.
  histogram_tester.ExpectUniqueSample("Variations.SeedUsage",
                                      SeedUsage::kNullSeedUsed, 1);
}

TEST_F(FieldTrialCreatorTest, LoadSeedFromTestSeedJsonPath) {
  base::ScopedTempDir temp_dir;
  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
  const base::FilePath test_seed_file =
      temp_dir.GetPath().Append(FILE_PATH_LITERAL("TEST SEED"));

  // This seed contains the data for a test experiment.
  base::WriteFile(test_seed_file,
                  base::StringPrintf("{\"variations_compressed_seed\": \"%s\","
                                     "\"variations_seed_signature\": \"%s\"}",
                                     kTestSeedData.base64_compressed_data,
                                     kTestSeedData.base64_signature));

  base::CommandLine::ForCurrentProcess()->AppendSwitchPath(
      variations::switches::kVariationsTestSeedJsonPath, test_seed_file);

  // Use a real VariationsFieldTrialCreator and VariationsSeedStore to exercise
  // the VariationsSeedStore::LoadSeed() logic.
  TestVariationsServiceClient variations_service_client;
  auto seed_store = CreateSeedStore(local_state(), seed_file_path());
  VariationsFieldTrialCreator field_trial_creator(
      &variations_service_client, std::move(seed_store), UIStringOverrider());
  metrics::TestEnabledStateProvider enabled_state_provider(
      /*consent=*/true,
      /*enabled=*/true);
  auto metrics_state_manager = metrics::MetricsStateManager::Create(
      local_state(), &enabled_state_provider, std::wstring(), base::FilePath());
  metrics_state_manager->InstantiateFieldTrialList();

  PlatformFieldTrials platform_field_trials;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());

  ASSERT_FALSE(base::FieldTrialList::TrialExists(kTestSeedData.study_names[0]));

  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials(
      /*variation_ids=*/{},
      /*command_line_variation_ids=*/std::string(),
      std::vector<base::FeatureList::FeatureOverrideInfo>(),
      std::make_unique<base::FeatureList>(), metrics_state_manager.get(),
      &platform_field_trials, &safe_seed_manager,
      /*add_entropy_source_to_variations_ids=*/true,
      *metrics_state_manager->CreateEntropyProviders(
          /*enable_limited_entropy_mode=*/false)));

  EXPECT_TRUE(base::FieldTrialList::TrialExists(kTestSeedData.study_names[0]));
  EXPECT_EQ(
      local_state()->GetInteger(prefs::kVariationsFailedToFetchSeedStreak), 0);
  EXPECT_EQ(local_state()->GetInteger(prefs::kVariationsCrashStreak), 0);
}

TEST_F(FieldTrialCreatorTest, LoadPermanentConsistencyCountry) {
  struct {
    const char* permanent_overridden_country_before;
    // Comma separated list, NULL if the pref isn't set initially.
    const char* permanent_consistency_country_before;
    const char* version;
    // NULL indicates that no latest country code is present.
    const char* latest_country_code;
    // Comma separated list.
    const char* permanent_consistency_country_after;
    std::string expected_country;
    LoadPermanentConsistencyCountryResult expected_result;
  } test_cases[] = {
      // Existing permanent overridden country.
      {"ca", "20.0.0.0,us", "20.0.0.0", "us", "20.0.0.0,us", "ca",
       LOAD_COUNTRY_HAS_PERMANENT_OVERRIDDEN_COUNTRY},
      {"us", "20.0.0.0,us", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_HAS_PERMANENT_OVERRIDDEN_COUNTRY},
      {"ca", "", "20.0.0.0", "", "", "ca",
       LOAD_COUNTRY_HAS_PERMANENT_OVERRIDDEN_COUNTRY},

      // Existing pref value present for this version.
      {"", "20.0.0.0,us", "20.0.0.0", "ca", "20.0.0.0,us", "us",
       LOAD_COUNTRY_HAS_BOTH_VERSION_EQ_COUNTRY_NEQ},
      {"", "20.0.0.0,us", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_HAS_BOTH_VERSION_EQ_COUNTRY_EQ},
      {"", "20.0.0.0,us", "20.0.0.0", "", "20.0.0.0,us", "us",
       LOAD_COUNTRY_HAS_PREF_NO_SEED_VERSION_EQ},

      // Existing pref value present for a different version.
      {"", "19.0.0.0,ca", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_HAS_BOTH_VERSION_NEQ_COUNTRY_NEQ},
      {"", "19.0.0.0,us", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_HAS_BOTH_VERSION_NEQ_COUNTRY_EQ},
      {"", "19.0.0.0,ca", "20.0.0.0", "", "19.0.0.0,ca", "",
       LOAD_COUNTRY_HAS_PREF_NO_SEED_VERSION_NEQ},

      // No existing pref value present.
      {"", "", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_NO_PREF_HAS_SEED},
      {"", "", "20.0.0.0", "", "", "", LOAD_COUNTRY_NO_PREF_NO_SEED},
      {"", "", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_NO_PREF_HAS_SEED},
      {"", "", "20.0.0.0", "", "", "", LOAD_COUNTRY_NO_PREF_NO_SEED},

      // Invalid existing pref value.
      {"", "20.0.0.0", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_INVALID_PREF_HAS_SEED},
      {"", "20.0.0.0", "20.0.0.0", "", "", "",
       LOAD_COUNTRY_INVALID_PREF_NO_SEED},
      {"", "20.0.0.0,us,element3", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_INVALID_PREF_HAS_SEED},
      {"", "20.0.0.0,us,element3", "20.0.0.0", "", "", "",
       LOAD_COUNTRY_INVALID_PREF_NO_SEED},
      {"", "badversion,ca", "20.0.0.0", "us", "20.0.0.0,us", "us",
       LOAD_COUNTRY_INVALID_PREF_HAS_SEED},
      {"", "badversion,ca", "20.0.0.0", "", "", "",
       LOAD_COUNTRY_INVALID_PREF_NO_SEED},
  };

  metrics::TestEnabledStateProvider enabled_state_provider(
      /*consent=*/true,
      /*enabled=*/true);
  auto metrics_state_manager = metrics::MetricsStateManager::Create(
      local_state(), &enabled_state_provider, std::wstring(), base::FilePath());
  metrics_state_manager->InstantiateFieldTrialList();

  for (const auto& test : test_cases) {
    if (!test.permanent_overridden_country_before) {
      local_state()->ClearPref(prefs::kVariationsPermanentOverriddenCountry);
    } else {
      local_state()->SetString(prefs::kVariationsPermanentOverriddenCountry,
                               test.permanent_overridden_country_before);
    }

    if (!test.permanent_consistency_country_before) {
      local_state()->ClearPref(prefs::kVariationsPermanentConsistencyCountry);
    } else {
      base::Value::List list_value;
      for (const std::string& component :
           base::SplitString(test.permanent_consistency_country_before, ",",
                             base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
        list_value.Append(component);
      }
      local_state()->SetList(prefs::kVariationsPermanentConsistencyCountry,
                             std::move(list_value));
    }

    std::string latest_country;
    if (test.latest_country_code) {
      latest_country = test.latest_country_code;
    }

    TestVariationsServiceClient variations_service_client;
    auto seed_store = CreateSeedStore(local_state(), seed_file_path());
    VariationsFieldTrialCreator field_trial_creator(
        &variations_service_client, std::move(seed_store), UIStringOverrider());

    base::HistogramTester histogram_tester;
    EXPECT_EQ(test.expected_country,
              field_trial_creator.LoadPermanentConsistencyCountry(
                  base::Version(test.version), latest_country))
        << test.permanent_consistency_country_before << ", " << test.version
        << ", " << test.latest_country_code;

    base::Value::List expected_list;
    for (const std::string& component :
         base::SplitString(test.permanent_consistency_country_after, ",",
                           base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
      expected_list.Append(component);
    }
    const base::Value::List& pref_list =
        local_state()->GetList(prefs::kVariationsPermanentConsistencyCountry);
    EXPECT_EQ(ListToString(expected_list), ListToString(pref_list))
        << test.permanent_consistency_country_before << ", " << test.version
        << ", " << test.latest_country_code;

    histogram_tester.ExpectUniqueSample(
        "Variations.LoadPermanentConsistencyCountryResult",
        test.expected_result, 1);
  }
}

#if BUILDFLAG(IS_ANDROID)
// This is a regression test for crbug/829527.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrials_LoadsCountryOnFirstRun) {
  // Simulate having received a seed in Java during First Run.
  const base::Time one_day_ago = base::Time::Now() - base::Days(1);
  auto initial_seed = std::make_unique<SeedResponse>();
  initial_seed->data = SerializeSeed(CreateTestSeedWithCountryFilter());
  initial_seed->signature = kTestSeedSignature;
  initial_seed->country = kTestSeedCountry;
  initial_seed->date = one_day_ago;
  initial_seed->is_gzip_compressed = false;

  TestVariationsServiceClient variations_service_client;
  PlatformFieldTrials platform_field_trials;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());

  // Note: Unlike other tests, this test does not mock out the seed store, since
  // the interaction between these two classes is what's being tested.
  auto seed_store = std::make_unique<VariationsSeedStore>(
      local_state(), std::move(initial_seed),
      /*signature_verification_enabled=*/false,
      std::make_unique<VariationsSafeSeedStoreLocalState>(
          local_state(),
          /*seed_file_dir=*/base::FilePath(), version_info::Channel::UNKNOWN,
          /*entropy_providers=*/nullptr),
      version_info::Channel::UNKNOWN, /*seed_file_dir=*/base::FilePath());
  VariationsFieldTrialCreator field_trial_creator(
      &variations_service_client, std::move(seed_store), UIStringOverrider());

  metrics::TestEnabledStateProvider enabled_state_provider(/*consent=*/true,
                                                           /*enabled=*/true);
  auto metrics_state_manager = metrics::MetricsStateManager::Create(
      local_state(), &enabled_state_provider, std::wstring(), base::FilePath());
  metrics_state_manager->InstantiateFieldTrialList();

  // Check that field trials are created from the seed. The test seed contains a
  // single study with an experiment targeting 100% of users in India. Since
  // |initial_seed| included the country code for India, this study should be
  // active.
  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials(
      /*variation_ids=*/std::vector<std::string>(),
      base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kForceVariationIds),
      std::vector<base::FeatureList::FeatureOverrideInfo>(),
      std::make_unique<base::FeatureList>(), metrics_state_manager.get(),
      &platform_field_trials, &safe_seed_manager,
      /*add_entropy_source_to_variations_ids=*/true,
      *metrics_state_manager->CreateEntropyProviders(
          /*enable_limited_entropy_mode=*/false)));

  EXPECT_EQ(kTestSeedExperimentName,
            base::FieldTrialList::FindFullName(kTestSeedStudyName));
}

// Tests that the hardware class is set on Android.
TEST_F(FieldTrialCreatorTest, ClientFilterableState_HardwareClass) {
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());

  TestVariationsServiceClient variations_service_client;
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  const base::Version& current_version = version_info::GetVersion();
  EXPECT_TRUE(current_version.IsValid());

  std::unique_ptr<ClientFilterableState> client_filterable_state =
      field_trial_creator.GetClientFilterableStateForVersion(current_version);
  EXPECT_NE(client_filterable_state->hardware_class, std::string());
}
#endif  // BUILDFLAG(IS_ANDROID)

#if BUILDFLAG(FIELDTRIAL_TESTING_ENABLED)
// Used to create a TestVariationsFieldTrialCreator with a valid unexpired seed.
std::unique_ptr<TestVariationsFieldTrialCreator>
SetUpFieldTrialCreatorWithValidSeed(
    PrefService* local_state,
    TestVariationsServiceClient* variations_service_client,
    NiceMock<MockSafeSeedManager>* safe_seed_manager) {
  // Set up a valid unexpired seed.
  const base::Time now = base::Time::Now();
  const base::Time seed_fetch_time = now - base::Days(1);
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      std::make_unique<TestVariationsFieldTrialCreator>(
          local_state, variations_service_client, safe_seed_manager);
  // Simulate the seed being stored.
  field_trial_creator->seed_store()->RecordLastFetchTime(seed_fetch_time);
  // Simulate a seed from an earlier (i.e. valid) milestone.
  local_state->SetInteger(prefs::kVariationsSeedMilestone, kTestSeedMilestone);
  return field_trial_creator;
}

// Verifies that a valid seed is used instead of the testing config when we
// disable it.
TEST_F(FieldTrialCreatorTest, NotSetUpFieldTrialConfig_ValidSeed) {
  // Create a field trial creator with a valid unexpired seed.
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      SetUpFieldTrialCreatorWithValidSeed(
          local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that |SetUpFieldTrials| uses the seed. |SetUpFieldTrials| returns
  // true if it used a seed.
  EXPECT_CALL(safe_seed_manager,
              DoSetActiveSeedState(kTestSeedSerializedData, kTestSeedSignature,
                                   kTestSeedMilestone, _, _))
      .Times(1);
  EXPECT_TRUE(field_trial_creator->SetUpFieldTrials());
  EXPECT_TRUE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that the |UnitTest| trial from the field trial testing config was
  // not registered.
  ASSERT_FALSE(base::FieldTrialList::TrialExists("UnitTest"));

  ResetVariations();
}

// Verifies that field trial testing config is used when enabled, even when
// there is a valid unexpired seed.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrialConfig_ValidSeed) {
  EnableTestingConfig();

  // Create a field trial creator with a valid unexpired seed.
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      SetUpFieldTrialCreatorWithValidSeed(
          local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that |SetUpFieldTrials| does not use the seed, despite it being
  // valid and unexpired. |SetUpFieldTrials| returns false if it did not use a
  // seed.
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);
  EXPECT_FALSE(field_trial_creator->SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that the |UnitTest| trial from the field trial testing config has
  // been registered, and that the group name is |Enabled|.
  ASSERT_EQ("Enabled", base::FieldTrialList::FindFullName("UnitTest"));

  // Verify the |UnitTest| trial params.
  base::FieldTrialParams params;
  ASSERT_TRUE(base::GetFieldTrialParams("UnitTest", &params));
  ASSERT_EQ(1U, params.size());
  EXPECT_EQ("1", params["x"]);

  // Verify that the |UnitTestEnabled| feature is active.
  static BASE_FEATURE(kFeature1, "UnitTestEnabled",
                      base::FEATURE_DISABLED_BY_DEFAULT);
  EXPECT_TRUE(base::FeatureList::IsEnabled(kFeature1));

  ResetVariations();
}

// Verifies that trials from the testing config and the |--force-fieldtrials|
// switch are registered when they are both used (assuming there are no
// conflicts).
TEST_F(FieldTrialCreatorTest, SetUpFieldTrialConfig_ForceFieldTrials) {
  EnableTestingConfig();

  // Simulate passing |--force-fieldtrials="UnitTest2/Enabled"|.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      ::switches::kForceFieldTrials, "UnitTest2/Enabled");
  // Simulate passing |--force-fieldtrial-params="UnitTest2.Enabled:y/1"|.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kForceFieldTrialParams, "UnitTest2.Enabled:y/1");
  // Simulate passing |--enable-features="UnitTest2Enabled<UnitTest2"|.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      ::switches::kEnableFeatures, "UnitTest2Enabled<UnitTest2");

  // Create a field trial creator with a valid unexpired seed.
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      SetUpFieldTrialCreatorWithValidSeed(
          local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that |SetUpFieldTrials| does not use the seed, despite it being
  // valid and unexpired. |SetUpFieldTrials| returns false if it did not use a
  // seed.
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);
  EXPECT_FALSE(field_trial_creator->SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that the |UnitTest| trial from the field trial testing config has
  // been registered, and that the group name is |Enabled|.
  ASSERT_EQ("Enabled", base::FieldTrialList::FindFullName("UnitTest"));
  // Verify that the |UnitTest2| trial from the |--force-fieldtrials| switch has
  // been registered, and that the group name is |Enabled|.
  ASSERT_EQ("Enabled", base::FieldTrialList::FindFullName("UnitTest2"));

  // Verify the |UnitTest| trial params.
  base::FieldTrialParams params;
  ASSERT_TRUE(base::GetFieldTrialParams("UnitTest", &params));
  ASSERT_EQ(1U, params.size());
  EXPECT_EQ("1", params["x"]);
  // Verify the |UnitTest2| trial params.
  base::FieldTrialParams params2;
  ASSERT_TRUE(base::GetFieldTrialParams("UnitTest2", &params2));
  ASSERT_EQ(1U, params2.size());
  EXPECT_EQ("1", params2["y"]);

  // Verify that the |UnitTestEnabled| and |UnitTestEnabled2| features are
  // active.
  static BASE_FEATURE(kFeature1, "UnitTestEnabled",
                      base::FEATURE_DISABLED_BY_DEFAULT);
  EXPECT_TRUE(base::FeatureList::IsEnabled(kFeature1));
  static BASE_FEATURE(kFeature2, "UnitTest2Enabled",
                      base::FEATURE_DISABLED_BY_DEFAULT);
  EXPECT_TRUE(base::FeatureList::IsEnabled(kFeature2));

  ResetVariations();
}

// Verifies that when field trial testing config is used, trials and groups
// specified using |--force-fieldtrials| take precedence if they specify the
// same trials but different groups.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrialConfig_ForceFieldTrialsOverride) {
  EnableTestingConfig();

  // Simulate passing |--force-fieldtrials="UnitTest/Disabled"| switch.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      ::switches::kForceFieldTrials, "UnitTest/Disabled");

  // Create a field trial creator with a valid unexpired seed.
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      SetUpFieldTrialCreatorWithValidSeed(
          local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that |SetUpFieldTrials| does not use the seed, despite it being
  // valid and unexpired. |SetUpFieldTrials| returns false if it did not use a
  // seed.
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);
  EXPECT_FALSE(field_trial_creator->SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that the |UnitTest| trial from the |--force-fieldtrials| switch (and
  // not from the field trial testing config) has been registered, and that the
  // group name is |Disabled|.
  ASSERT_EQ("Disabled", base::FieldTrialList::FindFullName("UnitTest"));

  // Verify that the |UnitTest| trial params from the field trial testing config
  // were not used. |GetFieldTrialParams| returns false if no parameters are
  // defined for a specified trial.
  base::FieldTrialParams params;
  ASSERT_FALSE(base::GetFieldTrialParams("UnitTest", &params));

  // Verify that the |UnitTestEnabled| feature from the testing config is not
  // active.
  static BASE_FEATURE(kFeature1, "UnitTestEnabled",
                      base::FEATURE_DISABLED_BY_DEFAULT);
  EXPECT_FALSE(base::FeatureList::IsEnabled(kFeature1));

  ResetVariations();
}

// Verifies that when field trial testing config is used, params specified using
// |--force-fieldtrial-params| take precedence if they specify the same trial
// and group.
TEST_F(FieldTrialCreatorTest, SetUpFieldTrialConfig_ForceFieldTrialParams) {
  EnableTestingConfig();

  // Simulate passing |--force-fieldtrial-params="UnitTest.Enabled:x/2/y/2"|
  // switch.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kForceFieldTrialParams, "UnitTest.Enabled:x/2/y/2");

  // Create a field trial creator with a valid unexpired seed.
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      SetUpFieldTrialCreatorWithValidSeed(
          local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that |SetUpFieldTrials| does not use the seed, despite it being
  // valid and unexpired. |SetUpFieldTrials| returns false if it did not use a
  // seed.
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);
  EXPECT_FALSE(field_trial_creator->SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that the |UnitTest| trial from the field trial testing config has
  // been registered, and that the group name is |Enabled|.
  ASSERT_EQ("Enabled", base::FieldTrialList::FindFullName("UnitTest"));

  // Verify the |UnitTest| trial params, and that the
  // |--force-fieldtrial-params| took precedence over the params defined in the
  // field trial testing config.
  base::FieldTrialParams params;
  ASSERT_TRUE(base::GetFieldTrialParams("UnitTest", &params));
  ASSERT_EQ(2U, params.size());
  EXPECT_EQ("2", params["x"]);
  EXPECT_EQ("2", params["y"]);

  // Verify that the |UnitTestEnabled| feature is still active.
  static BASE_FEATURE(kFeature1, "UnitTestEnabled",
                      base::FEATURE_DISABLED_BY_DEFAULT);
  EXPECT_TRUE(base::FeatureList::IsEnabled(kFeature1));

  ResetVariations();
}

class FieldTrialCreatorTestWithFeatures
    : public FieldTrialCreatorTest,
      public ::testing::WithParamInterface<const char*> {};

INSTANTIATE_TEST_SUITE_P(All,
                         FieldTrialCreatorTestWithFeatures,
                         ::testing::Values(::switches::kEnableFeatures,
                                           ::switches::kDisableFeatures));

// Verifies that studies from field trial testing config should be ignored
// if they enable/disable features overridden by |--enable-features| or
// |--disable-features|.
TEST_P(FieldTrialCreatorTestWithFeatures,
       SetUpFieldTrialConfig_OverrideFeatures) {
  EnableTestingConfig();

  // Simulate passing either |--enable-features="UnitTestEnabled"| or
  // |--disable-features="UnitTestEnabled"| switch.
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(GetParam(),
                                                            "UnitTestEnabled");

  // Create a field trial creator with a valid unexpired seed.
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  std::unique_ptr<TestVariationsFieldTrialCreator> field_trial_creator =
      SetUpFieldTrialCreatorWithValidSeed(
          local_state(), &variations_service_client, &safe_seed_manager);

  // Verify that |SetUpFieldTrials| does not use the seed, despite it being
  // valid and unexpired. |SetUpFieldTrials| returns false if it did not use a
  // seed.
  EXPECT_CALL(safe_seed_manager, DoSetActiveSeedState(_, _, _, _, _)).Times(0);
  EXPECT_FALSE(field_trial_creator->SetUpFieldTrials());
  EXPECT_FALSE(base::FieldTrialList::TrialExists(kTestSeedStudyName));

  // Verify that the |UnitTest| trial from the field trial testing config was
  // NOT registered. Even if the study |UnitTest| enables feature
  // |UnitTestEnabled|, and we pass |--enable-features="UnitTestEnabled"|, the
  // study should be disabled.
  EXPECT_FALSE(base::FieldTrialList::TrialExists("UnitTest"));

  // Verify that the |UnitTestEnabled| feature is enabled or disabled depending
  // on whether we passed it in |--enable-features| or |--disable-features|.
  static BASE_FEATURE(kFeature1, "UnitTestEnabled",
                      base::FEATURE_DISABLED_BY_DEFAULT);

  EXPECT_EQ(GetParam() == ::switches::kEnableFeatures,
            base::FeatureList::IsEnabled(kFeature1));

  ResetVariations();
}
#endif  // BUILDFLAG(FIELDTRIAL_TESTING_ENABLED)

// Verify that a beacon file is not written when passing an empty user data
// directory path. Some platforms deliberately pass an empty path.
TEST_F(FieldTrialCreatorTest, DoNotWriteBeaconFile) {
  TestVariationsServiceClient variations_service_client;
  // Ensure that Variations Safe Mode is not triggered.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  // Pass an empty path instead of a path to the user data dir.
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager,
      base::FilePath());

  base::HistogramTester histogram_tester;
  ASSERT_TRUE(field_trial_creator.SetUpFieldTrials());

  EXPECT_FALSE(base::PathExists(
      user_data_dir_path().Append(metrics::kCleanExitBeaconFilename)));
  histogram_tester.ExpectTotalCount(
      "Variations.ExtendedSafeMode.BeaconFileWrite", 0);
}

struct StartupVisibilityTestParams {
  const std::string test_name;
  metrics::StartupVisibility startup_visibility;
  bool extend_safe_mode;
};

class FieldTrialCreatorTestWithStartupVisibility
    : public FieldTrialCreatorTest,
      public ::testing::WithParamInterface<StartupVisibilityTestParams> {};

INSTANTIATE_TEST_SUITE_P(
    All,
    FieldTrialCreatorTestWithStartupVisibility,
    ::testing::Values(
        StartupVisibilityTestParams{
            .test_name = "UnknownVisibility",
            .startup_visibility = metrics::StartupVisibility::kUnknown,
            .extend_safe_mode = true},
        StartupVisibilityTestParams{
            .test_name = "BackgroundVisibility",
            .startup_visibility = metrics::StartupVisibility::kBackground,
            .extend_safe_mode = false},
        StartupVisibilityTestParams{
            .test_name = "ForegroundVisibility",
            .startup_visibility = metrics::StartupVisibility::kForeground,
            .extend_safe_mode = true}),
    [](const ::testing::TestParamInfo<StartupVisibilityTestParams>& params) {
      return params.param.test_name;
    });

// Verify that Chrome starts watching for crashes for unknown and foreground
// startup visibilities. Verify that Chrome does not start watching for crashes
// in background sessions.
TEST_P(FieldTrialCreatorTestWithStartupVisibility,
       StartupVisibilityAffectsBrowserCrashMonitoring) {
  TestVariationsServiceClient variations_service_client;
  // Ensure that Variations Safe Mode is not triggered.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  StartupVisibilityTestParams params = GetParam();
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager,
      user_data_dir_path(), params.startup_visibility);

  ASSERT_TRUE(field_trial_creator.SetUpFieldTrials());

  // Verify that Chrome did (or did not) start watching for crashes.
  EXPECT_EQ(base::PathExists(
                user_data_dir_path().Append(metrics::kCleanExitBeaconFilename)),
            params.extend_safe_mode);
}

// Verify that the beacon file contents are as expected when Chrome starts
// watching for browser crashes before setting up field trials.
TEST_F(FieldTrialCreatorTest, WriteBeaconFile) {
  TestVariationsServiceClient variations_service_client;
  // Ensure that Variations Safe Mode is not triggered.
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager,
      user_data_dir_path());

  base::HistogramTester histogram_tester;
  ASSERT_TRUE(field_trial_creator.SetUpFieldTrials());

  // Verify that the beacon file was written and that the contents are correct.
  const base::FilePath variations_file_path =
      user_data_dir_path().Append(metrics::kCleanExitBeaconFilename);
  EXPECT_TRUE(base::PathExists(variations_file_path));
  std::string beacon_file_contents;
  ASSERT_TRUE(
      base::ReadFileToString(variations_file_path, &beacon_file_contents));
  EXPECT_EQ(beacon_file_contents,
            "{\"user_experience_metrics.stability.exited_cleanly\":false,"
            "\"variations_crash_streak\":0}");

  // Verify metrics.
  histogram_tester.ExpectUniqueSample(
      "Variations.ExtendedSafeMode.BeaconFileWrite", 1, 1);
}

TEST_F(FieldTrialCreatorTest, GetGoogleGroupsFromPrefsWhenPrefNotPresent) {
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  ASSERT_EQ(field_trial_creator.GetGoogleGroupsFromPrefs(),
            base::flat_set<uint64_t>());
}

TEST_F(FieldTrialCreatorTest, GetGoogleGroupsFromPrefsWhenEmptyDict) {
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Add an empty dict value for the pref.
  base::Value::Dict google_groups_dict;
  local_state()->SetDict(prefs::kVariationsGoogleGroups,
                         std::move(google_groups_dict));

  ASSERT_EQ(field_trial_creator.GetGoogleGroupsFromPrefs(),
            base::flat_set<uint64_t>());
}

TEST_F(FieldTrialCreatorTest,
       GetGoogleGroupsFromPrefsWhenProfileWithEmptyList) {
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Add an empty dict value for the pref.
  base::Value::Dict google_groups_dict;
  base::Value::List profile_1_groups;
  google_groups_dict.Set("Profile 1", std::move(profile_1_groups));
  local_state()->SetDict(prefs::kVariationsGoogleGroups,
                         std::move(google_groups_dict));

  ASSERT_EQ(field_trial_creator.GetGoogleGroupsFromPrefs(),
            base::flat_set<uint64_t>());
}

TEST_F(FieldTrialCreatorTest,
       GetGoogleGroupsFromPrefsWhenProfileWithNonEmptyList) {
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Add an empty dict value for the pref.
  base::Value::Dict google_groups_dict;
  base::Value::List profile_1_groups;
  profile_1_groups.Append("123");
  profile_1_groups.Append("456");
  google_groups_dict.Set("Profile 1", std::move(profile_1_groups));
  local_state()->SetDict(prefs::kVariationsGoogleGroups,
                         std::move(google_groups_dict));

  ASSERT_EQ(field_trial_creator.GetGoogleGroupsFromPrefs(),
            base::flat_set<uint64_t>({123, 456}));
}

TEST_F(FieldTrialCreatorTest,
       GetGoogleGroupsFromPrefsWhenProfileWithNonNumericString) {
  TestVariationsServiceClient variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  // Add an empty dict value for the pref.
  base::Value::Dict google_groups_dict;
  base::Value::List profile_1_groups;
  profile_1_groups.Append("Alice");
  profile_1_groups.Append("Bob");
  google_groups_dict.Set("Profile 1", std::move(profile_1_groups));
  local_state()->SetDict(prefs::kVariationsGoogleGroups,
                         std::move(google_groups_dict));

  ASSERT_EQ(field_trial_creator.GetGoogleGroupsFromPrefs(),
            base::flat_set<uint64_t>());
}

TEST_F(FieldTrialCreatorTest, GetGoogleGroupsFromPrefsClearsDeletedProfiles) {
  NiceMock<MockVariationsServiceClient> variations_service_client;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());
  TestVariationsFieldTrialCreator field_trial_creator(
      local_state(), &variations_service_client, &safe_seed_manager);

  EXPECT_CALL(variations_service_client,
              RemoveGoogleGroupsFromPrefsForDeletedProfiles(local_state()));
  field_trial_creator.GetGoogleGroupsFromPrefs();
}

namespace {

enum class LimitedModeGate {
  ENABLED,
  DISABLED,
};

struct LimitedEntropyProcessingTestCase {
  std::string test_name;
  VariationsSeed seed;

  bool is_seed_rejection_expected;
  bool is_limited_study_active;
};

class LimitedEntropyProcessingTest
    : public FieldTrialCreatorTest,
      public ::testing::WithParamInterface<LimitedEntropyProcessingTestCase> {};

INSTANTIATE_TEST_SUITE_P(
    FieldTrialCreatorTest,
    LimitedEntropyProcessingTest,
    ::testing::Values(
        LimitedEntropyProcessingTestCase{
            .test_name = "ShouldProcessLimitedLayer",
            .seed = CreateTestSeedWithLimitedEntropyLayer(),
            .is_seed_rejection_expected = false,
            .is_limited_study_active = true},
        LimitedEntropyProcessingTestCase{
            .test_name = "ShouldRejectSeedWithExcessiveEntropyUse",
            .seed =
                CreateTestSeedWithLimitedEntropyLayerUsingExcessiveEntropy(),
            .is_seed_rejection_expected = true,
            .is_limited_study_active = false}),
    [](const ::testing::TestParamInfo<LimitedEntropyProcessingTestCase>& info) {
      return info.param.test_name;
    });

TEST_P(LimitedEntropyProcessingTest,
       RandomizeLimitedEntropyStudyOrRejectTheSeed) {
  const LimitedEntropyProcessingTestCase test_case = GetParam();

  auto encoded_and_compressed = GZipAndB64EncodeToHexString(test_case.seed);
  local_state()->SetString(prefs::kVariationsCompressedSeed,
                           encoded_and_compressed);

  // Allows and writes an empty signature for the test seed.
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kAcceptEmptySeedSignatureForTesting);
  local_state()->SetString(prefs::kVariationsSeedSignature, "");

  // Sets up dependencies and mocks.
  TestVariationsServiceClient variations_service_client;
  auto seed_store = CreateSeedStore(local_state(), seed_file_path());
  VariationsFieldTrialCreator field_trial_creator(
      &variations_service_client, std::move(seed_store), UIStringOverrider());
  metrics::TestEnabledStateProvider enabled_state_provider(
      /*consent=*/true,
      /*enabled=*/true);
  auto metrics_state_manager = metrics::MetricsStateManager::Create(
      local_state(), &enabled_state_provider, std::wstring(), base::FilePath());
  metrics_state_manager->InstantiateFieldTrialList();
  PlatformFieldTrials platform_field_trials;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());

  EXPECT_NE(
      test_case.is_seed_rejection_expected,
      field_trial_creator.SetUpFieldTrials(
          /*variation_ids=*/{},
          /*command_line_variation_ids=*/std::string(),
          std::vector<base::FeatureList::FeatureOverrideInfo>(),
          std::make_unique<base::FeatureList>(), metrics_state_manager.get(),
          &platform_field_trials, &safe_seed_manager,
          /*add_entropy_source_to_variations_ids=*/true,
          *metrics_state_manager->CreateEntropyProviders(
              /*enable_limited_entropy_mode=*/true)));

  // Verifies that the limited entropy test study is randomized.
  EXPECT_EQ(test_case.is_limited_study_active,
            base::FieldTrialList::TrialExists(kTestLimitedLayerStudyName));
}

// Test feature names prefixed with __ to avoid collision with real features.
BASE_FEATURE(kDesktopFeature, "__Desktop", base::FEATURE_DISABLED_BY_DEFAULT);
BASE_FEATURE(kPhoneFeature, "__Phone", base::FEATURE_DISABLED_BY_DEFAULT);
BASE_FEATURE(kTabletFeature, "__Tablet", base::FEATURE_DISABLED_BY_DEFAULT);
BASE_FEATURE(kKioskFeature, "__Kiosk", base::FEATURE_DISABLED_BY_DEFAULT);
BASE_FEATURE(kMeetFeature, "__Meet", base::FEATURE_DISABLED_BY_DEFAULT);
BASE_FEATURE(kTVFeature, "__TV", base::FEATURE_DISABLED_BY_DEFAULT);
BASE_FEATURE(kAutomotiveFeature, "__Auto", base::FEATURE_DISABLED_BY_DEFAULT);

class FieldTrialCreatorFormFactorTest
    : public FieldTrialCreatorTest,
      public ::testing::WithParamInterface<Study::FormFactor> {};

constexpr Study::FormFactor kAllFormFactors[] = {
    Study::DESKTOP,     Study::PHONE, Study::TABLET,    Study::KIOSK,
    Study::MEET_DEVICE, Study::TV,    Study::AUTOMOTIVE};

// A test seed that enables form-factor specific features across all platforms
// and channels. I.e. the __Desktop feature is enabled only on the Desktop form
// factor, the __Phone feature is enabled only on the Phone form factor, and so
// forth.  The seed applies to all platforms and all channels, except "unknown".
constexpr char kFormFactorTestSeedData[] =
    "H4sIAAAAAAAA/4TPT2vCQBAF8Gz+Z0qh7K20lVAvcxdkLzksVmRjLVqDPQ6xXTQoSakJ/"
    "fplrbeAe34zP96D4Xox2b115cfvWlZSqp1ScpVlw/FsLCfL0Wj1ozI+BV92bSNY/"
    "gC307rcHvXXa9nVn/s7to0hJDLx+yB1Upa6qYcOMnTRwwR9DDDECGMR8jlEL/"
    "p0aJtvwfJBX7qBhOhyYcEcPoNgXjWng2D5Y59KICI65xbIM+"
    "MWWrdXxpnYwvimz3Lf1PpKn3NugRiX4BYbwfL7vhKCT1RsLETAFYSF+"
    "TSjnvoMQEz0f2Ch3Gevro5/AQAA//8RFDdTJQIAAA==";
constexpr char kFormFactorTestSeedSignature[] = "";  // Deliberately empty.

}  // namespace

INSTANTIATE_TEST_SUITE_P(All,
                         FieldTrialCreatorFormFactorTest,
                         ::testing::ValuesIn(kAllFormFactors));

TEST_P(FieldTrialCreatorFormFactorTest, FilterByFormFactor) {
  base::CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kAcceptEmptySeedSignatureForTesting);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kFakeVariationsChannel,
      "dev");  // Seed supports canary, dev, beta and stable, but not "unknown".

  const auto current_form_factor = GetParam();

  // Override Local State seed prefs to use the form factor test seed constants.
  local_state()->SetString(prefs::kVariationsCompressedSeed,
                           kFormFactorTestSeedData);
  local_state()->SetString(prefs::kVariationsSeedSignature,
                           kFormFactorTestSeedSignature);
  local_state()->CommitPendingWrite();

  // Mock the variations service client to send the parameritized form factor.
  NiceMock<MockVariationsServiceClient> variations_service_client;
  ON_CALL(variations_service_client, GetCurrentFormFactor())
      .WillByDefault(Return(current_form_factor));

  // Create the other field trial creator dependencies.
  metrics::TestEnabledStateProvider enabled_state_provider(
      /*consent=*/true,
      /*enabled=*/true);
  auto metrics_state_manager = metrics::MetricsStateManager::Create(
      local_state(), &enabled_state_provider, std::wstring(), base::FilePath());
  metrics_state_manager->InstantiateFieldTrialList();

  PlatformFieldTrials platform_field_trials;
  NiceMock<MockSafeSeedManager> safe_seed_manager(local_state());

  // Set up the field trials.
  VariationsFieldTrialCreator field_trial_creator{
      &variations_service_client,
      CreateSeedStore(local_state(), seed_file_path()), UIStringOverrider()};
  EXPECT_TRUE(field_trial_creator.SetUpFieldTrials(
      /*variation_ids=*/{},
      /*command_line_variation_ids=*/std::string(),
      std::vector<base::FeatureList::FeatureOverrideInfo>(),
      std::make_unique<base::FeatureList>(), metrics_state_manager.get(),
      &platform_field_trials, &safe_seed_manager,
      /*add_entropy_source_to_variations_ids=*/true,
      *metrics_state_manager->CreateEntropyProviders(
          /*enable_limited_entropy_mode=*/false)));

  // Each form factor specific feature should be enabled iff the current form
  // factor matches the feature's targetted form factor.

  EXPECT_EQ(base::FeatureList::IsEnabled(kDesktopFeature),
            current_form_factor == Study::DESKTOP);

  EXPECT_EQ(base::FeatureList::IsEnabled(kPhoneFeature),
            current_form_factor == Study::PHONE);

  EXPECT_EQ(base::FeatureList::IsEnabled(kTabletFeature),
            current_form_factor == Study::TABLET);

  EXPECT_EQ(base::FeatureList::IsEnabled(kKioskFeature),
            current_form_factor == Study::KIOSK);

  EXPECT_EQ(base::FeatureList::IsEnabled(kMeetFeature),
            current_form_factor == Study::MEET_DEVICE);

  EXPECT_EQ(base::FeatureList::IsEnabled(kTVFeature),
            current_form_factor == Study::TV);

  EXPECT_EQ(base::FeatureList::IsEnabled(kAutomotiveFeature),
            current_form_factor == Study::AUTOMOTIVE);
}

}  // namespace variations