Rust Playbook

Course › Week 5 · Axum microservice › Day 7 · lesson 35 of 42 · 30 min reading + 1–2 h practice

Tests and the Week 5 checkpoint

Integration tests with oneshot and a fresh database per test, and the service’s exit check.

integration testsoneshot

On this page
  1. Setup
  2. 1. One request, no server
  3. 2. A fresh database for each test
  4. 3. Problem: a tidy-up that locks out the load balancer
  5. 4. Problem: a limit that does not limit
  6. 5. The Laravel side: Http::fake
  7. The Week 5 exit check
  8. Laravel feature tests and these tests
  9. Practice
  10. Remember

The build day’s runs showed the service working. Tests prove it keeps working: after a refactor, a dependency update, or a teammate’s change to the router. In Laravel these are feature tests, $this->postJson('/batches', […])->assertStatus(202) against a database that RefreshDatabase resets.

Rust has the same, in two pieces. tower::ServiceExt::oneshot sends one request straight to the router, with no server and no port. #[sqlx::test] gives each test its own fresh database. The tests go in tests/, where Cargo compiles them as a separate crate that sees only what lib.rs makes public, as an outside caller would.

Setup

Two changes to Cargo.toml. sqlx needs its macros feature for the test attribute, and three crates are needed by the tests only, so they go under [dev-dependencies]: they are not built into the service’s binary.

Cargo.toml (part)
sqlx = { version = "0.9.1", features = ["runtime-tokio", "postgres", "macros"] }

[dev-dependencies]
http-body-util = "0.1.5"
serde_json = "1.0.154"
tower = { version = "0.5.3", features = ["util"] }

And the tables, in tests/fixtures/schema.sql. They are the build day’s, without the drop:

tests/fixtures/schema.sql (part)
create table evaluations (
    id bigserial primary key,
    school varchar(255) not null,
    status varchar(20) not null default 'pending',
    average_tenths integer null,
    positive integer null,
    negative integer null,
    neutral integer null,
    analysed_at timestamp(0) without time zone null,
    created_at timestamp(0) without time zone null,
    updated_at timestamp(0) without time zone null
);
-- … answers, analysis_batches and analysis_batch_failures as on the build day, then the five evaluations

1. One request, no server

The top of the test file builds the real router with app, the function lib.rs exports, and test settings. The analysis URL points at a port where nothing listens: a batch a test creates is spawned as usual and fails quietly in the background, so no test depends on the analysis API.

send is the test’s postJson. router.oneshot(request) runs the request through every layer and handler and returns the response. into_body().collect() reads the whole body (http-body-util provides collect), and serde_json parses it into a Value, which can be indexed like a PHP array: body["errors"]["evaluation_ids"][0].

expect is the right tool in a test. A test that cannot build its request has failed, and a panic with a clear message is how a Rust test fails; assert_eq! panics the same way.

tests/api.rsnew file
//! The service's HTTP side, tested without a server: each test sends one request straight to the
//! router, against a fresh database that sqlx creates for that test.

use std::sync::Arc;

use analysis_service::analysis::Analyser;
use analysis_service::config::Config;
use analysis_service::{AppState, BATCHES_AT_ONCE, app};
use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use sqlx::PgPool;
use tokio::sync::Semaphore;
use tower::ServiceExt;

const KEY: &str = "test-key-0123456789";

/// The router of the real service, with test settings and the test's own database.
fn router(pool: PgPool) -> Router {
    let config = Config {
        address: String::from("127.0.0.1:0"),
        database_url: String::new(),
        // Nothing listens here: a batch the tests create fails in the background, never succeeds.
        analysis_url: String::from("http://127.0.0.1:9/api/analyse"),
        api_key: String::from(KEY),
        concurrency: 1,
    };
    let analyser = Analyser::new(&config.analysis_url).expect("the HTTP client builds");
    app(AppState {
        pool,
        analyser,
        config: Arc::new(config),
        slots: Arc::new(Semaphore::new(BATCHES_AT_ONCE)),
    })
}

/// Sends one request and returns the status and the body as JSON (Null for a body that is not JSON).
async fn send(router: Router, request: Request<Body>) -> (StatusCode, Value) {
    let response = router
        .oneshot(request)
        .await
        .expect("a router always answers");
    let status = response.status();
    let bytes = response
        .into_body()
        .collect()
        .await
        .expect("the body can be read")
        .to_bytes();
    (
        status,
        serde_json::from_slice(&bytes).unwrap_or(Value::Null),
    )
}

