File: report_scheduler_timer_unittest.cc

package info (click to toggle)
chromium 142.0.7444.175-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,295,352 kB
  • sloc: cpp: 35,488,378; ansic: 7,479,680; javascript: 4,259,373; python: 1,466,843; xml: 757,444; asm: 710,716; pascal: 187,980; sh: 89,247; perl: 88,690; objc: 79,984; sql: 56,984; cs: 42,192; fortran: 24,137; makefile: 22,913; tcl: 15,277; php: 14,018; yacc: 9,005; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (273 lines) | stat: -rw-r--r-- 7,947 bytes parent folder | download | duplicates (7)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/aggregation_service/report_scheduler_timer.h"

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

#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/gmock_move_support.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "build/buildflag.h"
#include "services/network/public/mojom/network_change_manager.mojom.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_ANDROID)
#include "base/android/application_status_listener.h"
#endif

namespace content {

namespace {

using testing::_;
using testing::InSequence;

using Checkpoint = testing::MockFunction<void(int step)>;

constexpr auto kExampleTime =
    base::Time::FromMillisecondsSinceUnixEpoch(1652984901234);

class MockReportSchedulerTimerDelegate : public ReportSchedulerTimer::Delegate {
 public:
  MOCK_METHOD(void,
              GetNextReportTime,
              (base::OnceCallback<void(std::optional<base::Time>)>, base::Time),
              (override));
  MOCK_METHOD(void,
              OnReportingTimeReached,
              (base::Time, base::Time),
              (override));

  MOCK_METHOD(void,
              AdjustOfflineReportTimes,
              (base::OnceCallback<void(std::optional<base::Time>)>),
              (override));
};

class ReportSchedulerTimerTest : public testing::Test {
 public:
  void SetUp() override {
    auto timer_delegate = std::make_unique<MockReportSchedulerTimerDelegate>();
    timer_delegate_ = timer_delegate.get();
    timer_ = std::make_unique<ReportSchedulerTimer>(std::move(timer_delegate));
  }

 protected:
  base::test::TaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};

  // Must outlive `timer_delegate_`.
  std::unique_ptr<ReportSchedulerTimer> timer_;

  raw_ptr<MockReportSchedulerTimerDelegate> timer_delegate_;
};

TEST_F(ReportSchedulerTimerTest, SetTimer_FiredAtAppropriateTime) {
  Checkpoint checkpoint;
  {
    InSequence seq;

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached).Times(0);

    EXPECT_CALL(checkpoint, Call(1));

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached);
    EXPECT_CALL(*timer_delegate_, GetNextReportTime);  // Called via Refresh().
  }

  timer_->MaybeSet(kExampleTime);

  base::TimeDelta fast_forward_required = kExampleTime - base::Time::Now();
  task_environment_.FastForwardBy(fast_forward_required - base::Seconds(1));

  checkpoint.Call(1);

  task_environment_.FastForwardBy(base::Seconds(1));
}

TEST_F(ReportSchedulerTimerTest, MultipleSetTimers_FiredAtAppropriateTime) {
  Checkpoint checkpoint;
  base::OnceCallback<void(std::optional<base::Time>)> saved_cb_1;
  base::OnceCallback<void(std::optional<base::Time>)> saved_cb_2;

  {
    InSequence seq;

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached).Times(0);

    EXPECT_CALL(checkpoint, Call(1));

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached);
    EXPECT_CALL(*timer_delegate_, GetNextReportTime)
        .WillOnce(MoveArg<0>(&saved_cb_1));  // Called via Refresh().

    EXPECT_CALL(checkpoint, Call(2));

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached).Times(0);

    EXPECT_CALL(checkpoint, Call(3));

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached);
    EXPECT_CALL(*timer_delegate_, GetNextReportTime)
        .WillOnce(MoveArg<0>(&saved_cb_2));  // Called via Refresh().

    EXPECT_CALL(checkpoint, Call(4));
  }
  // Test both simultaneous and non-simultaneous times.
  const base::Time kReportTimes[] = {kExampleTime, kExampleTime,
                                     kExampleTime + base::Hours(1)};

  for (base::Time report_time : kReportTimes) {
    timer_->MaybeSet(report_time);
  }

  checkpoint.Call(1);

  task_environment_.FastForwardBy(kExampleTime - base::Time::Now());

  checkpoint.Call(2);

  std::move(saved_cb_1).Run(kExampleTime + base::Hours(1));

  checkpoint.Call(3);

  task_environment_.FastForwardBy(base::Hours(1));

  checkpoint.Call(4);

  // Nothing should happen if no reports are left.
  std::move(saved_cb_2).Run(std::nullopt);
}

