File: upgrade_detector_impl_unittest.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; 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 (836 lines) | stat: -rw-r--r-- 34,737 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
// Copyright 2014 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/upgrade_detector/upgrade_detector_impl.h"

#include <array>
#include <initializer_list>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "base/i18n/time_formatting.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/time/clock.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/google/google_brand.h"
#include "chrome/browser/upgrade_detector/installed_version_poller.h"
#include "chrome/browser/upgrade_detector/upgrade_observer.h"
#include "chrome/browser/upgrade_detector/version_history_client.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 "components/network_time/network_time_pref_names.h"
#include "components/prefs/testing_pref_service.h"
#include "components/version_info/version_info.h"
#include "content/public/test/browser_task_environment.h"
#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h"
#include "services/network/test/test_url_loader_factory.h"
#include "services/network/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if !BUILDFLAG(IS_CHROMEOS)
#include "components/enterprise/browser/controller/fake_browser_dm_token_storage.h"
#endif  // !BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_WIN)
#include "chrome/install_static/install_modes.h"
#include "chrome/install_static/test/scoped_install_details.h"
#endif  // BUILDFLAG(IS_WIN)

using ::testing::AnyNumber;

namespace {

class TestUpgradeDetectorImpl : public UpgradeDetectorImpl {
 public:
  explicit TestUpgradeDetectorImpl(const base::Clock* clock,
                                   const base::TickClock* tick_clock)
      : UpgradeDetectorImpl(clock, tick_clock) {}

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

  ~TestUpgradeDetectorImpl() override = default;

  // Exposed for testing.
  using UpgradeDetector::set_upgrade_detected_time;
  using UpgradeDetectorImpl::clock;
  using UpgradeDetectorImpl::GetThresholdForLevel;
  using UpgradeDetectorImpl::NotifyOnUpgradeWithTimePassed;
  using UpgradeDetectorImpl::OnExperimentChangesDetected;
  using UpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR;
  using UpgradeDetectorImpl::UpgradeDetected;

  // UpgradeDetector:
  void TriggerCriticalUpdate() override {
    ++trigger_critical_update_call_count_;
  }

  int trigger_critical_update_call_count() const {
    return trigger_critical_update_call_count_;
  }

 private:
  // How many times TriggerCriticalUpdate() has been called. Expected to either
  // be 0 or 1.
  int trigger_critical_update_call_count_ = 0;
};

class TestUpgradeNotificationListener : public UpgradeObserver {
 public:
  explicit TestUpgradeNotificationListener(UpgradeDetector* detector)
      : notifications_count_(0), detector_(detector) {
    DCHECK(detector_);
    detector_->AddObserver(this);
  }

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

  ~TestUpgradeNotificationListener() override {
    detector_->RemoveObserver(this);
  }

  int notification_count() const { return notifications_count_; }

 private:
  // UpgradeObserver:
  void OnUpgradeRecommended() override { ++notifications_count_; }

  // The number of upgrade recommended notifications received.
  int notifications_count_;

  raw_ptr<UpgradeDetector> detector_;
};

class MockUpgradeObserver : public UpgradeObserver {
 public:
  explicit MockUpgradeObserver(UpgradeDetector* upgrade_detector)
      : upgrade_detector_(upgrade_detector) {
    upgrade_detector_->AddObserver(this);
  }

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

  ~MockUpgradeObserver() override { upgrade_detector_->RemoveObserver(this); }
  MOCK_METHOD0(OnUpdateOverCellularAvailable, void());
  MOCK_METHOD0(OnUpdateOverCellularOneTimePermissionGranted, void());
  MOCK_METHOD0(OnUpgradeRecommended, void());
  MOCK_METHOD0(OnCriticalUpgradeInstalled, void());
  MOCK_METHOD0(OnOutdatedInstall, void());
  MOCK_METHOD0(OnOutdatedInstallNoAutoUpdate, void());

