File: force_installed_metrics_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1616 lines) | stat: -rw-r--r-- 79,692 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/forced_extensions/force_installed_metrics.h"

#include <optional>

#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/time/time.h"
#include "base/timer/mock_timer.h"
#include "base/values.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/external_provider_impl.h"
#include "chrome/browser/extensions/forced_extensions/force_installed_test_base.h"
#include "chrome/browser/extensions/forced_extensions/force_installed_tracker.h"
#include "chrome/browser/extensions/forced_extensions/install_stage_tracker.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/testing_browser_process.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/disable_reason.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/install/crx_install_error.h"
#include "extensions/browser/install/sandboxed_unpacker_failure_reason.h"
#include "extensions/browser/pref_names.h"
#include "extensions/browser/updater/safe_manifest_parser.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "extensions/common/switches.h"
#include "net/base/net_errors.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chromeos/ash/experiences/arc/arc_prefs.h"
#include "components/user_manager/scoped_user_manager.h"
#include "components/user_manager/test_helper.h"
#include "components/user_manager/user_names.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
#include "chrome/browser/enterprise/browser_management/management_service_factory.h"
#include "components/policy/core/common/management/management_service.h"
#include "components/policy/core/common/management/scoped_management_service_override_for_testing.h"
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)

namespace {

// Intentionally invalid extension id.
constexpr char kExtensionId3[] = "cdefghijklmnopqrstuvwxyzabcdefgh";

const int kFetchTries = 5;
// HTTP_FORBIDDEN
const int kHttpCodeForbidden = 403;

constexpr char kLoadTimeStats[] = "Extensions.ForceInstalledLoadTime";
constexpr char kReadyTimeStats[] = "Extensions.ForceInstalledReadyTime";
constexpr char kTimedOutStats[] = "Extensions.ForceInstalledTimedOutCount";
constexpr char kTimedOutNotInstalledStats[] =
    "Extensions.ForceInstalledTimedOutAndNotInstalledCount";
constexpr char kInstallationFailureCacheStatus[] =
    "Extensions.ForceInstalledFailureCacheStatus";
constexpr char kFailureReasonsCWS[] =
    "Extensions.WebStore_ForceInstalledFailureReason3";
constexpr char kFailureReasonsSH[] =
    "Extensions.OffStore_ForceInstalledFailureReason3";
constexpr char kInstallationStages[] = "Extensions.ForceInstalledStage2";
constexpr char kInstallCreationStages[] =
    "Extensions.ForceInstalledCreationStage";
constexpr char kInstallationDownloadingStages[] =
    "Extensions.ForceInstalledDownloadingStage";
constexpr char kFailureCrxInstallErrorStats[] =
    "Extensions.ForceInstalledFailureCrxInstallError";
constexpr char kTotalCountStats[] =
    "Extensions.ForceInstalledTotalCandidateCount";
constexpr char kNetworkErrorCodeCrxFetchRetryStats[] =
    "Extensions.ForceInstalledCrxFetchRetryNetworkErrorCode";
constexpr char kHttpErrorCodeCrxFetchRetryStatsCWS[] =
    "Extensions.WebStore_ForceInstalledCrxFetchRetryHttpErrorCode2";
constexpr char kHttpErrorCodeCrxFetchRetryStatsSH[] =
    "Extensions.OffStore_ForceInstalledCrxFetchRetryHttpErrorCode2";
constexpr char kFetchRetriesCrxFetchRetryStats[] =
    "Extensions.ForceInstalledCrxFetchRetryFetchTries";
constexpr char kNetworkErrorCodeCrxFetchFailedStats[] =
    "Extensions.ForceInstalledNetworkErrorCode";
constexpr char kHttpErrorCodeCrxFetchFailedStats[] =
    "Extensions.ForceInstalledHttpErrorCode2";
constexpr char kHttpErrorCodeCrxFetchFailedStatsCWS[] =
    "Extensions.WebStore_ForceInstalledHttpErrorCode2";
constexpr char kHttpErrorCodeCrxFetchFailedStatsSH[] =
    "Extensions.OffStore_ForceInstalledHttpErrorCode2";
constexpr char kFetchRetriesCrxFetchFailedStats[] =
    "Extensions.ForceInstalledFetchTries";
constexpr char kNetworkErrorCodeManifestFetchRetryStats[] =
    "Extensions.ForceInstalledManifestFetchRetryNetworkErrorCode";
constexpr char kHttpErrorCodeManifestFetchRetryStatsCWS[] =
    "Extensions.WebStore_ForceInstalledManifestFetchRetryHttpErrorCode2";
constexpr char kHttpErrorCodeManifestFetchRetryStatsSH[] =
    "Extensions.OffStore_ForceInstalledManifestFetchRetryHttpErrorCode2";
constexpr char kFetchRetriesManifestFetchRetryStats[] =
    "Extensions.ForceInstalledManifestFetchRetryFetchTries";
constexpr char kNetworkErrorCodeManifestFetchFailedStats[] =
    "Extensions.ForceInstalledManifestFetchFailedNetworkErrorCode";
constexpr char kHttpErrorCodeManifestFetchFailedStats[] =
    "Extensions.ForceInstalledManifestFetchFailedHttpErrorCode2";
constexpr char kHttpErrorCodeManifestFetchFailedStatsCWS[] =
    "Extensions.WebStore_ForceInstalledManifestFetchFailedHttpErrorCode2";
constexpr char kHttpErrorCodeManifestFetchFailedStatsSH[] =
    "Extensions.OffStore_ForceInstalledManifestFetchFailedHttpErrorCode2";
constexpr char kFetchRetriesManifestFetchFailedStats[] =
    "Extensions.ForceInstalledManifestFetchFailedFetchTries";
constexpr char kSandboxUnpackFailureReason[] =
    "Extensions.ForceInstalledFailureSandboxUnpackFailureReason2";
#if BUILDFLAG(IS_CHROMEOS)
constexpr char kFailureSessionStats[] =
    "Extensions.ForceInstalledFailureSessionType";
constexpr char kStuckInCreateStageSessionType[] =
    "Extensions.ForceInstalledFailureSessionType."
    "ExtensionStuckInInitialCreationStage";
#endif  // BUILDFLAG(IS_CHROMEOS)
constexpr char kPossibleNonMisconfigurationFailures[] =
    "Extensions.ForceInstalledSessionsWithNonMisconfigurationFailureOccured";
constexpr char kDisableReason[] =
    "Extensions.ForceInstalledNotLoadedDisableReason";
constexpr char kBlocklisted[] = "Extensions.ForceInstalledAndBlockListed";
constexpr char kWebStoreExtensionManifestInvalid[] =
    "Extensions.WebStore_ForceInstalledFailureManifestInvalidErrorDetail2";
constexpr char kOffStoreExtensionManifestInvalid[] =
    "Extensions.OffStore_ForceInstalledFailureManifestInvalidErrorDetail2";
constexpr char kManifestNoUpdatesInfo[] =
    "Extensions.ForceInstalledFailureNoUpdatesInfo";
constexpr char kExtensionManifestInvalidAppStatusError[] =
    "Extensions.ForceInstalledFailureManifestInvalidAppStatusError";
constexpr char kManifestDownloadTimeStats[] =
    "Extensions.ForceInstalledTime.DownloadingStartTo.ManifestDownloadComplete";
constexpr char kCRXDownloadTimeStats[] =
    "Extensions.ForceInstalledTime.ManifestDownloadCompleteTo."
    "CRXDownloadComplete";
constexpr char kVerificationTimeStats[] =
    "Extensions.ForceInstalledTime.VerificationStartTo.CopyingStart";
constexpr char kCopyingTimeStats[] =
    "Extensions.ForceInstalledTime.CopyingStartTo.UnpackingStart";
constexpr char kUnpackingTimeStats[] =
    "Extensions.ForceInstalledTime.UnpackingStartTo.CheckingExpectationsStart";
constexpr char kCheckingExpectationsTimeStats[] =
    "Extensions.ForceInstalledTime.CheckingExpectationsStartTo.FinalizingStart";
constexpr char kFinalizingTimeStats[] =
    "Extensions.ForceInstalledTime.FinalizingStartTo.CRXInstallComplete";
constexpr char kCrxHeaderInvalidFailureIsCWS[] =
    "Extensions.ForceInstalledFailureWithCrxHeaderInvalidIsCWS";
constexpr char kCrxHeaderInvalidFailureFromCache[] =
    "Extensions.ForceInstalledFailureWithCrxHeaderInvalidIsFromCache";
// TODO(crbug.com/394876083): Need investigation once ExtensionService is fully
// implemented for Android for Desktop.
#if BUILDFLAG(ENABLE_EXTENSIONS)
constexpr char kStuckInCreatedStageAreExtensionsEnabled[] =
    "Extensions."
    "ForceInstalledFailureStuckInInitialCreationStageAreExtensionsEnabled";
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)
}  // namespace

