capy-testing 0.4.0

In-process HTTP testing utilities for Capy applications.
Documentation
//! Integration tests against an Axum service, without TCP or background servers.

use axum::{
    body::{to_bytes, Body, Bytes},
    http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
    Router,
};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use tower::ServiceExt;

/// An in-process application service. Construct it from `App::into_router`.
#[derive(Clone)]
pub struct TestApp {
    router: Router,
}

impl TestApp {
    /// Wrap a configured Axum service. The caller owns database isolation.
    pub fn new(router: Router) -> Self {
        Self { router }
    }

    /// Build a request with an arbitrary HTTP method.
    pub fn request(&self, method: Method, uri: &str) -> TestRequest {
        TestRequest {
            router: self.router.clone(),
            builder: Request::builder().method(method).uri(uri),
            body: Body::empty(),
        }
    }

    /// Build a GET request.
    pub fn get(&self, uri: &str) -> TestRequest {
        self.request(Method::GET, uri)
    }
    /// Build a POST request.
    pub fn post(&self, uri: &str) -> TestRequest {
        self.request(Method::POST, uri)
    }
    /// Build a PUT request.
    pub fn put(&self, uri: &str) -> TestRequest {
        self.request(Method::PUT, uri)
    }
    /// Build a PATCH request.
    pub fn patch(&self, uri: &str) -> TestRequest {
        self.request(Method::PATCH, uri)
    }
    /// Build a DELETE request.
    pub fn delete(&self, uri: &str) -> TestRequest {
        self.request(Method::DELETE, uri)
    }
}

/// A fluent request builder used only in tests; invalid requests panic clearly.
pub struct TestRequest {
    router: Router,
    builder: axum::http::request::Builder,
    body: Body,
}

impl TestRequest {
    /// Serialize a JSON body and set the content type.
    pub fn json(mut self, value: impl Serialize) -> Self {
        self.builder = self.builder.header("content-type", "application/json");
        self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
        self
    }

    /// Set a header, for example authorization or content type.
    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.builder = self.builder.header(name, value);
        self
    }

    /// Set a raw body, useful for malformed request tests.
    pub fn body(mut self, body: impl Into<Body>) -> Self {
        self.body = body.into();
        self
    }

    /// Execute the request directly against the service.
    pub async fn send(self) -> TestResponse {
        let response = self
            .router
            .oneshot(self.builder.body(self.body).expect("invalid test request"))
            .await
            .expect("Axum service is infallible");
        let (parts, body) = response.into_parts();
        TestResponse {
            status: parts.status,
            headers: parts.headers,
            body: to_bytes(body, 16 * 1024 * 1024)
                .await
                .expect("test response exceeds 16 MiB or cannot be read"),
        }
    }
}

/// A fully buffered test response with chainable assertions.
#[derive(Debug)]
pub struct TestResponse {
    /// HTTP response status.
    pub status: StatusCode,
    /// HTTP response headers.
    pub headers: HeaderMap,
    /// Raw response bytes.
    pub body: Bytes,
}

impl TestResponse {
    /// Assert any HTTP status, including custom application error statuses.
    pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
        assert_eq!(
            self.status,
            status.into(),
            "response: {}",
            String::from_utf8_lossy(&self.body)
        );
        self
    }
    /// Assert HTTP 200.
    pub fn assert_ok(&self) -> &Self {
        self.assert_status(StatusCode::OK)
    }
    /// Assert HTTP 201.
    pub fn assert_created(&self) -> &Self {
        self.assert_status(StatusCode::CREATED)
    }
    /// Assert HTTP 204 and an empty response body.
    pub fn assert_no_content(&self) -> &Self {
        self.assert_status(StatusCode::NO_CONTENT);
        assert!(self.body.is_empty(), "204 responses must be empty");
        self
    }
    /// Deserialize the response into a JSON value or application response type.
    pub fn json<T: DeserializeOwned>(&self) -> T {
        serde_json::from_slice(&self.body)
            .expect("response must be valid JSON of the requested type")
    }
    /// Assert exact JSON equality, independent of object key order.
    pub fn assert_json(&self, expected: Value) -> &Self {
        assert_eq!(self.json::<Value>(), expected);
        self
    }
}