File: affiliation_fetch_throttler_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 (478 lines) | stat: -rw-r--r-- 20,214 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
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/affiliations/core/browser/affiliation_fetch_throttler.h"

#include <stddef.h>
#include <stdint.h>

#include <cmath>
#include <memory>
#include <optional>

#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/safe_math.h"
#include "base/test/task_environment.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "components/affiliations/core/browser/affiliation_fetch_throttler_delegate.h"
#include "net/base/net_errors.h"
#include "net/http/http_status_code.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace affiliations {
namespace {

class MockAffiliationFetchThrottlerDelegate
    : public AffiliationFetchThrottlerDelegate {
 public:
  // The |tick_clock| should outlive this instance.
  explicit MockAffiliationFetchThrottlerDelegate(
      const base::TickClock* tick_clock)
      : tick_clock_(tick_clock),
        emulated_return_value_(true),
        can_send_count_(0u) {}

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

  ~MockAffiliationFetchThrottlerDelegate() override {
    EXPECT_EQ(0u, can_send_count_);
  }

  void set_emulated_return_value(bool value) { emulated_return_value_ = value; }
  void reset_can_send_count() { can_send_count_ = 0u; }
  size_t can_send_count() const { return can_send_count_; }
  base::TimeTicks last_can_send_time() const { return last_can_send_time_; }

  // AffiliationFetchThrottlerDelegate:
  bool OnCanSendNetworkRequest() override {
    ++can_send_count_;
    last_can_send_time_ = tick_clock_->NowTicks();
    return emulated_return_value_;
  }

 private:
  raw_ptr<const base::TickClock> tick_clock_;
  bool emulated_return_value_;
  size_t can_send_count_;
  base::TimeTicks last_can_send_time_;
};

}  // namespace

class AffiliationFetchThrottlerTest : public testing::Test {
 public:
  AffiliationFetchThrottlerTest() { SimulateHasNetworkConnectivity(true); }

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

  std::unique_ptr<AffiliationFetchThrottler> CreateThrottler() {
    return std::make_unique<AffiliationFetchThrottler>(
        &mock_delegate_, task_runner_,
        network::TestNetworkConnectionTracker::GetInstance(),
        task_runner_->GetMockTickClock());
  }

  void SimulateHasNetworkConnectivity(bool has_connectivity) {
    network::TestNetworkConnectionTracker::GetInstance()->SetConnectionType(
        has_connectivity ? network::mojom::ConnectionType::CONNECTION_ETHERNET
                         : network::mojom::ConnectionType::CONNECTION_NONE);
    task_environment_.RunUntilIdle();
  }

  // Runs the task runner until no tasks remain, and asserts that by this time,
  // OnCanSendNetworkRequest() will have been called exactly once, with a delay
  // between |min_delay_ms| and |max_delay_ms|, modulo 0.5 ms to allow for
  // floating point errors. When OnCanSendNetworkRequest() is called, the mock
  // will return |emulated_return_value|. This value normally indicates whether
  // or not a request was actually issued in response to the call.
  void AssertReleaseInBetween(bool emulated_return_value,
                              double min_delay_ms,
                              double max_delay_ms) {
    ASSERT_EQ(0u, mock_delegate_.can_send_count());
    base::TimeTicks ticks_at_start = task_runner_->NowTicks();
    mock_delegate_.set_emulated_return_value(emulated_return_value);
    task_runner_->FastForwardUntilNoTasksRemain();
    ASSERT_EQ(1u, mock_delegate_.can_send_count());
    base::TimeDelta delay =
        mock_delegate_.last_can_send_time() - ticks_at_start;
    EXPECT_LE(min_delay_ms - 1, delay.InMillisecondsF());
    EXPECT_GE(max_delay_ms + 1, delay.InMillisecondsF());
    mock_delegate_.reset_can_send_count();
  }

