Sub topic 17
Testing async code
This chapter assumes you can write async fn and spawn tasks, and that you know how tokio::sleep, timeout and mpsc channels work. It also assumes you can run cargo test.
Why `#[test]` is not enough
A plain #[test] function cannot be async. The test harness calls it like any other function, and there is no runtime to poll the future. The #[tokio::test] attribute fixes this. It wraps your async body in a new runtime and calls block_on on it, much as #[tokio::main] does for main.
Each test gets its own runtime. Tasks you spawn in one test cannot leak into another. When the test function returns, the runtime shuts down and drops any tasks that are still running.
Setup
The macros and the time-control features are behind Cargo features. Enable them for tests only:
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "sync", "test-util"] }Without macros, #[tokio::test] does not compile. Without test-util, the start_paused option and tokio::time::pause and advance are missing.
A first test
use tokio::sync::mpsc;
#[tokio::test]
async fn worker_sends_then_closes() {
let (tx, mut rx) = mpsc::channel::<u32>(4);
tokio::spawn(async move {
tx.send(1).await.unwrap();
tx.send(2).await.unwrap();
});
assert_eq!(rx.recv().await, Some(1));
assert_eq!(rx.recv().await, Some(2));
assert_eq!(rx.recv().await, None);
}The last assertion checks that recv returns None once the only sender is dropped. That is the same shutdown signal you used in the channels chapter.
Runtime flavor in tests
#[tokio::test] uses the current-thread runtime by default. This keeps tests fast and makes scheduling more predictable. If the code under test needs real parallelism, ask for the multi-thread flavor:
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn runs_on_multiple_workers() {
let sum = tokio::task::spawn_blocking(|| (1..=100u64).sum::<u64>())
.await
.unwrap();
assert_eq!(sum, 5050);
}Controlling time
Tests that really sleep for seconds are slow. With start_paused = true, Tokio's clock is virtual. When every task is waiting on a timer, the runtime jumps the clock forward to the next deadline instead of waiting.
use std::time::Duration;
use tokio::time::{sleep, timeout, Instant};
async fn slow_double(x: u32) -> u32 {
sleep(Duration::from_secs(5)).await;
x * 2
}
#[tokio::test(start_paused = true)]
async fn finishes_after_five_virtual_seconds() {
let start = Instant::now();
assert_eq!(slow_double(21).await, 42);
assert!(start.elapsed() >= Duration::from_secs(5));
}
#[tokio::test(start_paused = true)]
async fn times_out_after_one_virtual_second() {
let result = timeout(Duration::from_secs(1), slow_double(1)).await;
assert!(result.is_err());
}Both tests finish in milliseconds of real time. Use tokio::time::Instant here, not std::time::Instant. Only the Tokio type follows the virtual clock.
Common errors
async fnwith plain#[test]: the compiler reports that the function is never awaited, or the test passes without running the body. Use#[tokio::test].- A test that hangs: usually a
recvloop where one sender was never dropped. Wrap the awaited operation intimeoutso a hang becomes a failure. - Blocking calls in a current-thread test:
std::thread::sleepfreezes the only worker, so spawned tasks cannot run. - Flaky ordering: tests that depend on thread timing. Prefer channels and
joinhandles oversleepto synchronize.
Exercise
A test uses #[tokio::test(start_paused = true)] and awaits tokio::time::sleep(Duration::from_secs(60)). Roughly how long does it take in real time, and which Cargo feature must be enabled for the attribute option to work?
Show answer
It takes almost no real time. The runtime sees that all tasks are waiting on timers and advances the virtual clock straight to the 60-second deadline. The test-util feature of the tokio crate must be enabled, usually under [dev-dependencies].