File: system_notification_manager_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 (1647 lines) | stat: -rw-r--r-- 73,047 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
// Copyright 2021 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/ash/extensions/file_manager/system_notification_manager.h"

#include <optional>
#include <set>
#include <string_view>

#include "ash/webui/file_manager/url_constants.h"
#include "base/containers/flat_map.h"
#include "base/files/file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "chrome/browser/ash/extensions/file_manager/device_event_router.h"
#include "chrome/browser/ash/extensions/file_manager/event_router.h"
#include "chrome/browser/ash/file_manager/copy_or_move_io_task.h"
#include "chrome/browser/ash/file_manager/io_task.h"
#include "chrome/browser/ash/file_manager/volume_manager.h"
#include "chrome/browser/ash/file_manager/volume_manager_factory.h"
#include "chrome/browser/ash/policy/dlp/dialogs/files_policy_dialog.h"
#include "chrome/browser/ash/policy/dlp/files_policy_notification_manager.h"
#include "chrome/browser/ash/policy/dlp/files_policy_notification_manager_factory.h"
#include "chrome/browser/ash/policy/dlp/test/mock_files_policy_notification_manager.h"
#include "chrome/browser/notifications/notification_display_service_impl.h"
#include "chrome/browser/notifications/notification_platform_bridge_delegator.h"
#include "chrome/common/extensions/api/file_manager_private.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "chromeos/ash/components/dbus/cros_disks/cros_disks_client.h"
#include "chromeos/ash/components/disks/disk.h"
#include "chromeos/ash/components/disks/fake_disk_mount_manager.h"
#include "chromeos/ash/experiences/arc/arc_prefs.h"
#include "content/public/test/browser_task_environment.h"
#include "storage/browser/file_system/file_system_url.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/browser/test/async_file_test_helper.h"
#include "storage/browser/test/test_file_system_context.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/chromeos/strings/grit/ui_chromeos_strings.h"

namespace file_manager {
namespace {

namespace fmp = extensions::api::file_manager_private;

using ash::DeviceType;
using ash::disks::Disk;
using base::BindOnce;
using base::FilePath;
using extensions::Event;
using message_center::NotificationDelegate;
using testing::IsEmpty;

using enum extensions::events::HistogramValue;

// Strings that would be seen on a notification.
struct Strings {
  std::u16string title;
  std::u16string message;
  std::vector<std::u16string> buttons;
};

// Notification platform bridge implementation for testing.
class TestNotificationPlatformBridgeDelegator
    : public NotificationPlatformBridgeDelegator {
 public:
  explicit TestNotificationPlatformBridgeDelegator(Profile* profile)
      : NotificationPlatformBridgeDelegator(profile, base::DoNothing()) {}
  ~TestNotificationPlatformBridgeDelegator() override = default;

  // NotificationPlatformBridgeDelegator:
  void Display(
      NotificationHandler::Type notification_type,
      const message_center::Notification& notification,
      std::unique_ptr<NotificationCommon::Metadata> metadata) override {
    Strings strings;
    notification_ids_.insert(notification.id());
    strings.title = notification.title();
    strings.message = notification.message();
    for (const message_center::ButtonInfo& button : notification.buttons()) {
      strings.buttons.push_back(button.title);
    }
    notifications_[notification.id()] = std::move(strings);
    delegates_[notification.id()] = notification.delegate();
  }

  void Close(NotificationHandler::Type notification_type,
             const std::string& notification_id) override {
    notification_ids_.erase(notification_id);
    notifications_.erase(notification_id);
    delegates_.erase(notification_id);
  }

  void GetDisplayed(GetDisplayedNotificationsCallback callback) const override {
    std::move(callback).Run(notification_ids_, /*supports_sync=*/true);
  }

  // Gets the strings that would have been seen on the notification.
  Strings GetStrings(const std::string& notification_id) {
    const auto it = notifications_.find(notification_id);
    if (it == notifications_.end()) {
      LOG(ERROR) << "Cannot find notification " << notification_id;
      return {};
    }

    return it->second;
  }

  // Clicks a notification button.
  void ClickButton(const std::string& notification_id, int button_index) {
    const auto it = delegates_.find(notification_id);
    if (it == delegates_.end()) {
      LOG(ERROR) << "Cannot find delegate " << notification_id;
      return;
    }

    it->second->Click(button_index, std::nullopt);
  }

  // Clicks a notification body.
  void ClickNotification(const std::string& notification_id) {
    const auto it = delegates_.find(notification_id);
    if (it == delegates_.end()) {
      LOG(ERROR) << "Cannot find delegate " << notification_id;
      return;
    }

    it->second->Click(std::nullopt, std::nullopt);
  }

 private:
  // Notification IDs.
  std::set<std::string> notification_ids_;

  // Maps a notification ID to its displayed title and message.
  base::flat_map<std::string, Strings> notifications_;

  // Maps a notification ID to its delegate to verify click handlers.
  base::flat_map<std::string, scoped_refptr<NotificationDelegate>> delegates_;
};

// DeviceEventRouter implementation for testing.
class DeviceEventRouterImpl : public DeviceEventRouter {
 public:
  DeviceEventRouterImpl(SystemNotificationManager* notification_manager,
                        Profile* profile)
      : DeviceEventRouter(notification_manager) {}