TEST_F(ReportSchedulerTimerTest, NetworkChange) {
  base::RunLoop run_loop;

  Checkpoint checkpoint;
  {
    InSequence seq;

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached).Times(0);
    EXPECT_CALL(checkpoint, Call(1));
    EXPECT_CALL(*timer_delegate_, AdjustOfflineReportTimes).WillOnce([&](auto) {
      run_loop.Quit();
    });
  }

  timer_->MaybeSet(kExampleTime);

  // Go offline
  network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType(
      network::mojom::ConnectionType::CONNECTION_NONE);

  task_environment_.FastForwardBy(kExampleTime - base::Time::Now());

  checkpoint.Call(1);

  // Go back online.
  network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType(
      network::mojom::ConnectionType::CONNECTION_WIFI);

  run_loop.Run();
}

// TODO(apaseltiner): Figure out how to test the case in which the network
// connection tracker is uninitialized.
TEST(ReportSchedulerTimer, Constructor_AdjustsOfflineReportTimes) {
  constexpr struct {
    network::mojom::ConnectionType connection_type;
    bool call_expected;
  } kTestCases[] = {
      // Call is skipped because the browser is offline.
      {
          network::mojom::ConnectionType::CONNECTION_NONE,
          false,
      },
      // Call is made because the browser is online.
      {
          network::mojom::ConnectionType::CONNECTION_ETHERNET,
          true,
      },
  };

  for (const auto& test_case : kTestCases) {
    for (bool synchronous : {true, false}) {
      base::test::TaskEnvironment task_environment{
          base::test::TaskEnvironment::TimeSource::MOCK_TIME};

      auto* tracker = network::TestNetworkConnectionTracker::GetInstance();
      tracker->SetRespondSynchronously(synchronous);
      tracker->SetConnectionType(test_case.connection_type);

      auto timer_delegate =
          std::make_unique<MockReportSchedulerTimerDelegate>();

      EXPECT_CALL(*timer_delegate, AdjustOfflineReportTimes)
          .Times(test_case.call_expected);

      ReportSchedulerTimer timer(std::move(timer_delegate));

      // Flush the async call.
      if (!synchronous) {
        task_environment.RunUntilIdle();
      }
    }
  }
}

#if BUILDFLAG(IS_ANDROID)
class ObserveAppStateReportSchedulerTimerTest
    : public ReportSchedulerTimerTest {
 public:
  void SetUp() override {
    auto timer_delegate = std::make_unique<MockReportSchedulerTimerDelegate>();
    timer_delegate_ = timer_delegate.get();
    timer_ = std::make_unique<ReportSchedulerTimer>(std::move(timer_delegate),
                                                    /*observe_app_state=*/true);
  }
};

TEST_F(ObserveAppStateReportSchedulerTimerTest, AndroidAppStatus) {
  base::RunLoop run_loop;

  Checkpoint checkpoint;
  {
    InSequence seq;

    EXPECT_CALL(*timer_delegate_, OnReportingTimeReached).Times(0);
    EXPECT_CALL(checkpoint, Call(1));
    EXPECT_CALL(*timer_delegate_, AdjustOfflineReportTimes).WillOnce([&](auto) {
      run_loop.Quit();
    });
  }

  timer_->MaybeSet(kExampleTime);

  // Go offline
  base::android::ApplicationStatusListener::NotifyApplicationStateChange(
      base::android::APPLICATION_STATE_HAS_STOPPED_ACTIVITIES);

  task_environment_.FastForwardBy(kExampleTime - base::Time::Now());

  checkpoint.Call(1);

  // Go back online.
  base::android::ApplicationStatusListener::NotifyApplicationStateChange(
      base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES);

  run_loop.Run();
}
#endif  // BUILDFLAG(IS_ANDROID)

}  // namespace

}  // namespace content