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 session cookie without depending on an application's user model.
77    /// Use TestResponse::cookie to reuse a server-issued cookie.
78    pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
79        cookie.set_sensitive(true);
80        self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
81        self
82    }
83
84    /// Set a raw body, useful for malformed request tests.
85    pub fn body(mut self, body: impl Into<Body>) -> Self {
86        self.body = body.into();
87        self
88    }
89
90    /// Execute the request directly against the service.
91    pub async fn send(self) -> TestResponse {
92        let response = self
93            .router
94            .oneshot(self.builder.body(self.body).expect("invalid test request"))
95            .await
96            .expect("Axum service is infallible");
97        let (parts, body) = response.into_parts();
98        TestResponse {
99            status: parts.status,
100            headers: parts.headers,
101            body: to_bytes(body, 16 * 1024 * 1024)
102                .await
103                .expect("test response exceeds 16 MiB or cannot be read"),
104        }
105    }
106}
107
108/// A fully buffered test response with chainable assertions.
109pub struct TestResponse {
110    /// HTTP response status.
111    pub status: StatusCode,
112    /// HTTP response headers.
113    pub headers: HeaderMap,
114    /// Raw response bytes.
115    pub body: Bytes,
116}
117
118impl std::fmt::Debug for TestResponse {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("TestResponse")
121            .field("status", &self.status)
122            .field("body_bytes", &self.body.len())
123            .finish_non_exhaustive()
124    }
125}
126
127impl TestResponse {
128    /// Extract only a named cookie's name/value pair; omit Set-Cookie attributes.
129    /// The returned sensitive header value redacts its Debug output.
130    pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
131        self.headers
132            .get_all(axum::http::header::SET_COOKIE)
133            .iter()
134            .find_map(|value| {
135                let pair = value.to_str().ok()?.split(';').next()?;
136                let (key, _) = pair.split_once('=')?;
137                if key != name {
138                    return None;
139                }
140                let mut value = HeaderValue::from_str(pair).ok()?;
141                value.set_sensitive(true);
142                Some(value)
143            })
144    }
145
146    /// Assert any HTTP status, including custom application error statuses.
147    pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
148        assert_eq!(
149            self.status,
150            status.into(),
151            "response: {}",
152            String::from_utf8_lossy(&self.body)
153        );
154        self
155    }
156    /// Assert HTTP 200.
157    pub fn assert_ok(&self) -> &Self {
158        self.assert_status(StatusCode::OK)
159    }
160    /// Assert HTTP 201.
161    pub fn assert_created(&self) -> &Self {
162        self.assert_status(StatusCode::CREATED)
163    }
164    /// Assert HTTP 204 and an empty response body.
165    pub fn assert_no_content(&self) -> &Self {
166        self.assert_status(StatusCode::NO_CONTENT);
167        assert!(self.body.is_empty(), "204 responses must be empty");
168        self
169    }
170    /// Deserialize the response into a JSON value or application response type.
171    pub fn json<T: DeserializeOwned>(&self) -> T {
172        serde_json::from_slice(&self.body)
173            .expect("response must be valid JSON of the requested type")
174    }
175    /// Assert exact JSON equality, independent of object key order.
176    pub fn assert_json(&self, expected: Value) -> &Self {
177        assert_eq!(self.json::<Value>(), expected);
178        self
179    }
180}
181
182/// Real-persistence job tests. Own an isolated database and apply jobs migrations first.
183#[cfg(feature = "jobs")]
184pub struct TestQueue {
185    queue: capy_jobs::Queue,
186    worker: capy_jobs::Worker,
187}
188#[cfg(feature = "jobs")]
189impl TestQueue {
190    /// Use the application's actual registry, Serde serialization and queue tables.
191    pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
192        Ok(Self {
193            queue: capy_jobs::Queue::new(context.db.clone()),
194            worker: capy_jobs::Worker::new(context, jobs)?,
195        })
196    }
197    /// Inspect/dispatch through the real default queue.
198    pub fn queue(&self) -> &capy_jobs::Queue {
199        &self.queue
200    }
201    /// Assert that at least one job of this name/version remains queued.
202    pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
203        assert!(
204            self.queue.count::<J>().await? > 0,
205            "Expected a persisted job of type {}",
206            J::NAME
207        );
208        Ok(())
209    }
210    /// Execute one currently available job synchronously with the real worker policy.
211    pub async fn run_next_job(&self) -> capy_core::Result<bool> {
212        self.worker.run_next().await
213    }
214    /// Drain at most `limit` available jobs; never sleep through durable delays.
215    pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
216        let mut processed = 0;
217        while processed < limit && self.worker.run_next().await? {
218            processed += 1;
219        }
220        Ok(processed)
221    }
222}
223
224/// Real-rendering capture transport for mail tests.
225#[cfg(feature = "mail")]
226pub use capy_mail::CaptureTransport as TestMailer;