]> git.lizzy.rs Git - rust.git/blob - tests/pass/time.rs
make tests pass again
[rust.git] / tests / pass / time.rs
1 //@compile-flags: -Zmiri-disable-isolation
2
3 use std::time::{Duration, Instant, SystemTime};
4
5 fn duration_sanity(diff: Duration) {
6     // On my laptop, I observed times around 15-40ms. Add 10x lee-way both ways.
7     assert!(diff.as_millis() > 1);
8     assert!(diff.as_millis() < 500);
9 }
10
11 // Sleeping on Windows is not supported yet.
12 #[cfg(unix)]
13 fn test_sleep() {
14     let before = Instant::now();
15     std::thread::sleep(Duration::from_millis(100));
16     let after = Instant::now();
17     assert!((after - before).as_millis() >= 100);
18 }
19
20 fn main() {
21     // Check `SystemTime`.
22     let now1 = SystemTime::now();
23     let seconds_since_epoch = now1.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
24     let years_since_epoch = seconds_since_epoch / 3600 / 24 / 365;
25     let year = 1970 + years_since_epoch;
26     assert!(2020 <= year && year < 2100);
27     // Do some work to make time pass.
28     for _ in 0..10 {
29         drop(vec![42]);
30     }
31     let now2 = SystemTime::now();
32     assert!(now2 > now1);
33     // Sanity-check the difference we got.
34     let diff = now2.duration_since(now1).unwrap();
35     assert_eq!(now1 + diff, now2);
36     assert_eq!(now2 - diff, now1);
37     duration_sanity(diff);
38
39     // Check `Instant`.
40     let now1 = Instant::now();
41     // Do some work to make time pass.
42     for _ in 0..10 {
43         drop(vec![42]);
44     }
45     let now2 = Instant::now();
46     assert!(now2 > now1);
47     // Sanity-check the difference we got.
48     let diff = now2.duration_since(now1);
49     assert_eq!(now1 + diff, now2);
50     assert_eq!(now2 - diff, now1);
51     duration_sanity(diff);
52
53     #[cfg(unix)]
54     test_sleep();
55 }