fn post(body: Value) -> Request<Body> {
    Request::post("/batches")
        .header("x-api-key", KEY)
        .header("content-type", "application/json")
        .body(Body::from(body.to_string()))
        .expect("a valid request")
}

fn get(uri: &str, key: Option<&str>) -> Request<Body> {
    let mut request = Request::get(uri);
    if let Some(key) = key {
        request = request.header("x-api-key", key);
    }
    request.body(Body::empty()).expect("a valid request")
}

#[sqlx::test(fixtures("schema"))]
async fn health_needs_no_key(pool: PgPool) {
    let (status, _) = send(router(pool), get("/health", None)).await;
    assert_eq!(status, StatusCode::OK);
}

#[sqlx::test(fixtures("schema"))]
async fn batches_need_the_key(pool: PgPool) {
    let (status, body) = send(router(pool.clone()), get("/batches/1", None)).await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
    assert_eq!(body, json!({"message": "Unauthenticated."}));

    let (status, _) = send(
        router(pool),
        get("/batches/1", Some("wrong-key-0123456789")),
    )
    .await;
    assert_eq!(status, StatusCode::UNAUTHORIZED);
}

#[sqlx::test(fixtures("schema"))]
async fn a_new_batch_is_accepted(pool: PgPool) {
    let (status, body) = send(
        router(pool),
        post(json!({"reference": "test-1", "evaluation_ids": [1043, 1042, 1042]})),
    )
    .await;
    assert_eq!(status, StatusCode::ACCEPTED);
    assert_eq!(body["status"], "queued");
    assert_eq!(body["total"], 2);
}

#[sqlx::test(fixtures("schema"))]
async fn a_retry_returns_the_same_batch(pool: PgPool) {
    let batch = json!({"reference": "test-1", "evaluation_ids": [1042, 1043]});
    let (_, first) = send(router(pool.clone()), post(batch.clone())).await;
    let (status, second) = send(router(pool.clone()), post(batch)).await;

    assert_eq!(status, StatusCode::OK);
    assert_eq!(second["id"], first["id"]);
    let batches: i64 = sqlx::query_scalar("select count(*) from analysis_batches")
        .fetch_one(&pool)
        .await
        .expect("the count query runs");
    assert_eq!(batches, 1);
}

#[sqlx::test(fixtures("schema"))]
async fn a_reference_cannot_be_reused_for_other_ids(pool: PgPool) {
    send(
        router(pool.clone()),
        post(json!({"reference": "test-1", "evaluation_ids": [1042]})),
    )
    .await;
    let (status, _) = send(
        router(pool),
        post(json!({"reference": "test-1", "evaluation_ids": [1046]})),
    )
    .await;
    assert_eq!(status, StatusCode::CONFLICT);
}

#[sqlx::test(fixtures("schema"))]
async fn an_empty_batch_is_invalid(pool: PgPool) {
    let (status, body) = send(
        router(pool),
        post(json!({"reference": "test-1", "evaluation_ids": []})),
    )
    .await;
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(
        body["errors"]["evaluation_ids"][0],
        "Send between 1 and 500 evaluation ids."
    );
}

#[sqlx::test(fixtures("schema"))]
async fn a_body_that_is_not_json_gets_a_json_answer(pool: PgPool) {
    let request = Request::post("/batches")
        .header("x-api-key", KEY)
        .header("content-type", "application/json")
        .body(Body::from("{\"reference\":"))
        .expect("a valid request");
    let (status, body) = send(router(pool), request).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
    assert!(body["message"].is_string());
}

#[sqlx::test(fixtures("schema"))]
async fn an_unknown_batch_is_not_found(pool: PgPool) {
    let (status, body) = send(router(pool), get("/batches/99", Some(KEY))).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_eq!(body, json!({"message": "Batch not found."}));
}

2. A fresh database for each test

#[sqlx::test(fixtures("schema"))] does what RefreshDatabase does, and more strictly. For each test it creates a new database, runs tests/fixtures/schema.sql in it, and passes the test a PgPool connected to it. Tests run at the same time and never see each other’s batches, so a_retry_returns_the_same_batch can count the rows of analysis_batches and expect exactly 1.

