Skip to main content

IndexRustTutorial

Testing an Axum API: Unit, Integration and Database Tests

Part 14 of Rust for web developers: test an Axum API with cargo test, call the router directly with tower's oneshot, and give each test its own database.

By LearnWebCraft Team29 min readBeginner

Part 14 of 15 · Rust for web developers

Every feature in linkbox so far, I've checked by hand. I start the server, run a list of curl commands, read the output, and decide it looks right. That worked when linkbox was one file. After part 13, it has registration, login, sessions, ownership rules, validation, a body limit and CORS, and checking all of that by hand takes a while. I'd also have to remember to do it, every time, for every change.

The thing that worries me most is a quiet regression. In part 13, the only thing stopping Bo from deleting Ana's links is AND user_id = $2 at the end of one SQL statement. Someone tidies up that query six months from now, every route still returns sensible responses, and the app now lets anyone delete anything. Near the end of this part, I'll make exactly that change and show what catches it.

By the end, linkbox will have 28 tests (plus one we'll talk about separately): unit tests for validation and password hashing, and integration tests that send real HTTP requests through the real router into a real PostgreSQL database. There's no running server, no open port, no mocks, and each test gets its own empty database. Once it's compiled, the whole suite runs in under two seconds.

This ran on Rust 1.100.0, Axum 0.8.9, tower 0.5.3 and SQLx 0.9.1, against PostgreSQL 18.7. Every output is real.

How tests work in Rust

If you're coming from Jest or Vitest, here's the good news: there's nothing to install or configure. Testing is built into cargo. You write a function, mark it with #[test], and cargo test finds it, compiles it and runs it.

There are three places tests can live.

Unit tests go in the same file as the code they test, inside a module marked #[cfg(test)]. That attribute means the module only gets compiled when you run tests, so it adds nothing to your real binary. Because the test module is a child of the module it tests, it can see private functions, which Jest can't do without exporting them.

Integration tests go in a tests/ folder next to src/. Each file in there is compiled as a separate crate that uses your library from the outside, exactly like another project would. They can only use what's pub. This is why part 11 split linkbox into lib.rs and main.rs: the router is built by pub fn app() in the library, so tests can build the same router main does.

Doc tests are code examples in /// comments, which cargo test compiles and runs to make sure your documentation stays correct. They're great for libraries. For an API like linkbox, I won't use them.

The first unit tests

NewLink in models.rs has validation rules from part 13. Here are tests for them, at the bottom of the same file:

Fig. 1rust
#[cfg(test)]
mod tests {
    use super::*;

    fn link(url: &str, title: &str, tag_count: usize) -> NewLink {
        NewLink {
            url: url.to_string(),
            title: title.to_string(),
            tags: vec!["tag".to_string(); tag_count],
        }
    }

    #[test]
    fn a_normal_link_is_valid() {
        assert!(link("https://www.rust-lang.org", "Rust", 2).validate().is_ok());
    }

    #[test]
    fn only_http_and_https_urls_are_allowed() {
        for url in ["ftp://example.com", "mailto:ana@example.com", "javascript:alert(1)", "not a url"] {
            let errors = link(url, "Title", 0).validate().unwrap_err();
            assert!(errors.field_errors().contains_key("url"), "{url} should be rejected");
        }
    }

    #[test]
    fn titles_are_measured_in_characters_not_bytes() {
        // "é" is two bytes in UTF-8. 200 of them is 400 bytes, but 200 characters.
        assert!(link("https://example.com", &"é".repeat(200), 0).validate().is_ok());
        assert!(link("https://example.com", &"é".repeat(201), 0).validate().is_err());
        assert!(link("https://example.com", "", 0).validate().is_err());
    }

    #[test]
    fn at_most_ten_tags() {
        assert!(link("https://example.com", "Title", 10).validate().is_ok());
        assert!(link("https://example.com", "Title", 11).validate().is_err());
    }
}

use super::* brings everything from the parent module into scope, including private items. The small link helper keeps each test to the part that matters.

There are three assertion macros, and they cover almost everything. assert! checks that something is true. assert_eq! and assert_ne! compare two values, and when they fail, they print both, which is the main reason to prefer them over assert!(a == b). Every one of them takes an optional message with format arguments after the condition, like the "{url} should be rejected" above. In a loop, that message is how you know which input failed.

javascript:alert(1) is in that list on purpose. It parses as a valid URL, so the url rule alone accepts it, and a link like that in a frontend becomes a script that runs when someone clicks it. The http_or_https rule is what rejects it, and now a test says so.

The title test exists because in part 13 I claimed that length counts characters, not bytes. I'd rather check that than trust my memory, and a test is a good way to check something about a library. If a future version of validator changes that behavior, this test will tell me.

Async unit tests

Password hashing is async, because it runs Argon2 in spawn_blocking. A normal #[test] function can't be async. Tokio provides #[tokio::test], which creates a runtime for the test and runs the async function on it, the same way #[tokio::main] does for main:

Fig. 2rust
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn a_password_only_verifies_against_its_own_hash() {
        let hash = hash_password("correct horse battery".into()).await.unwrap();
        assert!(hash.starts_with("$argon2id$"));
        assert!(verify_password("correct horse battery".into(), hash.clone()).await.unwrap());
        assert!(!verify_password("Correct horse battery".into(), hash).await.unwrap());
    }

    #[tokio::test]
    async fn the_same_password_gets_a_different_hash_each_time() {
        let first = hash_password("same password".into()).await.unwrap();
        let second = hash_password("same password".into()).await.unwrap();
        assert_ne!(first, second);
    }

    #[test]
    fn tokens_are_random_hex() {
        let token = new_token();
        assert_eq!(token.len(), 64);
        assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
        assert_ne!(token, new_token());
    }

    #[test]
    fn a_token_hash_is_stable_and_is_not_the_token() {
        let token = new_token();
        assert_eq!(hash_token(&token), hash_token(&token));
        assert_ne!(hash_token(&token), token);
    }
}

