1 #![warn(rust_2018_idioms)]
2 #![cfg(feature = "full")]
3 
4 use rand::SeedableRng;
5 use rand::{rngs::StdRng, Rng};
6 use tokio::time::{self, Duration, Instant};
7 use tokio_test::assert_err;
8 
9 #[tokio::test]
pause_time_in_main()10 async fn pause_time_in_main() {
11     tokio::time::pause();
12 }
13 
14 #[tokio::test]
pause_time_in_task()15 async fn pause_time_in_task() {
16     let t = tokio::spawn(async {
17         tokio::time::pause();
18     });
19 
20     t.await.unwrap();
21 }
22 
23 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
24 #[should_panic]
pause_time_in_main_threads()25 async fn pause_time_in_main_threads() {
26     tokio::time::pause();
27 }
28 
29 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
pause_time_in_spawn_threads()30 async fn pause_time_in_spawn_threads() {
31     let t = tokio::spawn(async {
32         tokio::time::pause();
33     });
34 
35     assert_err!(t.await);
36 }
37 
38 #[test]
paused_time_is_deterministic()39 fn paused_time_is_deterministic() {
40     let run_1 = paused_time_stress_run();
41     let run_2 = paused_time_stress_run();
42 
43     assert_eq!(run_1, run_2);
44 }
45 
46 #[tokio::main(flavor = "current_thread", start_paused = true)]
paused_time_stress_run() -> Vec<Duration>47 async fn paused_time_stress_run() -> Vec<Duration> {
48     let mut rng = StdRng::seed_from_u64(1);
49 
50     let mut times = vec![];
51     let start = Instant::now();
52     for _ in 0..10_000 {
53         let sleep = rng.gen_range(Duration::from_secs(0)..Duration::from_secs(1));
54         time::sleep(sleep).await;
55         times.push(start.elapsed());
56     }
57 
58     times
59 }
60