It reads DATABASE_URL to find the server, and needs a user allowed to create databases. A passing test’s database is dropped; a failing test’s database is kept, so you can connect to it and look at what the test left behind.

$ cargo test
running 2 tests
test process::tests::averages_in_tenths ... ok
test process::tests::groups_answers_and_reports_what_cannot_be_analysed ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 8 tests
test a_body_that_is_not_json_gets_a_json_answer ... ok
test a_new_batch_is_accepted ... ok
test a_reference_cannot_be_reused_for_other_ids ... ok
test a_retry_returns_the_same_batch ... ok
test an_empty_batch_is_invalid ... ok
test an_unknown_batch_is_not_found ... ok
test batches_need_the_key ... ok
test health_needs_no_key ... ok

test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.65s

Ten tests: the two unit tests the worker brought, in process.rs, and the eight HTTP tests. Each one would have caught a real mistake: a 202 for a retry starts a second batch; a 200 for the same reference with other ids hides a bug in the caller; an HTML or plain-text error breaks Laravel’s $response->json().

pool.clone() in a test that sends two requests: each router(…) takes a pool, and the clone is a second handle to the same one. oneshot uses the router up, so each request gets a fresh router; building one is cheap.

3. Problem: a tidy-up that locks out the load balancer

A teammate tidies app, putting the public route first because “it reads better”. The service compiles, every batch request still works, and the change looks harmless in review:

