ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

Operating

TestingTestAppClocks in testsAsserting failures

Reference

Testing

Clocks in tests

Tokio's paused clock for apps without servers, and ScriptedTimer for apps that own them.

A startup backoff, a deadline and a drain window are all waits on the app's clock. A test should neither sleep for real nor race them. The app's Timer is the seam: under Tokio::current() it is tokio's clock, and a test can replace it.

Tokio's paused clock

When the app binds no server, the paused clock works. #[tokio::test(start_paused = true)] moves time forward whenever the runtime has nothing else to do, so a wait passes instantly and the test can assert how long it was. Enable tokio's test-util feature in dev-dependencies.

This test from examples/09-lifecycle pins a readiness check that fails twice before it passes, with a 500 ms backoff between attempts:

#[tokio::test(start_paused = true)]
async fn hooks_run_in_dependency_order_and_in_reverse_at_close() {
    let started = Instant::now();
    let app = builder(2).runtime(Tokio::current()).wire().unwrap().connect().await.unwrap();
    // ...
    assert_eq!(started.elapsed(), 2 * BACKOFF, "two refused attempts waited one backoff each");
}

This one, from examples/12-standalone, pins an execution deadline:

#[tokio::test(start_paused = true)]
async fn a_deadline_cancels_the_execution_on_the_apps_clock() {
    let deadline = Duration::from_secs(30);
    let app = builder().runtime(Tokio::current()).wire().unwrap().connect().await.unwrap();

    let started = Instant::now();
    let options = ExecOptions::new().deadline((started + deadline).into_std());
    // ... the closure awaits exec.cancelled()
    assert_eq!(started.elapsed(), deadline);
}

A service reads the same clock as Dep<dyn Timer>, so it observes the pause. examples/13-testing has an Uptime provider that measures time since startup from the app's timer, and its test advances tokio's clock by 90 seconds:

#[tokio::test(start_paused = true)]
async fn a_paused_clock_sets_what_the_app_reads_as_time() {
    let app = test_app().connect().await.unwrap();
    let uptime: Dep<Uptime> = app.get().await.unwrap();
    assert_eq!(uptime.elapsed(), Duration::ZERO);
    tokio::time::advance(Duration::from_secs(90)).await;
    assert_eq!(uptime.elapsed(), Duration::from_secs(90));
    app.close(Signal::new("test")).await.unwrap();
}

The test reads Uptime in process, with no server bound. A running server holds timers of its own, and a paused clock jumps to them while a request is in flight.

ScriptedTimer for apps with servers

A paused tokio clock is the wrong tool for an app that owns servers. It advances on its own whenever the runtime has nothing else to run, and a server waiting on a request in flight has only its own timers, so the clock jumps to them. A request held across the drain window measured 28 to 61 seconds of clock time in the framework's own examples.

ulo::testing::ScriptedTimer moves only where the test says. No sleep it hands out ends until the test calls advance. It counts the live sleeps by length (live), records the clock time at which a sleep last answered Pending (pending_at), and can answer a named length as a runtime that has shut down does (refuse, refused). It needs no runtime and no cargo feature, so a test names it with ulo as the only dependency.

use std::future::Future;
use std::task::{Context, Poll, Waker};
use std::time::Duration;
use ulo::Timer;
use ulo::testing::ScriptedTimer;

let clock = ScriptedTimer::new();
let grace = Duration::from_secs(30);
let mut sleep = clock.sleep(grace);
let mut cx = Context::from_waker(Waker::noop());

// Nothing moves the clock but the test: the sleep stays pending however long it is polled.
assert!(sleep.as_mut().poll(&mut cx).is_pending());
assert_eq!(clock.live(grace), 1);

clock.advance(Duration::from_secs(29));
assert!(sleep.as_mut().poll(&mut cx).is_pending());
assert_eq!(clock.pending_at(grace), Some(clock.elapsed()));

clock.advance(Duration::from_secs(1));
assert!(sleep.as_mut().poll(&mut cx).is_ready());
drop(sleep);
assert_eq!(clock.live(grace), 0);

That block is the doctest in the module documentation of ulo::testing.

To give an app the scripted clock on a real executor, set the clock after the runtime:

pub async fn start_on(app: AppBuilder, clock: ScriptedTimer) -> Served {
    start_with(app.runtime(Tokio::current()).timer(clock)).await
}

.timer(..) overrides only the clock, so the app spawns on tokio and times on clock. In examples/10-shutdown, a held request meets a 5-second drain window. The test starts the shutdown, then moves the scripted clock by the window with a helper and asserts the outcome:

let clock = ScriptedTimer::new();
let server = start_on(builder(), clock.clone()).await;
// ... a request is held at /work
let closing = tokio::spawn(server.handle.close(Signal::new("deploy")));
server.handle.draining().await;

let report = advancing(&clock, DRAIN, closing).await.unwrap().unwrap();
assert_eq!((report.abandoned, report.terminal_skipped), (1, 0));
assert_eq!(clock.elapsed(), DRAIN);

advancing is a helper in examples/support.

When the held request is released inside the window instead, the drain ends with the last request and clock.elapsed() is still zero.

TestApp

Replacing a mock, a factory or a whole module in the production graph, and the refusals that keep a stale mock from passing.

Asserting failures

Testing that a mistake is refused: wiring, connect, load and lookup errors read as values.

On this page

Tokio's paused clockScriptedTimer for apps with servers