namespace extensions {

using ExtensionStatus = ForceInstalledTracker::ExtensionStatus;
using ExtensionOrigin = ForceInstalledTestBase::ExtensionOrigin;
using testing::_;
using testing::Return;

class ForceInstalledMetricsTest : public ForceInstalledTestBase {
 public:
  ForceInstalledMetricsTest() = default;

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

  void SetUp() override {
    ForceInstalledTestBase::SetUp();
    auto fake_timer = std::make_unique<base::MockOneShotTimer>();
    fake_timer_ = fake_timer.get();
    metrics_ = std::make_unique<ForceInstalledMetrics>(
        registry(), profile(), force_installed_tracker(),
        std::move(fake_timer));
  }

  void SetupExtensionManagementPref() {
    base::Value::Dict extension_entry =
        base::Value::Dict()
            .Set("installation_mode", "allowed")
            .Set(ExternalProviderImpl::kExternalUpdateUrl, kExtensionUpdateUrl);
    prefs()->SetManagedPref(
        pref_names::kExtensionManagement,
        base::Value::Dict().Set(kExtensionId1, std::move(extension_entry)));
  }

  void CreateExtensionService(bool extensions_enabled) {
    base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
    if (!extensions_enabled) {
      command_line.AppendSwitch(switches::kDisableExtensions);
    }
    extensions::TestExtensionSystem* test_ext_system =
        static_cast<extensions::TestExtensionSystem*>(
            extensions::ExtensionSystem::Get(profile()));
    test_ext_system->CreateExtensionService(&command_line, base::FilePath(),
                                            false);
  }

  // Report downloading manifest stage for both the extensions.
  void ReportDownloadingManifestStage() {
    install_stage_tracker()->ReportDownloadingStage(
        kExtensionId1,
        ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST);
    install_stage_tracker()->ReportDownloadingStage(
        kExtensionId2,
        ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST);
  }

  void ReportInstallationStarted(std::optional<base::TimeDelta> install_time) {
    install_stage_tracker()->ReportDownloadingStage(
        kExtensionId1, ExtensionDownloaderDelegate::Stage::MANIFEST_LOADED);
    install_stage_tracker()->ReportDownloadingStage(
        kExtensionId1, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX);
    if (install_time) {
      task_environment_.FastForwardBy(install_time.value());
    }
    install_stage_tracker()->ReportDownloadingStage(
        kExtensionId1, ExtensionDownloaderDelegate::Stage::FINISHED);
    install_stage_tracker()->ReportInstallationStage(
        kExtensionId1, InstallStageTracker::Stage::INSTALLING);
  }

 protected:
  base::HistogramTester histogram_tester_;
  raw_ptr<base::MockOneShotTimer, DanglingUntriaged> fake_timer_;
  std::unique_ptr<ForceInstalledMetrics> metrics_;
};

TEST_F(ForceInstalledMetricsTest, EmptyForcelist) {
  SetupEmptyForceList();
  // ForceInstalledMetrics is notified only when Forcelist is not empty.
  EXPECT_TRUE(fake_timer_->IsRunning());
  // Don't report metrics when the Forcelist is empty.
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kReadyTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutNotInstalledStats, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsSH, 0);
  histogram_tester_.ExpectTotalCount(kInstallationStages, 0);
  histogram_tester_.ExpectTotalCount(kFailureCrxInstallErrorStats, 0);
  histogram_tester_.ExpectTotalCount(kTotalCountStats, 0);
}

TEST_F(ForceInstalledMetricsTest, ExtensionsInstalled) {
  SetupForceList(ExtensionOrigin::kWebStore);

  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);

  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 1);
  histogram_tester_.ExpectTotalCount(kReadyTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutNotInstalledStats, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsSH, 0);
  histogram_tester_.ExpectTotalCount(kInstallationStages, 0);
  histogram_tester_.ExpectTotalCount(kFailureCrxInstallErrorStats, 0);
  histogram_tester_.ExpectUniqueSample(
      kTotalCountStats,
      prefs()->GetManagedPref(pref_names::kInstallForceList)->GetDict().size(),
      1);
}

// Verifies that failure is reported for the extensions which are listed in
// forced list, and their installation mode are overridden by ExtensionSettings
// policy to something else.
TEST_F(ForceInstalledMetricsTest, ExtensionSettingsOverrideForcedList) {
  SetupForceList(ExtensionOrigin::kWebStore);
  SetupExtensionManagementPref();
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(
      kFailureReasonsCWS,
      InstallStageTracker::FailureReason::OVERRIDDEN_BY_SETTINGS, 1);
}

TEST_F(ForceInstalledMetricsTest, ExtensionsInstallationTimedOut) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kPending);
  registry()->AddEnabled(ext.get());
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  // Metrics are reported due to timeout.
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectUniqueSample(kTimedOutStats, 2, 1);
  histogram_tester_.ExpectUniqueSample(kTimedOutNotInstalledStats, 1, 1);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 1);
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 1);
  histogram_tester_.ExpectTotalCount(kInstallationStages, 1);
  histogram_tester_.ExpectTotalCount(kFailureCrxInstallErrorStats, 0);
  histogram_tester_.ExpectUniqueSample(
      kTotalCountStats,
      prefs()->GetManagedPref(pref_names::kInstallForceList)->GetDict().size(),
      1);
}