  // DeviceEventRouter overrides.
  void OnDeviceEvent(fmp::DeviceEventType type,
                     const std::string& device_path,
                     const std::string& device_label) override {
    fmp::DeviceEvent event;
    event.type = type;
    event.device_path = device_path;
    event.device_label = device_label;

    system_notification_manager()->HandleDeviceEvent(event);
  }
};

constexpr char kDevicePath[] = "/device/test";
constexpr char kMountPath[] = "/mnt/media/sda1";
std::u16string kRemovableDeviceTitle = u"Removable device detected";

}  // namespace

class SystemNotificationManagerTest
    : public io_task::IOTaskController::Observer,
      public ::testing::Test {
 public:
  void SetUp() override {
    testing::Test::SetUp();
    ASSERT_TRUE(profile_manager_.SetUp());
    profile_ = profile_manager_.CreateTestingProfile("testing_profile");
    display_service_ = static_cast<NotificationDisplayServiceImpl*>(
        NotificationDisplayServiceFactory::GetForProfile(profile_));
    auto bridge =
        std::make_unique<TestNotificationPlatformBridgeDelegator>(profile_);
    bridge_ = bridge.get();
    display_service_->SetNotificationPlatformBridgeDelegatorForTesting(
        std::move(bridge));
    notification_manager_ =
        std::make_unique<SystemNotificationManager>(profile_);
    event_router_ = std::make_unique<DeviceEventRouterImpl>(
        notification_manager_.get(), profile_);

    VolumeManagerFactory::GetInstance()->SetTestingFactory(
        profile_,
        base::BindLambdaForTesting([this](content::BrowserContext* context) {
          return std::unique_ptr<KeyedService>(std::make_unique<VolumeManager>(
              Profile::FromBrowserContext(context), nullptr, nullptr,
              &disk_mount_manager_, nullptr,
              VolumeManager::GetMtpStorageInfoCallback()));
        }));
    VolumeManager* const volume_manager = VolumeManager::Get(profile_);

    // SystemNotificationManager needs the IOTaskController to be able to cancel
    // the task.
    io_task_controller = volume_manager->io_task_controller();
    notification_manager_->SetIOTaskController(io_task_controller);
    io_task_controller->AddObserver(this);

    ASSERT_TRUE(dir_.CreateUniqueTempDir());
    ASSERT_TRUE(dir_.GetPath().IsAbsolute());
    file_system_context_ = storage::CreateFileSystemContextForTesting(
        /*quota_manager_proxy=*/nullptr, dir_.GetPath());

    volume_manager->AddVolumeForTesting(
        CreateTestFile("volume/").path(), VOLUME_TYPE_DOWNLOADS_DIRECTORY,
        DeviceType::kUnknown, false /* read only */);
  }

  void TearDown() override {
    io_task_controller->RemoveObserver(this);
    profile_ = nullptr;
    profile_manager_.DeleteAllTestingProfiles();
  }

  // IOTaskController::Observer override:
  // In production code the observer is EventRouter which forwards the status to
  // SystemNotificationManager.
  void OnIOTaskStatus(const io_task::ProgressStatus& status) override {
    task_statuses_[status.task_id].push_back(status.state);
    notification_manager_->HandleIOTaskProgress(status);
  }

  size_t GetNotificationCount() {
    display_service_->GetDisplayed(
        BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
                 weak_ptr_factory_.GetWeakPtr()));
    return notification_count_;
  }

  void GetNotificationsCallback(std::set<std::string> displayed_notifications,
                                bool supports_synchronization) {
    notification_count_ = displayed_notifications.size();
  }

  // Creates a file or directory to use in the test.
  storage::FileSystemURL CreateTestFile(const std::string& path) {
    const blink::StorageKey storage_key =
        blink::StorageKey::CreateFromStringForTesting(
            ash::file_manager::kChromeUIFileManagerURL);

    auto file_url = file_system_context_->CreateCrackedFileSystemURL(
        storage_key, storage::kFileSystemTypeTest,
        FilePath::FromUTF8Unsafe(path));

    if (base::EndsWith(path, "/")) {
      CHECK(base::File::FILE_OK ==
            storage::AsyncFileTestHelper::CreateDirectory(
                file_system_context_.get(), file_url));
    } else {
      CHECK(base::File::FILE_OK == storage::AsyncFileTestHelper::CreateFile(
                                       file_system_context_.get(), file_url));
    }

    return file_url;
  }

  content::BrowserTaskEnvironment task_environment_;
  ash::disks::FakeDiskMountManager disk_mount_manager_;
  TestingProfileManager profile_manager_{TestingBrowserProcess::GetGlobal()};
  // Externally owned raw pointers:
  // profile_ is owned by TestingProfileManager.
  raw_ptr<TestingProfile> profile_;
  // notification_display_service is owned by NotificationDisplayServiceFactory.
  raw_ptr<NotificationDisplayServiceImpl, DanglingUntriaged> display_service_;
  std::unique_ptr<SystemNotificationManager> notification_manager_;
  std::unique_ptr<DeviceEventRouterImpl> event_router_;

  // Temporary directory used to test IOTask progress.
  base::ScopedTempDir dir_;

  size_t notification_count_ = 0;

  // notification_platform_bridge is owned by NotificationDisplayService.
  raw_ptr<TestNotificationPlatformBridgeDelegator, DanglingUntriaged> bridge_;

  // Used for tests with IOTask:
  raw_ptr<io_task::IOTaskController, DanglingUntriaged> io_task_controller;
  scoped_refptr<storage::FileSystemContext> file_system_context_;

  // Keep track of the task state transitions.
  base::flat_map<io_task::IOTaskId, std::vector<io_task::State>> task_statuses_;

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

TEST_F(SystemNotificationManagerTest, ExternalStorageDisabled) {
  base::HistogramTester histogram_tester;
  // Send the event.
  event_router_->OnDiskAddBlockedByPolicy(kDevicePath);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("disabled");
  // Check: the expected strings match.
  std::u16string kExternalStorageDisabledMesssage =
      u"Sorry, your administrator has disabled external storage on your "
      u"account.";
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message, kExternalStorageDisabledMesssage);
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_EXTERNAL_STORAGE_DISABLED, 1);
}

