Sub topic 13
Testing timeouts with paused time
This chapter assumes you know the basics of Tokio: #[tokio::test], tokio::time::sleep, and tokio::time::timeout. You should also know that a timeout drops the future it wraps when the deadline passes.
Why real-time tests hurt
A test for a 30-second timeout seems to need a 30-second wait. A shorter timeout in the test makes it run faster, but the code under test is no longer the code you ship. Short real timeouts also cause flaky failures on a slow CI machine, because a task can run late and miss a deadline it should have met.
Tokio solves this by letting a test control the clock. With the clock paused, sleeps do not wait on wall time. Tokio advances its own clock instead.
Enabling paused time
Paused time needs the test-util feature of Tokio. Add it to your dev dependencies:
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt", "time", "test-util"] }Then ask for a paused clock in the test attribute:
use std::time::Duration;
use tokio::time::{sleep, timeout};
#[tokio::test(start_paused = true)]
async fn operation_times_out() {
let result = timeout(Duration::from_secs(1), sleep(Duration::from_secs(60))).await;
assert!(result.is_err());
}This test finishes almost instantly, even though it sleeps for 60 seconds.
How auto-advance works
When the clock is paused, Tokio moves it forward on its own, but only when the runtime is idle. Idle means every task is waiting and none can make progress. At that point Tokio jumps the clock to the next pending timer and wakes it.
In the example above, two timers are pending: the 1-second timeout and the 60-second sleep. The runtime is idle, so the clock jumps to 1 second. The timeout fires first and drops the sleep. The 60-second timer never fires.
Because the clock only jumps when nothing else can run, ordering stays correct. Work that does not wait on a timer always finishes before time moves.
Checking elapsed time
You can assert on how much virtual time has passed. Use tokio::time::Instant, not std::time::Instant. Only the Tokio type follows the paused clock.
use std::time::Duration;
use tokio::time::{sleep, Instant};
#[tokio::test(start_paused = true)]
async fn sleep_advances_virtual_clock() {
let start = Instant::now();
sleep(Duration::from_secs(90)).await;
assert_eq!(start.elapsed(), Duration::from_secs(90));
}The elapsed time is exact, so you can use assert_eq! here. A real clock would never allow that.
Controlling the clock by hand
Sometimes you want to move time yourself. Call tokio::time::pause() inside a test to freeze the clock, and tokio::time::advance to move it forward by a set amount.
use std::time::Duration;
use tokio::time::{self, timeout};
#[tokio::test]
async fn advance_by_hand() {
time::pause();
let handle = tokio::spawn(async {
timeout(Duration::from_secs(5), std::future::pending::<()>()).await
});
// Let the spawned task start and register its timer.
tokio::task::yield_now().await;
time::advance(Duration::from_secs(6)).await;
let result = handle.await.unwrap();
assert!(result.is_err());
}The yield_now call matters. The spawned task must run far enough to register its timer before you advance the clock.
Common errors
- Missing feature. Without
test-util,start_pausedandpausedo not compile or fail. Check the dev dependencies first. - Wrong
Instant.std::time::Instantreads the real clock, so elapsed-time assertions will not match virtual time. - Current-thread runtime only.
pauserequires the current-thread runtime, which is the default for#[tokio::test]. A multi-thread test runtime will panic when you pause. - Real I/O. Auto-advance happens when the runtime is idle. A task blocked on a real socket or file counts as waiting, so the clock can jump past a deadline while real I/O is still pending. Use paused time with in-memory channels and fakes, not live network calls.
Which tool to choose
| Need | Use |
|---|---|
| Skip all waiting in a simple test | `#[tokio::test(start_paused = true)]` |
| Check state at an exact moment | `time::pause()` and `time::advance(...)` |
| Measure virtual elapsed time | `tokio::time::Instant` |
Exercise
A test is marked #[tokio::test(start_paused = true)]. It spawns a task that sleeps for 10 seconds, then waits on a timeout of 2 seconds around that task's JoinHandle. Does the timeout fire, and how long does the test take in real time?
Show answer
The timeout fires and the join handle is dropped. The runtime is idle after both timers register, so the clock jumps to 2 seconds, which is the earliest timer. The 10-second sleep never completes in the test's lifetime. The test finishes in about a millisecond of real time. Note that dropping a JoinHandle detaches the task rather than cancelling it, so the spawned task is still sleeping when the test ends and is dropped with the runtime.
Exercise
Why does assert_eq!(start.elapsed(), Duration::from_secs(90)) fail if start comes from std::time::Instant::now() in a paused-time test?
Show answer
std::time::Instant reads the real system clock, which barely moved during the test, so the elapsed time is a few microseconds. Only tokio::time::Instant follows the paused virtual clock.