backoff_timer_unittest.cc 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "remoting/host/backoff_timer.h"
  5. #include "base/bind.h"
  6. #include "base/test/task_environment.h"
  7. #include "base/time/time.h"
  8. #include "testing/gtest/include/gtest/gtest.h"
  9. namespace remoting {
  10. class BackoffTimerTest : public testing::Test {
  11. public:
  12. BackoffTimerTest()
  13. : task_environment_(base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
  14. ~BackoffTimerTest() override = default;
  15. void IncrementCounter() { ++counter_; }
  16. void AssertNextDelayAndFastForwardBy(base::TimeDelta delay) {
  17. ASSERT_EQ(task_environment_.NextMainThreadPendingTaskDelay(), delay);
  18. task_environment_.FastForwardBy(delay);
  19. }
  20. int counter() const { return counter_; }
  21. private:
  22. base::test::TaskEnvironment task_environment_;
  23. int counter_ = 0;
  24. };
  25. TEST_F(BackoffTimerTest, Basic) {
  26. BackoffTimer backoff_timer;
  27. ASSERT_FALSE(backoff_timer.IsRunning());
  28. constexpr base::TimeDelta initial_delay = base::Milliseconds(10);
  29. constexpr base::TimeDelta max_delay = base::Milliseconds(50);
  30. backoff_timer.Start(FROM_HERE, initial_delay, max_delay,
  31. base::BindRepeating(&BackoffTimerTest::IncrementCounter,
  32. base::Unretained(this)));
  33. ASSERT_TRUE(backoff_timer.IsRunning());
  34. ASSERT_EQ(0, counter());
  35. // The backoff timer always immediately fires without delay.
  36. AssertNextDelayAndFastForwardBy(base::TimeDelta());
  37. ASSERT_TRUE(backoff_timer.IsRunning());
  38. ASSERT_EQ(1, counter());
  39. // The next delay is equal to the initial delay.
  40. AssertNextDelayAndFastForwardBy(initial_delay);
  41. ASSERT_TRUE(backoff_timer.IsRunning());
  42. ASSERT_EQ(2, counter());
  43. // The next delay is doubled.
  44. AssertNextDelayAndFastForwardBy(2 * initial_delay);
  45. ASSERT_TRUE(backoff_timer.IsRunning());
  46. ASSERT_EQ(3, counter());
  47. // The next delay is doubled again.
  48. AssertNextDelayAndFastForwardBy(4 * initial_delay);
  49. ASSERT_TRUE(backoff_timer.IsRunning());
  50. ASSERT_EQ(4, counter());
  51. // The next delay is clamped to the max delay. Otherwise, it would exceed it.
  52. ASSERT_GT(8 * initial_delay, max_delay);
  53. AssertNextDelayAndFastForwardBy(max_delay);
  54. ASSERT_TRUE(backoff_timer.IsRunning());
  55. ASSERT_EQ(5, counter());
  56. // The delay remains constant at the max delay.
  57. AssertNextDelayAndFastForwardBy(max_delay);
  58. ASSERT_TRUE(backoff_timer.IsRunning());
  59. ASSERT_EQ(6, counter());
  60. backoff_timer.Stop();
  61. ASSERT_FALSE(backoff_timer.IsRunning());
  62. }
  63. } // namespace remoting