constexpr char kDeviceLabel[] = "MyUSB";
std::u16string kFormatTitle = u"Format MyUSB";

TEST_F(SystemNotificationManagerTest, FormatStart) {
  base::HistogramTester histogram_tester;
  event_router_->OnFormatStarted(kDevicePath, kDeviceLabel,
                                 /*success=*/true);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("format_start");
  // Check: the expected strings match.
  std::u16string kFormatStartMesssage = u"Formatting MyUSB\x2026";
  EXPECT_EQ(strings.title, kFormatTitle);
  EXPECT_EQ(strings.message, kFormatStartMesssage);
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::FORMAT_START,
                                      1);
}

TEST_F(SystemNotificationManagerTest, FormatSuccess) {
  base::HistogramTester histogram_tester;
  event_router_->OnFormatCompleted(kDevicePath, kDeviceLabel,
                                   /*success=*/true);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("format_success");
  // Check: the expected strings match.
  std::u16string kFormatSuccessMesssage = u"Formatted MyUSB";
  EXPECT_EQ(strings.title, kFormatTitle);
  EXPECT_EQ(strings.message, kFormatSuccessMesssage);
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::FORMAT_SUCCESS,
                                      1);
}

TEST_F(SystemNotificationManagerTest, FormatFail) {
  base::HistogramTester histogram_tester;
  event_router_->OnFormatCompleted(kDevicePath, kDeviceLabel,
                                   /*success=*/false);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("format_fail");
  // Check: the expected strings match.
  std::u16string kFormatFailedMesssage = u"Could not format MyUSB";
  EXPECT_EQ(strings.title, kFormatTitle);
  EXPECT_EQ(strings.message, kFormatFailedMesssage);
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::FORMAT_FAIL,
                                      1);
}

constexpr char kPartitionLabel[] = "OEM";
std::u16string kPartitionTitle = u"Format OEM";

TEST_F(SystemNotificationManagerTest, PartitionFail) {
  base::HistogramTester histogram_tester;
  event_router_->OnPartitionCompleted(kDevicePath, kPartitionLabel,
                                      /*success=*/false);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("partition_fail");
  // Check: the expected strings match.
  std::u16string kPartitionFailMesssage = u"Could not format OEM";
  EXPECT_EQ(strings.title, kPartitionTitle);
  EXPECT_EQ(strings.message, kPartitionFailMesssage);
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::PARTITION_FAIL,
                                      1);
}

TEST_F(SystemNotificationManagerTest, RenameFail) {
  base::HistogramTester histogram_tester;
  event_router_->OnRenameCompleted(kDevicePath, kPartitionLabel,
                                   /*success=*/false);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("rename_fail");
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Renaming failed");
  EXPECT_EQ(strings.message, u"Aw, Snap! There was an error during renaming.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::RENAME_FAIL,
                                      1);
}

TEST_F(SystemNotificationManagerTest, DeviceHardUnplugged) {
  base::HistogramTester histogram_tester;
  const std::unique_ptr<const Disk> disk =
      Disk::Builder()
          .SetDevicePath(kDevicePath)
          .SetMountPath(kMountPath)
          .SetStorageDevicePath(kDevicePath)
          .SetIsReadOnlyHardware(false)
          .SetFileSystemType("vfat")
          .SetIsMounted(true)
          .Build();
  event_router_->OnDiskRemoved(*disk);
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("hard_unplugged");
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Whoa, there. Be careful.");
  EXPECT_EQ(strings.message,
            u"In the future, be sure to eject your removable device in the "
            u"Files app before unplugging it. Otherwise, you might lose data.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_HARD_UNPLUGGED, 1);
}

constexpr char kRemovableDeviceNotificationId[] = "swa-removable-device-id";

TEST_F(SystemNotificationManagerTest, DeviceNavigation) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kRemovableDeviceNotificationId);
  bridge_->ClickButton(kRemovableDeviceNotificationId, /*button_index=*/0);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Explore the device\x2019s content in the Files app.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_NAVIGATION, 1);
  histogram_tester.ExpectUniqueSample(
      kNotificationUserActionHistogramName,
      DeviceNotificationUserActionUmaType::OPEN_MEDIA_DEVICE_NAVIGATION, 1);
}

// Test for notification generated when enterprise read-only policy is set.
// Condition that triggers that is a mount event for a removable device
// and the volume has read only set.
TEST_F(SystemNotificationManagerTest, DeviceNavigationReadOnlyPolicy) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/true, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kRemovableDeviceNotificationId);
  bridge_->ClickButton(kRemovableDeviceNotificationId, /*button_index=*/0);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Explore the device's content in the Files app. The content is "
            u"restricted by an admin and can\x2019t be modified.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_NAVIGATION_READONLY_POLICY, 1);
  histogram_tester.ExpectUniqueSample(
      kNotificationUserActionHistogramName,
      DeviceNotificationUserActionUmaType::OPEN_MEDIA_DEVICE_NAVIGATION, 1);
}

// Test for notification generated when ARC++ is enabled on the device.
// Condition that triggers that is a mount event for a removable device
// when the removable access for ARC++ is disabled.
TEST_F(SystemNotificationManagerTest, DeviceNavigationAllowAppAccess) {
  base::HistogramTester histogram_tester;
  // Set the ARC++ enbled preference on the testing profile.
  PrefService* const service = profile_->GetPrefs();
  service->SetBoolean(arc::prefs::kArcEnabled, true);
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kRemovableDeviceNotificationId);
  bridge_->ClickButton(kRemovableDeviceNotificationId, /*button_index=*/0);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Explore the device\x2019s content in the Files app. For device "
            u"preferences, go to Settings.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_NAVIGATION_ALLOW_APP_ACCESS, 1);
  histogram_tester.ExpectUniqueSample(
      kNotificationUserActionHistogramName,
      DeviceNotificationUserActionUmaType::OPEN_MEDIA_DEVICE_NAVIGATION_ARC, 1);
}

