tower oneshot

Learn how tower oneshot sends exactly one request through an Axum Router in a test and returns the response without starting a server

oneshot is the method that sends exactly one request through a Tower service and returns the response. It belongs to the tower::ServiceExt trait, it consumes the service it is called on, and it returns a future that resolves to the response when awaited. In an Axum test, it is the call that replaces the whole network: instead of starting a server, picking a port, and sending a request over a socket, the test builds a request value, hands it to the Router through oneshot, and reads the response back in the same function.

Where This Fits

The page before this one introduced ServiceExt as the trait that adds test-friendly methods to a Router, and oneshot was its headline method. This page takes that one method apart. The trait gives a test many tools, and oneshot is the tool used in nearly every test, so it earns a page of its own. The idea is simple to state, one request in, one response out, and the details are what make tests written with it reliable.

Think of a single-use ticket. A season pass lets its holder enter again and again, and a single-use ticket is spent the moment it is used. oneshot spends the service the same way. It takes the Router, uses it for one request, and the Router is gone afterwards. A test that needs a second request buys a second ticket, which means building a second Router.

The Smallest Working Version

The smallest use of oneshot is a test that asks for one book and checks the status. The project is the same book app from the error pages, with the app function in src/lib.rs and the AppError type in src/errors.rs.

tests/oneshot_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn oneshot_get_returns_the_book() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

The Cargo.toml file is the same project file as the ServiceExt page, with tower as a dev-dependency and the util feature turned on, because oneshot comes from that trait and that feature.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[dev-dependencies]
tower = { version = "0.5.3", features = ["util"] }

Run it with cargo test, and it passes:

test oneshot_get_returns_the_book ... ok

Five things happen in the test, in order. app() builds the Router. Request::builder() builds the request. oneshot takes both and returns a future. .await runs that future until the response arrives. .unwrap() opens the Result and hands the test the response. The assertion then checks the status. Nothing in the chain touches the network.

Working Setup:

If cargo test prints ok for this test, oneshot is wired up: the trait is imported, the util feature is on, and the router answers a request in memory.

Understanding the Signature Line by Line

The method is defined in the tower crate, in tower::util, and its full signature is short enough to read piece by piece.

fn oneshot(self, req: Request) -> Oneshot<Self, Request>
where
    Self: Sized,

The first word to notice is self, with no & in front of it. That means the method takes ownership of the service. The Router moves into oneshot and does not come back, which is the single-use ticket from the opening. A test that writes router.oneshot(...) cannot use router again afterwards, and the compiler says so if it tries.

The second parameter is req: Request, the request value. Request here is the generic parameter of the trait, and for an Axum test it is Request<Body>, an HTTP request whose body is an Axum Body. The request carries the method, the URI, the headers, and the body, all built by Request::builder().

The return type is Oneshot<Self, Request>, a future type. A future is an async value that produces a result when awaited, and Oneshot is Tower's future for this one call. It resolves to Result<Self::Response, Self::Error>, a result holding either the response or the service error. The where Self: Sized bound means the method only works on services whose size is known at compile time, which covers Router and every concrete service type a test would use. It excludes trait objects, values whose exact type is hidden, and that is a deliberate limit, because oneshot needs to move the concrete service into the future.

Inside the future, two steps run. First it waits for the service to become ready, the same readiness check poll_ready performs. Then it calls the service once with the request and returns whatever the service returns. For a plain Router, readiness is immediate, so the wait is invisible. For a service wrapped in a layer that can be busy, the wait is what keeps the call correct.

The Result Type and Infallible

The future resolves to a Result, and the error side deserves attention because it decides whether .unwrap() is safe. For a Router, the Service::Error type is std::convert::Infallible. Infallible is a type in the standard library that has no values at all, which means a Result<Response, Infallible> can never hold an Err. There is no error value that could exist, so the Err case is impossible by construction.

That is why every test on this page calls .unwrap() on the awaited result without a second thought. The unwrap is not hiding a possible failure. The type system has already ruled the failure out. The same reasoning applies to the test that names the type explicitly:

tests/oneshot_test.rs
use axum::{
    body::Body,
    http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn oneshot_result_never_holds_a_router_error() {
    let result = app().oneshot(
        Request::builder()
            .uri("/books/1")
            .body(Body::empty())
            .unwrap(),
    );
    let response = result.await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

The test binds the future to result first, then awaits it, then unwraps it. Splitting the chain across lines changes nothing about the behaviour, and it makes the three stages visible: build the future, run it, open the result. A service wrapped in middleware that can fail, such as a layer that returns its own error type, would have a real error type instead of Infallible, and then .unwrap() would be a genuine risk. For a plain Router, it is safe.

Unwrap Is Safe Here Because the Type Says So:

Calling .unwrap() is usually a smell in production code, because it panics on an error. On a Router oneshot result it is fine, because the error type is Infallible and the Err case cannot exist. The safety comes from the type, not from confidence.

The Concept Behind One Request Per Service

The consuming design looks wasteful at first. Building a Router per request sounds expensive, and it is natural to ask why oneshot does not borrow the service and hand it back. The answer is that a Service is allowed to change while it handles a request. A load balancer rotates to the next backend, a rate limiter spends a token, a buffer fills up. A method that borrowed the service and returned it afterwards would have to promise the service is unchanged, and Tower does not make that promise. Consuming the service sidesteps the question entirely. The service is used once, and whatever state it gained or lost goes away with it.

For an Axum Router, the state change is nil. Routing is a pure lookup, handlers run and finish, and the router is the same afterwards as before. That is why cloning a router or rebuilding it with app() is cheap and correct. The consuming shape is a property of the general Service trait, and Router simply inherits it. Tests pay for the generality with one extra app() call per request, and they get back a method that works identically on every Tower service.

Why oneshot Instead of call

The Service trait already has call, which sends a request to a service. oneshot is call with the readiness wait built in, plus the consuming form. The plain call method has a rule: the caller must have checked readiness first, by awaiting ready or polling poll_ready until it reports ready. Calling call on a service that is not ready is a contract violation, and the service is allowed to panic or misbehave. A Router is always ready, so the rule is invisible for Axum tests, but the rule still exists, and oneshot is the method that follows it correctly without the test having to think about it.

The practical difference is one line versus three. With oneshot, the test builds the request and awaits the response. With call, the test must await ready, then call, then await the response future, and it must hold the router mutably across those steps. Both shapes appear in real code, and the ready plus call form is shown on the ServiceExt page. For a single request, oneshot is the shorter and safer choice, because the readiness step cannot be forgotten.

A Richer Complete Example

The smallest version asked for one book. A realistic test file asks for several things and checks that the router answers each one correctly, including the cases where the router itself says no. This file covers a successful GET, an unknown route, a wrong method, a POST with a JSON body, and the two-request rule.

tests/oneshot_test.rs
use axum::{
    body::Body,
    http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn oneshot_get_returns_the_book() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn oneshot_result_never_holds_a_router_error() {
    let result = app().oneshot(
        Request::builder()
            .uri("/books/1")
            .body(Body::empty())
            .unwrap(),
    );
    let response = result.await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn oneshot_unknown_route_returns_404() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/no-such-route")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn oneshot_wrong_method_returns_405() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::DELETE)
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn oneshot_post_with_a_json_body_creates_a_book() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn two_oneshots_need_two_routers() {
    let first = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(first.status(), StatusCode::OK);
    let second = app()
        .oneshot(
            Request::builder()
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(second.status(), StatusCode::OK);
}

Run it with cargo test, and all six tests pass:

test oneshot_get_returns_the_book ... ok
test oneshot_post_with_a_json_body_creates_a_book ... ok
test oneshot_result_never_holds_a_router_error ... ok
test oneshot_unknown_route_returns_404 ... ok
test oneshot_wrong_method_returns_405 ... ok
test two_oneshots_need_two_routers ... ok

The unknown-route test shows that oneshot does not treat a 404 as an error. The future resolves to Ok, and the response carries status 404. The router answered the request, and its answer was "no such route". The wrong-method test shows the same for 405. The route /books/1 exists for GET, and a DELETE to it gets 405 Method Not Allowed, which is Axum telling the client the path is real but the method is not. The POST test shows a request with a body: the method is set to POST, the content type header marks the body as JSON, and Body::from carries the JSON text. The create handler answers 201 Created, which is the status the app uses for a successful creation.

What oneshot Does With an Unknown Route

A beginner often expects a request to an unknown route to fail the test at the oneshot call, with an error result. It does not. Axum's router always produces a response, even for a path it does not know. The response has status 404 and an empty body, and the oneshot future resolves to Ok carrying it. The 404 is data in the response, not a failure of the call, and the test asserts on it like any other status. This is the same behaviour a real client sees over the network, and it is one of the reasons the in-memory test is trustworthy. The router does not have a special test mode. It answers the same way in both places.

What oneshot Does With the Wrong Method

The 405 case is subtler, and it catches beginners who only test the happy path. Axum matches on path and method together, so a path that exists for one method and not another is a distinct situation from a path that does not exist at all. A DELETE to /books/1 gets 405, not 404, because the path matched and the method did not. A test that asserts 405 proves the route table knows the path and restricts the method, which is a real property of the app worth pinning down. A test that only checks the GET case would never notice if a route accidentally accepted every method.

Sending a Request With a Body

A GET request has no body, so Body::empty() is the right body for it. A POST request carries its data in the body, and Body::from builds a body from a value. The example passes a string literal containing JSON, r#"{"title":"Dune"}"#, which is a raw string, a string written without escaping its quotes. The r#"..."# form lets the JSON quotes sit inside the string unchanged. The content type header matters as much as the body itself. The create handler reads the body with the Json extractor, and that extractor refuses a body that does not arrive marked as JSON. Without the header, the same request is rejected with 415 Unsupported Media Type, and the handler never runs. The request builder page takes the header and the body apart in detail, and the rule to carry away is that the body and its header travel together.

Two Requests Need Two Routers

The last test in the richer example is the rule this page opened with, shown as a passing test rather than a compiler error. Each oneshot call starts with its own app(), so each request gets a fresh router and nothing is reused after being moved. The alternative is cloning one router and handing the clone to the first call, which the ServiceExt page shows. Both are correct, and the fresh-router form is the simplest to read, because each test line owns everything it uses.

A helper that hides the repetition is a natural next step in a larger suite, and it looks like this:

tests/oneshot_test.rs
async fn get(path: &str) -> axum::response::Response {
    app()
        .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
        .await
        .unwrap()
}

#[tokio::test]
async fn helper_sends_a_get_request() {
    let response = get("/books/1").await;
    assert_eq!(response.status(), StatusCode::OK);
}

The helper builds a fresh router, builds the request, sends it, and returns the response, all in one place. Every test that needs a GET calls the helper with a path, and the oneshot mechanics live in exactly one spot. The status assertion page builds on this helper shape with one helper per method.

How a Request Travels Through oneshot

The diagram below follows one request from the test to the handler and back, with the oneshot future in the middle.

Test calls app() and builds a Request
        |
        v
oneshot takes the Router and the Request
        |
        v
Oneshot future waits for poll_ready
        |
        v
Service::call runs the Router on the Request
        |
        v
Router matches the route and runs the handler
        |
        v
Handler returns a value or an AppError
        |
        v
Future resolves to Ok(response)
        |
        v
Test unwraps the Result and asserts

Every step except the handler runs inside Tower or Axum, and the test only writes the first and last steps. The future in the middle is what makes the call async, and awaiting it is what makes the test wait for the answer instead of reading a value that is not there yet.

Testing the Method Itself

The test file in the richer example is the testing section for this page. It covers the method from five angles: a successful GET, the shape of the result, an unknown route, a wrong method, and a POST with a body, plus the two-router rule. All six tests passed against the scratch project with axum 0.8.9, tower 0.5.3, and tokio 1.54.1. Run them with cargo test --test oneshot_test to run just this file, or cargo test to run the whole suite.

Common Beginner Mistakes

Forgetting to await the future

// Wrong - the request never runs
let response = app()
    .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap());
assert_eq!(response.status(), StatusCode::OK);

Without .await, response is the Oneshot future, not a Result, and it has no status method. The compiler rejects the assertion, and it also warns that the future is never used. The fix is .await before .unwrap(). A future in Rust does nothing until it is awaited, and oneshot follows that rule like every other future.

A Future That Is Never Awaited Does Nothing:

Forgetting .await does not send the request slowly or send half a request. It sends nothing at all. The future is built and then dropped, and the handler never runs. If a test passes with no assertions running, check the await first.

Awaiting but not unwrapping

// Wrong - response is a Result, not a Response
let response = app()
    .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
    .await;
assert_eq!(response.status(), StatusCode::OK);

After .await, the value is a Result<Response, Infallible>, and Result has no status method. The fix is .unwrap() after .await, which opens the result and gives the test the Response inside. The order is fixed: await first, unwrap second.

Reusing the router after oneshot

// Wrong - the first oneshot moved the router
let router = app();
let first = router.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()).await.unwrap();
let second = router.oneshot(Request::builder().uri("/books/1").body(Body::empty()).unwrap()).await.unwrap();

The first call consumes router, so the second line fails with a "use of moved value" error. The fix is a fresh app() for the second request, or a .clone() of the router before the first call.

Expecting an error result for a 404

// Wrong - the future resolves to Ok with a 404 response inside
let result = app()
    .oneshot(Request::builder().uri("/no-such-route").body(Body::empty()).unwrap())
    .await;
assert!(result.is_err());

The result is Ok, because the router answered. The 404 lives in the response status, not in the result. The fix is to unwrap the result and assert on response.status(), as the unknown-route test does.

Using oneshot without the trait import

// Wrong - oneshot comes from ServiceExt, not from Router
let response = app()
    .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
    .await
    .unwrap();

Without use tower::ServiceExt; at the top of the file, the compiler reports no method named oneshot found for Router. The fix is the import line, plus the util feature in Cargo.toml if that is missing too.

Final Complete Example

Here is everything from this page in one place: the test file with all six tests and the helper, and the command to run them.

tests/oneshot_test.rs
use axum::{
    body::Body,
    http::{Method, Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;

#[tokio::test]
async fn oneshot_get_returns_the_book() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn oneshot_result_never_holds_a_router_error() {
    let result = app().oneshot(
        Request::builder()
            .uri("/books/1")
            .body(Body::empty())
            .unwrap(),
    );
    let response = result.await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

#[tokio::test]
async fn oneshot_unknown_route_returns_404() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/no-such-route")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn oneshot_wrong_method_returns_405() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::DELETE)
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}

#[tokio::test]
async fn oneshot_post_with_a_json_body_creates_a_book() {
    let response = app()
        .oneshot(
            Request::builder()
                .method(Method::POST)
                .uri("/books")
                .header("content-type", "application/json")
                .body(Body::from(r#"{"title":"Dune"}"#))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
}

#[tokio::test]
async fn two_oneshots_need_two_routers() {
    let first = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(first.status(), StatusCode::OK);
    let second = app()
        .oneshot(
            Request::builder()
                .uri("/books/1")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(second.status(), StatusCode::OK);
}

async fn get(path: &str) -> axum::response::Response {
    app()
        .oneshot(Request::builder().uri(path).body(Body::empty()).unwrap())
        .await
        .unwrap()
}

#[tokio::test]
async fn helper_sends_a_get_request() {
    let response = get("/books/1").await;
    assert_eq!(response.status(), StatusCode::OK);
}

Run the file with:

cargo test --test oneshot_test

All seven tests pass. Note that the helper and its test are an addition to the six tests run earlier, and the file as shown here is the complete version.

Summary

The method earns its page because it is the seam between the test and the app. One call takes the router and the request, waits for readiness, runs the handler, and hands back a response, and the type system guarantees the error case cannot happen for a plain router. The rule that governs its use is the ownership rule: the service is spent by the call, so each request needs its own router or its own clone. The habit that makes suites built on it stay readable is the helper, one small async function per method that hides the build-send-unwrap chain and leaves each test with a single line for the request and a single line for the assertion. Once that habit is in place, the test file stops being a list of oneshot incantations and becomes a list of behaviours the app promises, one test per promise, and the router answers each one without ever touching the network.