src/routes.rs (part)
pub fn app(state: AppState) -> Router {
    Router::new()
        .route("/health", get(health))
        .route("/batches", post(store))
        .route("/batches/{id}", get(show))
        .route_layer(middleware::from_fn_with_state(
            state.clone(),
            require_api_key,
        ))
        .layer(…
$ cargo test
running 2 tests
test process::tests::averages_in_tenths ... ok
test process::tests::groups_answers_and_reports_what_cannot_be_analysed ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 8 tests
test a_new_batch_is_accepted ... ok
test a_body_that_is_not_json_gets_a_json_answer ... ok
test a_reference_cannot_be_reused_for_other_ids ... ok
test a_retry_returns_the_same_batch ... ok
test an_empty_batch_is_invalid ... ok
test an_unknown_batch_is_not_found ... ok
test health_needs_no_key ... FAILED
test batches_need_the_key ... ok

failures:

---- health_needs_no_key stdout ----

thread 'health_needs_no_key' (10902) panicked at tests/api.rs:77:5:
assertion `left == right` failed
  left: 401
 right: 200
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    health_needs_no_key

test result: FAILED. 7 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.73s
Show what went wrong

route_layer applies to every route added before it. Moving /health above it put the health check behind the API key, so the load balancer, which sends no key, gets 401 and takes every copy of the service out of rotation: an outage from a change that touched no logic. A four-line test caught it before the deploy.

The fix is to move /health back below route_layer. If the order feels fragile, make it explicit: build the protected routes as their own Router with the layer, and .merge() the public ones into it, so the position of a line no longer decides who needs a key.

4. Problem: a limit that does not limit

Someone shortens the start of process::run. It compiles without a warning, and every test still passes:

src/process.rs (part)
pub async fn run(state: AppState, batch_id: i64) {
    if state.slots.acquire().await.is_err() {
        error!(batch_id, "the batch queue is closed");
        return;
    }
Show what went wrong

acquire() returns the permit, and the permit is the slot: the slot is free again as soon as the permit is dropped. Here the permit is a temporary inside the if condition, so it is dropped at the end of that line. Every batch takes a slot and gives it back at once, and ten clicks run ten batches together, 80 calls to the analysis API instead of 16.

That is why the build day wrote let Ok(_slot) = … else: a named binding lives until the end of the function. _slot works and _ does not, because _ is not a name: let _ = … drops the value immediately, the same trap as the Week 4 checkpoint’s future that was never awaited.

No test here catches it, and that is the second lesson: tests check what a request answers, not how much load the service puts on another system. Limits like this one are checked by reading the code, or by a load test against a fake API that counts the calls it receives at the same time.

5. The Laravel side: Http::fake

The Laravel half gets its tests in Laravel, with the controller registered as Route::post('/evaluations/analyse', AnalyseNowController::class). Http::fake replaces the service with fixed answers, so the controller’s choices are tested without the service running:

tests/Feature/AnalyseNowTest.php
<?php

namespace Tests\Feature;

use App\Jobs\WatchAnalysisBatch;
use App\Models\User;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Tests\TestCase;

final class AnalyseNowTest extends TestCase
{
    public function test_a_batch_is_sent_and_watched(): void
    {
        Queue::fake();
        Http::fake(['*/batches' => Http::response(['id' => 7, 'reference' => 'dashboard-x', 'status' => 'queued',
            'total' => 2, 'analysed' => 0, 'failed' => 0, 'error' => null, 'failures' => []], 202)]);

        $this->actingAs(User::factory()->create())
            ->postJson('/evaluations/analyse', ['evaluation_ids' => [1042, 1043]])
            ->assertStatus(202)
            ->assertJson(['batch' => 7, 'status' => 'queued']);

        Http::assertSent(fn (Request $request): bool => $request->hasHeader('X-Api-Key')
            && str_starts_with($request['reference'], 'dashboard-')
            && $request['evaluation_ids'] === [1042, 1043]);
        Queue::assertPushed(WatchAnalysisBatch::class, fn (WatchAnalysisBatch $job): bool => $job->batchId === 7);
    }

    public function test_the_user_is_told_when_the_service_is_down(): void
    {
        Queue::fake();
        Http::fake(['*/batches' => Http::response(['message' => 'The service is temporarily unavailable. Try again shortly.'], 503)]);

        $this->actingAs(User::factory()->create())
            ->postJson('/evaluations/analyse', ['evaluation_ids' => [1042]])
            ->assertStatus(503);

        Http::assertSentCount(3);   // the client retried a 503 three times, with the same reference
        Queue::assertNothingPushed();
    }
}

The second test checks the retry rule from the Laravel side: three attempts for a 503. Together with the Rust test a_retry_returns_the_same_batch, the two halves prove the promise Omar asked for: a retried click never starts a second batch.

The Week 5 exit check

The week’s goal was a Rust HTTP service a Laravel app can rely on. It is reached when each line holds on your machine:

CheckHow
POST /batches answers 202 at once, and the batch is done a moment laterThe build day’s first run, with the fixture API or your own
A retried POST returns the same batch with 200, and only one batch existsa_retry_returns_the_same_batch
Every error is JSON with a message, and a 422 has Laravel’s errors mapThe tests for 400, 401, 404, 409 and 422
A database error shows the client Server Error and logs the causeThe errors lesson’s missing-column request
The analysis API down: the batch is failed with a clear message, nothing savedPoint ANALYSIS_URL at a closed port
A batch cut off by a stop is resumed at the next startStop the service with Ctrl-C mid-batch, start it again
/health answers without a key; everything else needs onehealth_needs_no_key, batches_need_the_key
cargo test, cargo clippy --all-targets and cargo fmt --check are cleanRun them before every push, or in CI
The Laravel side: the controller and the poll job tested with Http::fake and Queue::fakeRun them in your Laravel app

Laravel feature tests and these tests

LaravelRust
Send a request without a server$this->postJson(…)router.oneshot(request)
A clean databaseRefreshDatabase (a transaction per test, rolled back)#[sqlx::test] (a new database per test, dropped)
Check the answer->assertStatus(202)->assertJson([…])assert_eq!(status, …), body["status"]
Fake an outside APIHttp::fake()Point the URL at a port nothing listens on, or run a small fake server
Where the tests livetests/Featuretests/, a separate crate that sees only the public API

One honest difference: RefreshDatabase wraps each test in a transaction, so it cannot test code that runs in another connection, like the service’s background batch. A database per test has no such limit, which is why it fits a service that works after the response.

PracticeTwo more tests

Exercise 1: the batch finishes

Write a test that posts a batch with the analysis URL pointed at the fixture API (http://127.0.0.1:8000/api/analyse, started with node build/fixtures/api.mjs from this site’s repository), then polls GET /batches/{id} every 100 ms, up to 50 times, until the status is done, and checks analysed. A loop with tokio::time::sleep, not one long sleep: the test is as fast as the service.

Exercise 2: protected and public routes, merged

Rewrite app as problem 3’s answer suggests: a protected router with the two batch routes and the key check as .layer, a public router with /health, and protected.merge(public). Run the tests: they are the proof that the rewrite changed nothing.

Remember

  • Test the router with oneshot and a database per test; a test is the cheapest guard against a refactor that changes who can reach a route.

Tomorrow: Laravel Rust, Laravel’s own framework for Rust, built on the axum of this week.