TEST_F(SystemNotificationManagerTest,
       DeviceNavigationAllowAppAccessSecondButton) {
  base::HistogramTester histogram_tester;
  // Set the ARC++ enbled preference on the testing profile.
  PrefService* const service = profile_->GetPrefs();
  service->SetBoolean(arc::prefs::kArcEnabled, true);
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  bridge_->ClickButton(kRemovableDeviceNotificationId, /*button_index=*/1);
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationUserActionHistogramName,
      DeviceNotificationUserActionUmaType::OPEN_SETTINGS_FOR_ARC_STORAGE, 1);
}

// Test for notification generated when ARC++ is enabled on the device.
// Condition that triggers that is a mount event for a removable device
// when the removable access for ARC++ is enabled.
TEST_F(SystemNotificationManagerTest, DeviceNavigationAppsHaveAccess) {
  base::HistogramTester histogram_tester;
  // Set the ARC++ enbled preference on the testing profile.
  PrefService* const service = profile_->GetPrefs();
  service->SetBoolean(arc::prefs::kArcEnabled, true);
  service->SetBoolean(arc::prefs::kArcHasAccessToRemovableMedia, true);
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kRemovableDeviceNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Explore the device\x2019s content in the Files app. Play Store "
            u"applications have access to this device.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_NAVIGATION_APPS_HAVE_ACCESS, 1);
}

constexpr char kDeviceFailNotificationId[] = "swa-device-fail-id";

// Device unsupported notifications are generated when a removable
// drive is mounted with an unsupported filesystem on a partition.
// The default message is used when there is no device label.
// In the notification generation logic there is a distinction
// between parent and child volumes found by the volume is_parent()
// method. Both parent and child unknown volume filesystems generate
// the same nofication.
TEST_F(SystemNotificationManagerTest, DeviceUnsupportedDefault) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")), "",
      "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kUnsupportedFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(
      strings.message,
      u"Sorry, your external storage device is not supported at this time.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::DEVICE_FAIL,
                                      1);
}

// The named version of the device unsupported notification is
// generated when the device includes a device label.
TEST_F(SystemNotificationManagerTest, DeviceUnsupportedNamed) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kUnsupportedFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, the device MyUSB is not supported at this time.");
  // Check that the correct UMA was emitted.
  histogram_tester.ExpectUniqueSample(kNotificationShowHistogramName,
                                      DeviceNotificationUmaType::DEVICE_FAIL,
                                      1);
}

// Multipart device unsupported notifications are generated when there is
// a multi-partition device inserted and one partition has a known filesystem
// but other partitions have unsupported file systems.
// Note: In such cases the Chrome OS device will generate 2 notifications:
//       1) A device navigation notification for the supported file system
//       2) The multipart device unsupported notification.
TEST_F(SystemNotificationManagerTest, MultipartDeviceUnsupportedDefault) {
  base::HistogramTester histogram_tester;
  // Build a supported file system volume and mount it.
  std::unique_ptr<Volume> volume1(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")), "",
      "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume1.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kRemovableDeviceNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Explore the device\x2019s content in the Files app.");
  // Build an unsupported file system volume and mount it on the same device.
  std::unique_ptr<Volume> volume2(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path2")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")), "",
      "unsupported"));
  event.status = fmp::MountError::kUnsupportedFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume2.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have two notifications.
  ASSERT_EQ(2u, notification_count_);
  // Get the strings for the displayed notification.
  strings = bridge_->GetStrings(kDeviceFailNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, at least one partition on your external storage device "
            u"could not be mounted.");
  // A DEVICE_NAVIGATION UMA is emitted during the setup so just check for the
  // occurrence of the DEVICE_FAIL sample instead.
  histogram_tester.ExpectBucketCount(kNotificationShowHistogramName,
                                     DeviceNotificationUmaType::DEVICE_FAIL, 1);
}

// The named version of the multipart device unsupported notification is
// generated when the device label exists and at least one partition can be
// mounted on a device with an unsupported file system on another partition.
TEST_F(SystemNotificationManagerTest, MultipartDeviceUnsupportedNamed) {
  base::HistogramTester histogram_tester;
  // Build a supported file system volume and mount it.
  std::unique_ptr<Volume> volume1(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "FAT32"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kSuccess;
  notification_manager_->HandleMountCompletedEvent(event, *volume1.get());
  // Ignore checking for the device navigation notification.
  // Build an unsupported file system volume and mount it on the same device.
  std::unique_ptr<Volume> volume2(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path2")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "unsupported"));
  event.status = fmp::MountError::kUnsupportedFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume2.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have two notifications.
  ASSERT_EQ(2u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, at least one partition on the device MyUSB could not be "
            u"mounted.");
  // A DEVICE_NAVIGATION UMA is emitted during the setup so just check for the
  // occurrence of the DEVICE_FAIL sample instead.
  histogram_tester.ExpectBucketCount(kNotificationShowHistogramName,
                                     DeviceNotificationUmaType::DEVICE_FAIL, 1);
}

// Device fail unknown notifications are generated when the type of filesystem
// on a removable device cannot be determined.
// The default version of the notifiication is generated when there is
// no drive label.
// These notifications are similar to the device unsupported notifications,
// the difference being an unknown vs. unsupported file system.
TEST_F(SystemNotificationManagerTest, DeviceFailUnknownDefault) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")), "",
      "unknown"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kUnknownFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  bridge_->ClickButton(kDeviceFailNotificationId, /*button_index=*/0);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, your external storage device could not be recognized.");
  EXPECT_EQ(strings.buttons.size(), 1u);
  EXPECT_EQ(strings.buttons[0], u"Format this device");
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_FAIL_UNKNOWN, 1);
  histogram_tester.ExpectUniqueSample(
      kNotificationUserActionHistogramName,
      DeviceNotificationUserActionUmaType::OPEN_MEDIA_DEVICE_FAIL, 1);
}