new_token and hash_token are private functions in auth.rs, and these tests call them directly. The second test checks that salting works: if hashing the same password twice gave the same result, something would be very wrong.

Using .unwrap() in tests is normal, and it's one of the few places I'd tell you to use it freely. If it panics, the test fails and prints the error, which is exactly what you want.

Running the tests

linkbox needs two dev-dependencies for the integration tests coming up, so let me add those now:

Fig. 3bash
cargo add --dev tower@0.5.3 --features util
cargo add --dev http-body-util@0.1.5

[dev-dependencies] are only compiled for tests, examples and benchmarks, never for your real build. It's the same idea as devDependencies in package.json.

Fig. 4toml
[dev-dependencies]
http-body-util = "0.1.5"
tower = { version = "0.5.3", features = ["util"] }

Then:

Fig. 5text
$ cargo test
    Finished `test` profile [unoptimized + debuginfo] target(s) in 1m 08s
     Running unittests src/lib.rs (target/debug/build/linkbox/fea1bf5c9483ca0e/out/linkbox-fea1bf5c9483ca0e)

running 8 tests
test auth::tests::tokens_are_random_hex ... ok
test auth::tests::a_token_hash_is_stable_and_is_not_the_token ... ok
test models::tests::a_normal_link_is_valid ... ok
test models::tests::only_http_and_https_urls_are_allowed ... ok
test models::tests::at_most_ten_tags ... ok
test models::tests::titles_are_measured_in_characters_not_bytes ... ok
test auth::tests::the_same_password_gets_a_different_hash_each_time ... ok
test auth::tests::a_password_only_verifies_against_its_own_hash ... ok

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

The first run includes compiling everything in test mode, which is where the minute went. After that, only what changed gets rebuilt.

Tests run in parallel by default, on as many threads as you have cores, which is why the order in the output isn't the order in the file. Every test has to be independent of the others. Hold on to that, because it's the hard part of testing anything with a database.

To run some tests and not others, give cargo test part of a name. cargo test models:: runs the four validation tests. cargo test token runs both token tests. cargo test --test links runs only the integration tests in tests/links.rs.

Calling the router without a server

Here's the idea that makes testing Axum pleasant. An Axum Router is a tower Service: something that takes a request and asynchronously returns a response. axum::serve is one way to feed it requests, from a TCP socket. But you can also call it yourself, in memory, with no socket at all.

tower::ServiceExt adds a method called oneshot to every service. It takes one request, waits until the service is ready, calls it, and gives you the response:

Fig. 6rust
use tower::ServiceExt;

let response = app.oneshot(request).await.unwrap();

That's the whole trick. Every layer runs (tracing, CORS, compression, the body limit, the timeout), every extractor runs, the handler runs, and you get back the exact response a client would have got. The only thing skipped is the network. It's like supertest in the Express world, which also calls your app without a real port, but here it's built into how the router works.

oneshot takes self, so it consumes the router. Routers are cheap to clone (the routes inside are shared behind an Arc), so the usual pattern is app.clone().oneshot(request).

The response body is a stream, because Axum supports streaming responses. To read it all in a test, http-body-util provides collect, which waits for the whole body and gives you the bytes.

A helper for requests

Building requests by hand in every test gets repetitive fast, so I wrote a small helper. It goes in tests/common/mod.rs:

Fig. 7rust
// Each file in tests/ is its own crate, and not every one uses every helper.
#![allow(dead_code)]

use axum::{
    Router,
    body::Body,
    http::{HeaderMap, Request, StatusCode, header},
};
use http_body_util::BodyExt;
use linkbox::{AppState, app};
use serde_json::{Value, json};
use sqlx::PgPool;
use tower::ServiceExt;