  // Runs the task runner for |secs| and asserts that OnCanSendNetworkRequest()
  // will not have been called by the end of this period.
  void AssertNoReleaseForSecs(int64_t secs) {
    task_runner_->FastForwardBy(base::Seconds(secs));
    ASSERT_EQ(0u, mock_delegate_.can_send_count());
  }

  // Runs the task runner until no tasks remain, and asserts that
  // OnCanSendNetworkRequest() will not have been called.
  void AssertNoReleaseUntilNoTasksRemain() {
    task_runner_->FastForwardUntilNoTasksRemain();
    ASSERT_EQ(0u, mock_delegate_.can_send_count());
  }

  size_t GetPendingTaskCount() const {
    return task_runner_->GetPendingTaskCount();
  }

 private:
  // Needed because NetworkConnectionTracker uses base::ObserverList, which
  // notifies observers on the sequence from which they have registered.
  base::test::TaskEnvironment task_environment_;
  scoped_refptr<base::TestMockTimeTaskRunner> task_runner_ =
      base::MakeRefCounted<base::TestMockTimeTaskRunner>();
  MockAffiliationFetchThrottlerDelegate mock_delegate_{
      task_runner_->GetMockTickClock()};
};

TEST_F(AffiliationFetchThrottlerTest, SuccessfulRequests) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));

  // Signal while request is in flight should be ignored.
  throttler->SignalNetworkRequestNeeded();
  AssertNoReleaseUntilNoTasksRemain();
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);
  AssertNoReleaseUntilNoTasksRemain();

  // Duplicate the second signal 3 times: still only 1 callback should arrive.
  throttler->SignalNetworkRequestNeeded();
  throttler->SignalNetworkRequestNeeded();
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
}

TEST_F(AffiliationFetchThrottlerTest, FailedRequests) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  // The request after the first failure should be delayed by |initial_delay_ms|
  // spread out over Uniform(1 - |jitter_factor|, 1).
  throttler->SignalNetworkRequestNeeded();
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kPolicy.initial_delay_ms * (1 - kPolicy.jitter_factor),
      kPolicy.initial_delay_ms));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);

  // After a successful request, the next one should be released immediately.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  // In general, the request after the n-th failure should be delayed by
  //   |multiply_factor| ^ (n-1) * |initial_delay_ms|,
  // spread out over Uniform(1 - |jitter_factor|, 1), up until
  //   |maximum_backoff_ms|
  // is reached.
  for (int num_failures = 1; num_failures < 100; ++num_failures) {
    throttler->SignalNetworkRequestNeeded();
    double max_delay_ms = kPolicy.initial_delay_ms *
                          pow(kPolicy.multiply_factor, num_failures - 1);
    double min_delay_ms = max_delay_ms * (1 - kPolicy.jitter_factor);
    if (max_delay_ms > kPolicy.maximum_backoff_ms)
      max_delay_ms = kPolicy.maximum_backoff_ms;
    if (min_delay_ms > kPolicy.maximum_backoff_ms)
      min_delay_ms = kPolicy.maximum_backoff_ms;
    ASSERT_NO_FATAL_FAILURE(
        AssertReleaseInBetween(true, min_delay_ms, max_delay_ms));
    throttler->InformOfNetworkRequestComplete(false, std::nullopt);
  }
}

