1 #![warn(rust_2018_idioms)] 2 #![cfg(feature = "full")] 3 4 use tokio::time::*; 5 6 use std::sync::mpsc; 7 8 #[test] timer_with_threaded_runtime()9fn timer_with_threaded_runtime() { 10 use tokio::runtime::Runtime; 11 12 let rt = Runtime::new().unwrap(); 13 let (tx, rx) = mpsc::channel(); 14 15 rt.spawn(async move { 16 let when = Instant::now() + Duration::from_millis(100); 17 18 delay_until(when).await; 19 assert!(Instant::now() >= when); 20 21 tx.send(()).unwrap(); 22 }); 23 24 rx.recv().unwrap(); 25 } 26 27 #[test] timer_with_basic_scheduler()28fn timer_with_basic_scheduler() { 29 use tokio::runtime::Builder; 30 31 let mut rt = Builder::new() 32 .basic_scheduler() 33 .enable_all() 34 .build() 35 .unwrap(); 36 let (tx, rx) = mpsc::channel(); 37 38 rt.block_on(async move { 39 let when = Instant::now() + Duration::from_millis(100); 40 41 delay_until(when).await; 42 assert!(Instant::now() >= when); 43 44 tx.send(()).unwrap(); 45 }); 46 47 rx.recv().unwrap(); 48 } 49 50 #[tokio::test] starving()51async fn starving() { 52 use std::future::Future; 53 use std::pin::Pin; 54 use std::task::{Context, Poll}; 55 56 struct Starve<T: Future<Output = ()> + Unpin>(T, u64); 57 58 impl<T: Future<Output = ()> + Unpin> Future for Starve<T> { 59 type Output = u64; 60 61 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<u64> { 62 if Pin::new(&mut self.0).poll(cx).is_ready() { 63 return Poll::Ready(self.1); 64 } 65 66 self.1 += 1; 67 68 cx.waker().wake_by_ref(); 69 70 Poll::Pending 71 } 72 } 73 74 let when = Instant::now() + Duration::from_millis(20); 75 let starve = Starve(delay_until(when), 0); 76 77 starve.await; 78 assert!(Instant::now() >= when); 79 } 80 81 #[tokio::test] timeout_value()82async fn timeout_value() { 83 use tokio::sync::oneshot; 84 85 let (_tx, rx) = oneshot::channel::<()>(); 86 87 let now = Instant::now(); 88 let dur = Duration::from_millis(20); 89 90 let res = timeout(dur, rx).await; 91 assert!(res.is_err()); 92 assert!(Instant::now() >= now + dur); 93 } 94