camel_test/time.rs
1// crates/camel-test/src/time.rs
2
3use std::time::Duration;
4
5/// Controls tokio's mock time inside a test.
6///
7/// Obtained from `CamelTestContextBuilder::with_time_control().build()`.
8/// Wraps `tokio::time::advance` and `tokio::time::resume`.
9///
10/// # Contract
11/// Only valid inside a `#[tokio::test]` runtime. `tokio::time::pause()`
12/// must have been called before use — `CamelTestContextBuilder::build()`
13/// handles this automatically.
14pub struct TimeController;
15
16impl TimeController {
17 /// Advance the mocked clock by `duration`.
18 ///
19 /// All pending `tokio::time::sleep` and `tokio::time::interval` futures
20 /// that would fire within this duration are resolved immediately.
21 pub async fn advance(&self, duration: Duration) {
22 tokio::time::advance(duration).await;
23 }
24
25 /// Resume real-time clock progression.
26 pub fn resume(&self) {
27 tokio::time::resume();
28 }
29}
30
31#[cfg(test)]
32mod tests {
33 use super::*;
34
35 #[tokio::test]
36 async fn advance_unblocks_sleep() {
37 tokio::time::pause();
38 let controller = TimeController;
39
40 let sleeper = tokio::spawn(async {
41 tokio::time::sleep(Duration::from_millis(100)).await;
42 42
43 });
44
45 controller.advance(Duration::from_millis(100)).await;
46 let got = sleeper.await.unwrap();
47 assert_eq!(got, 42);
48
49 controller.resume();
50 }
51}