 private:
  const raw_ptr<UpgradeDetector> upgrade_detector_;
};

}  // namespace

class UpgradeDetectorImplTest : public ::testing::Test {
 protected:
  UpgradeDetectorImplTest()
      : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        scoped_local_state_(TestingBrowserProcess::GetGlobal()),
        scoped_poller_disabler_(
            InstalledVersionPoller::MakeScopedDisableForTesting()) {
    TestingBrowserProcess::GetGlobal()->SetSharedURLLoaderFactory(
        url_loader_factory_.GetSafeWeakWrapper());
    // Disable the detector's check to see if autoupdates are enabled.
    // Without this, tests put the detector into an invalid state by detecting
    // upgrades before the detection task completes.
    scoped_local_state_.Get()->SetUserPref(prefs::kAttemptedToEnableAutoupdate,
                                           std::make_unique<base::Value>(true));
    scoped_local_state_.Get()->SetUserPref(
        network_time::prefs::kNetworkTimeQueriesEnabled, base::Value(false));
    UpgradeDetector::GetInstance()->Init();
  }

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

  ~UpgradeDetectorImplTest() override {
    UpgradeDetector::GetInstance()->Shutdown();
  }

  const base::Clock* GetMockClock() { return task_environment_.GetMockClock(); }

  const base::TickClock* GetMockTickClock() {
    return task_environment_.GetMockTickClock();
  }

  network::TestURLLoaderFactory& GetTestURLLoaderFactory() {
    return url_loader_factory_;
  }

  // Sets the browser.relaunch_notification_period preference in Local State to
  // |value|.
  void SetNotificationPeriodPref(base::TimeDelta value) {
    if (value.is_zero()) {
      scoped_local_state_.Get()->RemoveManagedPref(
          prefs::kRelaunchNotificationPeriod);
    } else {
      scoped_local_state_.Get()->SetManagedPref(
          prefs::kRelaunchNotificationPeriod,
          std::make_unique<base::Value>(
              base::saturated_cast<int>(value.InMilliseconds())));
    }
  }

  // Sets the browser.relaunch_window preference in Local State.
  void SetRelaunchWindowPref(int hour, int minute, int duration_mins) {
    // Create the dict representing relaunch time interval.
    base::Value::Dict entry;
    entry.SetByDottedPath("start.hour", hour);
    entry.SetByDottedPath("start.minute", minute);
    entry.Set("duration_mins", duration_mins);
    // Put it in a list.
    base::Value::List entries;
    entries.Append(std::move(entry));
    // Put the list in the policy value.
    base::Value::Dict dict;
    dict.Set("entries", std::move(entries));

    scoped_local_state_.Get()->SetManagedPref(prefs::kRelaunchWindow,
                                              base::Value(std::move(dict)));
  }

  // Sets the browser.relaunch_fast_if_outdated preference in Local State.
  void SetRelaunchFastIfOutdatedPref(int days) {
    scoped_local_state_.Get()->SetManagedPref(
        prefs::kRelaunchFastIfOutdated, base::Value(days));
  }

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

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

 private:
  // Override the brand code so that the test appears to be a non-organic brand
  // in order to suppress the outdated build detector.
  google_brand::BrandForTesting non_organic_{"BBBB"};
  content::BrowserTaskEnvironment task_environment_;
  network::TestURLLoaderFactory url_loader_factory_;
  ScopedTestingLocalState scoped_local_state_;
  InstalledVersionPoller::ScopedDisableForTesting scoped_poller_disabler_;

#if !BUILDFLAG(IS_CHROMEOS)
  policy::FakeBrowserDMTokenStorage dm_token_storage_;
#endif  // !BUILDFLAG(IS_CHROMEOS)
};