// Reporting the time for downloading the manifest of an extension and verifying
// that it is correctly recorded in the histogram.
TEST_F(ForceInstalledMetricsTest, ExtensionsManifestDownloadTime) {
  SetupForceList(ExtensionOrigin::kWebStore);
  ReportDownloadingManifestStage();
  const base::TimeDelta manifest_download_time = base::Milliseconds(200);
  task_environment_.FastForwardBy(manifest_download_time);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId1, ExtensionDownloaderDelegate::Stage::MANIFEST_LOADED);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_INVALID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kManifestDownloadTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kManifestDownloadTimeStats,
                                          manifest_download_time, 1);
}

// Reporting the time for downloading the CRX file of an extension and verifying
// that it is correctly recorded in the histogram.
TEST_F(ForceInstalledMetricsTest, ExtensionsCrxDownloadTime) {
  SetupForceList(ExtensionOrigin::kWebStore);
  ReportDownloadingManifestStage();
  const base::TimeDelta install_time = base::Milliseconds(200);
  ReportInstallationStarted(install_time);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_INVALID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kCRXDownloadTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kCRXDownloadTimeStats, install_time,
                                          1);
}

TEST_F(ForceInstalledMetricsTest,
       ExtensionsCrxDownloadTimeWhenFetchedFromCache) {
  SetupForceList(ExtensionOrigin::kWebStore);
  ReportDownloadingManifestStage();
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId1, ExtensionDownloaderDelegate::Stage::MANIFEST_LOADED);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId1, ExtensionDownloaderDelegate::Stage::FINISHED);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId1, InstallStageTracker::Stage::INSTALLING);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_INVALID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  // Time should not be recorded when CRX is fetched from cache.
  histogram_tester_.ExpectTotalCount(kCRXDownloadTimeStats, 0);
}

// Reporting the times for various stages in the extension installation process
// and verifying that the time consumed at each stage is correctly recorded in
// the histogram.
TEST_F(ForceInstalledMetricsTest, ExtensionsReportInstallationStageTimes) {
  SetupForceList(ExtensionOrigin::kWebStore);
  ReportDownloadingManifestStage();
  ReportInstallationStarted(std::nullopt);
  install_stage_tracker()->ReportCRXInstallationStage(
      kExtensionId1, InstallationStage::kVerification);

  const base::TimeDelta installation_stage_time = base::Milliseconds(200);
  task_environment_.FastForwardBy(installation_stage_time);
  install_stage_tracker()->ReportCRXInstallationStage(
      kExtensionId1, InstallationStage::kCopying);

  task_environment_.FastForwardBy(installation_stage_time);
  install_stage_tracker()->ReportCRXInstallationStage(
      kExtensionId1, InstallationStage::kUnpacking);

  task_environment_.FastForwardBy(installation_stage_time);
  install_stage_tracker()->ReportCRXInstallationStage(
      kExtensionId1, InstallationStage::kCheckingExpectations);

  task_environment_.FastForwardBy(installation_stage_time);
  install_stage_tracker()->ReportCRXInstallationStage(
      kExtensionId1, InstallationStage::kFinalizing);

  task_environment_.FastForwardBy(installation_stage_time);
  install_stage_tracker()->ReportCRXInstallationStage(
      kExtensionId1, InstallationStage::kComplete);

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_INVALID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kVerificationTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kVerificationTimeStats,
                                          installation_stage_time, 1);
  histogram_tester_.ExpectTotalCount(kCopyingTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kCopyingTimeStats,
                                          installation_stage_time, 1);
  histogram_tester_.ExpectTotalCount(kUnpackingTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kUnpackingTimeStats,
                                          installation_stage_time, 1);
  histogram_tester_.ExpectTotalCount(kCheckingExpectationsTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kCheckingExpectationsTimeStats,
                                          installation_stage_time, 1);
  histogram_tester_.ExpectTotalCount(kFinalizingTimeStats, 1);
  histogram_tester_.ExpectTimeBucketCount(kFinalizingTimeStats,
                                          installation_stage_time, 1);
}

// Reporting disable reason for the force installed extensions which are
// installed but not loaded when extension is disable due to single reason.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsInstalledButNotLoadedUniqueDisableReason) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kPending);
  registry()->AddDisabled(ext1.get());
  ExtensionPrefs::Get(profile())->AddDisableReason(
      kExtensionId1, disable_reason::DisableReason::DISABLE_NOT_VERIFIED);
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics should still keep running as kExtensionId1 is
  // installed but not loaded.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kDisableReason, disable_reason::DisableReason::DISABLE_NOT_VERIFIED, 1);
}

// Reporting disable reasons for the force installed extensions which are
// installed but not loaded when extension is disable due to multiple reasons.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsInstalledButNotLoadedMultipleDisableReason) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kPending);
  registry()->AddDisabled(ext1.get());
  ExtensionPrefs::Get(profile())->AddDisableReasons(
      kExtensionId1,
      {disable_reason::DisableReason::DISABLE_NOT_VERIFIED,
       disable_reason::DisableReason::DISABLE_UNSUPPORTED_REQUIREMENT});
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics should still keep running as kExtensionId1 is
  // installed but not loaded.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  // Verifies that only one disable reason is reported;
  histogram_tester_.ExpectUniqueSample(
      kDisableReason,
      disable_reason::DisableReason::DISABLE_UNSUPPORTED_REQUIREMENT, 1);
}

// Reporting DisableReason::DISABLE_NONE for the force installed extensions
// which are installed but not loaded when extension is enabled.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsInstalledButNotLoadedNoDisableReason) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kPending);
  registry()->AddEnabled(ext1.get());
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics should still keep running as kExtensionId1 is
  // installed but not loaded.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kDisableReason, disable_reason::DisableReason::DISABLE_NONE, 1);
}

// TODO(crbug.com/394876083): Need investigation once ExtensionService is fully
// implemented for Android for Desktop.
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Verifies if the metrics related to whether the extensions are enabled or not
// are recorded correctly for extensions stuck in
// NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_FORCED stage.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsStuckInCreatedStageAreExtensionsEnabled) {
  SetupForceList(ExtensionOrigin::kWebStore);
  CreateExtensionService(/*extensions_enabled=*/false);

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::CREATED);
  install_stage_tracker()->ReportInstallCreationStage(
      kExtensionId2, InstallStageTracker::InstallCreationStage::
                         NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_FORCED);

  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 1);
  histogram_tester_.ExpectBucketCount(kInstallationStages,
                                      InstallStageTracker::Stage::CREATED, 1);
  histogram_tester_.ExpectBucketCount(
      kInstallCreationStages,
      InstallStageTracker::InstallCreationStage::
          NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_FORCED,
      1);
  histogram_tester_.ExpectUniqueSample(kStuckInCreatedStageAreExtensionsEnabled,
                                       false, 1);
}
#endif  // BUILDFLAG(ENABLE_EXTENSIONS)

TEST_F(ForceInstalledMetricsTest, ExtensionForceInstalledAndBlocklisted) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kPending);
  registry()->AddBlocklisted(ext1.get());
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics should still keep running as kExtensionId1 is
  // installed but not loaded.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(kBlocklisted, 1, 1);
}