TEST_F(AffiliationFetchThrottlerTest, NonRetryableFailedRequestsSetLongDelay) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, net::HTTP_TOO_MANY_REQUESTS);

  // The request after a non-retryable failure should be delayed by
  // |kBackoffAfterNonRetryableErrorHours|
  throttler->SignalNetworkRequestNeeded();
  const auto& non_retryable_delay_in_ms =
      AffiliationFetchThrottler::kBackoffAfterNonRetryableErrorHours * 60 * 60 *
      1000;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, non_retryable_delay_in_ms, non_retryable_delay_in_ms));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);

  // After a successful request, the next one should be released immediately.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, net::HTTP_TOO_MANY_REQUESTS);

  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  // In general, non-retryable errors still contribute to the number of failed
  // requests and thus to the delay set by the backoff policy. This means that
  // a non-retryable error will effectively set a minimum delay.
  for (int num_failures = 1; num_failures < 100; ++num_failures) {
    throttler->SignalNetworkRequestNeeded();
    double max_delay_ms = kPolicy.initial_delay_ms *
                          pow(kPolicy.multiply_factor, num_failures - 1);
    double min_delay_ms = max_delay_ms * (1 - kPolicy.jitter_factor);
    if (max_delay_ms > kPolicy.maximum_backoff_ms) {
      max_delay_ms = kPolicy.maximum_backoff_ms;
    }
    if (min_delay_ms > kPolicy.maximum_backoff_ms) {
      min_delay_ms = kPolicy.maximum_backoff_ms;
    }
    if (max_delay_ms < non_retryable_delay_in_ms) {
      max_delay_ms = non_retryable_delay_in_ms;
    }
    if (min_delay_ms < non_retryable_delay_in_ms) {
      min_delay_ms = non_retryable_delay_in_ms;
    }
    ASSERT_NO_FATAL_FAILURE(
        AssertReleaseInBetween(true, min_delay_ms, max_delay_ms));
    throttler->InformOfNetworkRequestComplete(false,
                                              net::HTTP_TOO_MANY_REQUESTS);
  }
}

TEST_F(AffiliationFetchThrottlerTest, OnCanSendNetworkRequestReturnsFalse) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  // A need for a network request is signaled, but as OnCanSendNetworkRequest()
  // is called, the implementation returns false to indicate that the request
  // will not be needed after all. InformOfNetworkRequestComplete() must not be
  // called in this case.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(false, 0, 0));

  // A subsequent signaling, however, should result in OnCanSendNetworkRequest()
  // being called immediately.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
}

TEST_F(AffiliationFetchThrottlerTest, GracePeriodAfterConnectivityIsRestored) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());
  SimulateHasNetworkConnectivity(false);

  // After connectivity is restored, the first request should be delayed by the
  // grace period, spread out over Uniform(1 - |jitter_factor|, 1).
  throttler->SignalNetworkRequestNeeded();
  AssertNoReleaseUntilNoTasksRemain();

  SimulateHasNetworkConnectivity(true);
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kGraceMs * (1 - kPolicy.jitter_factor), kGraceMs));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);

  // The next request should not be delayed.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
}

// Same as GracePeriodAfterConnectivityIsRestored, but the network comes back
// just before SignalNetworkRequestNeeded() is called.
TEST_F(AffiliationFetchThrottlerTest, GracePeriodAfterConnectivityIsRestored2) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());
  SimulateHasNetworkConnectivity(false);

  SimulateHasNetworkConnectivity(true);
  throttler->SignalNetworkRequestNeeded();
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kGraceMs * (1 - kPolicy.jitter_factor), kGraceMs));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
}

TEST_F(AffiliationFetchThrottlerTest, ConnectivityLostDuringBackoff) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  throttler->SignalNetworkRequestNeeded();
  SimulateHasNetworkConnectivity(false);

  // Let the exponential backoff delay expire, and verify nothing happens.
  AssertNoReleaseUntilNoTasksRemain();

  // Verify that the request is, however, sent after the normal grace period
  // once connectivity is restored.
  SimulateHasNetworkConnectivity(true);
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kGraceMs * (1 - kPolicy.jitter_factor), kGraceMs));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);
}

TEST_F(AffiliationFetchThrottlerTest,
       ConnectivityLostAndRestoredDuringBackoff) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  throttler->SignalNetworkRequestNeeded();
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kPolicy.initial_delay_ms * (1 - kPolicy.jitter_factor),
      kPolicy.initial_delay_ms));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  SimulateHasNetworkConnectivity(false);
  SimulateHasNetworkConnectivity(true);

  // This test expects that the exponential backoff interval after the 2nd error
  // is larger than the normal grace period after connectivity is restored.
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  EXPECT_PRED_FORMAT2(testing::DoubleLE, kGraceMs,
                      kPolicy.initial_delay_ms * kPolicy.multiply_factor);

  // The release should come after the longest of the two intervals expire.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kPolicy.initial_delay_ms * kPolicy.multiply_factor *
                (1 - kPolicy.jitter_factor),
      kPolicy.initial_delay_ms * kPolicy.multiply_factor));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);
}