TEST_F(UpgradeDetectorImplTest, VariationsChanges) {
  TestUpgradeDetectorImpl detector(GetMockClock(), GetMockTickClock());
  TestUpgradeNotificationListener notifications_listener(&detector);
  detector.Init();
  EXPECT_FALSE(detector.notify_upgrade());
  EXPECT_EQ(0, notifications_listener.notification_count());

  detector.OnExperimentChangesDetected(
      variations::VariationsService::Observer::BEST_EFFORT);
  EXPECT_FALSE(detector.notify_upgrade());
  EXPECT_EQ(0, notifications_listener.notification_count());

  detector.NotifyOnUpgradeWithTimePassed(base::Days(30));
  EXPECT_TRUE(detector.notify_upgrade());
  EXPECT_EQ(1, notifications_listener.notification_count());
  EXPECT_EQ(0, detector.trigger_critical_update_call_count());

  // Execute tasks posted by |detector| referencing it while it's still in
  // scope.
  RunUntilIdle();
  detector.Shutdown();
}

TEST_F(UpgradeDetectorImplTest, VariationsCriticalChanges) {
  TestUpgradeDetectorImpl detector(GetMockClock(), GetMockTickClock());
  TestUpgradeNotificationListener notifications_listener(&detector);
  detector.Init();
  EXPECT_FALSE(detector.notify_upgrade());
  EXPECT_EQ(0, notifications_listener.notification_count());

  // Users are notified about critical updates immediately.
  detector.OnExperimentChangesDetected(
      variations::VariationsService::Observer::CRITICAL);
  EXPECT_TRUE(detector.notify_upgrade());
  EXPECT_EQ(1, notifications_listener.notification_count());
  EXPECT_EQ(1, detector.trigger_critical_update_call_count());

  // Execute tasks posted by |detector| referencing it while it's still in
  // scope.
  RunUntilIdle();

  detector.Shutdown();
}

TEST_F(UpgradeDetectorImplTest, RelaunchFastIfOutdated) {
  SetRelaunchFastIfOutdatedPref(7);

  TestUpgradeDetectorImpl upgrade_detector(GetMockClock(), GetMockTickClock());
  ::testing::StrictMock<MockUpgradeObserver> mock_observer(&upgrade_detector);
  upgrade_detector.Init();

  // Pretend that an upgrade was just detected now. Initially the period is
  // 7 days.
  upgrade_detector.UpgradeDetected(
      TestUpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR);
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            base::Days(7));

  base::Time end_time = base::Time::Now() - base::Days(7) - base::Hours(1);

  // This should've fired off a URL request to the VersionHistory API. After
  // it completes, the period should change to 2 hours.
  GURL version_history_url = GetVersionReleasesUrl(version_info::GetVersion());
  EXPECT_TRUE(GetTestURLLoaderFactory().IsPending(version_history_url.spec()));
  GetTestURLLoaderFactory().AddResponse(
      version_history_url.spec(),
      base::StringPrintf(R"({
        "releases": [{
          "serving": {
            "endTime": "%s"
          }
        }]
      })",
                         base::TimeFormatAsIso8601(end_time)),
      net::HTTP_OK);
  RunUntilIdle();
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            base::Hours(2));

  // Execute tasks posted by |detector| referencing it while it's still in
  // scope.
  RunUntilIdle();
  upgrade_detector.Shutdown();
}