TEST_F(ForceInstalledMetricsTest, ExtensionsInstallationCancelled) {
  SetupForceList(ExtensionOrigin::kWebStore);
  SetupEmptyForceList();
  // ForceInstalledMetrics does not shut down the timer, because it's still
  // waiting for the initial extensions to install.
  EXPECT_TRUE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutNotInstalledStats, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 0);
  histogram_tester_.ExpectTotalCount(kInstallationStages, 0);
  histogram_tester_.ExpectTotalCount(kFailureCrxInstallErrorStats, 0);
  histogram_tester_.ExpectTotalCount(kTotalCountStats, 0);
}

TEST_F(ForceInstalledMetricsTest, ForcedExtensionsAddedAfterManualExtensions) {
  // Report failure for an extension which is not in forced list.
  install_stage_tracker()->ReportFailure(
      kExtensionId3, InstallStageTracker::FailureReason::INVALID_ID);
  // ForceInstalledMetrics should keep running as the forced extensions are
  // still not loaded.
  EXPECT_TRUE(fake_timer_->IsRunning());
  SetupForceList(ExtensionOrigin::kWebStore);

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kReady);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::INVALID_ID);
  // ForceInstalledMetrics shuts down timer because kExtensionId1 was loaded and
  // kExtensionId2 was failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::INVALID_ID, 1);
}

TEST_F(ForceInstalledMetricsTest,
       ExtensionsInstallationTimedOutDifferentReasons) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::INVALID_ID);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_OTHER,
      CrxInstallErrorDetail::UNEXPECTED_ID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectUniqueSample(kTimedOutStats, 2, 1);
  histogram_tester_.ExpectUniqueSample(kTimedOutNotInstalledStats, 2, 1);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 2);
  histogram_tester_.ExpectBucketCount(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::INVALID_ID, 1);
  histogram_tester_.ExpectBucketCount(
      kFailureReasonsCWS,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_OTHER, 1);
  histogram_tester_.ExpectTotalCount(kInstallationStages, 0);
  histogram_tester_.ExpectUniqueSample(kFailureCrxInstallErrorStats,
                                       CrxInstallErrorDetail::UNEXPECTED_ID, 1);
  histogram_tester_.ExpectUniqueSample(
      kTotalCountStats,
      prefs()->GetManagedPref(pref_names::kInstallForceList)->GetDict().size(),
      1);
}

// Reporting SandboxedUnpackerFailureReason when the force installed extension
// fails to install with error CRX_INSTALL_ERROR_SANDBOXED_UNPACKER_FAILURE.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsCrxInstallErrorSandboxUnpackFailure) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportSandboxedUnpackerFailureReason(
      kExtensionId1,
      CrxInstallError(SandboxedUnpackerFailureReason::CRX_FILE_NOT_READABLE,
                      std::u16string()));
  install_stage_tracker()->ReportSandboxedUnpackerFailureReason(
      kExtensionId2,
      CrxInstallError(SandboxedUnpackerFailureReason::UNZIP_FAILED,
                      std::u16string()));
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kSandboxUnpackFailureReason, 2);
  histogram_tester_.ExpectBucketCount(
      kSandboxUnpackFailureReason,
      SandboxedUnpackerFailureReason::CRX_FILE_NOT_READABLE, 1);
  histogram_tester_.ExpectBucketCount(
      kSandboxUnpackFailureReason, SandboxedUnpackerFailureReason::UNZIP_FAILED,
      1);
}

// Reporting when the extension is downloaded from cache and it fails to install
// with error CRX_HEADER_INVALID.
TEST_F(ForceInstalledMetricsTest, ExtensionsCrxHeaderInvalidFromCache) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportDownloadingCacheStatus(
      kExtensionId1, ExtensionDownloaderDelegate::CacheStatus::CACHE_HIT);
  install_stage_tracker()->ReportSandboxedUnpackerFailureReason(
      kExtensionId1,
      CrxInstallError(SandboxedUnpackerFailureReason::CRX_HEADER_INVALID,
                      std::u16string()));
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kSandboxUnpackFailureReason, 1);
  histogram_tester_.ExpectBucketCount(
      kSandboxUnpackFailureReason,
      SandboxedUnpackerFailureReason::CRX_HEADER_INVALID, 1);
  histogram_tester_.ExpectBucketCount(kCrxHeaderInvalidFailureIsCWS, true, 1);
  histogram_tester_.ExpectBucketCount(kCrxHeaderInvalidFailureFromCache, true,
                                      1);
}

// Reporting when the extension is not downloaded from cache and it fails to
// install with error CRX_HEADER_INVALID.
TEST_F(ForceInstalledMetricsTest, ExtensionsCrxHeaderInvalidNotFromCache) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportDownloadingCacheStatus(
      kExtensionId1, ExtensionDownloaderDelegate::CacheStatus::CACHE_MISS);
  install_stage_tracker()->ReportSandboxedUnpackerFailureReason(
      kExtensionId1,
      CrxInstallError(SandboxedUnpackerFailureReason::CRX_HEADER_INVALID,
                      std::u16string()));
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kSandboxUnpackFailureReason, 1);
  histogram_tester_.ExpectBucketCount(
      kSandboxUnpackFailureReason,
      SandboxedUnpackerFailureReason::CRX_HEADER_INVALID, 1);
  histogram_tester_.ExpectBucketCount(kCrxHeaderInvalidFailureIsCWS, true, 1);
  histogram_tester_.ExpectBucketCount(kCrxHeaderInvalidFailureFromCache, false,
                                      1);
}

// Verifies that offstore extension that is downloaded from the update server
// and fails with CRX_HEADER_INVALID error is considered as a misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsCrxHeaderInvalidIsMisconfiguration) {
  SetupForceList(ExtensionOrigin::kOffStore);
  install_stage_tracker()->ReportDownloadingCacheStatus(
      kExtensionId1, ExtensionDownloaderDelegate::CacheStatus::CACHE_MISS);
  install_stage_tracker()->ReportSandboxedUnpackerFailureReason(
      kExtensionId1,
      CrxInstallError(SandboxedUnpackerFailureReason::CRX_HEADER_INVALID,
                      std::u16string()));
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kSandboxUnpackFailureReason, 1);
  histogram_tester_.ExpectBucketCount(
      kSandboxUnpackFailureReason,
      SandboxedUnpackerFailureReason::CRX_HEADER_INVALID, 1);
  histogram_tester_.ExpectBucketCount(kCrxHeaderInvalidFailureIsCWS, false, 1);
  histogram_tester_.ExpectBucketCount(kCrxHeaderInvalidFailureFromCache, false,
                                      1);
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// Verifies that extension failing with REPLACED_BY_SYSTEM_APP error is
// considered as a misconfiguration in ChromeOS.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsFailureReplacedBySystemAppIsMisconfiguration) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportFailure(
      kExtensionId1,
      InstallStageTracker::FailureReason::REPLACED_BY_SYSTEM_APP);
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(
      kFailureReasonsCWS,
      InstallStageTracker::FailureReason::REPLACED_BY_SYSTEM_APP, 1);
  bool expected_non_misconfiguration_failure = true;