TEST_F(AffiliationFetchThrottlerTest, FlakyConnectivity) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  // Run for a total of 5 grace periods and simulate connectivity being lost and
  // restored every second. This verifies that a flaky connection will not flood
  // the task queue with lots of of tasks and also that release will not happen
  // while the connection is flaky even once the first grace period has expired.
  throttler->SignalNetworkRequestNeeded();
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  int64_t five_grace_periods_secs =
      kGraceMs * 5 / base::Time::kMillisecondsPerSecond;
  for (int64_t t = 0; t < five_grace_periods_secs; ++t) {
    SimulateHasNetworkConnectivity(false);
    AssertNoReleaseForSecs(1);
    SimulateHasNetworkConnectivity(true);
    EXPECT_EQ(1u, GetPendingTaskCount());
  }
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kGraceMs * (1 - kPolicy.jitter_factor), kGraceMs));
}

TEST_F(AffiliationFetchThrottlerTest, ConnectivityLostDuringRequest) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));

  SimulateHasNetworkConnectivity(false);
  AssertNoReleaseUntilNoTasksRemain();
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);
  AssertNoReleaseUntilNoTasksRemain();
  throttler->SignalNetworkRequestNeeded();
  AssertNoReleaseUntilNoTasksRemain();

  SimulateHasNetworkConnectivity(true);

  // Verify that the next request is released after the normal grace period.
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kGraceMs * (1 - kPolicy.jitter_factor), kGraceMs));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);
}

TEST_F(AffiliationFetchThrottlerTest,
       ConnectivityLostAndRestoredDuringRequest) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));

  SimulateHasNetworkConnectivity(false);
  AssertNoReleaseUntilNoTasksRemain();
  SimulateHasNetworkConnectivity(true);
  AssertNoReleaseUntilNoTasksRemain();
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);

  // Even though the previous request succeeded, the next request should still
  // be held back for the normal grace period after connection is restored.
  throttler->SignalNetworkRequestNeeded();
  const auto& kPolicy = AffiliationFetchThrottler::kBackoffPolicy;
  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(
      true, kGraceMs * (1 - kPolicy.jitter_factor), kGraceMs));
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);
}

TEST_F(AffiliationFetchThrottlerTest,
       ConnectivityLostAndRestoredDuringRequest2) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));

  SimulateHasNetworkConnectivity(false);
  AssertNoReleaseUntilNoTasksRemain();
  SimulateHasNetworkConnectivity(true);

  const int64_t& kGraceMs =
      AffiliationFetchThrottler::kGracePeriodAfterReconnectMs;
  AssertNoReleaseForSecs(kGraceMs / base::Time::kMillisecondsPerSecond);
  throttler->InformOfNetworkRequestComplete(true, net::HTTP_OK);

  // The next request should not be held back.
  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
}

TEST_F(AffiliationFetchThrottlerTest, InstanceDestroyedWhileInBackoff) {
  std::unique_ptr<AffiliationFetchThrottler> throttler(CreateThrottler());

  throttler->SignalNetworkRequestNeeded();
  ASSERT_NO_FATAL_FAILURE(AssertReleaseInBetween(true, 0, 0));
  throttler->InformOfNetworkRequestComplete(false, std::nullopt);

  throttler->SignalNetworkRequestNeeded();
  throttler.reset();
  // We expect the task to be cancelled.
  EXPECT_EQ(0u, GetPendingTaskCount());
  AssertNoReleaseUntilNoTasksRemain();
}

}  // namespace affiliations