// Tests that the proper notifications are sent for the expected stages as the
// RelaunchNotificationPeriod policy is changed. The period is set to one day,
// such that the thresholds for the annoyance levels are expected to be:
// very low: 1h
// low: 8h
// elevated: 16h
// grace: 23h
// high: 24h
TEST_F(UpgradeDetectorImplTest, TestPeriodChanges) {
  TestUpgradeDetectorImpl upgrade_detector(GetMockClock(), GetMockTickClock());
  ::testing::StrictMock<MockUpgradeObserver> mock_observer(&upgrade_detector);
  upgrade_detector.Init();

  // Pretend that an upgrade was just detected now.
  upgrade_detector.UpgradeDetected(
      TestUpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR);
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            base::Days(7));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_GRACE),
            base::Days(7) - base::Hours(1));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED),
            base::Days(4));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_LOW),
            base::Days(2));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW),
            base::Hours(1));
  ::testing::Mock::VerifyAndClear(&mock_observer);

  // Fast forward an amount that is still in the "don't annoy me" period at the
  // default period.
  FastForwardBy(base::Minutes(59));
  ::testing::Mock::VerifyAndClear(&mock_observer);

  // Drop the period and notice that nothing changes (still below "very low").
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            base::Hours(24));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_GRACE),
            base::Hours(23));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED),
            base::Hours(16));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_LOW),
            base::Hours(8));
  EXPECT_EQ(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW),
            base::Hours(1));
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_NONE);

  // Fast forward to the "very low" annoyance level.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  FastForwardBy(base::Minutes(1));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Drop the period; staying within "very low".
  SetNotificationPeriodPref(base::Days(1));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Bring it back up.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::TimeDelta());
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Fast forward an amount that is still in the "very low" level at the default
  // period.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended()).Times(AnyNumber());
  FastForwardBy(base::Hours(7));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Drop the period so that the current time is in the "low" annoyance level.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_LOW);

  // Bring it back up.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::TimeDelta());
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Fast forward an amount that is still in the "very low" period at the
  // default period.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended()).Times(AnyNumber());
  FastForwardBy(base::Hours(8));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Drop the period so that the current time is in the "elevated" level.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);

  // Bring it back up.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::TimeDelta());
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Fast forward an amount that is still in the "very low" level at the default
  // period.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended()).Times(AnyNumber());
  FastForwardBy(base::Hours(7));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Drop the period so that the current time is in the "grace" level.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);

  // Bring it back up.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::TimeDelta());
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Fast forward an amount that is still in the "very low" level at the default
  // period.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended()).Times(AnyNumber());
  FastForwardBy(base::Hours(1));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Drop the period so that the current time is in the "high" level.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);

  // Expect no new notifications even if some time passes.
  FastForwardBy(base::Hours(1));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);

  // Bring the period back up.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::TimeDelta());
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Fast forward an amount that is still in the "very low" level at the default
  // period.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended()).Times(AnyNumber());
  FastForwardBy(base::Hours(12));
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  // Drop the period so that the current time is deep in the "high" level.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_HIGH);

  // Bring it back up.
  EXPECT_CALL(mock_observer, OnUpgradeRecommended());
  SetNotificationPeriodPref(base::TimeDelta());
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.upgrade_notification_stage(),
            UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);

  upgrade_detector.Shutdown();
}

// Appends the time and stage from detector to |notifications|.
ACTION_P2(AppendTicksAndStage, detector, notifications) {
  notifications->emplace_back(detector->clock()->Now(),
                              detector->upgrade_notification_stage());
}

// A value parameterized test fixture for running tests with different
// RelaunchNotificationPeriod settings.
class UpgradeDetectorImplTimerTest : public UpgradeDetectorImplTest,
                                     public ::testing::WithParamInterface<int> {
 public:
  UpgradeDetectorImplTimerTest(const UpgradeDetectorImplTimerTest&) = delete;
  UpgradeDetectorImplTimerTest& operator=(const UpgradeDetectorImplTimerTest&) =
      delete;

 protected:
  UpgradeDetectorImplTimerTest() {
    const int period_ms = GetParam();
    if (period_ms)
      SetNotificationPeriodPref(base::Milliseconds(period_ms));
  }

 private:
#if !BUILDFLAG(IS_CHROMEOS)
  policy::FakeBrowserDMTokenStorage dm_token_storage_;
#endif  // !BUILDFLAG(IS_CHROMEOS)
};

INSTANTIATE_TEST_SUITE_P(All,
                         UpgradeDetectorImplTimerTest,
                         ::testing::Values(0,           // Default period of 7d.
                                           86400000,    // 1d.
                                           11100000));  // 3:05:00.