#if BUILDFLAG(IS_CHROMEOS)
  expected_non_misconfiguration_failure = false;
#endif
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures,
                                      expected_non_misconfiguration_failure, 1);
}

// Reporting info when the force installed extension fails to install with error
// CRX_FETCH_URL_EMPTY due to no updates from the server.
TEST_F(ForceInstalledMetricsTest, ExtensionsNoUpdatesInfoReporting) {
  SetupForceList(ExtensionOrigin::kWebStore);

  install_stage_tracker()->ReportInfoOnNoUpdatesFailure(kExtensionId1,
                                                        "disabled by client");
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::CRX_FETCH_URL_EMPTY);
  install_stage_tracker()->ReportInfoOnNoUpdatesFailure(kExtensionId2, "");
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::CRX_FETCH_URL_EMPTY);

  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kManifestNoUpdatesInfo, 2);
  histogram_tester_.ExpectBucketCount(
      kManifestNoUpdatesInfo, InstallStageTracker::NoUpdatesInfo::kEmpty, 1);
  histogram_tester_.ExpectBucketCount(
      kManifestNoUpdatesInfo,
      InstallStageTracker::NoUpdatesInfo::kDisabledByClient, 1);
}

// Regression test to check if the metrics are collected properly for the
// extensions which are already installed and loaded and then fail with error
// ALREADY_INSTALLED.
TEST_F(ForceInstalledMetricsTest,
       ExtensionLoadedThenFailedWithAlreadyInstalledError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::ALREADY_INSTALLED);
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kLoaded);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 1);
  histogram_tester_.ExpectTotalCount(kTimedOutStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutNotInstalledStats, 0);
}

// Regression test to check if the metrics are collected properly for the
// extensions which are in state |kReady|. Also verifies that the failure
// reported after |kReady| state is not reflected in the statistics.
TEST_F(ForceInstalledMetricsTest, ExtensionsReady) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kReady);
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::ALREADY_INSTALLED);
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kReady);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 1);
  histogram_tester_.ExpectTotalCount(kReadyTimeStats, 1);
  histogram_tester_.ExpectTotalCount(kTimedOutStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutNotInstalledStats, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 0);
}

// Regression test to check if no metrics are reported for |kReady| state when
// some extensions are failed.
TEST_F(ForceInstalledMetricsTest, AllExtensionsNotReady) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kReady);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::INVALID_ID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kReadyTimeStats, 0);
  histogram_tester_.ExpectBucketCount(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::INVALID_ID, 1);
}

// Verifies that the installation stage is not overwritten by a previous stage.
TEST_F(ForceInstalledMetricsTest,
       ExtensionsPreviousInstallationStageReportedAgain) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::CREATED);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::PENDING);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::CREATED);
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 1);
  histogram_tester_.ExpectBucketCount(kInstallationStages,
                                      InstallStageTracker::Stage::PENDING, 1);
}

// Verifies that the installation stage is overwritten if DOWNLOADING stage is
// reported again after INSTALLING stage.
TEST_F(ForceInstalledMetricsTest, ExtensionsDownloadingStageReportedAgain) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::DOWNLOADING);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::INSTALLING);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::DOWNLOADING);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2, ExtensionDownloaderDelegate::Stage::PENDING);
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 1);
  histogram_tester_.ExpectBucketCount(
      kInstallationStages, InstallStageTracker::Stage::DOWNLOADING, 1);
}

TEST_F(ForceInstalledMetricsTest, ExtensionsStuck) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId1, InstallStageTracker::Stage::PENDING);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::DOWNLOADING);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2, ExtensionDownloaderDelegate::Stage::PENDING);
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectUniqueSample(kTimedOutStats, 2, 1);
  histogram_tester_.ExpectUniqueSample(kTimedOutNotInstalledStats, 2, 1);
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 2);
  histogram_tester_.ExpectBucketCount(kInstallationStages,
                                      InstallStageTracker::Stage::PENDING, 1);
  histogram_tester_.ExpectBucketCount(
      kInstallationStages, InstallStageTracker::Stage::DOWNLOADING, 1);
  histogram_tester_.ExpectTotalCount(kFailureCrxInstallErrorStats, 0);
  histogram_tester_.ExpectUniqueSample(
      kTotalCountStats,
      prefs()->GetManagedPref(pref_names::kInstallForceList)->GetDict().size(),
      1);
}

TEST_F(ForceInstalledMetricsTest, ExtensionStuckInCreatedStage) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::CREATED);
  install_stage_tracker()->ReportInstallCreationStage(
      kExtensionId2, InstallStageTracker::InstallCreationStage::
                         NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_NOT_FORCED);
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 1);
  histogram_tester_.ExpectUniqueSample(kInstallationStages,
                                       InstallStageTracker::Stage::CREATED, 1);
  histogram_tester_.ExpectUniqueSample(
      kInstallCreationStages,
      InstallStageTracker::InstallCreationStage::
          NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_NOT_FORCED,
      1);
}

#if BUILDFLAG(IS_CHROMEOS)
TEST_F(ForceInstalledMetricsTest, ReportManagedGuestSessionOnExtensionFailure) {
  auto* fake_user_manager = new ash::FakeChromeUserManager();
  user_manager::ScopedUserManager scoped_user_manager(
      base::WrapUnique(fake_user_manager));
  const AccountId account_id =
      AccountId::FromUserEmail(profile()->GetProfileUserName());
  fake_user_manager->AddPublicAccountUser(account_id);
  fake_user_manager->UserLoggedIn(
      account_id, user_manager::TestHelper::GetFakeUsernameHash(account_id));
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::INVALID_ID);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_OTHER,
      CrxInstallErrorDetail::UNEXPECTED_ID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(
      kFailureSessionStats,
      ForceInstalledMetrics::UserType::USER_TYPE_PUBLIC_ACCOUNT, 2);
}

TEST_F(ForceInstalledMetricsTest, ReportGuestSessionOnExtensionFailure) {
  auto* fake_user_manager = new ash::FakeChromeUserManager();
  user_manager::ScopedUserManager scoped_user_manager(
      base::WrapUnique(fake_user_manager));
  user_manager::User* user = fake_user_manager->AddGuestUser();
  fake_user_manager->UserLoggedIn(
      user->GetAccountId(),
      user_manager::TestHelper::GetFakeUsernameHash(user->GetAccountId()));
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::INVALID_ID);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_OTHER,
      CrxInstallErrorDetail::UNEXPECTED_ID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(
      kFailureSessionStats, ForceInstalledMetrics::UserType::USER_TYPE_GUEST,
      2);
}