// The named version of the device fail unknown notification is
// generated when the device includes a device label.
TEST_F(SystemNotificationManagerTest, DeviceFailUnknownNamed) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/false, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "unknown"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kUnknownFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  bridge_->ClickButton(kDeviceFailNotificationId, /*button_index=*/0);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, the device MyUSB could not be recognized.");
  EXPECT_EQ(strings.buttons.size(), 1u);
  EXPECT_EQ(strings.buttons[0], u"Format this device");
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_FAIL_UNKNOWN, 1);
  histogram_tester.ExpectUniqueSample(
      kNotificationUserActionHistogramName,
      DeviceNotificationUserActionUmaType::OPEN_MEDIA_DEVICE_FAIL, 1);
}

// Device fail unknown read only notifications are generated when
// volumes with read only set and an unknown file system is mounted.
// The default notification message is generated when there is
// no device label.
TEST_F(SystemNotificationManagerTest, DeviceFailUnknownReadOnlyDefault) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/true, FilePath(FILE_PATH_LITERAL("/device/test")), "",
      "unknown"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kUnknownFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, your external storage device could not be recognized.");
  // Device is read-only, expect no buttons present.
  EXPECT_EQ(strings.buttons.size(), 0u);
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_FAIL_UNKNOWN_READONLY, 1);
}

// The named version of the read only device fail unknown notification is
// generated when the device includes a device label.
TEST_F(SystemNotificationManagerTest, DeviceFailUnknownReadOnlyNamed) {
  base::HistogramTester histogram_tester;
  std::unique_ptr<Volume> volume(Volume::CreateForTesting(
      FilePath(FILE_PATH_LITERAL("/mount/path1")),
      VolumeType::VOLUME_TYPE_TESTING, DeviceType::kUSB,
      /*read_only=*/true, FilePath(FILE_PATH_LITERAL("/device/test")),
      kDeviceLabel, "unknown"));
  fmp::MountCompletedEvent event;
  event.event_type = fmp::MountCompletedEventType::kMount;
  event.should_notify = true;
  event.status = fmp::MountError::kUnknownFilesystem;
  notification_manager_->HandleMountCompletedEvent(event, *volume.get());
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(kDeviceFailNotificationId);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kRemovableDeviceTitle);
  EXPECT_EQ(strings.message,
            u"Sorry, the device MyUSB could not be recognized.");
  histogram_tester.ExpectUniqueSample(
      kNotificationShowHistogramName,
      DeviceNotificationUmaType::DEVICE_FAIL_UNKNOWN_READONLY, 1);
}

TEST_F(SystemNotificationManagerTest, HandleIOTaskProgressCopy) {
  // The system notification only sees the IOTask ProgressStatus.
  file_manager::io_task::ProgressStatus status;
  status.task_id = 1;
  status.state = file_manager::io_task::State::kQueued;
  status.type = file_manager::io_task::OperationType::kCopy;
  status.total_bytes = 100;
  status.bytes_transferred = 0;
  status.sources.emplace_back(CreateTestFile("volume/src_file.txt"),
                              std::nullopt);
  status.SetDestinationFolder(CreateTestFile("volume/dest_dir/"));

  // Send the copy begin/queued progress.
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the 1 notification.
  ASSERT_EQ(1u, GetNotificationCount());

  Strings strings = bridge_->GetStrings("swa-file-operation-1");

  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message, u"Copying src_file.txt\x2026");

  // Send the copy progress.
  status.bytes_transferred = 30;
  status.state = file_manager::io_task::State::kInProgress;
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the same notification.
  ASSERT_EQ(1u, GetNotificationCount());
  strings = bridge_->GetStrings("swa-file-operation-1");
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message, u"Copying src_file.txt\x2026");

  // Send the success progress status.
  status.bytes_transferred = 100;
  status.state = file_manager::io_task::State::kSuccess;
  notification_manager_->HandleIOTaskProgress(status);

  // Notification should disappear.
  ASSERT_EQ(0u, GetNotificationCount());
}

TEST_F(SystemNotificationManagerTest, HandleIOTaskProgressExtract) {
  // The system notification only sees the IOTask ProgressStatus.
  file_manager::io_task::ProgressStatus status;
  status.task_id = 1;
  status.state = file_manager::io_task::State::kQueued;
  status.type = file_manager::io_task::OperationType::kExtract;
  status.total_bytes = 100;
  status.bytes_transferred = 0;
  status.sources.emplace_back(CreateTestFile("volume/src_file.zip"),
                              std::nullopt);
  status.SetDestinationFolder(CreateTestFile("volume/src_file/"));

  // Send the copy begin/queued progress.
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the 1 notification.
  ASSERT_EQ(1u, GetNotificationCount());

  Strings strings = bridge_->GetStrings("swa-file-operation-1");

  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message, u"Extracting src_file.zip\x2026");

  // Send the copy progress.
  status.bytes_transferred = 30;
  status.state = file_manager::io_task::State::kInProgress;
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the same notification.
  ASSERT_EQ(1u, GetNotificationCount());
  strings = bridge_->GetStrings("swa-file-operation-1");
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message, u"Extracting src_file.zip\x2026");

  // Send the success progress status.
  status.bytes_transferred = 100;
  status.state = file_manager::io_task::State::kSuccess;
  notification_manager_->HandleIOTaskProgress(status);

  // Notification should disappear.
  ASSERT_EQ(0u, GetNotificationCount());
}

