1 /*
2 * Copyright 2004 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 "rtc_base/time_utils.h"
12
13 #include <memory>
14
15 #include "api/units/time_delta.h"
16 #include "rtc_base/event.h"
17 #include "rtc_base/fake_clock.h"
18 #include "rtc_base/helpers.h"
19 #include "rtc_base/location.h"
20 #include "rtc_base/message_handler.h"
21 #include "rtc_base/task_utils/to_queued_task.h"
22 #include "rtc_base/thread.h"
23 #include "test/gtest.h"
24
25 namespace rtc {
26
TEST(TimeTest,TimeInMs)27 TEST(TimeTest, TimeInMs) {
28 int64_t ts_earlier = TimeMillis();
29 Thread::SleepMs(100);
30 int64_t ts_now = TimeMillis();
31 // Allow for the thread to wakeup ~20ms early.
32 EXPECT_GE(ts_now, ts_earlier + 80);
33 // Make sure the Time is not returning in smaller unit like microseconds.
34 EXPECT_LT(ts_now, ts_earlier + 1000);
35 }
36
TEST(TimeTest,Intervals)37 TEST(TimeTest, Intervals) {
38 int64_t ts_earlier = TimeMillis();
39 int64_t ts_later = TimeAfter(500);
40
41 // We can't depend on ts_later and ts_earlier to be exactly 500 apart
42 // since time elapses between the calls to TimeMillis() and TimeAfter(500)
43 EXPECT_LE(500, TimeDiff(ts_later, ts_earlier));
44 EXPECT_GE(-500, TimeDiff(ts_earlier, ts_later));
45
46 // Time has elapsed since ts_earlier
47 EXPECT_GE(TimeSince(ts_earlier), 0);
48
49 // ts_earlier is earlier than now, so TimeUntil ts_earlier is -ve
50 EXPECT_LE(TimeUntil(ts_earlier), 0);
51
52 // ts_later likely hasn't happened yet, so TimeSince could be -ve
53 // but within 500
54 EXPECT_GE(TimeSince(ts_later), -500);
55
56 // TimeUntil ts_later is at most 500
57 EXPECT_LE(TimeUntil(ts_later), 500);
58 }
59
TEST(TimeTest,TestTimeDiff64)60 TEST(TimeTest, TestTimeDiff64) {
61 int64_t ts_diff = 100;
62 int64_t ts_earlier = rtc::TimeMillis();
63 int64_t ts_later = ts_earlier + ts_diff;
64 EXPECT_EQ(ts_diff, rtc::TimeDiff(ts_later, ts_earlier));
65 EXPECT_EQ(-ts_diff, rtc::TimeDiff(ts_earlier, ts_later));
66 }
67
68 class TimestampWrapAroundHandlerTest : public ::testing::Test {
69 public:
TimestampWrapAroundHandlerTest()70 TimestampWrapAroundHandlerTest() {}
71
72 protected:
73 TimestampWrapAroundHandler wraparound_handler_;
74 };
75
TEST_F(TimestampWrapAroundHandlerTest,Unwrap)76 TEST_F(TimestampWrapAroundHandlerTest, Unwrap) {
77 // Start value.
78 int64_t ts = 2;
79 EXPECT_EQ(ts,
80 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
81
82 // Wrap backwards.
83 ts = -2;
84 EXPECT_EQ(ts,
85 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
86
87 // Forward to 2 again.
88 ts = 2;
89 EXPECT_EQ(ts,
90 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
91
92 // Max positive skip ahead, until max value (0xffffffff).
93 for (uint32_t i = 0; i <= 0xf; ++i) {
94 ts = (i << 28) + 0x0fffffff;
95 EXPECT_EQ(
96 ts, wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
97 }
98
99 // Wrap around.
100 ts += 2;
101 EXPECT_EQ(ts,
102 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
103
104 // Max wrap backward...
105 ts -= 0x0fffffff;
106 EXPECT_EQ(ts,
107 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
108
109 // ...and back again.
110 ts += 0x0fffffff;
111 EXPECT_EQ(ts,
112 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
113 }
114
TEST_F(TimestampWrapAroundHandlerTest,NoNegativeStart)115 TEST_F(TimestampWrapAroundHandlerTest, NoNegativeStart) {
116 int64_t ts = 0xfffffff0;
117 EXPECT_EQ(ts,
118 wraparound_handler_.Unwrap(static_cast<uint32_t>(ts & 0xffffffff)));
119 }
120
121 class TmToSeconds : public ::testing::Test {
122 public:
TmToSeconds()123 TmToSeconds() {
124 // Set use of the test RNG to get deterministic expiration timestamp.
125 rtc::SetRandomTestMode(true);
126 }
~TmToSeconds()127 ~TmToSeconds() override {
128 // Put it back for the next test.
129 rtc::SetRandomTestMode(false);
130 }
131
TestTmToSeconds(int times)132 void TestTmToSeconds(int times) {
133 static char mdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
134 for (int i = 0; i < times; i++) {
135 // First generate something correct and check that TmToSeconds is happy.
136 int year = rtc::CreateRandomId() % 400 + 1970;
137
138 bool leap_year = false;
139 if (year % 4 == 0)
140 leap_year = true;
141 if (year % 100 == 0)
142 leap_year = false;
143 if (year % 400 == 0)
144 leap_year = true;
145
146 std::tm tm;
147 tm.tm_year = year - 1900; // std::tm is year 1900 based.
148 tm.tm_mon = rtc::CreateRandomId() % 12;
149 tm.tm_mday = rtc::CreateRandomId() % mdays[tm.tm_mon] + 1;
150 tm.tm_hour = rtc::CreateRandomId() % 24;
151 tm.tm_min = rtc::CreateRandomId() % 60;
152 tm.tm_sec = rtc::CreateRandomId() % 60;
153 int64_t t = rtc::TmToSeconds(tm);
154 EXPECT_TRUE(t >= 0);
155
156 // Now damage a random field and check that TmToSeconds is unhappy.
157 switch (rtc::CreateRandomId() % 11) {
158 case 0:
159 tm.tm_year = 1969 - 1900;
160 break;
161 case 1:
162 tm.tm_mon = -1;
163 break;
164 case 2:
165 tm.tm_mon = 12;
166 break;
167 case 3:
168 tm.tm_mday = 0;
169 break;
170 case 4:
171 tm.tm_mday = mdays[tm.tm_mon] + (leap_year && tm.tm_mon == 1) + 1;
172 break;
173 case 5:
174 tm.tm_hour = -1;
175 break;
176 case 6:
177 tm.tm_hour = 24;
178 break;
179 case 7:
180 tm.tm_min = -1;
181 break;
182 case 8:
183 tm.tm_min = 60;
184 break;
185 case 9:
186 tm.tm_sec = -1;
187 break;
188 case 10:
189 tm.tm_sec = 60;
190 break;
191 }
192 EXPECT_EQ(rtc::TmToSeconds(tm), -1);
193 }
194 // Check consistency with the system gmtime_r. With time_t, we can only
195 // portably test dates until 2038, which is achieved by the % 0x80000000.
196 for (int i = 0; i < times; i++) {
197 time_t t = rtc::CreateRandomId() % 0x80000000;
198 #if defined(WEBRTC_WIN)
199 std::tm* tm = std::gmtime(&t);
200 EXPECT_TRUE(tm);
201 EXPECT_TRUE(rtc::TmToSeconds(*tm) == t);
202 #else
203 std::tm tm;
204 EXPECT_TRUE(gmtime_r(&t, &tm));
205 EXPECT_TRUE(rtc::TmToSeconds(tm) == t);
206 #endif
207 }
208 }
209 };
210
TEST_F(TmToSeconds,TestTmToSeconds)211 TEST_F(TmToSeconds, TestTmToSeconds) {
212 TestTmToSeconds(100000);
213 }
214
215 // Test that all the time functions exposed by TimeUtils get time from the
216 // fake clock when it's set.
TEST(FakeClock,TimeFunctionsUseFakeClock)217 TEST(FakeClock, TimeFunctionsUseFakeClock) {
218 FakeClock clock;
219 SetClockForTesting(&clock);
220
221 clock.SetTime(webrtc::Timestamp::Micros(987654));
222 EXPECT_EQ(987u, Time32());
223 EXPECT_EQ(987, TimeMillis());
224 EXPECT_EQ(987654, TimeMicros());
225 EXPECT_EQ(987654000, TimeNanos());
226 EXPECT_EQ(1000u, TimeAfter(13));
227
228 SetClockForTesting(nullptr);
229 // After it's unset, we should get a normal time.
230 EXPECT_NE(987, TimeMillis());
231 }
232
TEST(FakeClock,InitialTime)233 TEST(FakeClock, InitialTime) {
234 FakeClock clock;
235 EXPECT_EQ(0, clock.TimeNanos());
236 }
237
TEST(FakeClock,SetTime)238 TEST(FakeClock, SetTime) {
239 FakeClock clock;
240 clock.SetTime(webrtc::Timestamp::Micros(123));
241 EXPECT_EQ(123000, clock.TimeNanos());
242 clock.SetTime(webrtc::Timestamp::Micros(456));
243 EXPECT_EQ(456000, clock.TimeNanos());
244 }
245
TEST(FakeClock,AdvanceTime)246 TEST(FakeClock, AdvanceTime) {
247 FakeClock clock;
248 clock.AdvanceTime(webrtc::TimeDelta::Micros(1u));
249 EXPECT_EQ(1000, clock.TimeNanos());
250 clock.AdvanceTime(webrtc::TimeDelta::Micros(2222u));
251 EXPECT_EQ(2223000, clock.TimeNanos());
252 clock.AdvanceTime(webrtc::TimeDelta::Millis(3333u));
253 EXPECT_EQ(3335223000, clock.TimeNanos());
254 clock.AdvanceTime(webrtc::TimeDelta::Seconds(4444u));
255 EXPECT_EQ(4447335223000, clock.TimeNanos());
256 }
257
258 // When the clock is advanced, threads that are waiting in a socket select
259 // should wake up and look at the new time. This allows tests using the
260 // fake clock to run much faster, if the test is bound by time constraints
261 // (such as a test for a STUN ping timeout).
TEST(FakeClock,SettingTimeWakesThreads)262 TEST(FakeClock, SettingTimeWakesThreads) {
263 int64_t real_start_time_ms = TimeMillis();
264
265 ThreadProcessingFakeClock clock;
266 SetClockForTesting(&clock);
267
268 std::unique_ptr<Thread> worker(Thread::CreateWithSocketServer());
269 worker->Start();
270
271 // Post an event that won't be executed for 10 seconds.
272 Event message_handler_dispatched;
273 worker->PostDelayedTask(webrtc::ToQueuedTask([&message_handler_dispatched] {
274 message_handler_dispatched.Set();
275 }),
276 /*milliseconds=*/60000);
277
278 // Wait for a bit for the worker thread to be started and enter its socket
279 // select(). Otherwise this test would be trivial since the worker thread
280 // would process the event as soon as it was started.
281 Thread::Current()->SleepMs(1000);
282
283 // Advance the fake clock, expecting the worker thread to wake up
284 // and dispatch the message instantly.
285 clock.AdvanceTime(webrtc::TimeDelta::Seconds(60u));
286 EXPECT_TRUE(message_handler_dispatched.Wait(0));
287 worker->Stop();
288
289 SetClockForTesting(nullptr);
290
291 // The message should have been dispatched long before the 60 seconds fully
292 // elapsed (just a sanity check).
293 int64_t real_end_time_ms = TimeMillis();
294 EXPECT_LT(real_end_time_ms - real_start_time_ms, 10000);
295 }
296
297 } // namespace rtc
298