// Verified that the metrics related to user type are reported correctly for
// extension stuck in NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_FORCED stage.
TEST_F(ForceInstalledMetricsTest,
       ReportGuestSessionForExtensionsStuckInCreatedStage) {
  auto* fake_user_manager = new ash::FakeChromeUserManager();
  user_manager::ScopedUserManager scoped_user_manager(
      base::WrapUnique(fake_user_manager));
  user_manager::User* user = fake_user_manager->AddGuestUser();
  fake_user_manager->UserLoggedIn(
      user->GetAccountId(),
      user_manager::TestHelper::GetFakeUsernameHash(user->GetAccountId()));

  SetupForceList(ExtensionOrigin::kWebStore);
  CreateExtensionService(/*extensions_enabled=*/true);

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::CREATED);
  install_stage_tracker()->ReportInstallCreationStage(
      kExtensionId2, InstallStageTracker::InstallCreationStage::
                         NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_FORCED);

  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 1);
  histogram_tester_.ExpectBucketCount(kInstallationStages,
                                      InstallStageTracker::Stage::CREATED, 1);
  histogram_tester_.ExpectBucketCount(
      kInstallCreationStages,
      InstallStageTracker::InstallCreationStage::
          NOTIFIED_FROM_MANAGEMENT_INITIAL_CREATION_FORCED,
      1);
  histogram_tester_.ExpectUniqueSample(kStuckInCreatedStageAreExtensionsEnabled,
                                       true, 1);
  histogram_tester_.ExpectBucketCount(
      kFailureSessionStats, ForceInstalledMetrics::UserType::USER_TYPE_GUEST,
      1);
  histogram_tester_.ExpectBucketCount(
      kStuckInCreateStageSessionType,
      ForceInstalledMetrics::UserType::USER_TYPE_GUEST, 1);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

TEST_F(ForceInstalledMetricsTest, ExtensionsAreDownloading) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId1, InstallStageTracker::Stage::DOWNLOADING);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId1, ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST);
  install_stage_tracker()->ReportInstallationStage(
      kExtensionId2, InstallStageTracker::Stage::DOWNLOADING);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX);
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectUniqueSample(kTimedOutStats, 2, 1);
  histogram_tester_.ExpectUniqueSample(kTimedOutNotInstalledStats, 2, 1);
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS, InstallStageTracker::FailureReason::IN_PROGRESS, 2);
  histogram_tester_.ExpectUniqueSample(
      kInstallationStages, InstallStageTracker::Stage::DOWNLOADING, 2);
  histogram_tester_.ExpectTotalCount(kInstallationDownloadingStages, 2);
  histogram_tester_.ExpectBucketCount(
      kInstallationDownloadingStages,
      ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST, 1);
  histogram_tester_.ExpectBucketCount(
      kInstallationDownloadingStages,
      ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX, 1);
  histogram_tester_.ExpectUniqueSample(
      kTotalCountStats,
      prefs()->GetManagedPref(pref_names::kInstallForceList)->GetDict().size(),
      1);
}

// Error Codes in case of CRX_FETCH_FAILED for CWS extensions.
TEST_F(ForceInstalledMetricsTest, ExtensionCrxFetchFailedCWS) {
  SetupForceList(ExtensionOrigin::kWebStore);
  ExtensionDownloaderDelegate::FailureData data1(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId1, InstallStageTracker::FailureReason::CRX_FETCH_FAILED,
      data1);
  ExtensionDownloaderDelegate::FailureData data2(
      -net::Error::ERR_INVALID_ARGUMENT, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId2, InstallStageTracker::FailureReason::CRX_FETCH_FAILED,
      data2);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeCrxFetchFailedStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeCrxFetchFailedStats,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeCrxFetchFailedStatsCWS,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeCrxFetchFailedStats,
                                      -net::Error::ERR_INVALID_ARGUMENT, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesCrxFetchFailedStats,
                                      kFetchTries, 2);
}

// Error Codes in case of CRX_FETCH_FAILED for self hosted extension.
TEST_F(ForceInstalledMetricsTest, ExtensionCrxFetchFailedSelfHosted) {
  SetupForceList(ExtensionOrigin::kOffStore);
  ExtensionDownloaderDelegate::FailureData data1(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId1, InstallStageTracker::FailureReason::CRX_FETCH_FAILED,
      data1);
  ExtensionDownloaderDelegate::FailureData data2(
      -net::Error::ERR_INVALID_ARGUMENT, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId2, InstallStageTracker::FailureReason::CRX_FETCH_FAILED,
      data2);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeCrxFetchFailedStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeCrxFetchFailedStats,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeCrxFetchFailedStatsSH,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeCrxFetchFailedStats,
                                      -net::Error::ERR_INVALID_ARGUMENT, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesCrxFetchFailedStats,
                                      kFetchTries, 2);
}

// Error Codes in case of MANIFEST_FETCH_FAILED for CWS extensions.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestFetchFailedCWS) {
  SetupForceList(ExtensionOrigin::kWebStore);
  ExtensionDownloaderDelegate::FailureData data1(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId1, InstallStageTracker::FailureReason::MANIFEST_FETCH_FAILED,
      data1);
  ExtensionDownloaderDelegate::FailureData data2(
      -net::Error::ERR_INVALID_ARGUMENT, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_FETCH_FAILED,
      data2);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeManifestFetchFailedStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeManifestFetchFailedStats,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeManifestFetchFailedStatsCWS,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeManifestFetchFailedStats,
                                      -net::Error::ERR_INVALID_ARGUMENT, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesManifestFetchFailedStats,
                                      kFetchTries, 2);
}

// Error Codes in case of MANIFEST_FETCH_FAILED for self hosted extensions. This
// test verifies that failure MANIFEST_FETCH_FAILED with 403 http error code
// (Forbidden) is considered as misconfiguration.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestFetchFailedSelfHosted) {
  SetupForceList(ExtensionOrigin::kOffStore);
  ExtensionDownloaderDelegate::FailureData data1(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId1, InstallStageTracker::FailureReason::MANIFEST_FETCH_FAILED,
      data1);
  ExtensionDownloaderDelegate::FailureData data2(
      -net::Error::ERR_INVALID_ARGUMENT, kFetchTries);
  install_stage_tracker()->ReportFetchError(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_FETCH_FAILED,
      data2);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeManifestFetchFailedStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeManifestFetchFailedStats,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeManifestFetchFailedStatsSH,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeManifestFetchFailedStats,
                                      -net::Error::ERR_INVALID_ARGUMENT, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesManifestFetchFailedStats,
                                      kFetchTries, 2);
}

// Error Codes in case of CWS extensions stuck in DOWNLOADING_MANIFEST_RETRY
// stage.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestFetchRetryCWS) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  ExtensionDownloaderDelegate::FailureData data(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2,
      ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST_RETRY);
  install_stage_tracker()->ReportFetchErrorCodes(kExtensionId2, data);
  // ForceInstalledMetrics timer is still running as |kExtensionId2| is still in
  // progress.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeManifestFetchRetryStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeManifestFetchRetryStatsCWS,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesManifestFetchRetryStats,
                                      kFetchTries, 1);
}