TEST_F(SystemNotificationManagerTest, CancelButtonIOTask) {
  // The system notification only sees the IOTask ProgressStatus.
  file_manager::io_task::ProgressStatus status;
  status.task_id = 1;
  status.state = file_manager::io_task::State::kQueued;
  status.type = file_manager::io_task::OperationType::kCopy;
  status.total_bytes = 100;
  status.bytes_transferred = 0;
  auto src = CreateTestFile("volume/src_file.txt");
  status.sources.emplace_back(src, std::nullopt);
  auto dst = CreateTestFile("volume/dest_dir/");
  status.SetDestinationFolder(dst);

  auto task = std::make_unique<file_manager::io_task::CopyOrMoveIOTask>(
      file_manager::io_task::OperationType::kCopy,
      std::vector<storage::FileSystemURL>({src}), dst, profile_,
      file_system_context_);

  // Send the copy begin/queued progress.
  const io_task::IOTaskId task_id = io_task_controller->Add(std::move(task));

  // Check: We have the 1 notification.
  ASSERT_EQ(1u, GetNotificationCount());

  // Click on the cancel button.
  bridge_->ClickButton("swa-file-operation-1", /*button_index=*/0);

  // Notification should disappear.
  ASSERT_EQ(0u, GetNotificationCount());

  // The last status observed should be Cancelled.
  ASSERT_EQ(io_task::State::kCancelled, task_statuses_[task_id].back());
}

TEST_F(SystemNotificationManagerTest, HandleIOTaskProgressPolicyScanning) {
  // The system notification only sees the IOTask ProgressStatus.
  file_manager::io_task::ProgressStatus status;
  status.task_id = 1;
  status.state = file_manager::io_task::State::kScanning;
  status.type = file_manager::io_task::OperationType::kCopy;
  status.total_bytes = 100;
  status.bytes_transferred = 123;
  status.sources_scanned = 1;
  status.sources.emplace_back(CreateTestFile("volume/src_file.txt"),
                              std::nullopt);
  status.SetDestinationFolder(CreateTestFile("volume/dest_dir/"));

  // Send the scanning progress.
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the 1 notification.
  ASSERT_EQ(1u, GetNotificationCount());

  Strings strings = bridge_->GetStrings("swa-file-operation-1");

  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message,
            l10n_util::GetStringUTF16(IDS_FILE_BROWSER_SCANNING_LABEL));

  // Send the success progress status.
  status.bytes_transferred = 100;
  status.state = file_manager::io_task::State::kSuccess;
  notification_manager_->HandleIOTaskProgress(status);

  // Notification should disappear.
  ASSERT_EQ(0u, GetNotificationCount());
}

std::u16string kGoogleDrive = u"Google Drive";

// Tests the bulk-pinning notifications.
TEST_F(SystemNotificationManagerTest, BulkPinningNotification) {
  using List = base::Value::List;
  const std::string_view event_name = "unused-event-name";

  // Event with no args should be ignored.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name, List()));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  file_manager_private::BulkPinProgress progress;
  progress.should_pin = true;

  // Handle an unparsable event.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Not enough space without going through syncing phase.
  EXPECT_FALSE(progress.emptied_queue);
  progress.stage = fmp::BulkPinStage::kNotEnoughSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Listing files.
  progress.stage = fmp::BulkPinStage::kListingFiles;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Not enough space after listing phase.
  progress.stage = fmp::BulkPinStage::kNotEnoughSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be one notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(1u, notification_count_);

  // Get the strings for the displayed notification.
  const std::string notification_id = "drive-bulk-pinning-error";
  {
    const Strings strings = bridge_->GetStrings(notification_id);
    EXPECT_EQ(strings.title, u"Couldn’t finish setting up file sync");
    EXPECT_EQ(strings.message,
              u"There isn’t enough storage space to sync all of your files");
    EXPECT_THAT(strings.buttons, IsEmpty());
  }

  // Click the notification body.
  bridge_->ClickNotification(notification_id);

  // The notification should have been closed.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Syncing.
  progress.stage = fmp::BulkPinStage::kSyncing;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Not enough space after syncing phase.
  progress.stage = fmp::BulkPinStage::kNotEnoughSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be one notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(1u, notification_count_);

  // Get the strings for the displayed notification.
  {
    const Strings strings = bridge_->GetStrings(notification_id);
    EXPECT_EQ(strings.title, u"Couldn’t finish setting up file sync");
    EXPECT_EQ(strings.message,
              u"There isn’t enough storage space to sync all of your files");
    EXPECT_THAT(strings.buttons, IsEmpty());
  }

  // Click the notification body.
  bridge_->ClickNotification(notification_id);

  // The notification should have been closed.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Not enough space without going through syncing phase.
  progress.stage = fmp::BulkPinStage::kNotEnoughSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Back to syncing stage. Pretend that everything has been synced.
  progress.stage = fmp::BulkPinStage::kSyncing;
  progress.emptied_queue = true;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Not enough space after syncing phase.
  progress.stage = fmp::BulkPinStage::kNotEnoughSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be one notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(1u, notification_count_);

  // Get the strings for the displayed notification.
  {
    const Strings strings = bridge_->GetStrings(notification_id);
    EXPECT_EQ(strings.title, u"File sync turned off");
    EXPECT_EQ(strings.message,
              u"There isn’t enough storage space to continue syncing files");
    EXPECT_THAT(strings.buttons, IsEmpty());
  }

  // Click the notification body.
  bridge_->ClickNotification(notification_id);

  // The notification should have been closed.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Back to syncing stage.
  progress.stage = fmp::BulkPinStage::kSyncing;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Error during syncing phase.
  progress.stage = fmp::BulkPinStage::kCannotGetFreeSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be one notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(1u, notification_count_);

  // Get the strings for the displayed notification.
  {
    const Strings strings = bridge_->GetStrings(notification_id);
    EXPECT_EQ(strings.title, u"File sync turned off");
    EXPECT_EQ(strings.message, u"Something went wrong.");
    EXPECT_THAT(strings.buttons, IsEmpty());
  }

  // Click the notification body.
  bridge_->ClickNotification(notification_id);

  // The notification should have been closed.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Listing files without having the intent of pinning them.
  progress.stage = fmp::BulkPinStage::kListingFiles;
  progress.should_pin = false;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);

  // Not enough space after listing phase.
  progress.stage = fmp::BulkPinStage::kNotEnoughSpace;
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_BULK_PIN_PROGRESS, event_name,
            List().Append(progress.ToValue())));

  // There should be no notification.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  EXPECT_EQ(0u, notification_count_);
}