pub const FRONTEND: &str = "http://localhost:5173";

/// The real router, on a test database, with one allowed CORS origin.
pub fn test_app(pool: PgPool) -> Router {
    app(AppState::new(pool), vec![FRONTEND.parse().unwrap()])
}

pub struct TestResponse {
    pub status: StatusCode,
    pub headers: HeaderMap,
    pub body: Value,
}

/// Send one request through the router, without a server or a socket.
pub async fn send(
    app: &Router,
    method: &str,
    uri: &str,
    token: Option<&str>,
    body: Option<Value>,
) -> TestResponse {
    let mut request = Request::builder().method(method).uri(uri);
    if let Some(token) = token {
        request = request.header(header::AUTHORIZATION, format!("Bearer {token}"));
    }
    let request = match body {
        Some(json) => request
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(json.to_string())),
        None => request.body(Body::empty()),
    }
    .unwrap();

    let response = app.clone().oneshot(request).await.unwrap();
    let status = response.status();
    let headers = response.headers().clone();
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let body = if bytes.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&bytes).unwrap()
    };
    TestResponse {
        status,
        headers,
        body,
    }
}

pub const PASSWORD: &str = "a long test password";

/// Register a user, log them in, and return their session token.
pub async fn login_as(app: &Router, email: &str) -> String {
    let creds = json!({ "email": email, "password": PASSWORD });
    let res = send(app, "POST", "/auth/register", None, Some(creds.clone())).await;
    assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
    let res = send(app, "POST", "/auth/login", None, Some(creds)).await;
    assert_eq!(res.status, StatusCode::OK, "{}", res.body);
    res.body["token"].as_str().unwrap().to_string()
}

Two Rust-specific details here.

The file is tests/common/mod.rs, not tests/common.rs. Cargo treats every .rs file directly inside tests/ as its own test crate. If the helpers were in tests/common.rs, cargo would compile them as a test binary with zero tests in it and list it in every run. Files in a subfolder aren't treated that way, so common/mod.rs is the conventional place for shared test code. Each test file then pulls it in with mod common;.

Because each test file is a separate crate, a helper that links.rs uses but auth.rs doesn't would cause a dead code warning when compiling auth.rs. #![allow(dead_code)] at the top of the module turns that off for the helpers only.

login_as does the real registration and login through the API, rather than inserting a user into the database directly. That's slower (it runs Argon2 twice), but it means every test that logs in is also testing that registration and login work. I'll come back to the speed.

A fresh database for every test

The router needs a PgPool, and here's where testing anything with a database gets hard. Tests run in parallel. If they share one database, a test that counts links sees links created by other tests, a test that registers ana@example.com fails if another test registered her first, and the results depend on what order things happened to run in. The usual fixes are to wipe tables between tests, which forces tests to run one at a time, or to wrap each test in a transaction and roll it back, which gets awkward when the code under test uses its own transactions.

SQLx has a better answer: #[sqlx::test]. It replaces #[tokio::test], and the test function takes a PgPool argument:

Fig. 8rust
#[sqlx::test]
async fn health_says_ok(pool: PgPool) {
    let app = test_app(pool);
    let res = send(&app, "GET", "/health", None, None).await;
    assert_eq!(res.status, StatusCode::OK);
    assert_eq!(res.body["status"], "ok");
}

For each test, SQLx connects to the server in DATABASE_URL, creates a brand new database with a generated name, runs every migration in migrations/ on it, and hands the test a pool connected to it. When the test finishes, the database is dropped. Every test starts from the same empty, fully migrated schema, and they can all run at the same time without seeing each other.

You need two things for it to work. DATABASE_URL has to point at a Postgres server (the .env file from part 12 is enough), and that user needs permission to create databases. The postgres superuser in our Docker container has it. A locked-down production user wouldn't, and shouldn't.

After the full test run, I checked whether anything was left behind:

Fig. 9text
$ psql -U postgres -tc "select count(*) from pg_database where datname like '_sqlx_test%'"
     0

Nothing. Each test's database was cleaned up after it passed.

Testing authentication

Here are the auth tests, in tests/auth.rs. Each one reads like a sentence describing a rule, which makes the test output useful by itself:

Fig. 10rust
mod common;

use std::time::{Duration, Instant};

use axum::{Router, http::StatusCode};
use common::{PASSWORD, login_as, send, test_app};
use serde_json::json;
use sqlx::PgPool;

#[sqlx::test]
async fn register_returns_the_user_without_a_password_hash(pool: PgPool) {
    let app = test_app(pool);

    let res = send(
        &app,
        "POST",
        "/auth/register",
        None,
        Some(json!({ "email": "Ana@Example.com", "password": "correct horse battery" })),
    )
    .await;

    assert_eq!(res.status, StatusCode::CREATED);
    assert_eq!(res.body["email"], "ana@example.com");
    assert!(res.body.get("password_hash").is_none());
}