// Tests that the notification timer is handled as desired.
TEST_P(UpgradeDetectorImplTimerTest, TestNotificationTimer) {
  using TimeAndStage =
      std::pair<base::Time, UpgradeDetector::UpgradeNotificationAnnoyanceLevel>;
  using Notifications = std::vector<TimeAndStage>;
  static constexpr base::TimeDelta kTwentyMinues = base::Minutes(20);

  TestUpgradeDetectorImpl detector(GetMockClock(), GetMockTickClock());
  ::testing::StrictMock<MockUpgradeObserver> mock_observer(&detector);
  detector.Init();
  // Pretend that an upgrade is detected.
  detector.UpgradeDetected(TestUpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR);

  // Cache the thresholds for the detector's annoyance levels.
  const std::array<base::TimeDelta, 5> thresholds = {
      detector.GetThresholdForLevel(
          UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW),
      detector.GetThresholdForLevel(UpgradeDetector::UPGRADE_ANNOYANCE_LOW),
      detector.GetThresholdForLevel(
          UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED),
      detector.GetThresholdForLevel(UpgradeDetector::UPGRADE_ANNOYANCE_GRACE),
      detector.GetThresholdForLevel(UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
  };
  EXPECT_LE(thresholds[4] - thresholds[3], base::Hours(1));

  ::testing::Mock::VerifyAndClear(&mock_observer);

  // Fast forward to the time that very low annoyance should be reached. One
  // notification should come in at exactly the very low annoyance threshold.
  Notifications notifications;
  EXPECT_CALL(mock_observer, OnUpgradeRecommended())
      .WillOnce(AppendTicksAndStage(&detector, &notifications));
  FastForwardBy(thresholds[0]);
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_THAT(notifications,
              ::testing::ContainerEq(Notifications({TimeAndStage(
                  detector.upgrade_detected_time() + thresholds[0],
                  UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW)})));

  // Move to the time that low annoyance should be reached. Notifications at
  // very low annoyance should arrive every 20 minutes with one final
  // notification at elevated annoyance.
  notifications.clear();
  EXPECT_CALL(mock_observer, OnUpgradeRecommended())
      .WillRepeatedly(AppendTicksAndStage(&detector, &notifications));
  FastForwardBy(thresholds[1] - thresholds[0]);
  ::testing::Mock::VerifyAndClear(&mock_observer);
  if (thresholds[1] - thresholds[0] >= kTwentyMinues) {
    ASSERT_GT(notifications.size(), 1U);
    EXPECT_EQ((notifications.end() - 2)->second,
              UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW);
  } else {
    EXPECT_EQ(notifications.size(), 1U);
  }
  EXPECT_EQ(notifications.back(),
            TimeAndStage(detector.upgrade_detected_time() + thresholds[1],
                         UpgradeDetector::UPGRADE_ANNOYANCE_LOW));

  // Move to the time that elevated annoyance should be reached. Notifications
  // at low annoyance should arrive every 20 minutes with one final notification
  // at elevated annoyance.
  notifications.clear();
  EXPECT_CALL(mock_observer, OnUpgradeRecommended())
      .WillRepeatedly(AppendTicksAndStage(&detector, &notifications));
  FastForwardBy(thresholds[2] - thresholds[1]);
  ::testing::Mock::VerifyAndClear(&mock_observer);
  ASSERT_GT(notifications.size(), 1U);
  EXPECT_EQ((notifications.end() - 2)->second,
            UpgradeDetector::UPGRADE_ANNOYANCE_LOW);
  EXPECT_EQ(notifications.back(),
            TimeAndStage(detector.upgrade_detected_time() + thresholds[2],
                         UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED));

  // Move to the time that grace annoyance level should be reached.
  // Notifications at elevated annoyance should arrive every 20 minutes with one
  // final notification at grace annoyance level.
  notifications.clear();
  EXPECT_CALL(mock_observer, OnUpgradeRecommended())
      .WillRepeatedly(AppendTicksAndStage(&detector, &notifications));
  FastForwardBy(thresholds[3] - thresholds[2]);
  ::testing::Mock::VerifyAndClear(&mock_observer);
  ASSERT_GT(notifications.size(), 1U);
  EXPECT_EQ((notifications.end() - 2)->second,
            UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED);
  EXPECT_EQ(notifications.back(),
            TimeAndStage(detector.upgrade_detected_time() + thresholds[3],
                         UpgradeDetector::UPGRADE_ANNOYANCE_GRACE));

  // Move to the time that high annoyance should be reached. Notifications at
  // grace annoyance level should arrive every 20 minutes with one final
  // notification at high annoyance.
  notifications.clear();
  EXPECT_CALL(mock_observer, OnUpgradeRecommended())
      .WillRepeatedly(AppendTicksAndStage(&detector, &notifications));
  FastForwardBy(thresholds[4] - thresholds[3]);
  ::testing::Mock::VerifyAndClear(&mock_observer);
  ASSERT_GT(notifications.size(), 1U);
  EXPECT_EQ((notifications.end() - 2)->second,
            UpgradeDetector::UPGRADE_ANNOYANCE_GRACE);
  EXPECT_EQ(notifications.back(),
            TimeAndStage(detector.upgrade_detected_time() + thresholds[4],
                         UpgradeDetector::UPGRADE_ANNOYANCE_HIGH));

  // No new notifications after high annoyance has been reached.
  FastForwardBy(thresholds[4]);
  ::testing::Mock::VerifyAndClear(&mock_observer);

  detector.Shutdown();
}

// Tests that the thresholds are adjusted according to the value of the relaunch
// window policy when default relaunch notification period is used.
TEST_F(UpgradeDetectorImplTest, TestDeadlineAdjustmentDefaultPeriod) {
  TestUpgradeDetectorImpl upgrade_detector(GetMockClock(), GetMockTickClock());
  ::testing::StrictMock<MockUpgradeObserver> mock_observer(&upgrade_detector);

  upgrade_detector.Init();
  SetRelaunchWindowPref(/*hour=*/7, /*minute=*/30, /*duration_mins=*/180);
  RunUntilIdle();

  // Set a custom time to be used as upgrade detected time.
  base::Time detect_time;
  ASSERT_TRUE(base::Time::FromString("1 Jan 2018 06:00", &detect_time));
  upgrade_detector.set_upgrade_detected_time(detect_time);
  upgrade_detector.UpgradeDetected(
      TestUpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR);

  // Deadline is adjusted to fall within relaunch window.
  base::Time deadline_lower_border, deadline_upper_border;
  ASSERT_TRUE(
      base::Time::FromString("8 Jan 2018 07:30", &deadline_lower_border));
  ASSERT_TRUE(
      base::Time::FromString("8 Jan 2018 10:30", &deadline_upper_border));
  EXPECT_GE(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_lower_border - detect_time);
  EXPECT_LT(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_upper_border - detect_time);
  ::testing::Mock::VerifyAndClear(&mock_observer);

  // Change in relaunch window preference forces to re-calculate the deadline to
  // fall within the new time interval.
  SetRelaunchWindowPref(/*hour=*/12, /*minute=*/30, /*duration_mins=*/120);
  RunUntilIdle();
  ASSERT_TRUE(
      base::Time::FromString("8 Jan 2018 12:30", &deadline_lower_border));
  ASSERT_TRUE(
      base::Time::FromString("8 Jan 2018 14:30", &deadline_upper_border));
  EXPECT_GE(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_lower_border - detect_time);
  EXPECT_LT(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_upper_border - detect_time);
  ::testing::Mock::VerifyAndClear(&mock_observer);

  upgrade_detector.Shutdown();
}

// Tests that the thresholds are adjusted according to the value of the relaunch
// window policy when a custom relaunch notification period is specified.
TEST_F(UpgradeDetectorImplTest, TestDeadlineAdjustmentCustomPeriod) {
  TestUpgradeDetectorImpl upgrade_detector(GetMockClock(), GetMockTickClock());
  ::testing::StrictMock<MockUpgradeObserver> mock_observer(&upgrade_detector);

  upgrade_detector.Init();
  SetNotificationPeriodPref(base::Days(5));
  SetRelaunchWindowPref(/*hour=*/7, /*minute=*/30, /*duration_mins=*/180);
  RunUntilIdle();

  // Set a custom time to be used as upgrade detected time.
  base::Time detect_time;
  ASSERT_TRUE(base::Time::FromString("5 Jan 2018 16:00", &detect_time));
  upgrade_detector.set_upgrade_detected_time(detect_time);
  upgrade_detector.UpgradeDetected(
      TestUpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR);

  // Deadline is adjusted to fall within relaunch window on next day.
  base::Time deadline_lower_border, deadline_upper_border;
  ASSERT_TRUE(
      base::Time::FromString("11 Jan 2018 07:30", &deadline_lower_border));
  ASSERT_TRUE(
      base::Time::FromString("11 Jan 2018 10:30", &deadline_upper_border));
  EXPECT_GE(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_lower_border - detect_time);
  EXPECT_LT(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_upper_border - detect_time);
  ::testing::Mock::VerifyAndClear(&mock_observer);

  // Change in relaunch window preference forces to re-calculate the deadline to
  // fall within the new time interval.
  SetRelaunchWindowPref(/*hour=*/20, /*minute=*/30, /*duration_mins=*/120);
  RunUntilIdle();
  ASSERT_TRUE(
      base::Time::FromString("10 Jan 2018 20:30", &deadline_lower_border));
  ASSERT_TRUE(
      base::Time::FromString("10 Jan 2018 22:30", &deadline_upper_border));
  EXPECT_GE(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_lower_border - detect_time);
  EXPECT_LT(upgrade_detector.GetThresholdForLevel(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            deadline_upper_border - detect_time);
  ::testing::Mock::VerifyAndClear(&mock_observer);

  upgrade_detector.Shutdown();
}

// Tests correct deadlines are set when an upgrade is detected.
TEST_F(UpgradeDetectorImplTest, AnnoyanceLevelDeadlines) {
  TestUpgradeDetectorImpl upgrade_detector(GetMockClock(), GetMockTickClock());
  ::testing::StrictMock<MockUpgradeObserver> mock_observer(&upgrade_detector);
  upgrade_detector.Init();

  // Deadline not set before upgrade detected.
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            base::Time());

  // Pretend that an upgrade was just detected now.
  upgrade_detector.UpgradeDetected(
      TestUpgradeDetectorImpl::UPGRADE_AVAILABLE_REGULAR);
  base::Time detect_time = upgrade_detector.upgrade_detected_time();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            detect_time + base::Days(7));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_GRACE),
            detect_time + base::Days(7) - base::Hours(1));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED),
            detect_time + base::Days(4));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_LOW),
            detect_time + base::Days(2));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW),
            detect_time + base::Hours(1));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_NONE),
            detect_time);

  // Drop the period and notice change in the deadlines.
  SetNotificationPeriodPref(base::Days(1));
  RunUntilIdle();
  ::testing::Mock::VerifyAndClear(&mock_observer);
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_HIGH),
            detect_time + base::Hours(24));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_GRACE),
            detect_time + base::Hours(23));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_ELEVATED),
            detect_time + base::Hours(16));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_LOW),
            detect_time + base::Hours(8));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_VERY_LOW),
            detect_time + base::Hours(1));
  EXPECT_EQ(upgrade_detector.GetAnnoyanceLevelDeadline(
                UpgradeDetector::UPGRADE_ANNOYANCE_NONE),
            detect_time);

  upgrade_detector.Shutdown();
}