// Tests all the various error notifications.
TEST_F(SystemNotificationManagerTest, Errors) {
  // Build a Drive sync error object.
  fmp::DriveSyncErrorEvent sync_error;
  sync_error.type = fmp::DriveSyncErrorType::kDeleteWithoutPermission;
  sync_error.file_url = "drivefs://fake.txt";

  // Send the delete without permission sync error event.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_DRIVE_SYNC_ERROR,
            file_manager_private::OnDriveSyncError::kEventName,
            file_manager_private::OnDriveSyncError::Create(sync_error)));
  // Get the number of notifications from the NotificationDisplayService.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  const char* id = ToString(sync_error.type);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings(id);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kGoogleDrive);
  EXPECT_EQ(strings.message,
            u"\"fake.txt\" has been shared with you. You cannot delete it "
            u"because you do not own it.");

  // Setup for the service unavailable error.
  sync_error.type = fmp::DriveSyncErrorType::kServiceUnavailable;

  // Send the service unavailable sync error event.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_DRIVE_SYNC_ERROR,
            file_manager_private::OnDriveSyncError::kEventName,
            file_manager_private::OnDriveSyncError::Create(sync_error)));
  // Get the number of notifications from the NotificationDisplayService.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have two notifications.
  ASSERT_EQ(2u, notification_count_);
  id = ToString(sync_error.type);
  // Get the strings for the displayed notification.
  strings = bridge_->GetStrings(id);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kGoogleDrive);
  EXPECT_EQ(strings.message,
            u"Google Drive is not available right now. Uploading will "
            u"automatically restart once Google Drive is back.");

  // Setup for the no server space error.
  sync_error.type = fmp::DriveSyncErrorType::kNoServerSpace;

  // Send the service unavailable sync error event.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_DRIVE_SYNC_ERROR,
            file_manager_private::OnDriveSyncError::kEventName,
            file_manager_private::OnDriveSyncError::Create(sync_error)));
  // Get the number of notifications from the NotificationDisplayService.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have three notifications.
  ASSERT_EQ(3u, notification_count_);
  id = ToString(sync_error.type);
  // Get the strings for the displayed notification.
  strings = bridge_->GetStrings(id);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kGoogleDrive);
  EXPECT_EQ(strings.message,
            u"There is not enough free space in your Google Drive to complete "
            u"the upload.");

  // Setup for the no local space error.
  sync_error.type = fmp::DriveSyncErrorType::kNoLocalSpace;

  // Send the service unavailable sync error event.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_DRIVE_SYNC_ERROR,
            file_manager_private::OnDriveSyncError::kEventName,
            file_manager_private::OnDriveSyncError::Create(sync_error)));
  // Get the number of notifications from the NotificationDisplayService.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have four notifications.
  ASSERT_EQ(4u, notification_count_);
  id = ToString(sync_error.type);
  // Get the strings for the displayed notification.
  strings = bridge_->GetStrings(id);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kGoogleDrive);
  EXPECT_EQ(strings.message, u"You have run out of space");

  // Setup for the miscellaneous sync error.
  sync_error.type = fmp::DriveSyncErrorType::kMisc;

  // Send the service unavailable sync error event.
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_DRIVE_SYNC_ERROR,
            file_manager_private::OnDriveSyncError::kEventName,
            file_manager_private::OnDriveSyncError::Create(sync_error)));
  // Get the number of notifications from the NotificationDisplayService.
  display_service_->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have five notifications.
  ASSERT_EQ(5u, notification_count_);
  id = ToString(sync_error.type);
  // Get the strings for the displayed notification.
  strings = bridge_->GetStrings(id);
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kGoogleDrive);
  EXPECT_EQ(strings.message,
            u"Google Drive was unable to sync \"fake.txt\" right now. Google "
            u"Drive will try again later.");
}