#[sqlx::test]
async fn wrong_password_and_unknown_email_get_the_same_answer(pool: PgPool) {
    let app = test_app(pool);
    login_as(&app, "ana@example.com").await;

    let wrong_password = send(
        &app,
        "POST",
        "/auth/login",
        None,
        Some(json!({ "email": "ana@example.com", "password": "not the password" })),
    )
    .await;
    let unknown_email = send(
        &app,
        "POST",
        "/auth/login",
        None,
        Some(json!({ "email": "nobody@example.com", "password": "not the password" })),
    )
    .await;

    assert_eq!(wrong_password.status, StatusCode::UNAUTHORIZED);
    assert_eq!(unknown_email.status, StatusCode::UNAUTHORIZED);
    assert_eq!(wrong_password.body, unknown_email.body);
}

#[sqlx::test]
async fn me_needs_a_valid_token(pool: PgPool) {
    let app = test_app(pool);
    let token = login_as(&app, "ana@example.com").await;

    let res = send(&app, "GET", "/auth/me", None, None).await;
    assert_eq!(res.status, StatusCode::UNAUTHORIZED);
    assert_eq!(res.headers["www-authenticate"], "Bearer");

    let res = send(&app, "GET", "/auth/me", Some("made-up"), None).await;
    assert_eq!(res.status, StatusCode::UNAUTHORIZED);

    let res = send(&app, "GET", "/auth/me", Some(&token), None).await;
    assert_eq!(res.status, StatusCode::OK);
    assert_eq!(res.body["email"], "ana@example.com");
}

#[sqlx::test]
async fn logout_revokes_the_token(pool: PgPool) {
    let app = test_app(pool);
    let token = login_as(&app, "ana@example.com").await;

    let res = send(&app, "POST", "/auth/logout", Some(&token), None).await;
    assert_eq!(res.status, StatusCode::NO_CONTENT);

    let res = send(&app, "GET", "/auth/me", Some(&token), None).await;
    assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}

The file also has tests for a duplicate email (409) and for registration errors listing both bad fields, which follow the same pattern.

serde_json::Value supports indexing with ["key"], and it returns Value::Null for a missing key instead of panicking. That makes res.body["error"]["fields"]["email"][0]["code"] safe to write even when the shape is wrong. The comparison just fails with a clear message. And a Value can be compared directly with a string or number, so assert_eq!(res.body["email"], "ana@example.com") works.

Reaching into the database

Some rules are hard to test through the API alone. Sessions expire after seven days, and I'm not waiting a week for a test. Because #[sqlx::test] gives me the pool, I can clone it before handing it to the app and keep a handle to the same database:

Fig. 11rust
#[sqlx::test]
async fn expired_sessions_are_rejected(pool: PgPool) {
    let app = test_app(pool.clone());
    let token = login_as(&app, "ana@example.com").await;

    // Reach into the database and move the expiry into the past.
    sqlx::query("UPDATE sessions SET expires_at = now() - interval '1 second'")
        .execute(&pool)
        .await
        .unwrap();

    let res = send(&app, "GET", "/auth/me", Some(&token), None).await;
    assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}

The UPDATE has no WHERE, which in a shared database would be alarming. Here it's fine, because this test's database contains exactly one session: the one it just created. That's the other benefit of a database per test. You can do blunt things to it.

Fig. 12text
     Running tests/auth.rs (target/debug/build/linkbox/e8e0605961b30e7b/out/auth-e8e0605961b30e7b)

running 8 tests
test failed_logins_take_about_the_same_time ... ignored, timing-based; run with cargo test -- --ignored
test register_reports_every_invalid_field ... ok
test register_returns_the_user_without_a_password_hash ... ok
test logout_revokes_the_token ... ok
test me_needs_a_valid_token ... ok
test expired_sessions_are_rejected ... ok
test registering_the_same_email_twice_is_a_conflict ... ok
test wrong_password_and_unknown_email_get_the_same_answer ... ok

test result: ok. 7 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 3.18s

Seven tests, seven separate databases, about three seconds. I'll explain the ignored one shortly.

tests/links.rs covers the link routes. The test I care most about is this one:

Fig. 13rust
#[sqlx::test]
async fn only_the_owner_can_change_or_delete_a_link(pool: PgPool) {
    let app = test_app(pool);
    let ana = login_as(&app, "ana@example.com").await;
    let bo = login_as(&app, "bo@example.com").await;

    let created = send(&app, "POST", "/links", Some(&ana), Some(learn_rust())).await;
    let path = format!("/links/{}", created.body["id"]);

    let res = send(&app, "DELETE", &path, Some(&bo), None).await;
    assert_eq!(res.status, StatusCode::NOT_FOUND);

    let hijack = json!({ "url": "https://evil.example", "title": "Hijacked" });
    let res = send(&app, "PUT", &path, Some(&bo), Some(hijack)).await;
    assert_eq!(res.status, StatusCode::NOT_FOUND);

    let res = send(&app, "GET", &path, None, None).await;
    assert_eq!(res.body["title"], "Learn Rust");

    let res = send(&app, "DELETE", &path, Some(&ana), None).await;
    assert_eq!(res.status, StatusCode::NO_CONTENT);
    let res = send(&app, "GET", &path, None, None).await;
    assert_eq!(res.status, StatusCode::NOT_FOUND);
}

