All jobs

Write Unit Tests for an Axum + SQLx API

Yes. An agent adds unit tests for your Axum API's JWT extractor, error type and slugs, plus router tests against a real Postgres, in a PR with cargo test output.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads how the crate is built and what it already tests before writing anything. In an API shaped like launchbadge/realworld-axum-sqlx, Cargo.toml pins axum 0.3.4, sqlx 0.5 with the postgres, uuid and time features, tokio 1.14, argon2 0.3 for password hashing and jwt 0.15 with hmac and sha2 for login tokens; Cargo.lock resolves sqlx to 0.5.9. src/main.rs parses DATABASE_URL and HMAC_KEY into the clap Config struct, opens a PgPool with 50 connections, runs sqlx::migrate!() against the four files in migrations/ and calls http::serve. The whole suite is one #[test], test_slugify at the bottom of src/http/articles/mod.rs, which the file's own comment calls the Realworld spec's one-unit-test requirement; the rest of the coverage is the Postman collection that .github/workflows/rust.yml runs against a started server after cargo install sqlx-cli and sqlx db setup on a Postgres service container.

It picks the untested code that holds logic rather than SQL. src/http/extractor.rs signs and verifies the Authorization: Token <jwt> header with HMAC-SHA-384 and a two-week exp, and has four refusal paths: a header that is not UTF-8, a scheme other than Token , a bad signature, and an expired claim. src/http/error.rs maps the Error enum to status codes, serialises UnprocessableEntity as the spec's {"errors": {field: [messages]}} body, adds WWW-Authenticate on 401, and its ResultExt::on_constraint turns a named Postgres constraint violation into a client error. src/http/types.rs round-trips Timestamptz through RFC 3339. src/http/articles/listing.rs builds the articles query from tag, author, favorited, limit and offset. Each of those is a pure function or a small struct the agent can drive without the server.

For the extractor it writes a #[cfg(test)] mod tests beside the code: build an ApiContext with a known hmac_key and a pool it never uses, call AuthUser::to_jwt, parse it back with from_authorization, then assert each refusal returns Error::Unauthorized, including a token signed with another key and one whose exp is in the past, which it builds by signing the claims struct itself. For error.rs it calls into_response on each variant and checks status, the WWW-Authenticate header and the JSON body of a 422. on_constraint gets a test with a real sqlx::Error from the database, which needs Postgres, so those tests live with the router tests.

