capy-testing 0.7.2

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).extension(
                axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 12345))),
            ),
            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 {
    /// Supply a simulated socket peer, independent of forwarded headers.
    pub fn peer_addr(mut self, peer: std::net::SocketAddr) -> Self {
        self.builder = self.builder.extension(axum::extract::ConnectInfo(peer));
        self
    }
    /// Omit socket metadata to test fail-closed custom-server behavior.
    pub fn without_peer(mut self) -> Self {
        if let Some(extensions) = self.builder.extensions_mut() {
            extensions.remove::<axum::extract::ConnectInfo<std::net::SocketAddr>>();
        }
        self
    }
    /// 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 session cookie without depending on an application's user model.
    /// Use TestResponse::cookie to reuse a server-issued cookie.
    pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
        cookie.set_sensitive(true);
        self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
        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.
pub struct TestResponse {
    /// HTTP response status.
    pub status: StatusCode,
    /// HTTP response headers.
    pub headers: HeaderMap,
    /// Raw response bytes.
    pub body: Bytes,
}

impl std::fmt::Debug for TestResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TestResponse")
            .field("status", &self.status)
            .field("body_bytes", &self.body.len())
            .finish_non_exhaustive()
    }
}

impl TestResponse {
    /// Extract only a named cookie's name/value pair; omit Set-Cookie attributes.
    /// The returned sensitive header value redacts its Debug output.
    pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
        self.headers
            .get_all(axum::http::header::SET_COOKIE)
            .iter()
            .find_map(|value| {
                let pair = value.to_str().ok()?.split(';').next()?;
                let (key, _) = pair.split_once('=')?;
                if key != name {
                    return None;
                }
                let mut value = HeaderValue::from_str(pair).ok()?;
                value.set_sensitive(true);
                Some(value)
            })
    }

    /// 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
    }
}

/// Real-persistence job tests. Own an isolated database and apply jobs migrations first.
#[cfg(feature = "jobs")]
pub struct TestQueue {
    queue: capy_jobs::Queue,
    worker: capy_jobs::Worker,
}
#[cfg(feature = "jobs")]
impl TestQueue {
    /// Use the application's actual registry, Serde serialization and queue tables.
    pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
        Ok(Self {
            queue: capy_jobs::Queue::new(context.db.clone()),
            worker: capy_jobs::Worker::new(context, jobs)?,
        })
    }
    /// Select one named queue for both assertions/dispatch and worker execution.
    /// Use `TestQueue::new(context, registry)?.on_queue("mail")?` for built-in
    /// queued mail, which uses the `mail` queue by default. Invalid names fail
    /// before persistence; this starts no background worker.
    pub fn on_queue(mut self, name: impl Into<String>) -> capy_core::Result<Self> {
        let name = capy_jobs::QueueName::new(name)?;
        self.queue = self.queue.named(name.clone());
        self.worker = self.worker.queues(vec![name])?;
        Ok(self)
    }
    /// Inspect/dispatch through the selected queue (default: `default`).
    pub fn queue(&self) -> &capy_jobs::Queue {
        &self.queue
    }
    /// Assert that at least one job of this name/version remains queued.
    pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
        assert!(
            self.queue.count::<J>().await? > 0,
            "Expected a persisted job of type {}",
            J::NAME
        );
        Ok(())
    }
    /// Execute one currently available job synchronously with the real worker policy.
    pub async fn run_next_job(&self) -> capy_core::Result<bool> {
        self.worker.run_next().await
    }
    /// Drain at most `limit` available jobs; never sleep through durable delays.
    pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
        let mut processed = 0;
        while processed < limit && self.worker.run_next().await? {
            processed += 1;
        }
        Ok(processed)
    }
}

/// Real-rendering capture transport for mail tests.
#[cfg(feature = "mail")]
pub use capy_mail::CaptureTransport as TestMailer;