learn_rust() is a little function at the top of the file that returns the same link JSON each time. The test checks both halves of the rule: Bo can't touch the link, and Ana can. A test that only checked the first half would pass on an app where nobody can delete anything.

The validation test checks that every broken field is reported, not only the first:

Fig. 14rust
#[sqlx::test]
async fn invalid_links_get_an_error_for_every_field(pool: PgPool) {
    let app = test_app(pool);
    let token = login_as(&app, "ana@example.com").await;

    let res = send(
        &app,
        "POST",
        "/links",
        Some(&token),
        Some(json!({ "url": "ftp://example.com", "title": "", "tags": vec!["t"; 11] })),
    )
    .await;

    assert_eq!(res.status, StatusCode::UNPROCESSABLE_ENTITY);
    let mut fields: Vec<_> = res.body["error"]["fields"]
        .as_object()
        .unwrap()
        .keys()
        .cloned()
        .collect();
    fields.sort();
    assert_eq!(fields, ["tags", "title", "url"]);
}

vec!["t"; 11] makes a vector of eleven "t"s, and json! accepts Rust values like that directly. The keys get sorted before comparing, because the test shouldn't depend on what order the JSON object happens to list them in.

There are also tests for the 401 without a login, creating and fetching a link, the unique URL rule, the 413 for a big body, the JSON 404 for an unknown route and the health check. They follow the same shape, so I won't list them all.

Testing CORS with a raw request

The CORS preflight needs headers that send doesn't support, like Origin. Rather than make the helper more complicated for two tests, I built those requests directly:

Fig. 15rust
async fn preflight(pool: PgPool, origin: &str) -> axum::response::Response {
    let request = Request::builder()
        .method("OPTIONS")
        .uri("/links")
        .header(header::ORIGIN, origin)
        .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
        .body(Body::empty())
        .unwrap();
    test_app(pool).oneshot(request).await.unwrap()
}

#[sqlx::test]
async fn cors_allows_the_frontend(pool: PgPool) {
    let res = preflight(pool, FRONTEND).await;
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], FRONTEND);
}

#[sqlx::test]
async fn cors_ignores_other_origins(pool: PgPool) {
    let res = preflight(pool, "https://evil.example").await;
    assert!(
        res.headers()
            .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
            .is_none()
    );
}

As part 13 showed, a disallowed origin still gets a 200. What matters is that the access-control-allow-origin header is missing, so that's what the test checks. These tests never touch the database, but they still need a pool to build the app, and #[sqlx::test] is the easy way to get one.

Fixtures: starting with data

The list endpoint filters by tag and paginates. Testing that needs several links in the database first. Creating them through the API would work, but it's a lot of setup for a test about reading. SQLx supports fixtures for this: SQL files that run after the migrations and before the test.

Fig. 16rust
#[sqlx::test(fixtures("links"))]
async fn list_filters_by_tag_and_paginates(pool: PgPool) {
    let app = test_app(pool);
    let titles = |body: &Value| -> Vec<String> {
        body.as_array()
            .unwrap()
            .iter()
            .map(|link| link["title"].as_str().unwrap().to_string())
            .collect()
    };

    let res = send(&app, "GET", "/links?tag=rust", None, None).await;
    assert_eq!(titles(&res.body), ["Rust", "Tokio", "Docs.rs"]);

    let res = send(&app, "GET", "/links?limit=2&offset=1", None, None).await;
    assert_eq!(titles(&res.body), ["Tokio", "MDN"]);
}

fixtures("links") means tests/fixtures/links.sql, relative to the test file. Links need an owner, so the fixture creates a user first. My first version gave the user a fixed id so the links could refer to it:

Fig. 17sql
INSERT INTO users (id, email, password_hash)
VALUES (1, 'fixture@example.com', 'not a real hash');

INSERT INTO links (user_id, url, title, tags) VALUES
    (1, 'https://www.rust-lang.org', 'Rust', '{rust}'),
    (1, 'https://tokio.rs', 'Tokio', '{rust,async}'),
    (1, 'https://developer.mozilla.org', 'MDN', '{web}'),
    (1, 'https://docs.rs', 'Docs.rs', '{rust,docs}');
Fig. 18text
---- list_filters_by_tag_and_paginates stdout ----