// This test verifies that failure MANIFEST_INVALID in case of offstore
// extensions is considered as misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       OffStoreExtensionManifestInvalidIsMisconfiguration) {
  SetupForceList(ExtensionOrigin::kOffStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::MANIFEST_INVALID);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsSH, InstallStageTracker::FailureReason::MANIFEST_INVALID,
      1);
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// This test verifies that failure OVERRIDDEN_BY_SETTINGS in case of offstore
// extensions is considered as misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       ExtensionOverridenBySettingsFailureIsMisconfiguration) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2,
      InstallStageTracker::FailureReason::OVERRIDDEN_BY_SETTINGS);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectUniqueSample(
      kFailureReasonsCWS,
      InstallStageTracker::FailureReason::OVERRIDDEN_BY_SETTINGS, 1);
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// Error Codes in case of self hosted extensions stuck in
// DOWNLOADING_MANIFEST_RETRY stage.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestFetchRetrySelfHosted) {
  SetupForceList(ExtensionOrigin::kOffStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  ExtensionDownloaderDelegate::FailureData data(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2,
      ExtensionDownloaderDelegate::Stage::DOWNLOADING_MANIFEST_RETRY);
  install_stage_tracker()->ReportFetchErrorCodes(kExtensionId2, data);
  // ForceInstalledMetrics timer is still running as |kExtensionId2| is still in
  // progress.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeManifestFetchRetryStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeManifestFetchRetryStatsSH,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesManifestFetchRetryStats,
                                      kFetchTries, 1);
}

// Error Codes in case of CWS extensions stuck in DOWNLOADING_CRX_RETRY stage.
TEST_F(ForceInstalledMetricsTest, ExtensionCrxFetchRetryCWS) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  ExtensionDownloaderDelegate::FailureData data(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX_RETRY);
  install_stage_tracker()->ReportFetchErrorCodes(kExtensionId2, data);
  // ForceInstalledMetrics timer is still running as |kExtensionId2| is still in
  // progress.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeCrxFetchRetryStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeCrxFetchRetryStatsCWS,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesCrxFetchRetryStats,
                                      kFetchTries, 1);
}

// Error Codes in case of self hosted extensions stuck in DOWNLOADING_CRX_RETRY
// stage.
TEST_F(ForceInstalledMetricsTest, ExtensionCrxFetchRetrySelfHosted) {
  SetupForceList(ExtensionOrigin::kOffStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  ExtensionDownloaderDelegate::FailureData data(
      net::Error::OK, kHttpCodeForbidden, kFetchTries);
  install_stage_tracker()->ReportDownloadingStage(
      kExtensionId2, ExtensionDownloaderDelegate::Stage::DOWNLOADING_CRX_RETRY);
  install_stage_tracker()->ReportFetchErrorCodes(kExtensionId2, data);
  // ForceInstalledMetrics timer is still running as |kExtensionId2| is still in
  // progress.
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectBucketCount(kNetworkErrorCodeCrxFetchRetryStats,
                                      net::Error::OK, 1);
  histogram_tester_.ExpectBucketCount(kHttpErrorCodeCrxFetchRetryStatsSH,
                                      kHttpCodeForbidden, 1);
  histogram_tester_.ExpectBucketCount(kFetchRetriesCrxFetchRetryStats,
                                      kFetchTries, 1);
}

// Errors occurred because the fetched update manifest for webstore extension
// was invalid.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestInvalidWebStore) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportManifestInvalidFailure(
      kExtensionId2,
      ExtensionDownloaderDelegate::FailureData(
          ManifestInvalidError::INVALID_PROTOCOL_ON_GUPDATE_TAG));
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectUniqueSample(
      kWebStoreExtensionManifestInvalid,
      ManifestInvalidError::INVALID_PROTOCOL_ON_GUPDATE_TAG, 1);
}

// Errors occurred because the fetched update manifest for offstore extension
// was invalid.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestInvalidOffStore) {
  SetupForceList(ExtensionOrigin::kOffStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportManifestInvalidFailure(
      kExtensionId2,
      ExtensionDownloaderDelegate::FailureData(
          ManifestInvalidError::INVALID_PROTOCOL_ON_GUPDATE_TAG));
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectUniqueSample(
      kOffStoreExtensionManifestInvalid,
      ManifestInvalidError::INVALID_PROTOCOL_ON_GUPDATE_TAG, 1);
}

// Errors occurred because the fetched update manifest was invalid because app
// status was not OK. Verifies that this error with app status error as
// "error-unknownApplication" is considered as a misconfiguration.
TEST_F(ForceInstalledMetricsTest, ExtensionManifestInvalidAppStatusError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportManifestInvalidFailure(
      kExtensionId2,
      ExtensionDownloaderDelegate::FailureData(
          ManifestInvalidError::BAD_APP_STATUS, "error-unknownApplication"));
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectUniqueSample(kWebStoreExtensionManifestInvalid,
                                       ManifestInvalidError::BAD_APP_STATUS, 1);
  histogram_tester_.ExpectUniqueSample(
      kExtensionManifestInvalidAppStatusError,
      InstallStageTracker::AppStatusError::kErrorUnknownApplication, 1);
  // Verify that the session with either all the extensions installed
  // successfully, or all failures as admin-side misconfigurations is recorded
  // here and BAD_APP_STATUS error is considered as a misconfiguration.
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// Session in which either all the extensions installed successfully, or all
// failures are admin-side misconfigurations. This test verifies that failure
// CRX_INSTALL_ERROR with detailed error KIOSK_MODE_ONLY is considered as
// misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailureNotPresentKioskModeOnlyError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_DECLINED,
      CrxInstallErrorDetail::KIOSK_MODE_ONLY);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// Session in which either all the extensions installed successfully, or all
// failures are admin-side misconfigurations. This test verifies that failure
// CRX_INSTALL_ERROR with detailed error DISALLOWED_BY_POLICY and when extension
// type which is not allowed to install according to policy
// kExtensionAllowedTypes is considered as misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailureNotPresentDisallowedByPolicyTypeError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  // Set TYPE_EXTENSION and TYPE_THEME as the allowed extension types.
  base::Value::List list =
      base::Value::List().Append("extension").Append("theme");
  prefs()->SetManagedPref(pref_names::kAllowedTypes, std::move(list));

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  // Hosted app is not a valid extension type, so this should report an error.
  install_stage_tracker()->ReportExtensionType(kExtensionId2,
                                               Manifest::Type::TYPE_HOSTED_APP);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_DECLINED,
      CrxInstallErrorDetail::DISALLOWED_BY_POLICY);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(
      kPossibleNonMisconfigurationFailures,
      0 /*Misconfiguration failure not present*/, 1 /*Count of the sample*/);
}

// Session in which at least one non misconfiguration failure occurred. One of
// the extension fails to install with DISALLOWED_BY_POLICY error but has
// extension type which is allowed by policy ExtensionAllowedTypes. This is not
// a misconfiguration failure.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailurePresentDisallowedByPolicyError) {
  SetupForceList(ExtensionOrigin::kWebStore);

  // Set TYPE_EXTENSION and TYPE_THEME as the allowed extension types.
  base::Value::List list =
      base::Value::List().Append("extension").Append("theme");
  prefs()->SetManagedPref(pref_names::kAllowedTypes, std::move(list));

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportExtensionType(kExtensionId2,
                                               Manifest::Type::TYPE_EXTENSION);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_DECLINED,
      CrxInstallErrorDetail::DISALLOWED_BY_POLICY);

  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures,
                                      1 /*Misconfiguration failure present*/,
                                      1 /*Count of the sample*/);
}

