async-time-mock-tokio
Asynchronous time mocking with a tokio compatible API based on async-time-mock-core, inspired by the approach described in Mocking Time In Async Rust.
NOTE: This library is still in it's infancy, the API is still likely to change (read: improve). Please leave your feedback and suggestions on GitHub.
Cargo features
mock
: Enable the mock clock. If you only enable this in tests, this library turns into a thin wrapper around tokio's time functions.
Example
use async_time_mock_tokio::MockableClock;
use std::{
sync::atomic::{AtomicBool, Ordering},
time::Duration,
};
static HAS_SLEPT: AtomicBool = AtomicBool::new(false);
async fn sleep(clock: MockableClock) {
let _guard = clock.sleep(Duration::from_secs(3600)).await;
println!("Slept for an hour");
HAS_SLEPT.store(true, Ordering::SeqCst);
}
#[tokio::main]
async fn main() {
let (clock, controller) = MockableClock::mock();
tokio::spawn(sleep(clock));
controller.advance_time(Duration::from_secs(600)).await;
assert!(!HAS_SLEPT.load(Ordering::SeqCst), "Timer won't trigger after just 10 minutes.");
controller.advance_time(Duration::from_secs(3000)).await;
assert!(HAS_SLEPT.load(Ordering::SeqCst), "Timer has triggered after 1 hour.")
}