1 // Copyright (c) 2012 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
5 #include "base/time/time.h"
6
7 #include <stdint.h>
8 #include <time.h>
9 #include <limits>
10 #include <string>
11
12 #include "base/build_time.h"
13 #include "base/compiler_specific.h"
14 #include "base/logging.h"
15 #include "base/macros.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/threading/platform_thread.h"
18 #include "base/time/time_override.h"
19 #include "build/build_config.h"
20 #include "testing/gtest/include/gtest/gtest.h"
21
22 #if defined(OS_ANDROID)
23 #include "base/android/jni_android.h"
24 #elif defined(OS_IOS)
25 #include "base/ios/ios_util.h"
26 #elif defined(OS_WIN)
27 #include <windows.h>
28 #endif
29
30 namespace base {
31
32 namespace {
33
TEST(TimeTestOutOfBounds,FromExplodedOutOfBoundsTime)34 TEST(TimeTestOutOfBounds, FromExplodedOutOfBoundsTime) {
35 // FromUTCExploded must set time to Time(0) and failure, if the day is set to
36 // 31 on a 28-30 day month. Test |exploded| returns Time(0) on 31st of
37 // February and 31st of April. New implementation handles this.
38
39 const struct DateTestData {
40 Time::Exploded explode;
41 bool is_valid;
42 } kDateTestData[] = {
43 // 31st of February
44 {{2016, 2, 0, 31, 12, 30, 0, 0}, true},
45 // 31st of April
46 {{2016, 4, 0, 31, 8, 43, 0, 0}, true},
47 // Negative month
48 {{2016, -5, 0, 2, 4, 10, 0, 0}, false},
49 // Negative date of month
50 {{2016, 6, 0, -15, 2, 50, 0, 0}, false},
51 // Negative hours
52 {{2016, 7, 0, 10, -11, 29, 0, 0}, false},
53 // Negative minutes
54 {{2016, 3, 0, 14, 10, -29, 0, 0}, false},
55 // Negative seconds
56 {{2016, 10, 0, 25, 7, 47, -30, 0}, false},
57 // Negative milliseconds
58 {{2016, 10, 0, 25, 7, 47, 20, -500}, false},
59 // Hours are too large
60 {{2016, 7, 0, 10, 26, 29, 0, 0}, false},
61 // Minutes are too large
62 {{2016, 3, 0, 14, 10, 78, 0, 0}, false},
63 // Seconds are too large
64 {{2016, 10, 0, 25, 7, 47, 234, 0}, false},
65 // Milliseconds are too large
66 {{2016, 10, 0, 25, 6, 31, 23, 1643}, false},
67 // Test overflow. Time is valid, but overflow case
68 // results in Time(0).
69 {{9840633, 1, 0, 1, 1, 1, 0, 0}, true},
70 // Underflow will fail as well.
71 {{-9840633, 1, 0, 1, 1, 1, 0, 0}, true},
72 // Test integer overflow and underflow cases for the values themselves.
73 {{std::numeric_limits<int>::min(), 1, 0, 1, 1, 1, 0, 0}, true},
74 {{std::numeric_limits<int>::max(), 1, 0, 1, 1, 1, 0, 0}, true},
75 {{2016, std::numeric_limits<int>::min(), 0, 1, 1, 1, 0, 0}, false},
76 {{2016, std::numeric_limits<int>::max(), 0, 1, 1, 1, 0, 0}, false},
77 };
78
79 for (const auto& test : kDateTestData) {
80 EXPECT_EQ(test.explode.HasValidValues(), test.is_valid);
81
82 base::Time result;
83 EXPECT_FALSE(base::Time::FromUTCExploded(test.explode, &result));
84 EXPECT_TRUE(result.is_null());
85 EXPECT_FALSE(base::Time::FromLocalExploded(test.explode, &result));
86 EXPECT_TRUE(result.is_null());
87 }
88 }
89
90 // Specialized test fixture allowing time strings without timezones to be
91 // tested by comparing them to a known time in the local zone.
92 // See also pr_time_unittests.cc
93 class TimeTest : public testing::Test {
94 protected:
SetUp()95 void SetUp() override {
96 // Use mktime to get a time_t, and turn it into a PRTime by converting
97 // seconds to microseconds. Use 15th Oct 2007 12:45:00 local. This
98 // must be a time guaranteed to be outside of a DST fallback hour in
99 // any timezone.
100 struct tm local_comparison_tm = {
101 0, // second
102 45, // minute
103 12, // hour
104 15, // day of month
105 10 - 1, // month
106 2007 - 1900, // year
107 0, // day of week (ignored, output only)
108 0, // day of year (ignored, output only)
109 -1 // DST in effect, -1 tells mktime to figure it out
110 };
111
112 time_t converted_time = mktime(&local_comparison_tm);
113 ASSERT_GT(converted_time, 0);
114 comparison_time_local_ = Time::FromTimeT(converted_time);
115
116 // time_t representation of 15th Oct 2007 12:45:00 PDT
117 comparison_time_pdt_ = Time::FromTimeT(1192477500);
118 }
119
120 Time comparison_time_local_;
121 Time comparison_time_pdt_;
122 };
123
124 // Test conversion to/from TimeDeltas elapsed since the Windows epoch.
125 // Conversions should be idempotent and non-lossy.
TEST_F(TimeTest,DeltaSinceWindowsEpoch)126 TEST_F(TimeTest, DeltaSinceWindowsEpoch) {
127 const TimeDelta delta = TimeDelta::FromMicroseconds(123);
128 EXPECT_EQ(delta,
129 Time::FromDeltaSinceWindowsEpoch(delta).ToDeltaSinceWindowsEpoch());
130
131 const Time now = Time::Now();
132 const Time actual =
133 Time::FromDeltaSinceWindowsEpoch(now.ToDeltaSinceWindowsEpoch());
134 EXPECT_EQ(now, actual);
135
136 // Null times should remain null after a round-trip conversion. This is an
137 // important invariant for the common use case of serialization +
138 // deserialization.
139 const Time should_be_null =
140 Time::FromDeltaSinceWindowsEpoch(Time().ToDeltaSinceWindowsEpoch());
141 EXPECT_TRUE(should_be_null.is_null());
142 }
143
144 // Test conversion to/from time_t.
TEST_F(TimeTest,TimeT)145 TEST_F(TimeTest, TimeT) {
146 EXPECT_EQ(10, Time().FromTimeT(10).ToTimeT());
147 EXPECT_EQ(10.0, Time().FromTimeT(10).ToDoubleT());
148
149 // Conversions of 0 should stay 0.
150 EXPECT_EQ(0, Time().ToTimeT());
151 EXPECT_EQ(0, Time::FromTimeT(0).ToInternalValue());
152 }
153
154 // Test conversions to/from time_t and exploding/unexploding (utc time).
TEST_F(TimeTest,UTCTimeT)155 TEST_F(TimeTest, UTCTimeT) {
156 // C library time and exploded time.
157 time_t now_t_1 = time(nullptr);
158 struct tm tms;
159 #if defined(OS_WIN)
160 gmtime_s(&tms, &now_t_1);
161 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
162 gmtime_r(&now_t_1, &tms);
163 #endif
164
165 // Convert to ours.
166 Time our_time_1 = Time::FromTimeT(now_t_1);
167 Time::Exploded exploded;
168 our_time_1.UTCExplode(&exploded);
169
170 // This will test both our exploding and our time_t -> Time conversion.
171 EXPECT_EQ(tms.tm_year + 1900, exploded.year);
172 EXPECT_EQ(tms.tm_mon + 1, exploded.month);
173 EXPECT_EQ(tms.tm_mday, exploded.day_of_month);
174 EXPECT_EQ(tms.tm_hour, exploded.hour);
175 EXPECT_EQ(tms.tm_min, exploded.minute);
176 EXPECT_EQ(tms.tm_sec, exploded.second);
177
178 // Convert exploded back to the time struct.
179 Time our_time_2;
180 EXPECT_TRUE(Time::FromUTCExploded(exploded, &our_time_2));
181 EXPECT_TRUE(our_time_1 == our_time_2);
182
183 time_t now_t_2 = our_time_2.ToTimeT();
184 EXPECT_EQ(now_t_1, now_t_2);
185 }
186
187 // Test conversions to/from time_t and exploding/unexploding (local time).
TEST_F(TimeTest,LocalTimeT)188 TEST_F(TimeTest, LocalTimeT) {
189 #if defined(OS_IOS) && TARGET_OS_SIMULATOR
190 // The function CFTimeZoneCopySystem() fails to determine the system timezone
191 // when running iOS 11.0 simulator on an host running High Sierra and return
192 // the "GMT" timezone. This causes Time::LocalExplode and localtime_r values
193 // to differ by the local timezone offset. Disable the test if simulating
194 // iOS 10.0 as it is not possible to check the version of the host mac.
195 // TODO(crbug.com/782033): remove this once support for iOS pre-11.0 is
196 // dropped or when the bug in CFTimeZoneCopySystem() is fixed.
197 if (ios::IsRunningOnIOS10OrLater() && !ios::IsRunningOnIOS11OrLater()) {
198 return;
199 }
200 #endif
201
202 // C library time and exploded time.
203 time_t now_t_1 = time(nullptr);
204 struct tm tms;
205 #if defined(OS_WIN)
206 localtime_s(&tms, &now_t_1);
207 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
208 localtime_r(&now_t_1, &tms);
209 #endif
210
211 // Convert to ours.
212 Time our_time_1 = Time::FromTimeT(now_t_1);
213 Time::Exploded exploded;
214 our_time_1.LocalExplode(&exploded);
215
216 // This will test both our exploding and our time_t -> Time conversion.
217 EXPECT_EQ(tms.tm_year + 1900, exploded.year);
218 EXPECT_EQ(tms.tm_mon + 1, exploded.month);
219 EXPECT_EQ(tms.tm_mday, exploded.day_of_month);
220 EXPECT_EQ(tms.tm_hour, exploded.hour);
221 EXPECT_EQ(tms.tm_min, exploded.minute);
222 EXPECT_EQ(tms.tm_sec, exploded.second);
223
224 // Convert exploded back to the time struct.
225 Time our_time_2;
226 EXPECT_TRUE(Time::FromLocalExploded(exploded, &our_time_2));
227 EXPECT_TRUE(our_time_1 == our_time_2);
228
229 time_t now_t_2 = our_time_2.ToTimeT();
230 EXPECT_EQ(now_t_1, now_t_2);
231 }
232
233 // Test conversions to/from javascript time.
TEST_F(TimeTest,JsTime)234 TEST_F(TimeTest, JsTime) {
235 Time epoch = Time::FromJsTime(0.0);
236 EXPECT_EQ(epoch, Time::UnixEpoch());
237 Time t = Time::FromJsTime(700000.3);
238 EXPECT_EQ(700.0003, t.ToDoubleT());
239 t = Time::FromDoubleT(800.73);
240 EXPECT_EQ(800730.0, t.ToJsTime());
241 }
242
243 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
TEST_F(TimeTest,FromTimeVal)244 TEST_F(TimeTest, FromTimeVal) {
245 Time now = Time::Now();
246 Time also_now = Time::FromTimeVal(now.ToTimeVal());
247 EXPECT_EQ(now, also_now);
248 }
249 #endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
250
TEST_F(TimeTest,FromExplodedWithMilliseconds)251 TEST_F(TimeTest, FromExplodedWithMilliseconds) {
252 // Some platform implementations of FromExploded are liable to drop
253 // milliseconds if we aren't careful.
254 Time now = Time::NowFromSystemTime();
255 Time::Exploded exploded1 = {0};
256 now.UTCExplode(&exploded1);
257 exploded1.millisecond = 500;
258 Time time;
259 EXPECT_TRUE(Time::FromUTCExploded(exploded1, &time));
260 Time::Exploded exploded2 = {0};
261 time.UTCExplode(&exploded2);
262 EXPECT_EQ(exploded1.millisecond, exploded2.millisecond);
263 }
264
TEST_F(TimeTest,ZeroIsSymmetric)265 TEST_F(TimeTest, ZeroIsSymmetric) {
266 Time zero_time(Time::FromTimeT(0));
267 EXPECT_EQ(0, zero_time.ToTimeT());
268
269 EXPECT_EQ(0.0, zero_time.ToDoubleT());
270 }
271
TEST_F(TimeTest,LocalExplode)272 TEST_F(TimeTest, LocalExplode) {
273 Time a = Time::Now();
274 Time::Exploded exploded;
275 a.LocalExplode(&exploded);
276
277 Time b;
278 EXPECT_TRUE(Time::FromLocalExploded(exploded, &b));
279
280 // The exploded structure doesn't have microseconds, and on Mac & Linux, the
281 // internal OS conversion uses seconds, which will cause truncation. So we
282 // can only make sure that the delta is within one second.
283 EXPECT_TRUE((a - b) < TimeDelta::FromSeconds(1));
284 }
285
TEST_F(TimeTest,UTCExplode)286 TEST_F(TimeTest, UTCExplode) {
287 Time a = Time::Now();
288 Time::Exploded exploded;
289 a.UTCExplode(&exploded);
290
291 Time b;
292 EXPECT_TRUE(Time::FromUTCExploded(exploded, &b));
293 EXPECT_TRUE((a - b) < TimeDelta::FromSeconds(1));
294 }
295
TEST_F(TimeTest,LocalMidnight)296 TEST_F(TimeTest, LocalMidnight) {
297 Time::Exploded exploded;
298 Time::Now().LocalMidnight().LocalExplode(&exploded);
299 EXPECT_EQ(0, exploded.hour);
300 EXPECT_EQ(0, exploded.minute);
301 EXPECT_EQ(0, exploded.second);
302 EXPECT_EQ(0, exploded.millisecond);
303 }
304
TEST_F(TimeTest,ParseTimeTest1)305 TEST_F(TimeTest, ParseTimeTest1) {
306 time_t current_time = 0;
307 time(¤t_time);
308
309 struct tm local_time = {};
310 char time_buf[64] = {};
311 #if defined(OS_WIN)
312 localtime_s(&local_time, ¤t_time);
313 asctime_s(time_buf, arraysize(time_buf), &local_time);
314 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
315 localtime_r(¤t_time, &local_time);
316 asctime_r(&local_time, time_buf);
317 #endif
318
319 Time parsed_time;
320 EXPECT_TRUE(Time::FromString(time_buf, &parsed_time));
321 EXPECT_EQ(current_time, parsed_time.ToTimeT());
322 }
323
TEST_F(TimeTest,DayOfWeekSunday)324 TEST_F(TimeTest, DayOfWeekSunday) {
325 Time time;
326 EXPECT_TRUE(Time::FromString("Sun, 06 May 2012 12:00:00 GMT", &time));
327 Time::Exploded exploded;
328 time.UTCExplode(&exploded);
329 EXPECT_EQ(0, exploded.day_of_week);
330 }
331
TEST_F(TimeTest,DayOfWeekWednesday)332 TEST_F(TimeTest, DayOfWeekWednesday) {
333 Time time;
334 EXPECT_TRUE(Time::FromString("Wed, 09 May 2012 12:00:00 GMT", &time));
335 Time::Exploded exploded;
336 time.UTCExplode(&exploded);
337 EXPECT_EQ(3, exploded.day_of_week);
338 }
339
TEST_F(TimeTest,DayOfWeekSaturday)340 TEST_F(TimeTest, DayOfWeekSaturday) {
341 Time time;
342 EXPECT_TRUE(Time::FromString("Sat, 12 May 2012 12:00:00 GMT", &time));
343 Time::Exploded exploded;
344 time.UTCExplode(&exploded);
345 EXPECT_EQ(6, exploded.day_of_week);
346 }
347
TEST_F(TimeTest,ParseTimeTest2)348 TEST_F(TimeTest, ParseTimeTest2) {
349 Time parsed_time;
350 EXPECT_TRUE(Time::FromString("Mon, 15 Oct 2007 19:45:00 GMT", &parsed_time));
351 EXPECT_EQ(comparison_time_pdt_, parsed_time);
352 }
353
TEST_F(TimeTest,ParseTimeTest3)354 TEST_F(TimeTest, ParseTimeTest3) {
355 Time parsed_time;
356 EXPECT_TRUE(Time::FromString("15 Oct 07 12:45:00", &parsed_time));
357 EXPECT_EQ(comparison_time_local_, parsed_time);
358 }
359
TEST_F(TimeTest,ParseTimeTest4)360 TEST_F(TimeTest, ParseTimeTest4) {
361 Time parsed_time;
362 EXPECT_TRUE(Time::FromString("15 Oct 07 19:45 GMT", &parsed_time));
363 EXPECT_EQ(comparison_time_pdt_, parsed_time);
364 }
365
TEST_F(TimeTest,ParseTimeTest5)366 TEST_F(TimeTest, ParseTimeTest5) {
367 Time parsed_time;
368 EXPECT_TRUE(Time::FromString("Mon Oct 15 12:45 PDT 2007", &parsed_time));
369 EXPECT_EQ(comparison_time_pdt_, parsed_time);
370 }
371
TEST_F(TimeTest,ParseTimeTest6)372 TEST_F(TimeTest, ParseTimeTest6) {
373 Time parsed_time;
374 EXPECT_TRUE(Time::FromString("Monday, Oct 15, 2007 12:45 PM", &parsed_time));
375 EXPECT_EQ(comparison_time_local_, parsed_time);
376 }
377
TEST_F(TimeTest,ParseTimeTest7)378 TEST_F(TimeTest, ParseTimeTest7) {
379 Time parsed_time;
380 EXPECT_TRUE(Time::FromString("10/15/07 12:45:00 PM", &parsed_time));
381 EXPECT_EQ(comparison_time_local_, parsed_time);
382 }
383
TEST_F(TimeTest,ParseTimeTest8)384 TEST_F(TimeTest, ParseTimeTest8) {
385 Time parsed_time;
386 EXPECT_TRUE(Time::FromString("15-OCT-2007 12:45pm", &parsed_time));
387 EXPECT_EQ(comparison_time_local_, parsed_time);
388 }
389
TEST_F(TimeTest,ParseTimeTest9)390 TEST_F(TimeTest, ParseTimeTest9) {
391 Time parsed_time;
392 EXPECT_TRUE(Time::FromString("16 Oct 2007 4:45-JST (Tuesday)", &parsed_time));
393 EXPECT_EQ(comparison_time_pdt_, parsed_time);
394 }
395
TEST_F(TimeTest,ParseTimeTest10)396 TEST_F(TimeTest, ParseTimeTest10) {
397 Time parsed_time;
398 EXPECT_TRUE(Time::FromString("15/10/07 12:45", &parsed_time));
399 EXPECT_EQ(parsed_time, comparison_time_local_);
400 }
401
402 // Test some of edge cases around epoch, etc.
TEST_F(TimeTest,ParseTimeTestEpoch0)403 TEST_F(TimeTest, ParseTimeTestEpoch0) {
404 Time parsed_time;
405
406 // time_t == epoch == 0
407 EXPECT_TRUE(Time::FromString("Thu Jan 01 01:00:00 +0100 1970",
408 &parsed_time));
409 EXPECT_EQ(0, parsed_time.ToTimeT());
410 EXPECT_TRUE(Time::FromString("Thu Jan 01 00:00:00 GMT 1970",
411 &parsed_time));
412 EXPECT_EQ(0, parsed_time.ToTimeT());
413 }
414
TEST_F(TimeTest,ParseTimeTestEpoch1)415 TEST_F(TimeTest, ParseTimeTestEpoch1) {
416 Time parsed_time;
417
418 // time_t == 1 second after epoch == 1
419 EXPECT_TRUE(Time::FromString("Thu Jan 01 01:00:01 +0100 1970",
420 &parsed_time));
421 EXPECT_EQ(1, parsed_time.ToTimeT());
422 EXPECT_TRUE(Time::FromString("Thu Jan 01 00:00:01 GMT 1970",
423 &parsed_time));
424 EXPECT_EQ(1, parsed_time.ToTimeT());
425 }
426
TEST_F(TimeTest,ParseTimeTestEpoch2)427 TEST_F(TimeTest, ParseTimeTestEpoch2) {
428 Time parsed_time;
429
430 // time_t == 2 seconds after epoch == 2
431 EXPECT_TRUE(Time::FromString("Thu Jan 01 01:00:02 +0100 1970",
432 &parsed_time));
433 EXPECT_EQ(2, parsed_time.ToTimeT());
434 EXPECT_TRUE(Time::FromString("Thu Jan 01 00:00:02 GMT 1970",
435 &parsed_time));
436 EXPECT_EQ(2, parsed_time.ToTimeT());
437 }
438
TEST_F(TimeTest,ParseTimeTestEpochNeg1)439 TEST_F(TimeTest, ParseTimeTestEpochNeg1) {
440 Time parsed_time;
441
442 // time_t == 1 second before epoch == -1
443 EXPECT_TRUE(Time::FromString("Thu Jan 01 00:59:59 +0100 1970",
444 &parsed_time));
445 EXPECT_EQ(-1, parsed_time.ToTimeT());
446 EXPECT_TRUE(Time::FromString("Wed Dec 31 23:59:59 GMT 1969",
447 &parsed_time));
448 EXPECT_EQ(-1, parsed_time.ToTimeT());
449 }
450
451 // If time_t is 32 bits, a date after year 2038 will overflow time_t and
452 // cause timegm() to return -1. The parsed time should not be 1 second
453 // before epoch.
TEST_F(TimeTest,ParseTimeTestEpochNotNeg1)454 TEST_F(TimeTest, ParseTimeTestEpochNotNeg1) {
455 Time parsed_time;
456
457 EXPECT_TRUE(Time::FromString("Wed Dec 31 23:59:59 GMT 2100",
458 &parsed_time));
459 EXPECT_NE(-1, parsed_time.ToTimeT());
460 }
461
TEST_F(TimeTest,ParseTimeTestEpochNeg2)462 TEST_F(TimeTest, ParseTimeTestEpochNeg2) {
463 Time parsed_time;
464
465 // time_t == 2 seconds before epoch == -2
466 EXPECT_TRUE(Time::FromString("Thu Jan 01 00:59:58 +0100 1970",
467 &parsed_time));
468 EXPECT_EQ(-2, parsed_time.ToTimeT());
469 EXPECT_TRUE(Time::FromString("Wed Dec 31 23:59:58 GMT 1969",
470 &parsed_time));
471 EXPECT_EQ(-2, parsed_time.ToTimeT());
472 }
473
TEST_F(TimeTest,ParseTimeTestEpoch1960)474 TEST_F(TimeTest, ParseTimeTestEpoch1960) {
475 Time parsed_time;
476
477 // time_t before Epoch, in 1960
478 EXPECT_TRUE(Time::FromString("Wed Jun 29 19:40:01 +0100 1960",
479 &parsed_time));
480 EXPECT_EQ(-299999999, parsed_time.ToTimeT());
481 EXPECT_TRUE(Time::FromString("Wed Jun 29 18:40:01 GMT 1960",
482 &parsed_time));
483 EXPECT_EQ(-299999999, parsed_time.ToTimeT());
484 EXPECT_TRUE(Time::FromString("Wed Jun 29 17:40:01 GMT 1960",
485 &parsed_time));
486 EXPECT_EQ(-300003599, parsed_time.ToTimeT());
487 }
488
TEST_F(TimeTest,ParseTimeTestEmpty)489 TEST_F(TimeTest, ParseTimeTestEmpty) {
490 Time parsed_time;
491 EXPECT_FALSE(Time::FromString("", &parsed_time));
492 }
493
TEST_F(TimeTest,ParseTimeTestInvalidString)494 TEST_F(TimeTest, ParseTimeTestInvalidString) {
495 Time parsed_time;
496 EXPECT_FALSE(Time::FromString("Monday morning 2000", &parsed_time));
497 }
498
TEST_F(TimeTest,ExplodeBeforeUnixEpoch)499 TEST_F(TimeTest, ExplodeBeforeUnixEpoch) {
500 static const int kUnixEpochYear = 1970; // In case this changes (ha!).
501 Time t;
502 Time::Exploded exploded;
503
504 t = Time::UnixEpoch() - TimeDelta::FromMicroseconds(1);
505 t.UTCExplode(&exploded);
506 EXPECT_TRUE(exploded.HasValidValues());
507 // Should be 1969-12-31 23:59:59 999 milliseconds (and 999 microseconds).
508 EXPECT_EQ(kUnixEpochYear - 1, exploded.year);
509 EXPECT_EQ(12, exploded.month);
510 EXPECT_EQ(31, exploded.day_of_month);
511 EXPECT_EQ(23, exploded.hour);
512 EXPECT_EQ(59, exploded.minute);
513 EXPECT_EQ(59, exploded.second);
514 EXPECT_EQ(999, exploded.millisecond);
515
516 t = Time::UnixEpoch() - TimeDelta::FromMicroseconds(1000);
517 t.UTCExplode(&exploded);
518 EXPECT_TRUE(exploded.HasValidValues());
519 // Should be 1969-12-31 23:59:59 999 milliseconds.
520 EXPECT_EQ(kUnixEpochYear - 1, exploded.year);
521 EXPECT_EQ(12, exploded.month);
522 EXPECT_EQ(31, exploded.day_of_month);
523 EXPECT_EQ(23, exploded.hour);
524 EXPECT_EQ(59, exploded.minute);
525 EXPECT_EQ(59, exploded.second);
526 EXPECT_EQ(999, exploded.millisecond);
527
528 t = Time::UnixEpoch() - TimeDelta::FromMicroseconds(1001);
529 t.UTCExplode(&exploded);
530 EXPECT_TRUE(exploded.HasValidValues());
531 // Should be 1969-12-31 23:59:59 998 milliseconds (and 999 microseconds).
532 EXPECT_EQ(kUnixEpochYear - 1, exploded.year);
533 EXPECT_EQ(12, exploded.month);
534 EXPECT_EQ(31, exploded.day_of_month);
535 EXPECT_EQ(23, exploded.hour);
536 EXPECT_EQ(59, exploded.minute);
537 EXPECT_EQ(59, exploded.second);
538 EXPECT_EQ(998, exploded.millisecond);
539
540 t = Time::UnixEpoch() - TimeDelta::FromMilliseconds(1000);
541 t.UTCExplode(&exploded);
542 EXPECT_TRUE(exploded.HasValidValues());
543 // Should be 1969-12-31 23:59:59.
544 EXPECT_EQ(kUnixEpochYear - 1, exploded.year);
545 EXPECT_EQ(12, exploded.month);
546 EXPECT_EQ(31, exploded.day_of_month);
547 EXPECT_EQ(23, exploded.hour);
548 EXPECT_EQ(59, exploded.minute);
549 EXPECT_EQ(59, exploded.second);
550 EXPECT_EQ(0, exploded.millisecond);
551
552 t = Time::UnixEpoch() - TimeDelta::FromMilliseconds(1001);
553 t.UTCExplode(&exploded);
554 EXPECT_TRUE(exploded.HasValidValues());
555 // Should be 1969-12-31 23:59:58 999 milliseconds.
556 EXPECT_EQ(kUnixEpochYear - 1, exploded.year);
557 EXPECT_EQ(12, exploded.month);
558 EXPECT_EQ(31, exploded.day_of_month);
559 EXPECT_EQ(23, exploded.hour);
560 EXPECT_EQ(59, exploded.minute);
561 EXPECT_EQ(58, exploded.second);
562 EXPECT_EQ(999, exploded.millisecond);
563
564 // Make sure we still handle at/after Unix epoch correctly.
565 t = Time::UnixEpoch();
566 t.UTCExplode(&exploded);
567 EXPECT_TRUE(exploded.HasValidValues());
568 // Should be 1970-12-31 00:00:00 0 milliseconds.
569 EXPECT_EQ(kUnixEpochYear, exploded.year);
570 EXPECT_EQ(1, exploded.month);
571 EXPECT_EQ(1, exploded.day_of_month);
572 EXPECT_EQ(0, exploded.hour);
573 EXPECT_EQ(0, exploded.minute);
574 EXPECT_EQ(0, exploded.second);
575 EXPECT_EQ(0, exploded.millisecond);
576
577 t = Time::UnixEpoch() + TimeDelta::FromMicroseconds(1);
578 t.UTCExplode(&exploded);
579 EXPECT_TRUE(exploded.HasValidValues());
580 // Should be 1970-01-01 00:00:00 0 milliseconds (and 1 microsecond).
581 EXPECT_EQ(kUnixEpochYear, exploded.year);
582 EXPECT_EQ(1, exploded.month);
583 EXPECT_EQ(1, exploded.day_of_month);
584 EXPECT_EQ(0, exploded.hour);
585 EXPECT_EQ(0, exploded.minute);
586 EXPECT_EQ(0, exploded.second);
587 EXPECT_EQ(0, exploded.millisecond);
588
589 t = Time::UnixEpoch() + TimeDelta::FromMicroseconds(1000);
590 t.UTCExplode(&exploded);
591 EXPECT_TRUE(exploded.HasValidValues());
592 // Should be 1970-01-01 00:00:00 1 millisecond.
593 EXPECT_EQ(kUnixEpochYear, exploded.year);
594 EXPECT_EQ(1, exploded.month);
595 EXPECT_EQ(1, exploded.day_of_month);
596 EXPECT_EQ(0, exploded.hour);
597 EXPECT_EQ(0, exploded.minute);
598 EXPECT_EQ(0, exploded.second);
599 EXPECT_EQ(1, exploded.millisecond);
600
601 t = Time::UnixEpoch() + TimeDelta::FromMilliseconds(1000);
602 t.UTCExplode(&exploded);
603 EXPECT_TRUE(exploded.HasValidValues());
604 // Should be 1970-01-01 00:00:01.
605 EXPECT_EQ(kUnixEpochYear, exploded.year);
606 EXPECT_EQ(1, exploded.month);
607 EXPECT_EQ(1, exploded.day_of_month);
608 EXPECT_EQ(0, exploded.hour);
609 EXPECT_EQ(0, exploded.minute);
610 EXPECT_EQ(1, exploded.second);
611 EXPECT_EQ(0, exploded.millisecond);
612
613 t = Time::UnixEpoch() + TimeDelta::FromMilliseconds(1001);
614 t.UTCExplode(&exploded);
615 EXPECT_TRUE(exploded.HasValidValues());
616 // Should be 1970-01-01 00:00:01 1 millisecond.
617 EXPECT_EQ(kUnixEpochYear, exploded.year);
618 EXPECT_EQ(1, exploded.month);
619 EXPECT_EQ(1, exploded.day_of_month);
620 EXPECT_EQ(0, exploded.hour);
621 EXPECT_EQ(0, exploded.minute);
622 EXPECT_EQ(1, exploded.second);
623 EXPECT_EQ(1, exploded.millisecond);
624 }
625
TEST_F(TimeTest,Max)626 TEST_F(TimeTest, Max) {
627 Time max = Time::Max();
628 EXPECT_TRUE(max.is_max());
629 EXPECT_EQ(max, Time::Max());
630 EXPECT_GT(max, Time::Now());
631 EXPECT_GT(max, Time());
632 }
633
TEST_F(TimeTest,MaxConversions)634 TEST_F(TimeTest, MaxConversions) {
635 Time t = Time::Max();
636 EXPECT_EQ(std::numeric_limits<int64_t>::max(), t.ToInternalValue());
637
638 t = Time::FromDoubleT(std::numeric_limits<double>::infinity());
639 EXPECT_TRUE(t.is_max());
640 EXPECT_EQ(std::numeric_limits<double>::infinity(), t.ToDoubleT());
641
642 t = Time::FromJsTime(std::numeric_limits<double>::infinity());
643 EXPECT_TRUE(t.is_max());
644 EXPECT_EQ(std::numeric_limits<double>::infinity(), t.ToJsTime());
645
646 t = Time::FromTimeT(std::numeric_limits<time_t>::max());
647 EXPECT_TRUE(t.is_max());
648 EXPECT_EQ(std::numeric_limits<time_t>::max(), t.ToTimeT());
649
650 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
651 struct timeval tval;
652 tval.tv_sec = std::numeric_limits<time_t>::max();
653 tval.tv_usec = static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1;
654 t = Time::FromTimeVal(tval);
655 EXPECT_TRUE(t.is_max());
656 tval = t.ToTimeVal();
657 EXPECT_EQ(std::numeric_limits<time_t>::max(), tval.tv_sec);
658 EXPECT_EQ(static_cast<suseconds_t>(Time::kMicrosecondsPerSecond) - 1,
659 tval.tv_usec);
660 #endif
661
662 #if defined(OS_MACOSX)
663 t = Time::FromCFAbsoluteTime(std::numeric_limits<CFAbsoluteTime>::infinity());
664 EXPECT_TRUE(t.is_max());
665 EXPECT_EQ(std::numeric_limits<CFAbsoluteTime>::infinity(),
666 t.ToCFAbsoluteTime());
667 #endif
668
669 #if defined(OS_WIN)
670 FILETIME ftime;
671 ftime.dwHighDateTime = std::numeric_limits<DWORD>::max();
672 ftime.dwLowDateTime = std::numeric_limits<DWORD>::max();
673 t = Time::FromFileTime(ftime);
674 EXPECT_TRUE(t.is_max());
675 ftime = t.ToFileTime();
676 EXPECT_EQ(std::numeric_limits<DWORD>::max(), ftime.dwHighDateTime);
677 EXPECT_EQ(std::numeric_limits<DWORD>::max(), ftime.dwLowDateTime);
678 #endif
679 }
680
681 #if defined(OS_MACOSX)
TEST_F(TimeTest,TimeTOverflow)682 TEST_F(TimeTest, TimeTOverflow) {
683 Time t = Time::FromInternalValue(std::numeric_limits<int64_t>::max() - 1);
684 EXPECT_FALSE(t.is_max());
685 EXPECT_EQ(std::numeric_limits<time_t>::max(), t.ToTimeT());
686 }
687 #endif
688
689 #if defined(OS_ANDROID)
TEST_F(TimeTest,FromLocalExplodedCrashOnAndroid)690 TEST_F(TimeTest, FromLocalExplodedCrashOnAndroid) {
691 // This crashed inside Time:: FromLocalExploded() on Android 4.1.2.
692 // See http://crbug.com/287821
693 Time::Exploded midnight = {2013, // year
694 10, // month
695 0, // day_of_week
696 13, // day_of_month
697 0, // hour
698 0, // minute
699 0, // second
700 };
701 // The string passed to putenv() must be a char* and the documentation states
702 // that it 'becomes part of the environment', so use a static buffer.
703 static char buffer[] = "TZ=America/Santiago";
704 putenv(buffer);
705 tzset();
706 Time t;
707 EXPECT_TRUE(Time::FromLocalExploded(midnight, &t));
708 EXPECT_EQ(1381633200, t.ToTimeT());
709 }
710 #endif // OS_ANDROID
711
TEST_F(TimeTest,FromExploded_MinMax)712 TEST_F(TimeTest, FromExploded_MinMax) {
713 Time::Exploded exploded = {0};
714 exploded.month = 1;
715 exploded.day_of_month = 1;
716
717 Time parsed_time;
718
719 if (Time::kExplodedMinYear != std::numeric_limits<int>::min()) {
720 exploded.year = Time::kExplodedMinYear;
721 EXPECT_TRUE(Time::FromUTCExploded(exploded, &parsed_time));
722 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
723 // On Windows, January 1, 1601 00:00:00 is actually the null time.
724 EXPECT_FALSE(parsed_time.is_null());
725 #endif
726
727 #if !defined(OS_ANDROID) && !defined(OS_MACOSX)
728 // The dates earlier than |kExplodedMinYear| that don't work are OS version
729 // dependent on Android and Mac (for example, macOS 10.13 seems to support
730 // dates before 1902).
731 exploded.year--;
732 EXPECT_FALSE(Time::FromUTCExploded(exploded, &parsed_time));
733 EXPECT_TRUE(parsed_time.is_null());
734 #endif
735 }
736
737 if (Time::kExplodedMaxYear != std::numeric_limits<int>::max()) {
738 exploded.year = Time::kExplodedMaxYear;
739 exploded.month = 12;
740 exploded.day_of_month = 31;
741 exploded.hour = 23;
742 exploded.minute = 59;
743 exploded.second = 59;
744 exploded.millisecond = 999;
745 EXPECT_TRUE(Time::FromUTCExploded(exploded, &parsed_time));
746 EXPECT_FALSE(parsed_time.is_null());
747
748 exploded.year++;
749 EXPECT_FALSE(Time::FromUTCExploded(exploded, &parsed_time));
750 EXPECT_TRUE(parsed_time.is_null());
751 }
752 }
753
754 class TimeOverride {
755 public:
Now()756 static Time Now() {
757 now_time_ += TimeDelta::FromSeconds(1);
758 return now_time_;
759 }
760
761 static Time now_time_;
762 };
763
764 // static
765 Time TimeOverride::now_time_;
766
TEST_F(TimeTest,NowOverride)767 TEST_F(TimeTest, NowOverride) {
768 TimeOverride::now_time_ = Time::UnixEpoch();
769
770 // Choose a reference time that we know to be in the past but close to now.
771 Time build_time = GetBuildTime();
772
773 // Override is not active. All Now() methods should return a time greater than
774 // the build time.
775 EXPECT_LT(build_time, Time::Now());
776 EXPECT_GT(Time::Max(), Time::Now());
777 EXPECT_LT(build_time, subtle::TimeNowIgnoringOverride());
778 EXPECT_GT(Time::Max(), subtle::TimeNowIgnoringOverride());
779 EXPECT_LT(build_time, Time::NowFromSystemTime());
780 EXPECT_GT(Time::Max(), Time::NowFromSystemTime());
781 EXPECT_LT(build_time, subtle::TimeNowFromSystemTimeIgnoringOverride());
782 EXPECT_GT(Time::Max(), subtle::TimeNowFromSystemTimeIgnoringOverride());
783
784 {
785 // Set override.
786 subtle::ScopedTimeClockOverrides overrides(&TimeOverride::Now, nullptr,
787 nullptr);
788
789 // Overridden value is returned and incremented when Now() or
790 // NowFromSystemTime() is called.
791 EXPECT_EQ(Time::UnixEpoch() + TimeDelta::FromSeconds(1), Time::Now());
792 EXPECT_EQ(Time::UnixEpoch() + TimeDelta::FromSeconds(2), Time::Now());
793 EXPECT_EQ(Time::UnixEpoch() + TimeDelta::FromSeconds(3),
794 Time::NowFromSystemTime());
795 EXPECT_EQ(Time::UnixEpoch() + TimeDelta::FromSeconds(4),
796 Time::NowFromSystemTime());
797
798 // IgnoringOverride methods still return real time.
799 EXPECT_LT(build_time, subtle::TimeNowIgnoringOverride());
800 EXPECT_GT(Time::Max(), subtle::TimeNowIgnoringOverride());
801 EXPECT_LT(build_time, subtle::TimeNowFromSystemTimeIgnoringOverride());
802 EXPECT_GT(Time::Max(), subtle::TimeNowFromSystemTimeIgnoringOverride());
803
804 // IgnoringOverride methods didn't call NowOverrideClock::Now().
805 EXPECT_EQ(Time::UnixEpoch() + TimeDelta::FromSeconds(5), Time::Now());
806 EXPECT_EQ(Time::UnixEpoch() + TimeDelta::FromSeconds(6),
807 Time::NowFromSystemTime());
808 }
809
810 // All methods return real time again.
811 EXPECT_LT(build_time, Time::Now());
812 EXPECT_GT(Time::Max(), Time::Now());
813 EXPECT_LT(build_time, subtle::TimeNowIgnoringOverride());
814 EXPECT_GT(Time::Max(), subtle::TimeNowIgnoringOverride());
815 EXPECT_LT(build_time, Time::NowFromSystemTime());
816 EXPECT_GT(Time::Max(), Time::NowFromSystemTime());
817 EXPECT_LT(build_time, subtle::TimeNowFromSystemTimeIgnoringOverride());
818 EXPECT_GT(Time::Max(), subtle::TimeNowFromSystemTimeIgnoringOverride());
819 }
820
TEST(TimeTicks,Deltas)821 TEST(TimeTicks, Deltas) {
822 for (int index = 0; index < 50; index++) {
823 TimeTicks ticks_start = TimeTicks::Now();
824 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
825 TimeTicks ticks_stop = TimeTicks::Now();
826 TimeDelta delta = ticks_stop - ticks_start;
827 // Note: Although we asked for a 10ms sleep, if the
828 // time clock has a finer granularity than the Sleep()
829 // clock, it is quite possible to wakeup early. Here
830 // is how that works:
831 // Time(ms timer) Time(us timer)
832 // 5 5010
833 // 6 6010
834 // 7 7010
835 // 8 8010
836 // 9 9000
837 // Elapsed 4ms 3990us
838 //
839 // Unfortunately, our InMilliseconds() function truncates
840 // rather than rounds. We should consider fixing this
841 // so that our averages come out better.
842 EXPECT_GE(delta.InMilliseconds(), 9);
843 EXPECT_GE(delta.InMicroseconds(), 9000);
844 EXPECT_EQ(delta.InSeconds(), 0);
845 }
846 }
847
HighResClockTest(TimeTicks (* GetTicks)())848 static void HighResClockTest(TimeTicks (*GetTicks)()) {
849 // IsHighResolution() is false on some systems. Since the product still works
850 // even if it's false, it makes this entire test questionable.
851 if (!TimeTicks::IsHighResolution())
852 return;
853
854 // Why do we loop here?
855 // We're trying to measure that intervals increment in a VERY small amount
856 // of time -- less than 15ms. Unfortunately, if we happen to have a
857 // context switch in the middle of our test, the context switch could easily
858 // exceed our limit. So, we iterate on this several times. As long as we're
859 // able to detect the fine-granularity timers at least once, then the test
860 // has succeeded.
861
862 const int kTargetGranularityUs = 15000; // 15ms
863
864 bool success = false;
865 int retries = 100; // Arbitrary.
866 TimeDelta delta;
867 while (!success && retries--) {
868 TimeTicks ticks_start = GetTicks();
869 // Loop until we can detect that the clock has changed. Non-HighRes timers
870 // will increment in chunks, e.g. 15ms. By spinning until we see a clock
871 // change, we detect the minimum time between measurements.
872 do {
873 delta = GetTicks() - ticks_start;
874 } while (delta.InMilliseconds() == 0);
875
876 if (delta.InMicroseconds() <= kTargetGranularityUs)
877 success = true;
878 }
879
880 // In high resolution mode, we expect to see the clock increment
881 // in intervals less than 15ms.
882 EXPECT_TRUE(success);
883 }
884
TEST(TimeTicks,HighRes)885 TEST(TimeTicks, HighRes) {
886 HighResClockTest(&TimeTicks::Now);
887 }
888
889 class TimeTicksOverride {
890 public:
Now()891 static TimeTicks Now() {
892 now_ticks_ += TimeDelta::FromSeconds(1);
893 return now_ticks_;
894 }
895
896 static TimeTicks now_ticks_;
897 };
898
899 // static
900 TimeTicks TimeTicksOverride::now_ticks_;
901
TEST(TimeTicks,NowOverride)902 TEST(TimeTicks, NowOverride) {
903 TimeTicksOverride::now_ticks_ = TimeTicks::Min();
904
905 // Override is not active. All Now() methods should return a sensible value.
906 EXPECT_LT(TimeTicks::Min(), TimeTicks::UnixEpoch());
907 EXPECT_LT(TimeTicks::UnixEpoch(), TimeTicks::Now());
908 EXPECT_GT(TimeTicks::Max(), TimeTicks::Now());
909 EXPECT_LT(TimeTicks::UnixEpoch(), subtle::TimeTicksNowIgnoringOverride());
910 EXPECT_GT(TimeTicks::Max(), subtle::TimeTicksNowIgnoringOverride());
911
912 {
913 // Set override.
914 subtle::ScopedTimeClockOverrides overrides(nullptr, &TimeTicksOverride::Now,
915 nullptr);
916
917 // Overridden value is returned and incremented when Now() is called.
918 EXPECT_EQ(TimeTicks::Min() + TimeDelta::FromSeconds(1), TimeTicks::Now());
919 EXPECT_EQ(TimeTicks::Min() + TimeDelta::FromSeconds(2), TimeTicks::Now());
920
921 // NowIgnoringOverride() still returns real ticks.
922 EXPECT_LT(TimeTicks::UnixEpoch(), subtle::TimeTicksNowIgnoringOverride());
923 EXPECT_GT(TimeTicks::Max(), subtle::TimeTicksNowIgnoringOverride());
924
925 // IgnoringOverride methods didn't call NowOverrideTickClock::NowTicks().
926 EXPECT_EQ(TimeTicks::Min() + TimeDelta::FromSeconds(3), TimeTicks::Now());
927 }
928
929 // All methods return real ticks again.
930 EXPECT_LT(TimeTicks::UnixEpoch(), TimeTicks::Now());
931 EXPECT_GT(TimeTicks::Max(), TimeTicks::Now());
932 EXPECT_LT(TimeTicks::UnixEpoch(), subtle::TimeTicksNowIgnoringOverride());
933 EXPECT_GT(TimeTicks::Max(), subtle::TimeTicksNowIgnoringOverride());
934 }
935
936 class ThreadTicksOverride {
937 public:
Now()938 static ThreadTicks Now() {
939 now_ticks_ += TimeDelta::FromSeconds(1);
940 return now_ticks_;
941 }
942
943 static ThreadTicks now_ticks_;
944 };
945
946 // static
947 ThreadTicks ThreadTicksOverride::now_ticks_;
948
949 // IOS doesn't support ThreadTicks::Now().
950 #if defined(OS_IOS)
951 #define MAYBE_NowOverride DISABLED_NowOverride
952 #else
953 #define MAYBE_NowOverride NowOverride
954 #endif
TEST(ThreadTicks,MAYBE_NowOverride)955 TEST(ThreadTicks, MAYBE_NowOverride) {
956 ThreadTicksOverride::now_ticks_ = ThreadTicks::Min();
957
958 // Override is not active. All Now() methods should return a sensible value.
959 ThreadTicks initial_thread_ticks = ThreadTicks::Now();
960 EXPECT_LE(initial_thread_ticks, ThreadTicks::Now());
961 EXPECT_GT(ThreadTicks::Max(), ThreadTicks::Now());
962 EXPECT_LE(initial_thread_ticks, subtle::ThreadTicksNowIgnoringOverride());
963 EXPECT_GT(ThreadTicks::Max(), subtle::ThreadTicksNowIgnoringOverride());
964
965 {
966 // Set override.
967 subtle::ScopedTimeClockOverrides overrides(nullptr, nullptr,
968 &ThreadTicksOverride::Now);
969
970 // Overridden value is returned and incremented when Now() is called.
971 EXPECT_EQ(ThreadTicks::Min() + TimeDelta::FromSeconds(1),
972 ThreadTicks::Now());
973 EXPECT_EQ(ThreadTicks::Min() + TimeDelta::FromSeconds(2),
974 ThreadTicks::Now());
975
976 // NowIgnoringOverride() still returns real ticks.
977 EXPECT_LE(initial_thread_ticks, subtle::ThreadTicksNowIgnoringOverride());
978 EXPECT_GT(ThreadTicks::Max(), subtle::ThreadTicksNowIgnoringOverride());
979
980 // IgnoringOverride methods didn't call NowOverrideTickClock::NowTicks().
981 EXPECT_EQ(ThreadTicks::Min() + TimeDelta::FromSeconds(3),
982 ThreadTicks::Now());
983 }
984
985 // All methods return real ticks again.
986 EXPECT_LE(initial_thread_ticks, ThreadTicks::Now());
987 EXPECT_GT(ThreadTicks::Max(), ThreadTicks::Now());
988 EXPECT_LE(initial_thread_ticks, subtle::ThreadTicksNowIgnoringOverride());
989 EXPECT_GT(ThreadTicks::Max(), subtle::ThreadTicksNowIgnoringOverride());
990 }
991
TEST(ThreadTicks,ThreadNow)992 TEST(ThreadTicks, ThreadNow) {
993 if (ThreadTicks::IsSupported()) {
994 ThreadTicks::WaitUntilInitialized();
995 TimeTicks begin = TimeTicks::Now();
996 ThreadTicks begin_thread = ThreadTicks::Now();
997 // Make sure that ThreadNow value is non-zero.
998 EXPECT_GT(begin_thread, ThreadTicks());
999 // Sleep for 10 milliseconds to get the thread de-scheduled.
1000 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
1001 ThreadTicks end_thread = ThreadTicks::Now();
1002 TimeTicks end = TimeTicks::Now();
1003 TimeDelta delta = end - begin;
1004 TimeDelta delta_thread = end_thread - begin_thread;
1005 // Make sure that some thread time have elapsed.
1006 EXPECT_GE(delta_thread.InMicroseconds(), 0);
1007 // But the thread time is at least 9ms less than clock time.
1008 TimeDelta difference = delta - delta_thread;
1009 EXPECT_GE(difference.InMicroseconds(), 9000);
1010 }
1011 }
1012
TEST(TimeTicks,SnappedToNextTickBasic)1013 TEST(TimeTicks, SnappedToNextTickBasic) {
1014 base::TimeTicks phase = base::TimeTicks::FromInternalValue(4000);
1015 base::TimeDelta interval = base::TimeDelta::FromMicroseconds(1000);
1016 base::TimeTicks timestamp;
1017
1018 // Timestamp in previous interval.
1019 timestamp = base::TimeTicks::FromInternalValue(3500);
1020 EXPECT_EQ(4000,
1021 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1022
1023 // Timestamp in next interval.
1024 timestamp = base::TimeTicks::FromInternalValue(4500);
1025 EXPECT_EQ(5000,
1026 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1027
1028 // Timestamp multiple intervals before.
1029 timestamp = base::TimeTicks::FromInternalValue(2500);
1030 EXPECT_EQ(3000,
1031 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1032
1033 // Timestamp multiple intervals after.
1034 timestamp = base::TimeTicks::FromInternalValue(6500);
1035 EXPECT_EQ(7000,
1036 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1037
1038 // Timestamp on previous interval.
1039 timestamp = base::TimeTicks::FromInternalValue(3000);
1040 EXPECT_EQ(3000,
1041 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1042
1043 // Timestamp on next interval.
1044 timestamp = base::TimeTicks::FromInternalValue(5000);
1045 EXPECT_EQ(5000,
1046 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1047
1048 // Timestamp equal to phase.
1049 timestamp = base::TimeTicks::FromInternalValue(4000);
1050 EXPECT_EQ(4000,
1051 timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1052 }
1053
TEST(TimeTicks,SnappedToNextTickOverflow)1054 TEST(TimeTicks, SnappedToNextTickOverflow) {
1055 // int(big_timestamp / interval) < 0, so this causes a crash if the number of
1056 // intervals elapsed is attempted to be stored in an int.
1057 base::TimeTicks phase = base::TimeTicks::FromInternalValue(0);
1058 base::TimeDelta interval = base::TimeDelta::FromMicroseconds(4000);
1059 base::TimeTicks big_timestamp =
1060 base::TimeTicks::FromInternalValue(8635916564000);
1061
1062 EXPECT_EQ(8635916564000,
1063 big_timestamp.SnappedToNextTick(phase, interval).ToInternalValue());
1064 EXPECT_EQ(8635916564000,
1065 big_timestamp.SnappedToNextTick(big_timestamp, interval)
1066 .ToInternalValue());
1067 }
1068
1069 #if defined(OS_ANDROID)
TEST(TimeTicks,Android_FromUptimeMillis_ClocksMatch)1070 TEST(TimeTicks, Android_FromUptimeMillis_ClocksMatch) {
1071 JNIEnv* const env = android::AttachCurrentThread();
1072 android::ScopedJavaLocalRef<jclass> clazz(
1073 android::GetClass(env, "android/os/SystemClock"));
1074 ASSERT_TRUE(clazz.obj());
1075 const jmethodID method_id =
1076 android::MethodID::Get<android::MethodID::TYPE_STATIC>(
1077 env, clazz.obj(), "uptimeMillis", "()J");
1078 ASSERT_FALSE(!method_id);
1079 // Subtract 1ms from the expected lower bound to allow millisecon-level
1080 // truncation performed in uptimeMillis().
1081 const TimeTicks lower_bound_ticks =
1082 TimeTicks::Now() - TimeDelta::FromMilliseconds(1);
1083 const TimeTicks converted_ticks = TimeTicks::FromUptimeMillis(
1084 env->CallStaticLongMethod(clazz.obj(), method_id));
1085 const TimeTicks upper_bound_ticks = TimeTicks::Now();
1086 EXPECT_LE(lower_bound_ticks, converted_ticks);
1087 EXPECT_GE(upper_bound_ticks, converted_ticks);
1088 }
1089 #endif // OS_ANDROID
1090
TEST(TimeDelta,FromAndIn)1091 TEST(TimeDelta, FromAndIn) {
1092 // static_assert also checks that the contained expression is a constant
1093 // expression, meaning all its components are suitable for initializing global
1094 // variables.
1095 static_assert(TimeDelta::FromDays(2) == TimeDelta::FromHours(48), "");
1096 static_assert(TimeDelta::FromHours(3) == TimeDelta::FromMinutes(180), "");
1097 static_assert(TimeDelta::FromMinutes(2) == TimeDelta::FromSeconds(120), "");
1098 static_assert(TimeDelta::FromSeconds(2) == TimeDelta::FromMilliseconds(2000),
1099 "");
1100 static_assert(
1101 TimeDelta::FromMilliseconds(2) == TimeDelta::FromMicroseconds(2000), "");
1102 static_assert(
1103 TimeDelta::FromSecondsD(2.3) == TimeDelta::FromMilliseconds(2300), "");
1104 static_assert(
1105 TimeDelta::FromMillisecondsD(2.5) == TimeDelta::FromMicroseconds(2500),
1106 "");
1107 EXPECT_EQ(TimeDelta::FromDays(13).InDays(), 13);
1108 EXPECT_EQ(TimeDelta::FromHours(13).InHours(), 13);
1109 EXPECT_EQ(TimeDelta::FromMinutes(13).InMinutes(), 13);
1110 EXPECT_EQ(TimeDelta::FromSeconds(13).InSeconds(), 13);
1111 EXPECT_EQ(TimeDelta::FromSeconds(13).InSecondsF(), 13.0);
1112 EXPECT_EQ(TimeDelta::FromMilliseconds(13).InMilliseconds(), 13);
1113 EXPECT_EQ(TimeDelta::FromMilliseconds(13).InMillisecondsF(), 13.0);
1114 EXPECT_EQ(TimeDelta::FromSecondsD(13.1).InSeconds(), 13);
1115 EXPECT_EQ(TimeDelta::FromSecondsD(13.1).InSecondsF(), 13.1);
1116 EXPECT_EQ(TimeDelta::FromMillisecondsD(13.3).InMilliseconds(), 13);
1117 EXPECT_EQ(TimeDelta::FromMillisecondsD(13.3).InMillisecondsF(), 13.3);
1118 EXPECT_EQ(TimeDelta::FromMicroseconds(13).InMicroseconds(), 13);
1119 EXPECT_EQ(TimeDelta::FromMicrosecondsD(13.3).InMicroseconds(), 13);
1120 EXPECT_EQ(TimeDelta::FromMillisecondsD(3.45678).InMillisecondsF(), 3.456);
1121 EXPECT_EQ(TimeDelta::FromNanoseconds(12345).InNanoseconds(), 12000);
1122 EXPECT_EQ(TimeDelta::FromNanosecondsD(12345.678).InNanoseconds(), 12000);
1123 }
1124
TEST(TimeDelta,InRoundsTowardsZero)1125 TEST(TimeDelta, InRoundsTowardsZero) {
1126 EXPECT_EQ(TimeDelta::FromHours(23).InDays(), 0);
1127 EXPECT_EQ(TimeDelta::FromHours(-23).InDays(), 0);
1128 EXPECT_EQ(TimeDelta::FromMinutes(59).InHours(), 0);
1129 EXPECT_EQ(TimeDelta::FromMinutes(-59).InHours(), 0);
1130 EXPECT_EQ(TimeDelta::FromSeconds(59).InMinutes(), 0);
1131 EXPECT_EQ(TimeDelta::FromSeconds(-59).InMinutes(), 0);
1132 EXPECT_EQ(TimeDelta::FromMilliseconds(999).InSeconds(), 0);
1133 EXPECT_EQ(TimeDelta::FromMilliseconds(-999).InSeconds(), 0);
1134 EXPECT_EQ(TimeDelta::FromMicroseconds(999).InMilliseconds(), 0);
1135 EXPECT_EQ(TimeDelta::FromMicroseconds(-999).InMilliseconds(), 0);
1136 }
1137
TEST(TimeDelta,InDaysFloored)1138 TEST(TimeDelta, InDaysFloored) {
1139 EXPECT_EQ(TimeDelta::FromHours(-25).InDaysFloored(), -2);
1140 EXPECT_EQ(TimeDelta::FromHours(-24).InDaysFloored(), -1);
1141 EXPECT_EQ(TimeDelta::FromHours(-23).InDaysFloored(), -1);
1142
1143 EXPECT_EQ(TimeDelta::FromHours(-1).InDaysFloored(), -1);
1144 EXPECT_EQ(TimeDelta::FromHours(0).InDaysFloored(), 0);
1145 EXPECT_EQ(TimeDelta::FromHours(1).InDaysFloored(), 0);
1146
1147 EXPECT_EQ(TimeDelta::FromHours(23).InDaysFloored(), 0);
1148 EXPECT_EQ(TimeDelta::FromHours(24).InDaysFloored(), 1);
1149 EXPECT_EQ(TimeDelta::FromHours(25).InDaysFloored(), 1);
1150 }
1151
TEST(TimeDelta,InMillisecondsRoundedUp)1152 TEST(TimeDelta, InMillisecondsRoundedUp) {
1153 EXPECT_EQ(TimeDelta::FromMicroseconds(-1001).InMillisecondsRoundedUp(), -1);
1154 EXPECT_EQ(TimeDelta::FromMicroseconds(-1000).InMillisecondsRoundedUp(), -1);
1155 EXPECT_EQ(TimeDelta::FromMicroseconds(-999).InMillisecondsRoundedUp(), 0);
1156
1157 EXPECT_EQ(TimeDelta::FromMicroseconds(-1).InMillisecondsRoundedUp(), 0);
1158 EXPECT_EQ(TimeDelta::FromMicroseconds(0).InMillisecondsRoundedUp(), 0);
1159 EXPECT_EQ(TimeDelta::FromMicroseconds(1).InMillisecondsRoundedUp(), 1);
1160
1161 EXPECT_EQ(TimeDelta::FromMicroseconds(999).InMillisecondsRoundedUp(), 1);
1162 EXPECT_EQ(TimeDelta::FromMicroseconds(1000).InMillisecondsRoundedUp(), 1);
1163 EXPECT_EQ(TimeDelta::FromMicroseconds(1001).InMillisecondsRoundedUp(), 2);
1164 }
1165
1166 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
TEST(TimeDelta,TimeSpecConversion)1167 TEST(TimeDelta, TimeSpecConversion) {
1168 TimeDelta delta = TimeDelta::FromSeconds(0);
1169 struct timespec result = delta.ToTimeSpec();
1170 EXPECT_EQ(result.tv_sec, 0);
1171 EXPECT_EQ(result.tv_nsec, 0);
1172 EXPECT_EQ(delta, TimeDelta::FromTimeSpec(result));
1173
1174 delta = TimeDelta::FromSeconds(1);
1175 result = delta.ToTimeSpec();
1176 EXPECT_EQ(result.tv_sec, 1);
1177 EXPECT_EQ(result.tv_nsec, 0);
1178 EXPECT_EQ(delta, TimeDelta::FromTimeSpec(result));
1179
1180 delta = TimeDelta::FromMicroseconds(1);
1181 result = delta.ToTimeSpec();
1182 EXPECT_EQ(result.tv_sec, 0);
1183 EXPECT_EQ(result.tv_nsec, 1000);
1184 EXPECT_EQ(delta, TimeDelta::FromTimeSpec(result));
1185
1186 delta = TimeDelta::FromMicroseconds(Time::kMicrosecondsPerSecond + 1);
1187 result = delta.ToTimeSpec();
1188 EXPECT_EQ(result.tv_sec, 1);
1189 EXPECT_EQ(result.tv_nsec, 1000);
1190 EXPECT_EQ(delta, TimeDelta::FromTimeSpec(result));
1191 }
1192 #endif // defined(OS_POSIX) || defined(OS_FUCHSIA)
1193
1194 // Our internal time format is serialized in things like databases, so it's
1195 // important that it's consistent across all our platforms. We use the 1601
1196 // Windows epoch as the internal format across all platforms.
TEST(TimeDelta,WindowsEpoch)1197 TEST(TimeDelta, WindowsEpoch) {
1198 Time::Exploded exploded;
1199 exploded.year = 1970;
1200 exploded.month = 1;
1201 exploded.day_of_week = 0; // Should be unusued.
1202 exploded.day_of_month = 1;
1203 exploded.hour = 0;
1204 exploded.minute = 0;
1205 exploded.second = 0;
1206 exploded.millisecond = 0;
1207 Time t;
1208 EXPECT_TRUE(Time::FromUTCExploded(exploded, &t));
1209 // Unix 1970 epoch.
1210 EXPECT_EQ(INT64_C(11644473600000000), t.ToInternalValue());
1211
1212 // We can't test 1601 epoch, since the system time functions on Linux
1213 // only compute years starting from 1900.
1214 }
1215
1216 // We could define this separately for Time, TimeTicks and TimeDelta but the
1217 // definitions would be identical anyway.
1218 template <class Any>
AnyToString(Any any)1219 std::string AnyToString(Any any) {
1220 std::ostringstream oss;
1221 oss << any;
1222 return oss.str();
1223 }
1224
TEST(TimeDelta,Magnitude)1225 TEST(TimeDelta, Magnitude) {
1226 constexpr int64_t zero = 0;
1227 static_assert(TimeDelta::FromMicroseconds(zero) ==
1228 TimeDelta::FromMicroseconds(zero).magnitude(),
1229 "");
1230
1231 constexpr int64_t one = 1;
1232 constexpr int64_t negative_one = -1;
1233 static_assert(TimeDelta::FromMicroseconds(one) ==
1234 TimeDelta::FromMicroseconds(one).magnitude(),
1235 "");
1236 static_assert(TimeDelta::FromMicroseconds(one) ==
1237 TimeDelta::FromMicroseconds(negative_one).magnitude(),
1238 "");
1239
1240 constexpr int64_t max_int64_minus_one =
1241 std::numeric_limits<int64_t>::max() - 1;
1242 constexpr int64_t min_int64_plus_two =
1243 std::numeric_limits<int64_t>::min() + 2;
1244 static_assert(
1245 TimeDelta::FromMicroseconds(max_int64_minus_one) ==
1246 TimeDelta::FromMicroseconds(max_int64_minus_one).magnitude(),
1247 "");
1248 static_assert(TimeDelta::FromMicroseconds(max_int64_minus_one) ==
1249 TimeDelta::FromMicroseconds(min_int64_plus_two).magnitude(),
1250 "");
1251 }
1252
TEST(TimeDelta,ZeroMinMax)1253 TEST(TimeDelta, ZeroMinMax) {
1254 constexpr TimeDelta kZero;
1255 static_assert(kZero.is_zero(), "");
1256
1257 constexpr TimeDelta kMax = TimeDelta::Max();
1258 static_assert(kMax.is_max(), "");
1259 static_assert(kMax == TimeDelta::Max(), "");
1260 static_assert(kMax > TimeDelta::FromDays(100 * 365), "");
1261 static_assert(kMax > kZero, "");
1262
1263 constexpr TimeDelta kMin = TimeDelta::Min();
1264 static_assert(kMin.is_min(), "");
1265 static_assert(kMin == TimeDelta::Min(), "");
1266 static_assert(kMin < TimeDelta::FromDays(-100 * 365), "");
1267 static_assert(kMin < kZero, "");
1268 }
1269
TEST(TimeDelta,MaxConversions)1270 TEST(TimeDelta, MaxConversions) {
1271 // static_assert also confirms constexpr works as intended.
1272 constexpr TimeDelta kMax = TimeDelta::Max();
1273 static_assert(kMax.ToInternalValue() == std::numeric_limits<int64_t>::max(),
1274 "");
1275 EXPECT_EQ(kMax.InDays(), std::numeric_limits<int>::max());
1276 EXPECT_EQ(kMax.InHours(), std::numeric_limits<int>::max());
1277 EXPECT_EQ(kMax.InMinutes(), std::numeric_limits<int>::max());
1278 EXPECT_EQ(kMax.InSecondsF(), std::numeric_limits<double>::infinity());
1279 EXPECT_EQ(kMax.InSeconds(), std::numeric_limits<int64_t>::max());
1280 EXPECT_EQ(kMax.InMillisecondsF(), std::numeric_limits<double>::infinity());
1281 EXPECT_EQ(kMax.InMilliseconds(), std::numeric_limits<int64_t>::max());
1282 EXPECT_EQ(kMax.InMillisecondsRoundedUp(), std::numeric_limits<int64_t>::max());
1283
1284 static_assert(TimeDelta::FromDays(std::numeric_limits<int>::max()).is_max(),
1285 "");
1286
1287 static_assert(TimeDelta::FromHours(std::numeric_limits<int>::max()).is_max(),
1288 "");
1289
1290 static_assert(
1291 TimeDelta::FromMinutes(std::numeric_limits<int>::max()).is_max(), "");
1292
1293 constexpr int64_t max_int = std::numeric_limits<int64_t>::max();
1294 constexpr int64_t min_int = std::numeric_limits<int64_t>::min();
1295
1296 static_assert(
1297 TimeDelta::FromSeconds(max_int / Time::kMicrosecondsPerSecond + 1)
1298 .is_max(),
1299 "");
1300
1301 static_assert(
1302 TimeDelta::FromMilliseconds(max_int / Time::kMillisecondsPerSecond + 1)
1303 .is_max(),
1304 "");
1305
1306 static_assert(TimeDelta::FromMicroseconds(max_int).is_max(), "");
1307
1308 static_assert(
1309 TimeDelta::FromSeconds(min_int / Time::kMicrosecondsPerSecond - 1)
1310 .is_min(),
1311 "");
1312
1313 static_assert(
1314 TimeDelta::FromMilliseconds(min_int / Time::kMillisecondsPerSecond - 1)
1315 .is_min(),
1316 "");
1317
1318 static_assert(TimeDelta::FromMicroseconds(min_int).is_min(), "");
1319
1320 static_assert(
1321 TimeDelta::FromMicroseconds(std::numeric_limits<int64_t>::min()).is_min(),
1322 "");
1323
1324 // Floating point arithmetic resulting in infinity isn't constexpr in C++14.
1325 EXPECT_TRUE(TimeDelta::FromSecondsD(std::numeric_limits<double>::infinity())
1326 .is_max());
1327
1328 // Note that max_int/min_int will be rounded when converted to doubles - they
1329 // can't be exactly represented.
1330 constexpr double max_d = static_cast<double>(max_int);
1331 constexpr double min_d = static_cast<double>(min_int);
1332
1333 static_assert(
1334 TimeDelta::FromSecondsD(max_d / Time::kMicrosecondsPerSecond + 1)
1335 .is_max(),
1336 "");
1337
1338 // Floating point arithmetic resulting in infinity isn't constexpr in C++14.
1339 EXPECT_TRUE(
1340 TimeDelta::FromMillisecondsD(std::numeric_limits<double>::infinity())
1341 .is_max());
1342
1343 static_assert(
1344 TimeDelta::FromMillisecondsD(max_d / Time::kMillisecondsPerSecond * 2)
1345 .is_max(),
1346 "");
1347
1348 static_assert(
1349 TimeDelta::FromSecondsD(min_d / Time::kMicrosecondsPerSecond - 1)
1350 .is_min(),
1351 "");
1352
1353 static_assert(
1354 TimeDelta::FromMillisecondsD(min_d / Time::kMillisecondsPerSecond * 2)
1355 .is_min(),
1356 "");
1357 }
1358
TEST(TimeDelta,NumericOperators)1359 TEST(TimeDelta, NumericOperators) {
1360 constexpr double d = 0.5;
1361 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1362 (TimeDelta::FromMilliseconds(1000) * d));
1363 static_assert(TimeDelta::FromMilliseconds(2000) ==
1364 (TimeDelta::FromMilliseconds(1000) / d),
1365 "");
1366 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1367 (TimeDelta::FromMilliseconds(1000) *= d));
1368 static_assert(TimeDelta::FromMilliseconds(2000) ==
1369 (TimeDelta::FromMilliseconds(1000) /= d),
1370 "");
1371 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1372 (d * TimeDelta::FromMilliseconds(1000)));
1373
1374 constexpr float f = 0.5;
1375 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1376 (TimeDelta::FromMilliseconds(1000) * f));
1377 static_assert(TimeDelta::FromMilliseconds(2000) ==
1378 (TimeDelta::FromMilliseconds(1000) / f),
1379 "");
1380 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1381 (TimeDelta::FromMilliseconds(1000) *= f));
1382 static_assert(TimeDelta::FromMilliseconds(2000) ==
1383 (TimeDelta::FromMilliseconds(1000) /= f),
1384 "");
1385 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1386 (f * TimeDelta::FromMilliseconds(1000)));
1387
1388 constexpr int i = 2;
1389 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1390 (TimeDelta::FromMilliseconds(1000) * i));
1391 static_assert(TimeDelta::FromMilliseconds(500) ==
1392 (TimeDelta::FromMilliseconds(1000) / i),
1393 "");
1394 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1395 (TimeDelta::FromMilliseconds(1000) *= i));
1396 static_assert(TimeDelta::FromMilliseconds(500) ==
1397 (TimeDelta::FromMilliseconds(1000) /= i),
1398 "");
1399 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1400 (i * TimeDelta::FromMilliseconds(1000)));
1401
1402 constexpr int64_t i64 = 2;
1403 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1404 (TimeDelta::FromMilliseconds(1000) * i64));
1405 static_assert(TimeDelta::FromMilliseconds(500) ==
1406 (TimeDelta::FromMilliseconds(1000) / i64),
1407 "");
1408 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1409 (TimeDelta::FromMilliseconds(1000) *= i64));
1410 static_assert(TimeDelta::FromMilliseconds(500) ==
1411 (TimeDelta::FromMilliseconds(1000) /= i64),
1412 "");
1413 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1414 (i64 * TimeDelta::FromMilliseconds(1000)));
1415
1416 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1417 (TimeDelta::FromMilliseconds(1000) * 0.5));
1418 static_assert(TimeDelta::FromMilliseconds(2000) ==
1419 (TimeDelta::FromMilliseconds(1000) / 0.5),
1420 "");
1421 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1422 (TimeDelta::FromMilliseconds(1000) *= 0.5));
1423 static_assert(TimeDelta::FromMilliseconds(2000) ==
1424 (TimeDelta::FromMilliseconds(1000) /= 0.5),
1425 "");
1426 EXPECT_EQ(TimeDelta::FromMilliseconds(500),
1427 (0.5 * TimeDelta::FromMilliseconds(1000)));
1428
1429 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1430 (TimeDelta::FromMilliseconds(1000) * 2));
1431 static_assert(TimeDelta::FromMilliseconds(500) ==
1432 (TimeDelta::FromMilliseconds(1000) / 2),
1433 "");
1434 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1435 (TimeDelta::FromMilliseconds(1000) *= 2));
1436 static_assert(TimeDelta::FromMilliseconds(500) ==
1437 (TimeDelta::FromMilliseconds(1000) /= 2),
1438 "");
1439 EXPECT_EQ(TimeDelta::FromMilliseconds(2000),
1440 (2 * TimeDelta::FromMilliseconds(1000)));
1441 }
1442
1443 // Basic test of operators between TimeDeltas (without overflow -- next test
1444 // handles overflow).
TEST(TimeDelta,TimeDeltaOperators)1445 TEST(TimeDelta, TimeDeltaOperators) {
1446 constexpr TimeDelta kElevenSeconds = TimeDelta::FromSeconds(11);
1447 constexpr TimeDelta kThreeSeconds = TimeDelta::FromSeconds(3);
1448
1449 EXPECT_EQ(TimeDelta::FromSeconds(14), kElevenSeconds + kThreeSeconds);
1450 EXPECT_EQ(TimeDelta::FromSeconds(14), kThreeSeconds + kElevenSeconds);
1451 EXPECT_EQ(TimeDelta::FromSeconds(8), kElevenSeconds - kThreeSeconds);
1452 EXPECT_EQ(TimeDelta::FromSeconds(-8), kThreeSeconds - kElevenSeconds);
1453 static_assert(3 == kElevenSeconds / kThreeSeconds, "");
1454 static_assert(0 == kThreeSeconds / kElevenSeconds, "");
1455 static_assert(TimeDelta::FromSeconds(2) == kElevenSeconds % kThreeSeconds,
1456 "");
1457 }
1458
TEST(TimeDelta,Overflows)1459 TEST(TimeDelta, Overflows) {
1460 // Some sanity checks. static_assert's used were possible to verify constexpr
1461 // evaluation at the same time.
1462 static_assert(TimeDelta::Max().is_max(), "");
1463 static_assert(-TimeDelta::Max() < TimeDelta(), "");
1464 static_assert(-TimeDelta::Max() > TimeDelta::Min(), "");
1465 static_assert(TimeDelta() > -TimeDelta::Max(), "");
1466
1467 TimeDelta large_delta = TimeDelta::Max() - TimeDelta::FromMilliseconds(1);
1468 TimeDelta large_negative = -large_delta;
1469 EXPECT_GT(TimeDelta(), large_negative);
1470 EXPECT_FALSE(large_delta.is_max());
1471 EXPECT_FALSE((-large_negative).is_min());
1472 constexpr TimeDelta kOneSecond = TimeDelta::FromSeconds(1);
1473
1474 // Test +, -, * and / operators.
1475 EXPECT_TRUE((large_delta + kOneSecond).is_max());
1476 EXPECT_TRUE((large_negative + (-kOneSecond)).is_min());
1477 EXPECT_TRUE((large_negative - kOneSecond).is_min());
1478 EXPECT_TRUE((large_delta - (-kOneSecond)).is_max());
1479 EXPECT_TRUE((large_delta * 2).is_max());
1480 EXPECT_TRUE((large_delta * -2).is_min());
1481 EXPECT_TRUE((large_delta / 0.5).is_max());
1482 EXPECT_TRUE((large_delta / -0.5).is_min());
1483
1484 // Test that double conversions overflow to infinity.
1485 EXPECT_EQ((large_delta + kOneSecond).InSecondsF(),
1486 std::numeric_limits<double>::infinity());
1487 EXPECT_EQ((large_delta + kOneSecond).InMillisecondsF(),
1488 std::numeric_limits<double>::infinity());
1489 EXPECT_EQ((large_delta + kOneSecond).InMicrosecondsF(),
1490 std::numeric_limits<double>::infinity());
1491
1492 // Test +=, -=, *= and /= operators.
1493 TimeDelta delta = large_delta;
1494 delta += kOneSecond;
1495 EXPECT_TRUE(delta.is_max());
1496 delta = large_negative;
1497 delta += -kOneSecond;
1498 EXPECT_TRUE((delta).is_min());
1499
1500 delta = large_negative;
1501 delta -= kOneSecond;
1502 EXPECT_TRUE((delta).is_min());
1503 delta = large_delta;
1504 delta -= -kOneSecond;
1505 EXPECT_TRUE(delta.is_max());
1506
1507 delta = large_delta;
1508 delta *= 2;
1509 EXPECT_TRUE(delta.is_max());
1510 delta = large_negative;
1511 delta *= 1.5;
1512 EXPECT_TRUE((delta).is_min());
1513
1514 delta = large_delta;
1515 delta /= 0.5;
1516 EXPECT_TRUE(delta.is_max());
1517 delta = large_negative;
1518 delta /= 0.5;
1519 EXPECT_TRUE((delta).is_min());
1520
1521 // Test operations with Time and TimeTicks.
1522 EXPECT_TRUE((large_delta + Time::Now()).is_max());
1523 EXPECT_TRUE((large_delta + TimeTicks::Now()).is_max());
1524 EXPECT_TRUE((Time::Now() + large_delta).is_max());
1525 EXPECT_TRUE((TimeTicks::Now() + large_delta).is_max());
1526
1527 Time time_now = Time::Now();
1528 EXPECT_EQ(kOneSecond, (time_now + kOneSecond) - time_now);
1529 EXPECT_EQ(-kOneSecond, (time_now - kOneSecond) - time_now);
1530
1531 TimeTicks ticks_now = TimeTicks::Now();
1532 EXPECT_EQ(-kOneSecond, (ticks_now - kOneSecond) - ticks_now);
1533 EXPECT_EQ(kOneSecond, (ticks_now + kOneSecond) - ticks_now);
1534 }
1535
TEST(TimeDeltaLogging,DCheckEqCompiles)1536 TEST(TimeDeltaLogging, DCheckEqCompiles) {
1537 DCHECK_EQ(TimeDelta(), TimeDelta());
1538 }
1539
TEST(TimeDeltaLogging,EmptyIsZero)1540 TEST(TimeDeltaLogging, EmptyIsZero) {
1541 constexpr TimeDelta kZero;
1542 EXPECT_EQ("0 s", AnyToString(kZero));
1543 }
1544
TEST(TimeDeltaLogging,FiveHundredMs)1545 TEST(TimeDeltaLogging, FiveHundredMs) {
1546 constexpr TimeDelta kFiveHundredMs = TimeDelta::FromMilliseconds(500);
1547 EXPECT_EQ("0.5 s", AnyToString(kFiveHundredMs));
1548 }
1549
TEST(TimeDeltaLogging,MinusTenSeconds)1550 TEST(TimeDeltaLogging, MinusTenSeconds) {
1551 constexpr TimeDelta kMinusTenSeconds = TimeDelta::FromSeconds(-10);
1552 EXPECT_EQ("-10 s", AnyToString(kMinusTenSeconds));
1553 }
1554
TEST(TimeDeltaLogging,DoesNotMessUpFormattingFlags)1555 TEST(TimeDeltaLogging, DoesNotMessUpFormattingFlags) {
1556 std::ostringstream oss;
1557 std::ios_base::fmtflags flags_before = oss.flags();
1558 oss << TimeDelta();
1559 EXPECT_EQ(flags_before, oss.flags());
1560 }
1561
TEST(TimeDeltaLogging,DoesNotMakeStreamBad)1562 TEST(TimeDeltaLogging, DoesNotMakeStreamBad) {
1563 std::ostringstream oss;
1564 oss << TimeDelta();
1565 EXPECT_TRUE(oss.good());
1566 }
1567
TEST(TimeLogging,DCheckEqCompiles)1568 TEST(TimeLogging, DCheckEqCompiles) {
1569 DCHECK_EQ(Time(), Time());
1570 }
1571
TEST(TimeLogging,ChromeBirthdate)1572 TEST(TimeLogging, ChromeBirthdate) {
1573 Time birthdate;
1574 ASSERT_TRUE(Time::FromString("Tue, 02 Sep 2008 09:42:18 GMT", &birthdate));
1575 EXPECT_EQ("2008-09-02 09:42:18.000 UTC", AnyToString(birthdate));
1576 }
1577
TEST(TimeLogging,DoesNotMessUpFormattingFlags)1578 TEST(TimeLogging, DoesNotMessUpFormattingFlags) {
1579 std::ostringstream oss;
1580 std::ios_base::fmtflags flags_before = oss.flags();
1581 oss << Time();
1582 EXPECT_EQ(flags_before, oss.flags());
1583 }
1584
TEST(TimeLogging,DoesNotMakeStreamBad)1585 TEST(TimeLogging, DoesNotMakeStreamBad) {
1586 std::ostringstream oss;
1587 oss << Time();
1588 EXPECT_TRUE(oss.good());
1589 }
1590
TEST(TimeTicksLogging,DCheckEqCompiles)1591 TEST(TimeTicksLogging, DCheckEqCompiles) {
1592 DCHECK_EQ(TimeTicks(), TimeTicks());
1593 }
1594
TEST(TimeTicksLogging,ZeroTime)1595 TEST(TimeTicksLogging, ZeroTime) {
1596 TimeTicks zero;
1597 EXPECT_EQ("0 bogo-microseconds", AnyToString(zero));
1598 }
1599
TEST(TimeTicksLogging,FortyYearsLater)1600 TEST(TimeTicksLogging, FortyYearsLater) {
1601 TimeTicks forty_years_later =
1602 TimeTicks() + TimeDelta::FromDays(365.25 * 40);
1603 EXPECT_EQ("1262304000000000 bogo-microseconds",
1604 AnyToString(forty_years_later));
1605 }
1606
TEST(TimeTicksLogging,DoesNotMessUpFormattingFlags)1607 TEST(TimeTicksLogging, DoesNotMessUpFormattingFlags) {
1608 std::ostringstream oss;
1609 std::ios_base::fmtflags flags_before = oss.flags();
1610 oss << TimeTicks();
1611 EXPECT_EQ(flags_before, oss.flags());
1612 }
1613
TEST(TimeTicksLogging,DoesNotMakeStreamBad)1614 TEST(TimeTicksLogging, DoesNotMakeStreamBad) {
1615 std::ostringstream oss;
1616 oss << TimeTicks();
1617 EXPECT_TRUE(oss.good());
1618 }
1619
1620 } // namespace
1621
1622 } // namespace base
1623