File: relaunch_notification_controller_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 (1239 lines) | stat: -rw-r--r-- 51,322 bytes parent folder | download | duplicates (5)
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
// 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/ui/views/relaunch_notification/relaunch_notification_controller.h"

#include <memory>
#include <optional>
#include <utility>

#include "ash/public/cpp/update_types.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/test/mock_callback.h"
#include "base/test/power_monitor_test.h"
#include "base/test/task_environment.h"
#include "base/time/clock.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/upgrade_detector/upgrade_detector.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/scoped_testing_local_state.h"
#include "chrome/test/base/testing_browser_process.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/shell.h"
#include "ash/test/ash_test_helper.h"
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "components/user_manager/scoped_user_manager.h"
#include "content/public/test/browser_task_environment.h"
#include "ui/display/manager/display_configurator.h"
#include "ui/display/manager/test/action_logger.h"
#include "ui/display/manager/test/test_native_display_delegate.h"
#else
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/test_with_browser_view.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

using ::testing::_;
using ::testing::Eq;
using ::testing::ResultOf;
using ::testing::Return;

namespace {

// A delegate interface for handling the actions taken by the controller.
class ControllerDelegate {
 public:
  virtual ~ControllerDelegate() = default;
  virtual void NotifyRelaunchRecommended() = 0;
  virtual void NotifyRelaunchRequired() = 0;
  virtual void Close() = 0;
  virtual void OnRelaunchDeadlineExpired() = 0;

 protected:
  ControllerDelegate() = default;
};

// A fake controller that asks a delegate to do work.
class FakeRelaunchNotificationController
    : public RelaunchNotificationController {
 public:
  FakeRelaunchNotificationController(UpgradeDetector* upgrade_detector,
                                     const base::Clock* clock,
                                     const base::TickClock* tick_clock,
                                     ControllerDelegate* delegate)
      : RelaunchNotificationController(upgrade_detector, clock, tick_clock),
        delegate_(delegate) {}

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

  using RelaunchNotificationController::kRelaunchGracePeriod;

  base::Time IncreaseRelaunchDeadlineOnShow() {
    return RelaunchNotificationController::IncreaseRelaunchDeadlineOnShow();
  }

 private:
  void DoNotifyRelaunchRecommended(bool /*past_deadline*/) override {
    delegate_->NotifyRelaunchRecommended();
  }

  void DoNotifyRelaunchRequired(
      base::Time deadline,
      base::OnceCallback<base::Time()> on_visible) override {
    delegate_->NotifyRelaunchRequired();
  }

  void Close() override { delegate_->Close(); }

  void OnRelaunchDeadlineExpired() override {
    delegate_->OnRelaunchDeadlineExpired();
  }

  raw_ptr<ControllerDelegate> delegate_;
};

// A mock delegate for testing.
class MockControllerDelegate : public ControllerDelegate {
 public:
  MOCK_METHOD(void, NotifyRelaunchRecommended, (), (override));
  MOCK_METHOD(void, NotifyRelaunchRequired, (), (override));
  MOCK_METHOD(void, Close, (), (override));
  MOCK_METHOD(void, OnRelaunchDeadlineExpired, (), (override));
};

// A fake UpgradeDetector.
class FakeUpgradeDetector : public UpgradeDetector {
 public:
  explicit FakeUpgradeDetector(const base::Clock* clock,
                               const base::TickClock* tick_clock)
      : UpgradeDetector(clock, tick_clock) {
    set_upgrade_detected_time(this->clock()->Now());
  }

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

