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, Sleep};
7 use tokio_test::{assert_elapsed, assert_err, assert_pending, assert_ready, assert_ready_eq, task};
8 
9 use std::{
10     future::Future,
11     pin::Pin,
12     task::{Context, Poll},
13 };
14 
15 #[tokio::test]
pause_time_in_main()16 async fn pause_time_in_main() {
17     tokio::time::pause();
18 }
19 
20 #[tokio::test]
pause_time_in_task()21 async fn pause_time_in_task() {
22     let t = tokio::spawn(async {
23         tokio::time::pause();
24     });
25 
26     t.await.unwrap();
27 }
28 
29 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
30 #[should_panic]
pause_time_in_main_threads()31 async fn pause_time_in_main_threads() {
32     tokio::time::pause();
33 }
34 
35 #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
pause_time_in_spawn_threads()36 async fn pause_time_in_spawn_threads() {
37     let t = tokio::spawn(async {
38         tokio::time::pause();
39     });
40 
41     assert_err!(t.await);
42 }
43 
44 #[test]
paused_time_is_deterministic()45 fn paused_time_is_deterministic() {
46     let run_1 = paused_time_stress_run();
47     let run_2 = paused_time_stress_run();
48 
49     assert_eq!(run_1, run_2);
50 }
51 
52 #[tokio::main(flavor = "current_thread", start_paused = true)]
paused_time_stress_run() -> Vec<Duration>53 async fn paused_time_stress_run() -> Vec<Duration> {
54     let mut rng = StdRng::seed_from_u64(1);
55 
56     let mut times = vec![];
57     let start = Instant::now();
58     for _ in 0..10_000 {
59         let sleep = rng.gen_range(Duration::from_secs(0)..Duration::from_secs(1));
60         time::sleep(sleep).await;
61         times.push(start.elapsed());
62     }
63 
64     times
65 }
66 
67 #[tokio::test(start_paused = true)]
advance_after_poll()68 async fn advance_after_poll() {
69     time::sleep(ms(1)).await;
70 
71     let start = Instant::now();
72 
73     let mut sleep = task::spawn(time::sleep_until(start + ms(300)));
74 
75     assert_pending!(sleep.poll());
76 
77     let before = Instant::now();
78     time::advance(ms(100)).await;
79     assert_elapsed!(before, ms(100));
80 
81     assert_pending!(sleep.poll());
82 }
83 
84 #[tokio::test(start_paused = true)]
sleep_no_poll()85 async fn sleep_no_poll() {
86     let start = Instant::now();
87 
88     // TODO: Skip this
89     time::advance(ms(1)).await;
90 
91     let mut sleep = task::spawn(time::sleep_until(start + ms(300)));
92 
93     let before = Instant::now();
94     time::advance(ms(100)).await;
95     assert_elapsed!(before, ms(100));
96 
97     assert_pending!(sleep.poll());
98 }
99 
100 enum State {
101     Begin,
102     AwaitingAdvance(Pin<Box<dyn Future<Output = ()>>>),
103     AfterAdvance,
104 }
105 
106 struct Tester {
107     sleep: Pin<Box<Sleep>>,
108     state: State,
109     before: Option<Instant>,
110     poll: bool,
111 }
112 
113 impl Future for Tester {
114     type Output = ();
115 
poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>116     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
117         match &mut self.state {
118             State::Begin => {
119                 if self.poll {
120                     assert_pending!(self.sleep.as_mut().poll(cx));
121                 }
122                 self.before = Some(Instant::now());
123                 let advance_fut = Box::pin(time::advance(ms(100)));
124                 self.state = State::AwaitingAdvance(advance_fut);
125                 self.poll(cx)
126             }
127             State::AwaitingAdvance(ref mut advance_fut) => match advance_fut.as_mut().poll(cx) {
128                 Poll::Pending => Poll::Pending,
129                 Poll::Ready(()) => {
130                     self.state = State::AfterAdvance;
131                     self.poll(cx)
132                 }
133             },
134             State::AfterAdvance => {
135                 assert_elapsed!(self.before.unwrap(), ms(100));
136 
137                 assert_pending!(self.sleep.as_mut().poll(cx));
138 
139                 Poll::Ready(())
140             }
141         }
142     }
143 }
144 
145 #[tokio::test(start_paused = true)]
sleep_same_task()146 async fn sleep_same_task() {
147     let start = Instant::now();
148 
149     // TODO: Skip this
150     time::advance(ms(1)).await;
151 
152     let sleep = Box::pin(time::sleep_until(start + ms(300)));
153 
154     Tester {
155         sleep,
156         state: State::Begin,
157         before: None,
158         poll: true,
159     }
160     .await;
161 }
162 
163 #[tokio::test(start_paused = true)]
sleep_same_task_no_poll()164 async fn sleep_same_task_no_poll() {
165     let start = Instant::now();
166 
167     // TODO: Skip this
168     time::advance(ms(1)).await;
169 
170     let sleep = Box::pin(time::sleep_until(start + ms(300)));
171 
172     Tester {
173         sleep,
174         state: State::Begin,
175         before: None,
176         poll: false,
177     }
178     .await;
179 }
180 
181 #[tokio::test(start_paused = true)]
interval()182 async fn interval() {
183     let start = Instant::now();
184 
185     // TODO: Skip this
186     time::advance(ms(1)).await;
187 
188     let mut i = task::spawn(time::interval_at(start, ms(300)));
189 
190     assert_ready_eq!(poll_next(&mut i), start);
191     assert_pending!(poll_next(&mut i));
192 
193     let before = Instant::now();
194     time::advance(ms(100)).await;
195     assert_elapsed!(before, ms(100));
196     assert_pending!(poll_next(&mut i));
197 
198     let before = Instant::now();
199     time::advance(ms(200)).await;
200     assert_elapsed!(before, ms(200));
201     assert_ready_eq!(poll_next(&mut i), start + ms(300));
202     assert_pending!(poll_next(&mut i));
203 
204     let before = Instant::now();
205     time::advance(ms(400)).await;
206     assert_elapsed!(before, ms(400));
207     assert_ready_eq!(poll_next(&mut i), start + ms(600));
208     assert_pending!(poll_next(&mut i));
209 
210     let before = Instant::now();
211     time::advance(ms(500)).await;
212     assert_elapsed!(before, ms(500));
213     assert_ready_eq!(poll_next(&mut i), start + ms(900));
214     assert_ready_eq!(poll_next(&mut i), start + ms(1200));
215     assert_pending!(poll_next(&mut i));
216 }
217 
218 #[tokio::test(start_paused = true)]
test_time_advance_sub_ms()219 async fn test_time_advance_sub_ms() {
220     let now = Instant::now();
221 
222     let dur = Duration::from_micros(51_592);
223     time::advance(dur).await;
224 
225     assert_eq!(now.elapsed(), dur);
226 
227     let now = Instant::now();
228     let dur = Duration::from_micros(1);
229     time::advance(dur).await;
230 
231     assert_eq!(now.elapsed(), dur);
232 }
233 
234 #[tokio::test(start_paused = true)]
test_time_advance_3ms_and_change()235 async fn test_time_advance_3ms_and_change() {
236     let now = Instant::now();
237 
238     let dur = Duration::from_micros(3_141_592);
239     time::advance(dur).await;
240 
241     assert_eq!(now.elapsed(), dur);
242 
243     let now = Instant::now();
244     let dur = Duration::from_micros(3_123_456);
245     time::advance(dur).await;
246 
247     assert_eq!(now.elapsed(), dur);
248 }
249 
250 #[tokio::test(start_paused = true)]
regression_3710_with_submillis_advance()251 async fn regression_3710_with_submillis_advance() {
252     let start = Instant::now();
253 
254     time::advance(Duration::from_millis(1)).await;
255 
256     let mut sleep = task::spawn(time::sleep_until(start + Duration::from_secs(60)));
257 
258     assert_pending!(sleep.poll());
259 
260     let before = Instant::now();
261     let dur = Duration::from_micros(51_592);
262     time::advance(dur).await;
263     assert_eq!(before.elapsed(), dur);
264 
265     assert_pending!(sleep.poll());
266 }
267 
268 #[tokio::test(start_paused = true)]
exact_1ms_advance()269 async fn exact_1ms_advance() {
270     let now = Instant::now();
271 
272     let dur = Duration::from_millis(1);
273     time::advance(dur).await;
274 
275     assert_eq!(now.elapsed(), dur);
276 
277     let now = Instant::now();
278     let dur = Duration::from_millis(1);
279     time::advance(dur).await;
280 
281     assert_eq!(now.elapsed(), dur);
282 }
283 
284 #[tokio::test(start_paused = true)]
advance_once_with_timer()285 async fn advance_once_with_timer() {
286     let mut sleep = task::spawn(time::sleep(Duration::from_millis(1)));
287     assert_pending!(sleep.poll());
288 
289     time::advance(Duration::from_micros(250)).await;
290     assert_pending!(sleep.poll());
291 
292     time::advance(Duration::from_micros(1500)).await;
293 
294     assert!(sleep.is_woken());
295     assert_ready!(sleep.poll());
296 }
297 
298 #[tokio::test(start_paused = true)]
advance_multi_with_timer()299 async fn advance_multi_with_timer() {
300     // Round to the nearest ms
301     // time::sleep(Duration::from_millis(1)).await;
302 
303     let mut sleep = task::spawn(time::sleep(Duration::from_millis(1)));
304     assert_pending!(sleep.poll());
305 
306     time::advance(Duration::from_micros(250)).await;
307     assert_pending!(sleep.poll());
308 
309     time::advance(Duration::from_micros(250)).await;
310     assert_pending!(sleep.poll());
311 
312     time::advance(Duration::from_micros(250)).await;
313     assert_pending!(sleep.poll());
314 
315     time::advance(Duration::from_micros(250)).await;
316     assert!(sleep.is_woken());
317     assert_ready!(sleep.poll());
318 }
319 
poll_next(interval: &mut task::Spawn<time::Interval>) -> Poll<Instant>320 fn poll_next(interval: &mut task::Spawn<time::Interval>) -> Poll<Instant> {
321     interval.enter(|cx, mut interval| interval.poll_tick(cx))
322 }
323 
ms(n: u64) -> Duration324 fn ms(n: u64) -> Duration {
325     Duration::from_millis(n)
326 }
327