blob: 79bce0616adf0023e0354fa4821b9a8db53ba49f [file] [log] [blame]
Sebastian Janssonecb68972019-01-18 10:30:54 +01001/*
2 * Copyright 2019 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include <atomic>
12#include <chrono> // Not allowed in production per Chromium style guide.
13#include <memory>
14#include <thread> // Not allowed in production per Chromium style guide.
15
16#include "absl/memory/memory.h"
17#include "rtc_base/event.h"
18#include "rtc_base/task_utils/repeating_task.h"
19#include "test/gmock.h"
20#include "test/gtest.h"
21
22// NOTE: Since these tests rely on real time behavior, they will be flaky
23// if run on heavily loaded systems.
24namespace webrtc {
25namespace {
26using ::testing::AtLeast;
27using ::testing::Invoke;
28using ::testing::MockFunction;
29using ::testing::NiceMock;
30using ::testing::Return;
31
32constexpr TimeDelta kTimeout = TimeDelta::Millis<1000>();
33
34void Sleep(TimeDelta time_delta) {
35 // Note that Chromium style guide prohibits use of <thread> and <chrono> in
36 // production code, used here since webrtc::SleepMs may return early.
37 std::this_thread::sleep_for(std::chrono::microseconds(time_delta.us()));
38}
39
40class MockClosure {
41 public:
42 MOCK_METHOD0(Call, TimeDelta());
43 MOCK_METHOD0(Delete, void());
44};
45
46class MoveOnlyClosure {
47 public:
48 explicit MoveOnlyClosure(MockClosure* mock) : mock_(mock) {}
49 MoveOnlyClosure(const MoveOnlyClosure&) = delete;
50 MoveOnlyClosure(MoveOnlyClosure&& other) : mock_(other.mock_) {
51 other.mock_ = nullptr;
52 }
53 ~MoveOnlyClosure() {
54 if (mock_)
55 mock_->Delete();
56 }
57 TimeDelta operator()() { return mock_->Call(); }
58
59 private:
60 MockClosure* mock_;
61};
62} // namespace
63
64TEST(RepeatingTaskTest, TaskIsStoppedOnStop) {
65 const TimeDelta kShortInterval = TimeDelta::ms(5);
66 const TimeDelta kLongInterval = TimeDelta::ms(20);
67 const int kShortIntervalCount = 4;
68 const int kMargin = 1;
69
70 rtc::TaskQueue task_queue("TestQueue");
71 std::atomic_int counter(0);
72 auto handle = RepeatingTaskHandle::Start(&task_queue, [&] {
73 if (++counter >= kShortIntervalCount)
74 return kLongInterval;
75 return kShortInterval;
76 });
77 // Sleep long enough to go through the initial phase.
78 Sleep(kShortInterval * (kShortIntervalCount + kMargin));
79 EXPECT_EQ(counter.load(), kShortIntervalCount);
80
81 handle.PostStop();
82 // Sleep long enough that the task would run at least once more if not
83 // stopped.
84 Sleep(kLongInterval * 2);
85 EXPECT_EQ(counter.load(), kShortIntervalCount);
86}
87
88TEST(RepeatingTaskTest, CompensatesForLongRunTime) {
89 const int kTargetCount = 20;
90 const int kTargetCountMargin = 2;
91 const TimeDelta kRepeatInterval = TimeDelta::ms(2);
92 // Sleeping inside the task for longer than the repeat interval once, should
93 // be compensated for by repeating the task faster to catch up.
94 const TimeDelta kSleepDuration = TimeDelta::ms(20);
95 const int kSleepAtCount = 3;
96
97 std::atomic_int counter(0);
98 rtc::TaskQueue task_queue("TestQueue");
99 RepeatingTaskHandle::Start(&task_queue, [&] {
100 if (++counter == kSleepAtCount)
101 Sleep(kSleepDuration);
102 return kRepeatInterval;
103 });
104 Sleep(kRepeatInterval * kTargetCount);
105 // Execution time should not have affected the run count,
106 // but we allow some margin to reduce flakiness.
107 EXPECT_GE(counter.load(), kTargetCount - kTargetCountMargin);
108}
109
110TEST(RepeatingTaskTest, CompensatesForShortRunTime) {
111 std::atomic_int counter(0);
112 rtc::TaskQueue task_queue("TestQueue");
113 RepeatingTaskHandle::Start(&task_queue, [&] {
114 ++counter;
115 // Sleeping for the 5 ms should be compensated.
116 Sleep(TimeDelta::ms(5));
117 return TimeDelta::ms(10);
118 });
119 Sleep(TimeDelta::ms(15));
120 // We expect that the task have been called twice, once directly at Start and
121 // once after 10 ms has passed.
122 EXPECT_EQ(counter.load(), 2);
123}
124
125TEST(RepeatingTaskTest, CancelDelayedTaskBeforeItRuns) {
126 rtc::Event done;
127 MockClosure mock;
128 EXPECT_CALL(mock, Call).Times(0);
129 EXPECT_CALL(mock, Delete).WillOnce(Invoke([&done] { done.Set(); }));
130 rtc::TaskQueue task_queue("queue");
131 auto handle = RepeatingTaskHandle::DelayedStart(
132 &task_queue, TimeDelta::ms(100), MoveOnlyClosure(&mock));
133 handle.PostStop();
134 EXPECT_TRUE(done.Wait(kTimeout.ms()));
135}
136
137TEST(RepeatingTaskTest, CancelTaskAfterItRuns) {
138 rtc::Event done;
139 MockClosure mock;
140 EXPECT_CALL(mock, Call).WillOnce(Return(TimeDelta::ms(100)));
141 EXPECT_CALL(mock, Delete).WillOnce(Invoke([&done] { done.Set(); }));
142 rtc::TaskQueue task_queue("queue");
143 auto handle = RepeatingTaskHandle::Start(&task_queue, MoveOnlyClosure(&mock));
144 handle.PostStop();
145 EXPECT_TRUE(done.Wait(kTimeout.ms()));
146}
147
148TEST(RepeatingTaskTest, TaskCanStopItself) {
149 std::atomic_int counter(0);
150 rtc::TaskQueue task_queue("TestQueue");
151 RepeatingTaskHandle handle;
152 task_queue.PostTask([&] {
153 handle = RepeatingTaskHandle::Start(&task_queue, [&] {
154 ++counter;
155 handle.Stop();
156 return TimeDelta::ms(2);
157 });
158 });
159 Sleep(TimeDelta::ms(10));
160 EXPECT_EQ(counter.load(), 1);
161}
162
163TEST(RepeatingTaskTest, ZeroReturnValueRepostsTheTask) {
164 NiceMock<MockClosure> closure;
165 rtc::Event done;
166 EXPECT_CALL(closure, Call())
167 .WillOnce(Return(TimeDelta::Zero()))
168 .WillOnce(Invoke([&done] {
169 done.Set();
170 return kTimeout;
171 }));
172 rtc::TaskQueue task_queue("queue");
173 RepeatingTaskHandle::Start(&task_queue, MoveOnlyClosure(&closure));
174 EXPECT_TRUE(done.Wait(kTimeout.ms()));
175}
176
177TEST(RepeatingTaskTest, StartPeriodicTask) {
178 MockFunction<TimeDelta()> closure;
179 rtc::Event done;
180 EXPECT_CALL(closure, Call())
181 .WillOnce(Return(TimeDelta::ms(20)))
182 .WillOnce(Return(TimeDelta::ms(20)))
183 .WillOnce(Invoke([&done] {
184 done.Set();
185 return kTimeout;
186 }));
187 rtc::TaskQueue task_queue("queue");
188 RepeatingTaskHandle::Start(&task_queue, closure.AsStdFunction());
189 EXPECT_TRUE(done.Wait(kTimeout.ms()));
190}
191
192TEST(RepeatingTaskTest, Example) {
193 class ObjectOnTaskQueue {
194 public:
195 void DoPeriodicTask() {}
196 TimeDelta TimeUntilNextRun() { return TimeDelta::ms(100); }
197 void StartPeriodicTask(RepeatingTaskHandle* handle,
198 rtc::TaskQueue* task_queue) {
199 *handle = RepeatingTaskHandle::Start(task_queue, [this] {
200 DoPeriodicTask();
201 return TimeUntilNextRun();
202 });
203 }
204 };
205 rtc::TaskQueue task_queue("queue");
206 auto object = absl::make_unique<ObjectOnTaskQueue>();
207 // Create and start the periodic task.
208 RepeatingTaskHandle handle;
209 object->StartPeriodicTask(&handle, &task_queue);
210 // Restart the task
211 handle.PostStop();
212 object->StartPeriodicTask(&handle, &task_queue);
213 handle.PostStop();
214 struct Destructor {
215 void operator()() { object.reset(); }
216 std::unique_ptr<ObjectOnTaskQueue> object;
217 };
218 task_queue.PostTask(Destructor{std::move(object)});
219 // Do not wait for the destructor closure in order to create a race between
220 // task queue destruction and running the desctructor closure.
221}
222
223} // namespace webrtc