  base::TimeDelta GetHighAnnoyanceLevelDelta() {
    return GetAnnoyanceLevelDeadline(UpgradeDetector::UPGRADE_ANNOYANCE_HIGH) -
           GetAnnoyanceLevelDeadline(
               UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  }

  // UpgradeDetector:
  base::Time GetAnnoyanceLevelDeadline(
      FakeUpgradeDetector::UpgradeNotificationAnnoyanceLevel level) override {
    switch (level) {
      case UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED:
        return upgrade_detected_time() + (2 / 3 * high_threshold_);
      case UpgradeDetector::UPGRADE_ANNOYANCE_HIGH:
        return upgrade_detected_time() + high_threshold_;
      case UpgradeDetector::UPGRADE_ANNOYANCE_GRACE:
      case UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW:
      case UpgradeDetector::UPGRADE_ANNOYANCE_LOW:
      case UpgradeDetector::UPGRADE_ANNOYANCE_NONE:
      case UpgradeDetector::UPGRADE_ANNOYANCE_CRITICAL:
        return base::Time();
    }
  }

  // Sets the annoyance level to |level| and broadcasts the change to all
  // observers.
  void BroadcastLevelChange(UpgradeNotificationAnnoyanceLevel level) {
    set_upgrade_notification_stage(level);
    NotifyUpgrade();
  }

  // Sets the high annoyance threshold to |high_threshold| and broadcasts the
  // change to all observers.
  void BroadcastHighThresholdChange(base::TimeDelta high_threshold) {
    high_threshold_ = high_threshold;
    NotifyUpgrade();
  }

  void BroadcastNotificationTypeOverriden(bool overridden) {
    NotifyRelaunchOverriddenToRequired(overridden);
  }

  base::TimeDelta high_threshold() const { return high_threshold_; }

 private:
  base::TimeDelta high_threshold_ = base::Days(7);
};

}  // namespace

// A test harness that provides facilities for manipulating the relaunch
// notification policy setting and for broadcasting upgrade notifications.
class RelaunchNotificationControllerTest : public ::testing::Test {
 public:
  RelaunchNotificationControllerTest(
      const RelaunchNotificationControllerTest&) = delete;
  RelaunchNotificationControllerTest& operator=(
      const RelaunchNotificationControllerTest&) = delete;

 protected:
  RelaunchNotificationControllerTest()
      : task_environment_(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME,
            base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED),
        scoped_local_state_(TestingBrowserProcess::GetGlobal()),
        upgrade_detector_(task_environment_.GetMockClock(),
                          task_environment_.GetMockTickClock()) {
    // Unittests failed when the system is on battery. This class is using a
    // mock power monitor source `power_monitor_source_` to ensure no real
    // power state or power notifications are delivered to the unittests.
    EXPECT_FALSE(base::PowerMonitor::GetInstance()->IsOnBatteryPower());
  }

  UpgradeDetector* upgrade_detector() { return &upgrade_detector_; }
  FakeUpgradeDetector& fake_upgrade_detector() { return upgrade_detector_; }

  // Sets the browser.relaunch_notification preference in Local State to
  // |value|.
  void SetNotificationPref(int value) {
    scoped_local_state_.Get()->SetManagedPref(
        prefs::kRelaunchNotification, std::make_unique<base::Value>(value));
  }

  // Returns the TaskEnvironment's MockClock.
  const base::Clock* GetMockClock() { return task_environment_.GetMockClock(); }

  // Returns the TaskEnvironment's MockTickClock.
  const base::TickClock* GetMockTickClock() {
    return task_environment_.GetMockTickClock();
  }

  // Fast-forwards virtual time by |delta|.
  void FastForwardBy(base::TimeDelta delta) {
    task_environment_.FastForwardBy(delta);
  }

  void RunUntilIdle() { task_environment_.RunUntilIdle(); }

 private:
  // Use a mock power monitor source to ensure the test is in control of the
  // power notifications.
  base::test::ScopedPowerMonitorTestSource power_monitor_source_;

  base::test::TaskEnvironment task_environment_;
  ScopedTestingLocalState scoped_local_state_;
  FakeUpgradeDetector upgrade_detector_;
};

TEST_F(RelaunchNotificationControllerTest, CreateDestroy) {
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);
}

// Without the browser.relaunch_notification preference set, the controller
// should not be observing the UpgradeDetector, and should therefore never
// attempt to show any notifications.

// TODO(crbug.com/40099078) Disabled due to race condition.
#if defined(THREAD_SANATIZER)
#define MAYBE_PolicyUnset DISABLED_PolicyUnset
#else
#define MAYBE_PolicyUnset PolicyUnset
#endif
TEST_F(RelaunchNotificationControllerTest, MAYBE_PolicyUnset) {
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
}