The router tests need a database because every handler runs a query! macro, and those macros also need DATABASE_URL at compile time since the repository has no offline sqlx-data.json. In its sandbox the agent installs Postgres, creates the database, installs sqlx-cli and runs sqlx db setup as the workflow does, then adds tests/api.rs that builds the router with a small change to src/http/mod.rs, a pub fn app(config, db) -> Router that serve now calls, and drives it with tower::ServiceExt::oneshot: register a user, log in, read /api/user with the token, hit a user_username_key collision and assert the 422 body names username. sqlx::test arrives in 0.6, so each test uses unique usernames instead of a fresh schema and the file says so. It runs cargo fmt --check, cargo build and cargo test and puts the output in the pull request.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Write the missing tests for this Axum + SQLx API. Read Cargo.toml, Cargo.lock, .env.sample, .github/workflows/rust.yml, src/main.rs, src/config.rs, src/http/mod.rs, src/http/error.rs, src/http/extractor.rs, src/http/types.rs, src/http/users.rs, src/http/articles/mod.rs, src/http/articles/listing.rs and migrations/*.sql first. The only test today is test_slugify. Add unit tests in cfg(test) modules for the JWT extractor (round trip, wrong scheme, wrong key, expired exp, non-UTF-8 header), the Error type (status per variant, WWW-Authenticate on 401, the 422 errors body) and Timestamptz serialisation. Install Postgres in your sandbox, create the database, run sqlx db setup, and add tests/api.rs that builds the router through a new pub fn in src/http/mod.rs and drives it with tower's oneshot: register, login, read the current user, and a username collision mapped by on_constraint to a 422 naming the field; use unique usernames per test because sqlx 0.5 has no sqlx::test. Do not change handler behaviour; if a test reveals a bug, keep the test, leave the code, and say so. Run cargo fmt --check, cargo build and cargo test, and open a pull request with the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request adds tests/api.rs and test modules at the bottom of src/http/extractor.rs, src/http/error.rs and src/http/types.rs, and makes one non-test change: the router constructor in src/http/mod.rs becomes public so the integration tests can build it with a test Config and pool. Its description quotes the cargo test summary with each test name, the cargo fmt --check result and the exact commands used to prepare Postgres, so the same steps can go into rust.yml before the Postman step.

Handler code is unchanged. Where a test found behaviour the comments did not promise, such as which Error variant a malformed exp claim produces, the test asserts what the code does today and the description lists it as a question rather than silently fixing it.

Before merging, a reviewer checks that the new pub fn does not widen the crate's API more than needed, decides whether the tests/api.rs cases should also run in CI on the existing Postgres service container, and reads the one-line notes on any behaviour the tests pinned down.

Run it on every night

An automation with a schedule trigger, cron 0 2 * * * and your timezone, runs this prompt in the Project's repository each night. The sandbox needs a Postgres it can reach as DATABASE_URL before cargo build, because the query! macros check SQL at compile time and this repository ships no offline query data, so the prompt tells the agent to install and prepare one first, the same way the workflow does.

Each night opens one pull request on its own branch with the tests it added and the cargo test output; a night when the suite already covers the paths it was asked about ends with a short note and no pull request. max_runs_per_hour on the automation keeps a mis-set schedule from starting more than one.

The use case this job follows, with its automation and trigger: Write the missing tests.

Why run it on Rush?

Testing this crate means compiling against a live Postgres, and that setup is the reason the suite stayed at one test: the query! macros refuse to build without a database, sqlx-cli has to be installed and the migrations applied before the first cargo test. The agent does that in its own sandbox from the workflow's own steps, so the tests it writes have run against the real schema, with the real argon2 hashing and the real constraint names from migrations/2_user.sql, before they reach the pull request.

The transcript keeps every command: the Postgres install, sqlx db setup, the compile and the test run, so the reviewer sees what passed and under what conditions without reproducing the environment. Several crates can be done at once, each with its own database, and a test that pins down surprising behaviour is reported as a question instead of becoming a quiet fix.

Frequently asked questions

Why does a unit test run need Postgres at all?

Because sqlx::query! and query_scalar! check each SQL string against a database when the crate compiles, and this repository has no sqlx-data.json for offline mode. Even a test that only exercises the JWT extractor compiles the whole crate, so DATABASE_URL must point at a prepared database first. The agent installs Postgres in its sandbox and runs sqlx db setup, as rust.yml does on its service container.

Does it change the handlers to make them testable?

One small change: the private router constructor in src/http/mod.rs gets a public wrapper that takes a Config and a PgPool, and serve calls it. That lets tests/api.rs drive the router with oneshot and no socket. Handler bodies, the ApiContext shape and the error mapping stay as they are.

What about sqlx::test for a fresh database per test?

#[sqlx::test] arrived in sqlx 0.6, and Cargo.lock resolves this project to 0.5.9. Rather than bump a major dependency inside a test change, the integration tests use unique usernames and emails per test and clean up nothing, which the file explains. Upgrading sqlx is its own pull request.

What if a test shows a bug?

The prompt says to keep the test, leave the code and report it. An example is what the extractor does with a token whose exp is missing or malformed: the test asserts today's behaviour and the pull request lists it as a question. Fixing it is a decision for the maintainer, not a side effect of a test run.

Will the Postman collection in CI still run?

Yes. Nothing in rust.yml changes in this pull request. The description shows the exact sandbox commands so the new tests/api.rs can be added to the workflow after the sqlx db setup step, before the Realworld collection starts the server.

More Axum jobs

The same job on other stacks

Keep reading