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).extension(
29                axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 12345))),
30            ),
31            body: Body::empty(),
32        }
33    }
34
35    /// Build a GET request.
36    pub fn get(&self, uri: &str) -> TestRequest {
37        self.request(Method::GET, uri)
38    }
39    /// Build a POST request.
40    pub fn post(&self, uri: &str) -> TestRequest {
41        self.request(Method::POST, uri)
42    }
43    /// Build a PUT request.
44    pub fn put(&self, uri: &str) -> TestRequest {
45        self.request(Method::PUT, uri)
46    }
47    /// Build a PATCH request.
48    pub fn patch(&self, uri: &str) -> TestRequest {
49        self.request(Method::PATCH, uri)
50    }
51    /// Build a DELETE request.
52    pub fn delete(&self, uri: &str) -> TestRequest {
53        self.request(Method::DELETE, uri)
54    }
55}
56
57/// A fluent request builder used only in tests; invalid requests panic clearly.
58pub struct TestRequest {
59    router: Router,
60    builder: axum::http::request::Builder,
61    body: Body,
62}
63
64impl TestRequest {
65    /// Supply a simulated socket peer, independent of forwarded headers.
66    pub fn peer_addr(mut self, peer: std::net::SocketAddr) -> Self {
67        self.builder = self.builder.extension(axum::extract::ConnectInfo(peer));
68        self
69    }
70    /// Omit socket metadata to test fail-closed custom-server behavior.
71    pub fn without_peer(mut self) -> Self {
72        if let Some(extensions) = self.builder.extensions_mut() {
73            extensions.remove::<axum::extract::ConnectInfo<std::net::SocketAddr>>();
74        }
75        self
76    }
77    /// Serialize a JSON body and set the content type.
78    pub fn json(mut self, value: impl Serialize) -> Self {
79        self.builder = self.builder.header("content-type", "application/json");
80        self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
81        self
82    }
83
84    /// Set a header, for example authorization or content type.
85    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
86        self.builder = self.builder.header(name, value);
87        self
88    }
89
90    /// Set a session cookie without depending on an application's user model.
91    /// Use TestResponse::cookie to reuse a server-issued cookie.
92    pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
93        cookie.set_sensitive(true);
94        self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
95        self
96    }
97
98    /// Set a raw body, useful for malformed request tests.
99    pub fn body(mut self, body: impl Into<Body>) -> Self {
100        self.body = body.into();
101        self
102    }
103
104    /// Execute the request directly against the service.
105    pub async fn send(self) -> TestResponse {
106        let response = self
107            .router
108            .oneshot(self.builder.body(self.body).expect("invalid test request"))
109            .await
110            .expect("Axum service is infallible");
111        let (parts, body) = response.into_parts();
112        TestResponse {
113            status: parts.status,
114            headers: parts.headers,
115            body: to_bytes(body, 16 * 1024 * 1024)
116                .await
117                .expect("test response exceeds 16 MiB or cannot be read"),
118        }
119    }
120}
121
122/// A fully buffered test response with chainable assertions.
123pub struct TestResponse {
124    /// HTTP response status.
125    pub status: StatusCode,
126    /// HTTP response headers.
127    pub headers: HeaderMap,
128    /// Raw response bytes.
129    pub body: Bytes,
130}
131
132impl std::fmt::Debug for TestResponse {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.debug_struct("TestResponse")
135            .field("status", &self.status)
136            .field("body_bytes", &self.body.len())
137            .finish_non_exhaustive()
138    }
139}
140
141impl TestResponse {
142    /// Extract only a named cookie's name/value pair; omit Set-Cookie attributes.
143    /// The returned sensitive header value redacts its Debug output.
144    pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
145        self.headers
146            .get_all(axum::http::header::SET_COOKIE)
147            .iter()
148            .find_map(|value| {
149                let pair = value.to_str().ok()?.split(';').next()?;
150                let (key, _) = pair.split_once('=')?;
151                if key != name {
152                    return None;
153                }
154                let mut value = HeaderValue::from_str(pair).ok()?;
155                value.set_sensitive(true);
156                Some(value)
157            })
158    }
159
160    /// Assert any HTTP status, including custom application error statuses.
161    pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
162        assert_eq!(
163            self.status,
164            status.into(),
165            "response: {}",
166            String::from_utf8_lossy(&self.body)
167        );
168        self
169    }
170    /// Assert HTTP 200.
171    pub fn assert_ok(&self) -> &Self {
172        self.assert_status(StatusCode::OK)
173    }
174    /// Assert HTTP 201.
175    pub fn assert_created(&self) -> &Self {
176        self.assert_status(StatusCode::CREATED)
177    }
178    /// Assert HTTP 204 and an empty response body.
179    pub fn assert_no_content(&self) -> &Self {
180        self.assert_status(StatusCode::NO_CONTENT);
181        assert!(self.body.is_empty(), "204 responses must be empty");
182        self
183    }
184    /// Deserialize the response into a JSON value or application response type.
185    pub fn json<T: DeserializeOwned>(&self) -> T {
186        serde_json::from_slice(&self.body)
187            .expect("response must be valid JSON of the requested type")
188    }
189    /// Assert exact JSON equality, independent of object key order.
190    pub fn assert_json(&self, expected: Value) -> &Self {
191        assert_eq!(self.json::<Value>(), expected);
192        self
193    }
194}
195
196/// Real-persistence job tests. Own an isolated database and apply jobs migrations first.
197#[cfg(feature = "jobs")]
198pub struct TestQueue {
199    queue: capy_jobs::Queue,
200    worker: capy_jobs::Worker,
201}
202#[cfg(feature = "jobs")]
203impl TestQueue {
204    /// Use the application's actual registry, Serde serialization and queue tables.
205    pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
206        Ok(Self {
207            queue: capy_jobs::Queue::new(context.db.clone()),
208            worker: capy_jobs::Worker::new(context, jobs)?,
209        })
210    }
211    /// Select one named queue for both assertions/dispatch and worker execution.
212    /// Use `TestQueue::new(context, registry)?.on_queue("mail")?` for built-in
213    /// queued mail, which uses the `mail` queue by default. Invalid names fail
214    /// before persistence; this starts no background worker.
215    pub fn on_queue(mut self, name: impl Into<String>) -> capy_core::Result<Self> {
216        let name = capy_jobs::QueueName::new(name)?;
217        self.queue = self.queue.named(name.clone());
218        self.worker = self.worker.queues(vec![name])?;
219        Ok(self)
220    }
221    /// Inspect/dispatch through the selected queue (default: `default`).
222    pub fn queue(&self) -> &capy_jobs::Queue {
223        &self.queue
224    }
225    /// Assert that at least one job of this name/version remains queued.
226    pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
227        assert!(
228            self.queue.count::<J>().await? > 0,
229            "Expected a persisted job of type {}",
230            J::NAME
231        );
232        Ok(())
233    }
234    /// Execute one currently available job synchronously with the real worker policy.
235    pub async fn run_next_job(&self) -> capy_core::Result<bool> {
236        self.worker.run_next().await
237    }
238    /// Drain at most `limit` available jobs; never sleep through durable delays.
239    pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
240        let mut processed = 0;
241        while processed < limit && self.worker.run_next().await? {
242            processed += 1;
243        }
244        Ok(processed)
245    }
246}
247
248/// Real-rendering capture transport for mail tests.
249#[cfg(feature = "mail")]
250pub use capy_mail::CaptureTransport as TestMailer;