// With the browser.relaunch_notification preference set to 1, the controller
// should be observing the UpgradeDetector and should show "Requested"
// notifications on each level change above "very low".
TEST_F(RelaunchNotificationControllerTest, RecommendedByPolicy) {
  SetNotificationPref(1);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // Nothing shown if the level is broadcast at NONE or VERY_LOW.
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Show for each level change, but not for repeat notifications.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // First move time to the high annoyance deadline.
  base::Time high_annoyance_deadline =
      upgrade_detector()->GetAnnoyanceLevelDeadline(
          UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  FastForwardBy(high_annoyance_deadline - GetMockClock()->Now());

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // The timer should be running to reshow at the detector's delta.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  FastForwardBy(fake_upgrade_detector().GetHighAnnoyanceLevelDelta());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  FastForwardBy(fake_upgrade_detector().GetHighAnnoyanceLevelDelta());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Drop back to elevated to stop the reshows and ensure there are none.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  FastForwardBy(fake_upgrade_detector().GetHighAnnoyanceLevelDelta());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And closed if the level drops back to very low.
  EXPECT_CALL(mock_controller_delegate, Close());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Back up to elevated brings the bubble back.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And it is closed if the level drops back to none.
  EXPECT_CALL(mock_controller_delegate, Close());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// With the browser.relaunch_notification preference set to 2, the controller
// should be observing the UpgradeDetector and should show "Required"
// notifications on each level change.
TEST_F(RelaunchNotificationControllerTest, RequiredByPolicy) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // Nothing shown if the level is broadcast at NONE.
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Show for each change to a higher level, but not for repeat notifications.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And closed if the level drops back to none.
  EXPECT_CALL(mock_controller_delegate, Close());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_NONE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Flipping the policy should have no effect when at level NONE or VERY_LOW.
TEST_F(RelaunchNotificationControllerTest, PolicyChangesNoUpgrade) {
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  SetNotificationPref(1);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(3);  // Bogus value!
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(0);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(1);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(3);  // Bogus value!
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(0);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Policy changes at an elevated level should show the appropriate notification.
TEST_F(RelaunchNotificationControllerTest, PolicyChangesWithUpgrade) {
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  SetNotificationPref(1);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, Close());
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  SetNotificationPref(2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, Close());
  SetNotificationPref(0);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Relaunch is forced when the deadline is reached.
TEST_F(RelaunchNotificationControllerTest, RequiredDeadlineReached) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // As in the RequiredByPolicy test, the dialog should be shown.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And the relaunch should be forced after the deadline passes.
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// No forced relaunch if the dialog is closed.
TEST_F(RelaunchNotificationControllerTest, RequiredDeadlineReachedNoPolicy) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // As in the RequiredByPolicy test, the dialog should be shown.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And then closed if the policy is cleared.
  EXPECT_CALL(mock_controller_delegate, Close());
  SetNotificationPref(0);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And no relaunch should take place.
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// NotificationPeriod changes should do nothing at any policy setting when the
// annoyance level is at none.
TEST_F(RelaunchNotificationControllerTest, NonePeriodChange) {
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // Reduce the period.
  fake_upgrade_detector().BroadcastHighThresholdChange(base::Days(1));
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(1);
  fake_upgrade_detector().BroadcastHighThresholdChange(base::Hours(23));
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(2);
  fake_upgrade_detector().BroadcastHighThresholdChange(base::Hours(22));
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// NotificationPeriod changes should do nothing at any policy setting when the
// annoyance level is at very low.
TEST_F(RelaunchNotificationControllerTest, VeryLowPeriodChange) {
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Reduce the period.
  fake_upgrade_detector().BroadcastHighThresholdChange(base::Days(1));
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(1);
  fake_upgrade_detector().BroadcastHighThresholdChange(base::Hours(23));
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(2);
  fake_upgrade_detector().BroadcastHighThresholdChange(base::Hours(22));
  FastForwardBy(fake_upgrade_detector().high_threshold());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// NotificationPeriod changes impact reshows of the relaunch recommended bubble.
TEST_F(RelaunchNotificationControllerTest, PeriodChangeRecommended) {
  SetNotificationPref(1);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // First move time to the high annoyance deadline.
  base::Time high_annoyance_deadline =
      upgrade_detector()->GetAnnoyanceLevelDeadline(
          UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  FastForwardBy(high_annoyance_deadline - GetMockClock()->Now());

  // Get up to high annoyance so that the reshow timer is running.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Advance time partway to the reshow, but not all the way there.
  FastForwardBy(fake_upgrade_detector().GetHighAnnoyanceLevelDelta() * 0.9);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Now shorten the period dramatically and expect an immediate reshow.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  fake_upgrade_detector().BroadcastHighThresholdChange(
      fake_upgrade_detector().high_threshold() / 10);
  RunUntilIdle();
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And expect another reshow at the new delta.
  base::TimeDelta short_reshow_delta =
      fake_upgrade_detector().GetHighAnnoyanceLevelDelta();
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  FastForwardBy(short_reshow_delta);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Now lengthen the period and expect no immediate reshow.
  fake_upgrade_detector().BroadcastHighThresholdChange(
      fake_upgrade_detector().high_threshold() * 10);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Move forward by the short delta to be sure there's no reshow there.
  FastForwardBy(short_reshow_delta);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Move forward the rest of the way to the new delta and expect a reshow.
  base::TimeDelta long_reshow_delta =
      fake_upgrade_detector().GetHighAnnoyanceLevelDelta();
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  FastForwardBy(long_reshow_delta - short_reshow_delta);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Similar to the above, move time forward a little bit.
  FastForwardBy(long_reshow_delta * 0.1);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Shorten the period a bit, but not enough to force a reshow.
  fake_upgrade_detector().BroadcastHighThresholdChange(
      fake_upgrade_detector().high_threshold() * 0.9);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // And ensure that moving forward the rest of the way to the new delta causes
  // a reshow.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRecommended());
  FastForwardBy(fake_upgrade_detector().GetHighAnnoyanceLevelDelta() -
                long_reshow_delta * 0.1);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// NotificationPeriod changes impact reshows of the relaunch required dialog.
TEST_F(RelaunchNotificationControllerTest, PeriodChangeRequired) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Move forward partway to the current deadline. Nothing should happen.
  base::Time high_annoyance_deadline =
      upgrade_detector()->GetAnnoyanceLevelDeadline(
          UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  FastForwardBy((high_annoyance_deadline - GetMockClock()->Now()) / 2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Lengthen the period, thereby pushing out the deadline.
  fake_upgrade_detector().BroadcastHighThresholdChange(
      fake_upgrade_detector().high_threshold() * 2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Ensure that nothing happens when the old deadline passes.
  FastForwardBy(high_annoyance_deadline - GetMockClock()->Now());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Now we enter elevated annoyance level and show the dialog.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Now we enter grace annoyance level and again show the dialog.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Jumping to the new deadline relaunches the browser.
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(upgrade_detector()->GetAnnoyanceLevelDeadline(
                    UpgradeDetector::UPGRADE_ANNOYANCE_HIGH) -
                GetMockClock()->Now());
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Shorten the period, bringing in the deadline. Expect the dialog to show and
  // a relaunch after the grace period passes.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastHighThresholdChange(
      fake_upgrade_detector().high_threshold() / 2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(FakeRelaunchNotificationController::kRelaunchGracePeriod);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Test that grace period is given to the user to relaunch if the deadline is
// shortened to be in the past due to change in notification period.
TEST_F(RelaunchNotificationControllerTest, DeadlineShortenGracePeriod) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Move forward partway to the current deadline. Nothing should happen.
  base::Time high_annoyance_deadline =
      upgrade_detector()->GetAnnoyanceLevelDeadline(
          UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  FastForwardBy((high_annoyance_deadline - GetMockClock()->Now()) / 2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Shorten the period, thereby pushing the deadline in the past. Expect the
  // dialog to show and a relaunch after the grace period passes.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastHighThresholdChange(
      fake_upgrade_detector().high_threshold() / 3);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(FakeRelaunchNotificationController::kRelaunchGracePeriod);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Test that grace period is given to the user to relaunch if the device goes to
// sleep beyond the deadline before showing the notification.
TEST_F(RelaunchNotificationControllerTest, DeviceSleepBeforeNotification) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Assume device goes to sleep beyond the deadline.
  base::Time high_annoyance_deadline =
      upgrade_detector()->GetAnnoyanceLevelDeadline(
          UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  FastForwardBy((high_annoyance_deadline - GetMockClock()->Now()) * 1.2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // As device awakes high annoyance is notified. Expect the
  // dialog to show and a relaunch after the grace period passes.
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(FakeRelaunchNotificationController::kRelaunchGracePeriod);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Test that the deadline is extended by the grace period when the
// notification is potentially seen.
TEST_F(RelaunchNotificationControllerTest, DeferredRequired) {
  SetNotificationPref(2);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());

  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Move time just before the original deadline.
  FastForwardBy(fake_upgrade_detector().high_threshold() -
                0.5 * FakeRelaunchNotificationController::kRelaunchGracePeriod);

  // Suddenly, the UX becomes available.
  base::Time deadline = controller.IncreaseRelaunchDeadlineOnShow();
  ASSERT_EQ(deadline,
            GetMockClock()->Now() +
                FakeRelaunchNotificationController::kRelaunchGracePeriod);

  // And the relaunch is extended by the grace period.
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(FakeRelaunchNotificationController::kRelaunchGracePeriod);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Call to override the current relaunch notification type should override it to
// required and policy change should not affect it.
TEST_F(RelaunchNotificationControllerTest, OverriddenToRequired) {
  SetNotificationPref(1);
  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;

  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  fake_upgrade_detector().BroadcastNotificationTypeOverriden(true);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  SetNotificationPref(0);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, Close());
  fake_upgrade_detector().BroadcastNotificationTypeOverriden(false);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

// Tests that the required notification is shown all three times when the clock
// moves along with the elevations.
TEST_F(RelaunchNotificationControllerTest, NotifyAllWithShortestPeriod) {
  SetNotificationPref(2);

  ::testing::StrictMock<MockControllerDelegate> mock_controller_delegate;
  FakeRelaunchNotificationController controller(
      upgrade_detector(), GetMockClock(), GetMockTickClock(),
      &mock_controller_delegate);

  // Advance to the low threshold and raise the annoyance level.
  const auto delta = fake_upgrade_detector().high_threshold() / 3;
  FastForwardBy(delta);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Advance to the elevated threshold and raise the annoyance level.
  FastForwardBy(fake_upgrade_detector().high_threshold() - delta * 2);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Advance to the grace threshold and raise the annoyance level.
  FastForwardBy(delta - base::Hours(1));
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  EXPECT_CALL(mock_controller_delegate, NotifyRelaunchRequired());
  fake_upgrade_detector().BroadcastLevelChange(
      UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);

  // Advance to the deadline to restart.
  EXPECT_CALL(mock_controller_delegate, OnRelaunchDeadlineExpired());
  FastForwardBy(base::Hours(1));
  ASSERT_EQ(GetMockClock()->Now(),
            upgrade_detector()->GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH));
  ::testing::Mock::VerifyAndClearExpectations(&mock_controller_delegate);
}

#if BUILDFLAG(IS_CHROMEOS)

// RelaunchNotificationControllerPlatformImpl but SetRelaunchNotificationState
// and ResetRelaunchNotification are fake for testing.
class FakeRelaunchNotificationControllerPlatformImpl
    : public RelaunchNotificationControllerPlatformImpl {
 public:
  const std::vector<ash::RelaunchNotificationState>& states() const {
    return states_;
  }

 private:
  void SetRelaunchNotificationState(const ash::RelaunchNotificationState&
                                        relaunch_notification_state) override {
    states_.push_back(relaunch_notification_state);
  }
  void ResetRelaunchNotification() override {}

  std::vector<ash::RelaunchNotificationState> states_;
};

class RelaunchNotificationControllerPlatformImplTest : public ::testing::Test {
 protected:
  RelaunchNotificationControllerPlatformImplTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}

  ~RelaunchNotificationControllerPlatformImplTest() override = default;

  void SetUp() override {
    ash::AshTestHelper::InitParams init_params;
    init_params.start_session = false;
    ash_test_helper_ = std::make_unique<ash::AshTestHelper>();
    ash_test_helper_->SetUp(std::move(init_params));

    user_manager_.Reset(std::make_unique<ash::FakeChromeUserManager>());
    auto* session_manager = session_manager::SessionManager::Get();
    session_manager->OnUserManagerCreated(user_manager_.Get());

    const char test_user_email[] = "test_user@example.com";
    const AccountId test_account_id(AccountId::FromUserEmail(test_user_email));
    auto* user = user_manager_->AddUser(test_account_id);
    user_manager_->LoginUser(test_account_id);

    // SessionManager is created by
    // |AshTestHelper::bluetooth_config_test_helper()|.
    session_manager::SessionManager::Get()->CreateSession(
        user->GetAccountId(), test_user_email,
        /*new_user=*/false,
        /*has_active_session=*/false);
    session_manager::SessionManager::Get()->SetSessionState(
        session_manager::SessionState::ACTIVE);

    logger_ = std::make_unique<display::test::ActionLogger>();
    native_display_delegate_ =
        new display::test::TestNativeDisplayDelegate(logger_.get());
    ash::Shell::Get()->display_configurator()->SetDelegateForTesting(
        std::unique_ptr<display::NativeDisplayDelegate>(
            native_display_delegate_));
  }

  void TearDown() override {
    native_display_delegate_ = nullptr;
    logger_.reset();
    ash_test_helper_->TearDown();
    ash_test_helper_.reset();
    // UserManager needs to be removed after ash_test_helper_, because it holds
    // SessionManager instance, which needs to be destroyed before UserManager.
    user_manager_.Reset();
  }

  void LockScreen() {
    session_manager::SessionManager::Get()->SetSessionState(
        session_manager::SessionState::LOCKED);
  }

  void UnLockScreen() {
    session_manager::SessionManager::Get()->SetSessionState(
        session_manager::SessionState::ACTIVE);
  }

  void TurnDisplayOff() {
    ash::Shell::Get()->display_configurator()->SetDisplayPower(
        chromeos::DISPLAY_POWER_ALL_OFF, 0, base::DoNothing());
  }

  void TurnDisplayOn() {
    ash::Shell::Get()->display_configurator()->SetDisplayPower(
        chromeos::DISPLAY_POWER_ALL_ON, 0, base::DoNothing());
  }

  RelaunchNotificationControllerPlatformImpl& platform_impl() { return impl_; }
  FakeRelaunchNotificationControllerPlatformImpl& fake_platform_impl() {
    return impl_;
  }

  // Returns the TaskEnvironment's MockClock.
  const base::Clock* GetMockClock() { return task_environment_.GetMockClock(); }

 private:
  content::BrowserTaskEnvironment task_environment_;

  // NOTE: This is mostly the real implementation except for two methods:
  // SetRelaunchNotificationState and ResetRelaunchNotification.
  FakeRelaunchNotificationControllerPlatformImpl impl_;

  std::unique_ptr<ash::AshTestHelper> ash_test_helper_;
  user_manager::TypedScopedUserManager<ash::FakeChromeUserManager>
      user_manager_;
  std::unique_ptr<display::test::ActionLogger> logger_;
  raw_ptr<display::NativeDisplayDelegate> native_display_delegate_;
};

// SynchronousNotification
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       SynchronousNotification) {
  UnLockScreen();
  TurnDisplayOn();

  // Expect the platform_impl to query for the deadline synchronously.
  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;
  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(), /*is_notification_type_overriden=*/false,
      callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

// Deferred Notification when the display is off then on.
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       DeferredNotificationDisplayOff) {
  TurnDisplayOff();

  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;

  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(), /*is_notification_type_overriden=*/false,
      callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  EXPECT_CALL(callback, Run());
  TurnDisplayOn();
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

// Deferred Notification when the display is off then on.
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       DeferredNotificationSessionLocked) {
  LockScreen();

  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;

  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(), /*is_notification_type_overriden=*/false,
      callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  EXPECT_CALL(callback, Run());
  UnLockScreen();
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

// Multiple screen on & off.
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       RequiredDeadlineReachedAfterMultipleResume) {
  TurnDisplayOff();

  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;

  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(), /*is_notification_type_overriden=*/false,
      callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  EXPECT_CALL(callback, Run());
  TurnDisplayOn();

  TurnDisplayOff();
  TurnDisplayOn();
  TurnDisplayOff();
  TurnDisplayOn();
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

// Multiple session locks & unlocks.
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       RequiredDeadlineReachedBeforeMultipleUnlock) {
  LockScreen();

  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;

  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(), /*is_notification_type_overriden=*/false,
      callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  EXPECT_CALL(callback, Run());
  UnLockScreen();

  LockScreen();
  UnLockScreen();
  LockScreen();
  UnLockScreen();
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

// Correct relaunch notification state for required notification type.
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       RelaunchNotificationStateRequired) {
  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(), /*is_notification_type_overriden=*/false,
      base::BindOnce([]() { return base::Time(); }));

  const auto& states = fake_platform_impl().states();
  ASSERT_EQ(states.size(), static_cast<size_t>(1));
  const auto& relaunch_notification_state = states[0];

  EXPECT_EQ(relaunch_notification_state.requirement_type,
            ash::RelaunchNotificationState::kRequired);
  EXPECT_EQ(relaunch_notification_state.policy_source,
            ash::RelaunchNotificationState::kUser);
  EXPECT_LE(relaunch_notification_state.rounded_time_until_reboot_required,
            base::Seconds(1));
}

// Correct relaunch notification state for required notification type with an
// override.
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       RelaunchNotificationStateRequiredWithOverride) {
  platform_impl().NotifyRelaunchRequired(
      GetMockClock()->Now(),
      /*is_notification_type_overriden=*/true,
      base::BindOnce([]() { return base::Time(); }));

  const auto& states = fake_platform_impl().states();
  ASSERT_EQ(states.size(), static_cast<size_t>(1));
  const auto& relaunch_notification_state = states[0];

  EXPECT_EQ(relaunch_notification_state.requirement_type,
            ash::RelaunchNotificationState::kRequired);
  EXPECT_EQ(relaunch_notification_state.policy_source,
            ash::RelaunchNotificationState::kDevice);
  EXPECT_LE(relaunch_notification_state.rounded_time_until_reboot_required,
            base::Seconds(1));
}

#else  // BUILDFLAG(IS_CHROMEOS)

class RelaunchNotificationControllerPlatformImplTest
    : public TestWithBrowserView {
 protected:
  RelaunchNotificationControllerPlatformImplTest() = default;

  void SetUp() override {
    TestWithBrowserView::SetUp();
    impl_.emplace();
  }

  void SetVisibility(bool is_visible) {
    if (is_visible) {
      browser_view()->Show();
    } else {
      browser_view()->Hide();
    }

    // Allow UI tasks to run so that the browser becomes fully active/inactive.
    task_environment()->RunUntilIdle();
  }

  RelaunchNotificationControllerPlatformImpl& platform_impl() { return *impl_; }

 private:
  std::optional<RelaunchNotificationControllerPlatformImpl> impl_;
};

// Flaky on all platforms: https://crbug.com/1294032
TEST_F(RelaunchNotificationControllerPlatformImplTest,
       DISABLED_SynchronousNotification) {
  // Make the UX visible to the user so that no delay will be incurred
  ASSERT_NO_FATAL_FAILURE(SetVisibility(true));

  // Expect the platform_impl to show the notification synchronously.
  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;

  base::Time deadline = base::Time::Now() + base::Hours(1);

  // There should be no query at the time of showing.
  platform_impl().NotifyRelaunchRequired(deadline, callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  ASSERT_NO_FATAL_FAILURE(SetVisibility(false));

  // There should be no query because the browser isn't visible.
  platform_impl().NotifyRelaunchRequired(deadline, callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  // There should be no query because this isn't the first time to show the
  // notification.
  ASSERT_NO_FATAL_FAILURE(SetVisibility(true));
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

//  Flaky on Mac: https://crbug.com/1312578
#if BUILDFLAG(IS_MAC)
#define MAYBE_DeferredDeadline DISABLED_DeferredDeadline
#else
#define MAYBE_DeferredDeadline DeferredDeadline
#endif
TEST_F(RelaunchNotificationControllerPlatformImplTest, MAYBE_DeferredDeadline) {
  ::testing::StrictMock<base::MockOnceCallback<base::Time()>> callback;

  base::Time deadline = base::Time::Now() + base::Hours(1);

  // There should be no query because the browser isn't visible.
  platform_impl().NotifyRelaunchRequired(deadline, callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  // The query should happen once the notification is potentially seen.
  EXPECT_CALL(callback, Run()).WillOnce(Return(deadline));
  ASSERT_NO_FATAL_FAILURE(SetVisibility(true));

  ::testing::Mock::VerifyAndClearExpectations(&callback);

  ASSERT_NO_FATAL_FAILURE(SetVisibility(false));

  // There should be no query because the browser isn't visible.
  platform_impl().NotifyRelaunchRequired(deadline, callback.Get());
  ::testing::Mock::VerifyAndClearExpectations(&callback);

  // There should be no query because this isn't the first time to show the
  // notification.
  ASSERT_NO_FATAL_FAILURE(SetVisibility(true));
  ::testing::Mock::VerifyAndClearExpectations(&callback);
}

#endif  // BUILDFLAG(IS_CHROMEOS)