2019-08-10 00:07:57 +09:00
|
|
|
#![warn(rust_2018_idioms)]
|
2018-06-06 16:04:39 -07:00
|
|
|
|
|
|
|
|
use tokio::runtime::{self, current_thread};
|
2019-10-21 16:45:13 -07:00
|
|
|
use tokio::timer::clock::Clock;
|
2018-06-06 16:04:39 -07:00
|
|
|
use tokio::timer::*;
|
|
|
|
|
|
2019-08-07 20:02:13 -07:00
|
|
|
use std::sync::mpsc;
|
|
|
|
|
use std::time::{Duration, Instant};
|
|
|
|
|
|
2018-06-06 16:04:39 -07:00
|
|
|
struct MockNow(Instant);
|
|
|
|
|
|
2019-10-21 16:45:13 -07:00
|
|
|
impl tokio::timer::clock::Now for MockNow {
|
2018-06-06 16:04:39 -07:00
|
|
|
fn now(&self) -> Instant {
|
|
|
|
|
self.0
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn clock_and_timer_concurrent() {
|
|
|
|
|
let when = Instant::now() + Duration::from_millis(5_000);
|
|
|
|
|
let clock = Clock::new_with_now(MockNow(when));
|
|
|
|
|
|
2019-06-10 12:54:27 -07:00
|
|
|
let rt = runtime::Builder::new().clock(clock).build().unwrap();
|
2018-06-06 16:04:39 -07:00
|
|
|
|
|
|
|
|
let (tx, rx) = mpsc::channel();
|
|
|
|
|
|
2019-08-07 20:02:13 -07:00
|
|
|
rt.spawn(async move {
|
2019-08-20 17:39:55 +02:00
|
|
|
delay(when).await;
|
2019-08-07 20:02:13 -07:00
|
|
|
assert!(Instant::now() < when);
|
|
|
|
|
tx.send(()).unwrap();
|
2018-06-06 16:04:39 -07:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
rx.recv().unwrap();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn clock_and_timer_single_threaded() {
|
|
|
|
|
let when = Instant::now() + Duration::from_millis(5_000);
|
|
|
|
|
let clock = Clock::new_with_now(MockNow(when));
|
|
|
|
|
|
2019-02-21 11:56:15 -08:00
|
|
|
let mut rt = current_thread::Builder::new().clock(clock).build().unwrap();
|
2018-06-06 16:04:39 -07:00
|
|
|
|
2019-08-07 20:02:13 -07:00
|
|
|
rt.block_on(async move {
|
2019-08-20 17:39:55 +02:00
|
|
|
delay(when).await;
|
2019-08-07 20:02:13 -07:00
|
|
|
assert!(Instant::now() < when);
|
|
|
|
|
});
|
2018-06-06 16:04:39 -07:00
|
|
|
}
|
2019-09-19 20:20:18 +02:00
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
|
fn mocked_clock_delay_for() {
|
|
|
|
|
tokio_test::clock::mock(|handle| {
|
|
|
|
|
let mut f = tokio_test::task::spawn(delay_for(Duration::from_millis(1)));
|
|
|
|
|
tokio_test::assert_pending!(f.poll());
|
|
|
|
|
handle.advance(Duration::from_millis(1));
|
|
|
|
|
tokio_test::assert_ready!(f.poll());
|
|
|
|
|
});
|
|
|
|
|
}
|