// Session in which at least one non misconfiguration failure occurred.
// Misconfiguration failure includes error KIOSK_MODE_ONLY, when force installed
// extension fails to install with failure reason CRX_INSTALL_ERROR.
TEST_F(ForceInstalledMetricsTest, NonMisconfigurationFailurePresent) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportFailure(
      kExtensionId1, InstallStageTracker::FailureReason::INVALID_ID);
  install_stage_tracker()->ReportCrxInstallError(
      kExtensionId2,
      InstallStageTracker::FailureReason::CRX_INSTALL_ERROR_DECLINED,
      CrxInstallErrorDetail::KIOSK_MODE_ONLY);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 1,
                                      1);
}

#if BUILDFLAG(IS_CHROMEOS)
// Session in which either all the extensions installed successfully, or all
// failures are admin-side misconfigurations. This test verifies that failure
// REPLACED_BY_ARC_APP is not considered as misconfiguration when ARC++ is
// enabled for the profile.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailureNotPresentReplacedByArcAppErrorArcEnabled) {
  // Enable ARC++ for this profile.
  prefs()->SetManagedPref(arc::prefs::kArcEnabled,
                          std::make_unique<base::Value>(true));
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::REPLACED_BY_ARC_APP);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// Session in which at least one non misconfiguration failure occurred. This
// test verifies that failure REPLACED_BY_ARC_APP is not considered as
// misconfiguration when ARC++ is disabled for the profile.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailureNotPresentReplacedByArcAppErrorArcDisabled) {
  // Enable ARC++ for this profile.
  prefs()->SetManagedPref(arc::prefs::kArcEnabled,
                          std::make_unique<base::Value>(false));
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::REPLACED_BY_ARC_APP);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 1,
                                      1);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

// Session in which either all the extensions installed successfully, or all
// failures are admin-side misconfigurations. This test verifies that failure
// NOT_PERFORMING_NEW_INSTALL is considered as misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailureNotPresentNotPerformingNewInstallError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportFailure(
      kExtensionId2,
      InstallStageTracker::FailureReason::NOT_PERFORMING_NEW_INSTALL);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// Session in which either all the extensions installed successfully, or all
// failures are admin-side misconfigurations. This test verifies that failure
// CRX_FETCH_URL_EMPTY with empty info field is considered as misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailureNotPresentCrxFetchUrlEmptyError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInfoOnNoUpdatesFailure(kExtensionId2, "");
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::CRX_FETCH_URL_EMPTY);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      1);
}

// This test verifies that failure CRX_FETCH_URL_EMPTY with non empty info field
// is not considered as a misconfiguration.
TEST_F(ForceInstalledMetricsTest,
       NonMisconfigurationFailurePresentCrxFetchUrlEmptyError) {
  SetupForceList(ExtensionOrigin::kWebStore);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kLoaded);
  install_stage_tracker()->ReportInfoOnNoUpdatesFailure(kExtensionId2,
                                                        "rate limit");
  install_stage_tracker()->ReportFailure(
      kExtensionId2, InstallStageTracker::FailureReason::CRX_FETCH_URL_EMPTY);
  // ForceInstalledMetrics shuts down timer because all extension are either
  // loaded or failed.
  EXPECT_FALSE(fake_timer_->IsRunning());
  histogram_tester_.ExpectBucketCount(kPossibleNonMisconfigurationFailures, 0,
                                      0);
}

TEST_F(ForceInstalledMetricsTest, NoExtensionsConfigured) {
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  histogram_tester_.ExpectTotalCount(kLoadTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kReadyTimeStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutStats, 0);
  histogram_tester_.ExpectTotalCount(kTimedOutNotInstalledStats, 0);
  histogram_tester_.ExpectTotalCount(kFailureReasonsCWS, 0);
  histogram_tester_.ExpectTotalCount(kInstallationStages, 0);
  histogram_tester_.ExpectTotalCount(kFailureCrxInstallErrorStats, 0);
  histogram_tester_.ExpectTotalCount(kTotalCountStats, 0);
}

TEST_F(ForceInstalledMetricsTest, CachedExtensions) {
  SetupForceList(ExtensionOrigin::kWebStore);
  install_stage_tracker()->ReportDownloadingCacheStatus(
      kExtensionId1, ExtensionDownloaderDelegate::CacheStatus::CACHE_HIT);
  install_stage_tracker()->ReportDownloadingCacheStatus(
      kExtensionId2, ExtensionDownloaderDelegate::CacheStatus::CACHE_MISS);
  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kPending);
  registry()->AddEnabled(ext1.get());
  EXPECT_TRUE(fake_timer_->IsRunning());
  fake_timer_->Fire();
  // If an extension was installed successfully, don't mention it in statistics.
  histogram_tester_.ExpectUniqueSample(
      kInstallationFailureCacheStatus,
      ExtensionDownloaderDelegate::CacheStatus::CACHE_MISS, 1);
}

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
class ManagementAuthorityTrustworthinessMetricsTest
    : public ForceInstalledMetricsTest,
      public testing::WithParamInterface<
          policy::EnterpriseManagementAuthority> {
 protected:
  std::map<policy::EnterpriseManagementAuthority,
           policy::ManagementAuthorityTrustworthiness>
      authority_map_ = {
          {policy::EnterpriseManagementAuthority::NONE,
           policy::ManagementAuthorityTrustworthiness::NONE},
          {policy::EnterpriseManagementAuthority::COMPUTER_LOCAL,
           policy::ManagementAuthorityTrustworthiness::LOW},
          {policy::EnterpriseManagementAuthority::CLOUD,
           policy::ManagementAuthorityTrustworthiness::TRUSTED},
          {policy::EnterpriseManagementAuthority::CLOUD_DOMAIN,
           policy::ManagementAuthorityTrustworthiness::FULLY_TRUSTED}};

  base::HistogramTester histograms_;
};

TEST_P(ManagementAuthorityTrustworthinessMetricsTest, HistogramLogged) {
  SetupForceList(ExtensionOrigin::kWebStore);
  policy::ScopedManagementServiceOverrideForTesting browser_management(
      policy::ManagementServiceFactory::GetForPlatform(), GetParam());

  scoped_refptr<const Extension> ext1 = CreateNewExtension(
      kExtensionName1, kExtensionId1, ExtensionStatus::kReady);
  scoped_refptr<const Extension> ext2 = CreateNewExtension(
      kExtensionName2, kExtensionId2, ExtensionStatus::kReady);

  histograms_.ExpectUniqueSample(
      "Extensions.ForceInstalledManagementAuthorityTrustworthiness",
      authority_map_[GetParam()], 1);
}

INSTANTIATE_TEST_SUITE_P(
    All,
    ManagementAuthorityTrustworthinessMetricsTest,
    testing::Values(policy::EnterpriseManagementAuthority::NONE,
                    policy::EnterpriseManagementAuthority::COMPUTER_LOCAL,
                    policy::EnterpriseManagementAuthority::CLOUD,
                    policy::EnterpriseManagementAuthority::CLOUD_DOMAIN));
#endif

}  // namespace extensions