File: safety_hub_service_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (239 lines) | stat: -rw-r--r-- 8,013 bytes parent folder | download | duplicates (6)
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
// Copyright 2023 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/safety_hub/safety_hub_service.h"

#include <memory>
#include <string>
#include <utility>

#include "base/json/values_util.h"
#include "base/observer_list_types.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/ui/safety_hub/safety_hub_test_util.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/testing_profile.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {
constexpr base::TimeDelta kUpdateIntervalForTest = base::Days(7);

class MockSafetyHubResult : public SafetyHubService::Result {
 public:
  explicit MockSafetyHubResult(base::Time timestamp = base::Time::Now())
      : SafetyHubService::Result(timestamp) {}
  ~MockSafetyHubResult() override = default;

  std::unique_ptr<SafetyHubService::Result> Clone() const override {
    return std::make_unique<MockSafetyHubResult>(*this);
  }

  base::Value::Dict ToDictValue() const override { return BaseToDictValue(); }

  bool IsTriggerForMenuNotification() const override { return true; }

  bool WarrantsNewMenuNotification(
      const base::Value::Dict& previousResult) const override {
    return true;
  }

  std::u16string GetNotificationString() const override {
    return std::u16string();
  }

  int GetNotificationCommandId() const override { return 0; }

  int GetVal() const { return val_; }

  void SetVal(int val) { val_ = val; }

  void IncreaseVal() { ++val_; }

 private:
  int val_ = 0;
};

class MockSafetyHubService : public SafetyHubService {
 public:
  MockSafetyHubService() {
    // Note: for testing purposes, the repeated updates are not started in the
    // constructor.

    InitializeLatestResult();
  }

  // Returns the number of times that the UpdateOnBackgroundThread function was
  // called.
  int GetNumBackgroundUpdates() const { return num_updates_background_; }

  // Returns the number of times that the UpdateOnBackgroundThread function was
  // called.
  int GetNumUIUpdates() const { return num_updates_ui_; }

  // Set the latest result to a specific value - 42 in this case.
  std::unique_ptr<SafetyHubService::Result> InitializeLatestResultImpl()
      override {
    auto init_result = std::make_unique<MockSafetyHubResult>();
    init_result->SetVal(42);
    return init_result;
  }

 protected:
  // For testing purposes, the UpdateOnBackgroundThread function will be
  // executed every seven days.
  base::TimeDelta GetRepeatedUpdateInterval() override {
    return kUpdateIntervalForTest;
  }

  base::OnceCallback<std::unique_ptr<Result>()> GetBackgroundTask() override {
    auto init_result = std::make_unique<MockSafetyHubResult>();
    return base::BindOnce(&UpdateOnBackgroundThread, std::move(init_result));
  }

  static std::unique_ptr<Result> UpdateOnBackgroundThread(
      std::unique_ptr<Result> result) {
    auto background_result = std::make_unique<MockSafetyHubResult>();
    background_result->IncreaseVal();
    return background_result;
  }

  std::unique_ptr<SafetyHubService::Result> UpdateOnUIThread(
      std::unique_ptr<Result> result) override {
    num_updates_background_ +=
        static_cast<MockSafetyHubResult*>(result.get())->GetVal();
    ++num_updates_ui_;
    return std::make_unique<MockSafetyHubResult>();
  }

  base::WeakPtr<SafetyHubService> GetAsWeakRef() override {
    return weak_factory_.GetWeakPtr();
  }

 private:
  int num_updates_background_ = 0;
  int num_updates_ui_ = 0;

  base::WeakPtrFactory<MockSafetyHubService> weak_factory_{this};
};

class MockObserver : public SafetyHubService::Observer {
 public:
  void OnResultAvailable(const SafetyHubService::Result* result) override {
    ++num_calls_;
    if (callback_) {
      callback_.Run();
    }
  }

  void SetCallback(const base::RepeatingClosure& callback) {
    callback_ = callback;
  }

  // Returns the number of times that the observer was notified.
  int GetNumCalls() const { return num_calls_; }

 private:
  int num_calls_ = 0;
  base::RepeatingClosure callback_;
};

}  // namespace

