Skip to main content

capy_testing/
lib.rs

1//! Integration tests against an Axum service, without TCP or background servers.
2
3use axum::{
4    body::{to_bytes, Body, Bytes},
5    http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
6    Router,
7};
8use serde::{de::DeserializeOwned, Serialize};
9use serde_json::Value;
10use tower::ServiceExt;
11
12/// An in-process application service. Construct it from `App::into_router`.
13#[derive(Clone)]
14pub struct TestApp {
15    router: Router,
16}
17
18impl TestApp {
19    /// Wrap a configured Axum service. The caller owns database isolation.
20    pub fn new(router: Router) -> Self {
21        Self { router }
22    }
23
24    /// Build a request with an arbitrary HTTP method.
25    pub fn request(&self, method: Method, uri: &str) -> TestRequest {
26        TestRequest {
27            router: self.router.clone(),
28            builder: Request::builder().method(method).uri(uri),
29            body: Body::empty(),
30        }
31    }
32
33    /// Build a GET request.
34    pub fn get(&self, uri: &str) -> TestRequest {
35        self.request(Method::GET, uri)
36    }
37    /// Build a POST request.
38    pub fn post(&self, uri: &str) -> TestRequest {
39        self.request(Method::POST, uri)
40    }
41    /// Build a PUT request.
42    pub fn put(&self, uri: &str) -> TestRequest {
43        self.request(Method::PUT, uri)
44    }
45    /// Build a PATCH request.
46    pub fn patch(&self, uri: &str) -> TestRequest {
47        self.request(Method::PATCH, uri)
48    }
49    /// Build a DELETE request.
50    pub fn delete(&self, uri: &str) -> TestRequest {
51        self.request(Method::DELETE, uri)
52    }
53}
54
55/// A fluent request builder used only in tests; invalid requests panic clearly.
56pub struct TestRequest {
57    router: Router,
58    builder: axum::http::request::Builder,
59    body: Body,
60}
61
62impl TestRequest {
63    /// Serialize a JSON body and set the content type.
64    pub fn json(mut self, value: impl Serialize) -> Self {
65        self.builder = self.builder.header("content-type", "application/json");
66        self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
67        self
68    }
69
70    /// Set a header, for example authorization or content type.
71    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
72        self.builder = self.builder.header(name, value);
73        self
74    }
75
76    /// Set a raw body, useful for malformed request tests.
77    pub fn body(mut self, body: impl Into<Body>) -> Self {
78        self.body = body.into();
79        self
80    }
81
82    /// Execute the request directly against the service.
83    pub async fn send(self) -> TestResponse {
84        let response = self
85            .router
86            .oneshot(self.builder.body(self.body).expect("invalid test request"))
87            .await
88            .expect("Axum service is infallible");
89        let (parts, body) = response.into_parts();
90        TestResponse {
91            status: parts.status,
92            headers: parts.headers,
93            body: to_bytes(body, 16 * 1024 * 1024)
94                .await
95                .expect("test response exceeds 16 MiB or cannot be read"),
96        }
97    }
98}
99
100/// A fully buffered test response with chainable assertions.
101#[derive(Debug)]
102pub struct TestResponse {
103    /// HTTP response status.
104    pub status: StatusCode,
105    /// HTTP response headers.
106    pub headers: HeaderMap,
107    /// Raw response bytes.
108    pub body: Bytes,
109}
110
111impl TestResponse {
112    /// Assert any HTTP status, including custom application error statuses.
113    pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
114        assert_eq!(
115            self.status,
116            status.into(),
117            "response: {}",
118            String::from_utf8_lossy(&self.body)
119        );
120        self
121    }
122    /// Assert HTTP 200.
123    pub fn assert_ok(&self) -> &Self {
124        self.assert_status(StatusCode::OK)
125    }
126    /// Assert HTTP 201.
127    pub fn assert_created(&self) -> &Self {
128        self.assert_status(StatusCode::CREATED)
129    }
130    /// Assert HTTP 204 and an empty response body.
131    pub fn assert_no_content(&self) -> &Self {
132        self.assert_status(StatusCode::NO_CONTENT);
133        assert!(self.body.is_empty(), "204 responses must be empty");
134        self
135    }
136    /// Deserialize the response into a JSON value or application response type.
137    pub fn json<T: DeserializeOwned>(&self) -> T {
138        serde_json::from_slice(&self.body)
139            .expect("response must be valid JSON of the requested type")
140    }
141    /// Assert exact JSON equality, independent of object key order.
142    pub fn assert_json(&self, expected: Value) -> &Self {
143        assert_eq!(self.json::<Value>(), expected);
144        self
145    }
146}