thread 'list_filters_by_tag_and_paginates' (3151) panicked at /usr/local/cargo/registry/src/index.crates.io-1949cf8c6b5b557f/sqlx-core-0.9.1/src/testing/mod.rs:269:33:
failed to apply test fixture "fixtures/links.sql": Database(PgDatabaseError { severity: Error, code: "428C9", message: "cannot insert a non-DEFAULT value into column \"id\"", detail: Some("Column \"id\" is an identity column defined as GENERATED ALWAYS."), hint: Some("Use OVERRIDING SYSTEM VALUE to override."), position: None, where: None, schema: None, table: None, column: None, data_type: None, constraint: None, file: Some("rewriteHandler.c"), line: Some(942), routine: Some("rewriteTargetListIU") })

That's the GENERATED ALWAYS from part 12 doing its job. It refuses ids from outside, which protects real code from inserting ids by accident. A fixture has a legitimate reason to, and Postgres's hint says how to ask:

Fig. 19sql
INSERT INTO users (id, email, password_hash)
OVERRIDING SYSTEM VALUE
VALUES (1, 'fixture@example.com', 'not a real hash');

The password hash is a placeholder, because no test logs in as this user. If one needed to, I'd create the user through the API instead.

The slow test, and #[ignore]

In part 13, the most interesting bug was a timing leak: logins for unknown emails returned in 2 milliseconds while wrong passwords took hundreds, which told an attacker which emails had accounts. A test for that has to measure time:

Fig. 20rust
async fn time_login(app: &Router, email: &str) -> Duration {
    let start = Instant::now();
    let res = send(
        app,
        "POST",
        "/auth/login",
        None,
        Some(json!({ "email": email, "password": PASSWORD.to_uppercase() })),
    )
    .await;
    assert_eq!(res.status, StatusCode::UNAUTHORIZED);
    start.elapsed()
}

#[sqlx::test]
#[ignore = "timing-based; run with cargo test -- --ignored"]
async fn failed_logins_take_about_the_same_time(pool: PgPool) {
    let app = test_app(pool);
    login_as(&app, "ana@example.com").await;

    let mut known = Duration::ZERO;
    let mut unknown = Duration::ZERO;
    for _ in 0..5 {
        known += time_login(&app, "ana@example.com").await;
        unknown += time_login(&app, "nobody@example.com").await;
    }

    let ratio = unknown.as_secs_f64() / known.as_secs_f64();
    println!("known email: {known:?}, unknown email: {unknown:?}, ratio {ratio:.2}");
    assert!(
        (0.5..2.0).contains(&ratio),
        "unknown emails took {ratio:.2}x as long as known ones"
    );
}

Timing tests are flaky by nature. A CI machine running other jobs can stall any request for a moment, and a test that sometimes fails for no reason trains everyone to ignore failures. So this one is marked #[ignore], with a reason. It's skipped in a normal run, and you ask for it explicitly:

Fig. 21text
$ cargo test --test auth -- --ignored --nocapture
known email: 2.051773951s, unknown email: 2.483911769s, ratio 1.21
test failed_logins_take_about_the_same_time ... ok

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

The -- separates options for cargo from options for the test runner. --ignored runs only ignored tests. --nocapture shows println! output, which the test runner normally hides unless a test fails. The bounds are wide on purpose. Without the dummy hash, the ratio was around 0.005, so any real regression is far outside 0.5 to 2.

Catching the regression

Now for the change I promised at the start. Say someone is tidying up state.rs and decides the delete query is more complicated than it needs to be. They remove the ownership check from the SQL:

Fig. 22rust
let result = sqlx::query!(
    "DELETE FROM links WHERE id = $1",
    id,
    user_id
)
Fig. 23text
error: expected 1 parameters, got 2
   --> src/state.rs:102:22
    |
102 |           let result = sqlx::query!(
    |  ______________________^
103 | |             "DELETE FROM links WHERE id = $1",
104 | |             id,
105 | |             user_id
106 | |         )
    | |_________^

SQLx's compile-time checks catch a half-finished edit: the query now has one placeholder and two arguments. That's nice, but it's luck. A determined tidier finishes the job, drops the argument, and renames the now-unused parameter to _user_id to quiet the warning:

Fig. 24rust
pub async fn remove(&self, _user_id: i64, id: i64) -> Result<bool, sqlx::Error> {
    let result = sqlx::query!("DELETE FROM links WHERE id = $1", id)

That compiles cleanly. Clippy is happy. Every handler still returns sensible responses. And:

Fig. 25text
$ cargo test --test links
...
failures:

---- only_the_owner_can_change_or_delete_a_link stdout ----

thread 'only_the_owner_can_change_or_delete_a_link' (786) panicked at tests/links.rs:80:5:
assertion `left == right` failed
  left: 204
 right: 404


failures:
    only_the_owner_can_change_or_delete_a_link

test result: FAILED. 10 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 8.37s

Bo's delete returned 204 instead of 404. Line 80 is the first assertion after Bo's DELETE, so the failure points straight at the broken rule. The compiler checks that the code is consistent. Only a test can check that it does what you meant. Putting the check back makes the suite green again.

Writing the test first

Tests are also a good way to build something new. The first exercise in part 13 was about making links private, and a smaller step in that direction is a route that lists only your own links: GET /links/mine. Instead of writing the route and then poking at it with curl, I'll write down what it should do first, as two tests at the bottom of tests/links.rs:

Fig. 26rust
#[sqlx::test]
async fn mine_lists_only_my_links(pool: PgPool) {
    let app = test_app(pool);
    let ana = login_as(&app, "ana@example.com").await;
    let bo = login_as(&app, "bo@example.com").await;
    send(&app, "POST", "/links", Some(&ana), Some(learn_rust())).await;
    let tokio = json!({ "url": "https://tokio.rs", "title": "Tokio" });
    send(&app, "POST", "/links", Some(&bo), Some(tokio)).await;

    let res = send(&app, "GET", "/links/mine", Some(&ana), None).await;

    assert_eq!(res.status, StatusCode::OK, "{}", res.body);
    let titles: Vec<_> = res.body.as_array().unwrap().iter().map(|l| &l["title"]).collect();
    assert_eq!(titles, ["Learn Rust"]);
}

#[sqlx::test]
async fn mine_needs_a_login(pool: PgPool) {
    let app = test_app(pool);
    let res = send(&app, "GET", "/links/mine", None, None).await;
    assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body);
}

The "{}", res.body message on the status assertions is a habit worth having. When a status check fails, the body usually says why, and without the message you'd only see two numbers.

Running only these two, before writing any code for them:

Fig. 27text
$ cargo test -q --test links mine

running 2 tests
mine_needs_a_login --- FAILED
mine_lists_only_my_links --- FAILED

failures:

---- mine_needs_a_login stdout ----

thread 'mine_needs_a_login' (293) panicked at tests/links.rs:202:5:
assertion `left == right` failed: {"error":{"code":"invalid_path","message":"Cannot parse `mine` to a `i64`"}}
  left: 400
 right: 401

---- mine_lists_only_my_links stdout ----

thread 'mine_lists_only_my_links' (292) panicked at tests/links.rs:187:5:
assertion `left == right` failed: {"error":{"code":"invalid_path","message":"Cannot parse `mine` to a `i64`"}}
  left: 400
 right: 200

Both fail, which is the point of this step: a test that passes before the feature exists isn't testing the feature. And the message explains the failure. There's no /links/mine route yet, so the request matched /links/{id} with mine as the id, and parsing that as an i64 failed. -q is quiet mode, which prints a dot or a short line per test instead of the full list.

The implementation is a query and a handler. In state.rs:

Fig. 28rust
/// Every link that belongs to one user, oldest first.
pub async fn list_for_user(&self, user_id: i64) -> Result<Vec<Link>, sqlx::Error> {
    sqlx::query_as!(
        Link,
        "SELECT id, url, title, tags, created_at FROM links WHERE user_id = $1 ORDER BY id",
        user_id,
    )
    .fetch_all(&self.pool)
    .await
}

And in routes/links.rs:

Fig. 29rust
pub fn router() -> Router<AppState> {
    Router::new()
        .route("/", get(list).post(create))
        .route("/mine", get(mine))
        .route("/{id}", get(show).put(replace).delete(remove))
}

async fn mine(
    State(state): State<AppState>,
    user: AuthUser,
) -> Result<AppJson<Vec<Link>>, AppError> {
    let links = state.list_for_user(user.id).await?;
    Ok(AppJson(links))
}

/mine and /{id} overlap: mine could be an id. Axum's router allows that, and a fixed segment wins over a parameter, so /links/mine goes to mine and /links/5 still goes to show.

Fig. 30text
$ cargo test -q --test links mine

running 2 tests
..
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 11 filtered out; finished in 0.54s

Then the whole suite, to make sure nothing else broke:

Fig. 31text
$ cargo test -q
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.09s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
test result: ok. 7 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.67s
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.99s
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Twenty-eight tests in under two seconds (this run already has the speed-up from the next section). The new query also means one more file in .sqlx, so I ran cargo sqlx prepare again before committing.

I didn't write a test-first section to sell you on test-driven development as a religion. I do it when the behavior is easy to describe before the code exists, like a route with clear inputs and outputs. When I'm still working out what something should do, I write the code first and the tests once it settles.

Making the suite faster

The integration tests spend most of their time in Argon2. Every login_as hashes a password once and verifies it once, and in a debug build, each of those takes around 400 milliseconds, as we saw in part 13. Test builds use the debug profile, so the tests pay that cost on every login.