// Tests the generation of the DriveFS enable offline notification.
// This is triggered when users make files available offline and the
// Google Drive offline setting at https://drive.google.com isn't enabled.
TEST_F(SystemNotificationManagerTest, EnableDocsOffline) {
  file_manager_private::DriveConfirmDialogEvent drive_event;
  drive_event.type =
      file_manager_private::DriveConfirmDialogType::kEnableDocsOffline;
  drive_event.file_url = "drivefs://fake";
  notification_manager_->HandleEvent(
      Event(FILE_MANAGER_PRIVATE_ON_DRIVE_CONFIRM_DIALOG,
            file_manager_private::OnDriveConfirmDialog::kEventName,
            file_manager_private::OnDriveConfirmDialog::Create(drive_event)));
  // Get the number of notifications from the NotificationDisplayService.
  NotificationDisplayServiceFactory::GetForProfile(profile_)->GetDisplayed(
      BindOnce(&SystemNotificationManagerTest::GetNotificationsCallback,
               weak_ptr_factory_.GetWeakPtr()));
  // Check: We have one notification.
  ASSERT_EQ(1u, notification_count_);
  // Get the strings for the displayed notification.
  Strings strings = bridge_->GetStrings("swa-drive-confirm-dialog");
  // Check: the expected strings match.
  EXPECT_EQ(strings.title, kGoogleDrive);
  EXPECT_EQ(strings.message,
            u"Enable Google Docs Offline to make Docs, Sheets and Slides "
            u"available offline.");
}

class SystemNotificationManagerPolicyTest
    : public SystemNotificationManagerTest {
 public:
  void SetUp() override {
    SystemNotificationManagerTest::SetUp();
    // Set FilesPolicyNotificationManager.
    policy::FilesPolicyNotificationManagerFactory::GetInstance()
        ->SetTestingFactory(
            profile_.get(),
            base::BindRepeating(&SystemNotificationManagerPolicyTest::
                                    SetFilesPolicyNotificationManager,
                                base::Unretained(this)));
    ASSERT_TRUE(
        policy::FilesPolicyNotificationManagerFactory::GetForBrowserContext(
            profile_.get()));
    ASSERT_TRUE(fpnm_);
  }

  policy::MockFilesPolicyNotificationManager* fpnm() { return fpnm_; }

 private:
  std::unique_ptr<KeyedService> SetFilesPolicyNotificationManager(
      content::BrowserContext* context) {
    auto fpnm = std::make_unique<policy::MockFilesPolicyNotificationManager>(
        profile_.get());
    fpnm_ = fpnm.get();

    return fpnm;
  }

  raw_ptr<policy::MockFilesPolicyNotificationManager, DanglingUntriaged> fpnm_ =
      nullptr;
};

TEST_F(SystemNotificationManagerPolicyTest, HandleIOTaskProgressWarning) {
  // The system notification only sees the IOTask ProgressStatus.
  file_manager::io_task::ProgressStatus status;
  status.task_id = 1;
  status.state = file_manager::io_task::State::kQueued;
  status.type = file_manager::io_task::OperationType::kCopy;
  status.total_bytes = 100;
  status.bytes_transferred = 0;
  status.sources.emplace_back(CreateTestFile("volume/src_file1.txt"),
                              std::nullopt);
  status.sources.emplace_back(CreateTestFile("volume/src_file2.txt"),
                              std::nullopt);
  status.SetDestinationFolder(CreateTestFile("volume/dest_dir/"));

  // Send the copy begin/queued progress.
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the 1 notification.
  ASSERT_EQ(1u, GetNotificationCount());

  Strings strings = bridge_->GetStrings("swa-file-operation-1");

  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message, u"Copying 2 items\x2026");

  // Set the status to warning.
  status.state = file_manager::io_task::State::kPaused;
  status.pause_params.policy_params =
      io_task::PolicyPauseParams(policy::Policy::kDlp);
  // The manager delegates to FPNM to show the notification.
  EXPECT_CALL(
      *fpnm(),
      ShowFilesPolicyNotification(
          "swa-file-operation-1",
          AllOf(testing::Field(&file_manager::io_task::ProgressStatus::task_id,
                               status.task_id),
                testing::Field(&file_manager::io_task::ProgressStatus::state,
                               file_manager::io_task::State::kPaused),
                testing::Field(
                    &file_manager::io_task::ProgressStatus::pause_params,
                    status.pause_params))))
      .Times(1);
  notification_manager_->HandleIOTaskProgress(status);
}

TEST_F(SystemNotificationManagerPolicyTest, HandleIOTaskProgressPolicyError) {
  // The system notification only sees the IOTask ProgressStatus.
  file_manager::io_task::ProgressStatus status;
  status.task_id = 1;
  status.state = file_manager::io_task::State::kQueued;
  status.type = file_manager::io_task::OperationType::kCopy;
  status.total_bytes = 100;
  status.bytes_transferred = 0;
  status.sources.emplace_back(CreateTestFile("volume/src_file.txt"),
                              std::nullopt);
  status.SetDestinationFolder(CreateTestFile("volume/dest_dir/"));

  // Send the copy begin/queued progress.
  notification_manager_->HandleIOTaskProgress(status);

  // Check: We have the 1 notification.
  ASSERT_EQ(1u, GetNotificationCount());

  Strings strings = bridge_->GetStrings("swa-file-operation-1");

  // Check: the expected strings match.
  EXPECT_EQ(strings.title, u"Files");
  EXPECT_EQ(strings.message, u"Copying src_file.txt\x2026");

  // Set the security error value.
  status.state = file_manager::io_task::State::kError;
  status.policy_error.emplace(
      file_manager::io_task::PolicyErrorType::kEnterpriseConnectors,
      /*blocked_files=*/1);
  // The manager delegates to FPNM to show the notification.
  EXPECT_CALL(
      *fpnm(),
      ShowFilesPolicyNotification(
          "swa-file-operation-1",
          AllOf(testing::Field(&file_manager::io_task::ProgressStatus::task_id,
                               status.task_id),
                testing::Field(&file_manager::io_task::ProgressStatus::state,
                               file_manager::io_task::State::kError),
                testing::Field(
                    &file_manager::io_task::ProgressStatus::policy_error,
                    status.policy_error))))
      .Times(1);

  notification_manager_->HandleIOTaskProgress(status);
}

}  // namespace file_manager