class SafetyHubServiceTest : public testing::Test {
 public:
  SafetyHubServiceTest() = default;
  ~SafetyHubServiceTest() override = default;

  void SetUp() override { service_ = std::make_unique<MockSafetyHubService>(); }

  void TearDown() override { service_->Shutdown(); }

 protected:
  void FastForwardBy(base::TimeDelta delta) {
    task_environment_.FastForwardBy(delta);
  }

  MockSafetyHubService* service() { return service_.get(); }

 private:
  std::unique_ptr<MockSafetyHubService> service_;

  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
};

TEST_F(SafetyHubServiceTest, ManageObservers) {
  auto observer = std::make_unique<MockObserver>();
  // The list of observers should initially be empty.
  EXPECT_FALSE(service()->observers_.HasObserver(observer.get()));
  service()->AddObserver(observer.get());
  // After adding the observer, the observer should be registered in the list of
  // observers, but should not be called yet.
  EXPECT_TRUE(service()->observers_.HasObserver(observer.get()));
  EXPECT_EQ(observer->GetNumCalls(), 0);
  auto result = std::make_unique<MockSafetyHubResult>();
  // Notify all observers.
  service()->NotifyObservers(result.get());
  // Ensure that the observer was called just once.
  EXPECT_EQ(observer->GetNumCalls(), 1);
  service()->NotifyObservers(result.get());
  // Ensure that the observer was called again.
  EXPECT_EQ(observer->GetNumCalls(), 2);
  service()->RemoveObserver(observer.get());
  // The observer should be removed from the list of observers, and not get
  // called again when observers are notified.
  EXPECT_FALSE(service()->observers_.HasObserver(observer.get()));
  service()->NotifyObservers(result.get());
  EXPECT_EQ(observer->GetNumCalls(), 2);
}

TEST_F(SafetyHubServiceTest, UpdateOnBackgroundThread) {
  EXPECT_EQ(service()->GetNumUIUpdates(), 0);
  EXPECT_EQ(service()->GetNumBackgroundUpdates(), 0);
  // As long as StartRepeatedUpdates() has not been called, no updates should
  // be made.
  FastForwardBy(kUpdateIntervalForTest);
  EXPECT_EQ(service()->GetNumUIUpdates(), 0);
  EXPECT_EQ(service()->GetNumBackgroundUpdates(), 0);
  // The update will be run asynchronously as soon as StartRepeatedUpdates() is
  // called.
  base::RunLoop loop;
  auto observer = std::make_shared<MockObserver>();
  observer->SetCallback(loop.QuitClosure());
  service()->AddObserver(observer.get());
  service()->StartRepeatedUpdates();
  loop.Run();
  EXPECT_EQ(service()->GetNumUIUpdates(), 1);
  EXPECT_EQ(service()->GetNumBackgroundUpdates(), 1);
  // Move forward a full update interval, which will trigger another update.
  base::RunLoop loop2;
  observer->SetCallback(loop2.QuitClosure());
  FastForwardBy(kUpdateIntervalForTest);
  loop2.Run();
  EXPECT_EQ(service()->GetNumUIUpdates(), 2);
  EXPECT_EQ(service()->GetNumBackgroundUpdates(), 2);
}

TEST_F(SafetyHubServiceTest, GetCachedResult) {
  // The mock service initializes the latest result on construction, so its
  // value should be those that we'd expect.
  std::optional<std::unique_ptr<SafetyHubService::Result>> opt_result =
      service()->GetCachedResult();
  EXPECT_TRUE(opt_result.has_value());
  MockSafetyHubResult* result =
      static_cast<MockSafetyHubResult*>(opt_result.value().get());
  EXPECT_EQ(result->GetVal(), 42);
}

TEST_F(SafetyHubServiceTest, ResultBaseToDict) {
  base::Time time = base::Time::Now() - base::Days(5);
  auto result = std::make_unique<MockSafetyHubResult>(time);
  EXPECT_EQ(result->timestamp(), time);
  // The timestamp saved in the dict should be the Value of time.
  base::Value::Dict dict = result->ToDictValue();
  EXPECT_EQ(*dict.Find(kSafetyHubTimestampResultKey), base::TimeToValue(time));
}