Cargo lets you change the optimization level for a single dependency while keeping your own code in fast-to-compile debug mode. In Cargo.toml:

Fig. 32toml
[profile.dev.package.argon2]
opt-level = 3

That compiles only the argon2 crate with full optimizations, in debug and test builds. Your code still builds quickly and stays easy to debug. The difference, from test result lines before and after:

Test binary Before After
Unit tests (src/lib.rs) 1.37s 0.12s
tests/auth.rs 3.36s 0.69s
tests/links.rs 2.98s 0.85s

About four times faster overall, for two lines of config. It also makes cargo run logins fast during development. The same trick works for any dependency that does heavy computation (image processing and compression crates are common candidates).

What I didn't test, and why

Not everything needs a test, and some tests cost more than they're worth.

I didn't test that TraceLayer logs requests, or that CompressionLayer compresses. Those are other people's code with their own tests. I tested my configuration of CORS, because the list of allowed origins is mine and getting it wrong is a security problem.

I didn't test the 500 response when the database is down. It's possible (close the pool, then send a request), and part 12 showed the behavior by hand. I'd add it if the error handling got more complicated.

I didn't mock the database. Some codebases put the database behind a trait and swap in an in-memory fake for tests. That makes tests faster and lets them run without Postgres, but the fake never behaves exactly like Postgres. It won't enforce the unique constraints, the foreign keys or the GENERATED ALWAYS rule that just bit me. With #[sqlx::test] making a real database this cheap, I'd rather test against the real thing.

Running the tests in CI

#[sqlx::test] needs a running Postgres, so CI does too. Most CI systems can start one next to your job. Here's a GitHub Actions workflow to start from:

Fig. 33yaml
name: test
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: linkbox
        ports: ["5432:5432"]
        options: >-
          --health-cmd pg_isready
          --health-interval 5s
          --health-retries 10
    env:
      DATABASE_URL: postgres://postgres:postgres@localhost:5432/linkbox
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt
      - run: cargo fmt --check
      - run: cargo clippy --all-targets -- -D warnings
      - run: cargo test
      - run: cargo install sqlx-cli --no-default-features --features postgres
      - run: cargo sqlx migrate run
      - run: cargo sqlx prepare --check

The health check makes the job wait until Postgres accepts connections. cargo test doesn't need the migrations run first, because #[sqlx::test] applies them to each test database, but prepare --check reads the schema of the linkbox database itself, so that one does. It fails if someone changed a query without updating the .sqlx folder, which is what part 15's Docker build depends on. Installing sqlx-cli from source takes a few minutes, so on a busy project you'd cache it.

Jest and Vitest compared

Node Rust
Install Jest or Vitest and configure it Built into cargo test
*.test.ts files next to the code #[cfg(test)] mod tests in the same file
Can only test exported functions Unit tests can see private functions
describe and it blocks Test function names that read like sentences
expect(a).toBe(b) assert_eq!(a, b)
it.skip #[ignore = "reason"]
jest -t "token" cargo test token
supertest(app).get("/health") app.oneshot(request)
Shared test database plus cleanup hooks A new database per test with #[sqlx::test]
Seed scripts in beforeEach #[sqlx::test(fixtures("links"))]
Runs test files in parallel workers Runs individual tests in parallel threads

Jest has a few things Rust's built-in runner doesn't, like snapshot testing and watch mode. Both exist as add-ons: the insta crate does snapshots, and cargo watch -x test or bacon reruns tests when files change. cargo-nextest is a popular faster test runner that also gives each test its own process.

Exercises

  1. Add a test that a user can't log in with their email in a different case and a wrong password, and can log in with their email in a different case and the right password. Does the API already handle it?
  2. Write a test for PUT /links/{id} by the owner. Check that the response has the new title, and that a GET afterwards returns it too.
  3. Add a second fixture, users.sql, and change links.sql to depend on it. Then use #[sqlx::test(fixtures("users", "links"))]. What happens if you list them in the other order?
  4. Write a test that GET /links?limit=1000 returns at most 100 links, because of the clamp in the query. You'll need a fixture with more than 100 rows. Postgres's generate_series can make them in one statement.
  5. Write a test that the API returns a 500 with a generic message when the database is unreachable. Hint: pool.close().await before sending the request.
  6. Install cargo-nextest with cargo install cargo-nextest and run cargo nextest run. How does the output compare, and is it faster on your machine?

Next up: deploying

linkbox works, it's tested, and it only runs on my machine. Part 15 is the last part of the series, and it gets linkbox onto the internet.

We'll write a multi-stage Dockerfile that builds a release binary with SQLX_OFFLINE and ships it in a small image, add graceful shutdown so in-flight requests finish when the container stops, run it with Postgres using Docker Compose, and look at where to host it, from a plain VPS to platforms like Fly.io and Railway, along with the production settings that matter: secrets, the health check, logs and HTTPS.