Sub topic 17
Testing async code
This chapter shows how to write reliable tests for async Rust. It assumes you can write a basic Tokio program, you know tokio::spawn, channels and timeout, and you know how Cargo test modules work. The aim is tests that are fast, deterministic and unable to hang forever.
Why async tests need a runtime
The test harness calls plain functions. An async fn returns a future, and nothing runs until an executor polls it. A test written as async fn therefore needs a runtime to drive it. The #[tokio::test] attribute does for tests what #[tokio::main] does for main. It rewrites your function into a synchronous one that builds a runtime and calls block_on on your body.
Enable the features the tests use. This chapter uses these:
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "sync", "time", "net", "io-util", "test-util"] }The test-util feature unlocks paused time, which is covered below. Keep it in dev-dependencies so production builds do not carry it.
Here is the smallest useful test:
use std::time::Duration;
use tokio::time::sleep;
pub async fn double_later(n: u32) -> u32 {
sleep(Duration::from_millis(100)).await;
n * 2
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn doubles() {
assert_eq!(double_later(21).await, 42);
}
}Each test gets its own runtime
#[tokio::test] builds a new runtime for every test and drops it when the test ends. This has two consequences:
- Tests cannot share spawned tasks or runtime state. A task spawned in one test is cancelled when that test's runtime shuts down.
- Tests still run in parallel on separate OS threads, as with any Rust test suite. Shared resources such as fixed ports or files can still collide.
The default flavor is current_thread, unlike #[tokio::main], which defaults to multi-thread. The default is usually what you want. It is cheaper, and spawned tasks only run when your test body yields. That makes interleavings more predictable.
Pick the multi-thread flavor only when the code under test needs it, for example when it calls block_in_place, which panics on a current-thread runtime:
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn works_on_multi_thread() {
let value = tokio::spawn(async { 1 + 1 }).await.unwrap();
assert_eq!(value, 2);
}Testing time without waiting for it
A test that sleeps for real is slow, and a test that asserts on real elapsed time is flaky. Tokio can pause its clock. With start_paused = true, time stands still until every task is idle. The runtime then jumps the clock forward to the next timer. A one-hour sleep returns almost instantly:
use std::time::Duration;
use tokio::time::{self, Instant};
#[tokio::test(start_paused = true)]
async fn sleep_is_instant() {
let start = Instant::now();
time::sleep(Duration::from_secs(3600)).await;
assert!(start.elapsed() >= Duration::from_secs(3600));
}Use tokio::time::Instant, not std::time::Instant. Only the Tokio version follows the paused clock.
Timeouts become easy to test the same way:
use std::time::Duration;
use tokio::time::{self, sleep};
async fn slow() {
sleep(Duration::from_secs(10)).await;
}
#[tokio::test(start_paused = true)]
async fn slow_call_times_out() {
let result = time::timeout(Duration::from_secs(1), slow()).await;
assert!(result.is_err());
}Advancing the clock by hand
Sometimes you want to check state midway through a delay. Call tokio::time::advance to move the clock a fixed amount:
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::time;
#[tokio::test(start_paused = true)]
async fn advance_by_hand() {
let done = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&done);
tokio::spawn(async move {
time::sleep(Duration::from_secs(10)).await;
flag.store(true, Ordering::SeqCst);
});
// Let the spawned task start and register its sleep.
tokio::task::yield_now().await;
time::advance(Duration::from_secs(9)).await;
assert!(!done.load(Ordering::SeqCst));
time::advance(Duration::from_secs(1)).await;
tokio::task::yield_now().await;
assert!(done.load(Ordering::SeqCst));
}The first yield_now matters. A spawned task has not run yet, so it has not created its sleep. If you advanced the clock first, the sleep would be measured from the new time, and your arithmetic would be off.
Testing channels and workers
A worker task that reads from one channel and writes to another is easy to test if you control both ends. The pattern is to send inputs, drop the input sender so the worker sees the channel close, read the outputs, and then await the worker's handle:
use tokio::sync::mpsc;
pub async fn uppercase_worker(mut rx: mpsc::Receiver<String>, tx: mpsc::Sender<String>) {
while let Some(msg) = rx.recv().await {
if tx.send(msg.to_uppercase()).await.is_err() {
break;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn worker_uppercases_and_stops() {
let (in_tx, in_rx) = mpsc::channel(4);
let (out_tx, mut out_rx) = mpsc::channel(4);
let worker = tokio::spawn(uppercase_worker(in_rx, out_tx));
in_tx.send("hello".to_string()).await.unwrap();
drop(in_tx);
assert_eq!(out_rx.recv().await.as_deref(), Some("HELLO"));
assert_eq!(out_rx.recv().await, None);
worker.await.unwrap();
}
}The test checks three things: the transformation, the clean shutdown when the input closes, and that the worker did not panic. Awaiting the JoinHandle at the end is what surfaces the last one. If you skip it, a worker that panics after your last assertion goes unnoticed.
Testing panics and task failures
A panic inside a spawned task does not unwind into your test. It is captured and returned as a JoinError from the handle. Assert on that error:
#[tokio::test]
async fn panic_is_reported_by_join_handle() {
let handle = tokio::spawn(async {
panic!("boom");
});
let err = handle.await.unwrap_err();
assert!(err.is_panic());
}For a panic in the test body itself, #[should_panic] works as usual with #[tokio::test]. Prefer the JoinError check when the failure happens in a task. It states exactly which failure you expect.
Testing a network server
Tests that open sockets should bind to port 0. The OS then picks a free port, and parallel tests cannot collide. Read the real address back with local_addr. To make the server testable, accept a bound listener instead of binding inside the function:
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
pub async fn serve(listener: TcpListener) -> std::io::Result<()> {
loop {
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let mut buf = [0u8; 1024];
loop {
match socket.read(&mut buf).await {
Ok(0) | Err(_) => return,
Ok(n) => {
if socket.write_all(&buf[..n]).await.is_err() {
return;
}
}
}
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn echoes_bytes() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(serve(listener));
let mut client = TcpStream::connect(addr).await.unwrap();
client.write_all(b"ping").await.unwrap();
let mut reply = [0u8; 4];
client.read_exact(&mut reply).await.unwrap();
assert_eq!(&reply, b"ping");
server.abort();
}
}The final server.abort() cancels the accept loop. Without it the runtime would still drop the task at the end of the test, but aborting makes the intent explicit.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Test hangs forever | A task waits on a channel whose sender is still alive, or on an event that never comes | Wrap the body in `tokio::time::timeout`, and drop senders you no longer need |
| `there is no reactor running` panic | A plain `#[test]` calls code that needs Tokio | Use `#[tokio::test]`, or build a runtime by hand |
| `start_paused` panics | The test uses the multi-thread flavor | Use the default current-thread flavor |
| Flaky timing assertions | Real clock and a loaded machine | Use paused time and `advance` |
| Spawned task's assertion never runs | The test ended first, and the runtime dropped the task | Await the `JoinHandle` before the test returns |
| Address already in use | A fixed port shared between parallel tests | Bind to `127.0.0.1:0` |
A guard against hangs is worth adding to any test that waits on other tasks. A hung test blocks the whole suite, while a timeout fails with a clear error:
use std::time::Duration;
use tokio::time::timeout;
#[tokio::test]
async fn finishes_in_reasonable_time() {
let result = timeout(Duration::from_secs(5), async {
tokio::task::yield_now().await;
"done"
})
.await;
assert_eq!(result.unwrap(), "done");
}Exercise
A test spawns a task that does sleep(Duration::from_secs(5)).await and then sets a flag. The test uses #[tokio::test(start_paused = true)]. It calls advance(Duration::from_secs(5)).await immediately after tokio::spawn, then asserts the flag is set, and the assertion fails. What went wrong, and how do you fix it?
Show answer
The spawned task had not been polled yet when advance ran, so its sleep was not registered. The clock jumped first, and the task then created a sleep that ends 5 seconds after the new time. Insert tokio::task::yield_now().await after spawn so the task registers its sleep before advancing. Add another yield_now after advance so the woken task can run and set the flag before the assertion.
Exercise
Why does the channel worker test drop in_tx before reading the final None from out_rx?
Show answer
The worker's while let Some(..) = rx.recv().await loop only ends when every sender for its input channel is dropped. While in_tx is alive, the worker keeps waiting. It never finishes, it never drops out_tx, and out_rx.recv() never returns None, so the test would hang.