Skip to main content

capy_testing/
lib.rs

1//! Integration tests against an Axum service, without TCP or background servers.
2
3mod boot;
4mod factory;
5mod session;
6pub use boot::{TestAppBuilder, TestApplication, TestDatabase};
7pub use factory::{Factory, FactoryBuilder};
8pub use session::{SessionRequest, TestSession};
9
10use axum::{
11    body::{to_bytes, Body, Bytes},
12    http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
13    Router,
14};
15use serde::{de::DeserializeOwned, Serialize};
16use serde_json::Value;
17use tower::ServiceExt;
18
19/// An in-process application using the normal factory, isolated data and real middleware.
20/// Prefer `TestApp::boot(application())`; `new(router)` remains the low-level adapter.
21#[derive(Clone)]
22pub struct TestApp {
23    seeds: Option<capy_db::Seeds>,
24    router: Router,
25    context: Option<capy_core::AppContext>,
26    database: Option<std::sync::Arc<boot::DatabaseGuard>>,
27    peer: std::net::SocketAddr,
28    csrf: bool,
29    #[cfg(feature = "jobs")]
30    jobs: Option<TestQueue>,
31    #[cfg(feature = "mail")]
32    mail: Option<TestMailer>,
33}
34
35impl TestApp {
36    /// Wrap a configured Axum service. The caller owns database isolation.
37    pub fn new(router: Router) -> Self {
38        Self {
39            seeds: None,
40            router,
41            context: None,
42            database: None,
43            peer: ([127, 0, 0, 1], 12345).into(),
44            csrf: false,
45            #[cfg(feature = "jobs")]
46            jobs: None,
47            #[cfg(feature = "mail")]
48            mail: None,
49        }
50    }
51
52    /// Boot the ordinary application builder with an isolated SQLite database and migrations.
53    pub async fn boot(application: impl TestApplication) -> capy_core::Result<Self> {
54        Self::builder(application).boot().await
55    }
56
57    /// Configure database isolation, migrations, configuration and deterministic peer identity.
58    pub fn builder<A: TestApplication>(application: A) -> TestAppBuilder<A> {
59        TestAppBuilder::new(application)
60    }
61
62    /// Attach the context used by the real router. Used by application boot adapters.
63    pub fn with_context(mut self, context: capy_core::AppContext) -> Self {
64        self.context = Some(context);
65        self
66    }
67
68    /// Attach the same seeds registered by the application factory. Never runs them implicitly.
69    pub fn with_seeds(mut self, seeds: Option<capy_db::Seeds>) -> Self {
70        self.seeds = seeds;
71        self
72    }
73
74    /// Run the application's registered seeds against this isolated database.
75    pub async fn seed(&self) -> capy_core::Result<()> {
76        let seeds = self.seeds.as_ref().ok_or_else(|| {
77            capy_core::AppError::Configuration(
78                "Register application-owned seeds with App::seeds.".into(),
79            )
80        })?;
81        seeds.run(self.context()).await
82    }
83
84    /// Enable real CSRF bootstrap for sessions when the application installs Capy auth.
85    pub fn with_csrf(mut self, enabled: bool) -> Self {
86        self.csrf = enabled;
87        self
88    }
89
90    /// Context of a booted application. Low-level `new(router)` has no attached context.
91    pub fn context(&self) -> &capy_core::AppContext {
92        self.context
93            .as_ref()
94            .expect("Use TestApp::boot or attach the real application context")
95    }
96
97    /// The isolated application database; also usable with native SeaORM transactions.
98    pub fn db(&self) -> &sea_orm::DatabaseConnection {
99        &self.context().db
100    }
101
102    /// Create an independent same-origin browser session. No identity is fabricated.
103    pub fn session(&self) -> TestSession {
104        TestSession::new(self.clone())
105    }
106
107    /// Authenticate through the real login endpoint, including password, throttling and CSRF.
108    /// A failed login returns a safe setup error; use `session.login` to assert failures.
109    pub async fn login(&self, email: &str, password: &str) -> capy_core::Result<TestSession> {
110        let mut session = self.session();
111        if !session.login(email, password).await?.status.is_success() {
112            return Err(capy_core::AppError::Configuration(
113                "Test login failed; inspect it with TestSession::login (credentials redacted)."
114                    .into(),
115            ));
116        }
117        Ok(session)
118    }
119
120    /// Construct an application-owned factory using this database.
121    pub fn factory<F: Factory + Default>(
122        &self,
123    ) -> FactoryBuilder<'_, F, sea_orm::DatabaseConnection> {
124        FactoryBuilder::new(F::default(), self.db())
125    }
126
127    /// Explicitly close the test pool and drop a provisioned PostgreSQL database.
128    /// Existing sessions/clones become unusable. Drop alone is best-effort cleanup.
129    pub async fn cleanup(self) -> capy_core::Result<()> {
130        if let Some(database) = &self.database {
131            database.cleanup().await?;
132        }
133        Ok(())
134    }
135
136    /// Attach the actual registered job handlers, including captured dependencies.
137    #[cfg(feature = "jobs")]
138    pub fn with_jobs(mut self, jobs: TestQueue) -> Self {
139        self.jobs = Some(jobs);
140        self
141    }
142
143    /// Run/assert persisted jobs through the application's real worker registry.
144    #[cfg(feature = "jobs")]
145    pub fn jobs(&self) -> &TestQueue {
146        self.jobs
147            .as_ref()
148            .expect("Register jobs in the application factory")
149    }
150
151    /// Attach a capture transport explicitly wired into the actual application factory.
152    #[cfg(feature = "mail")]
153    pub fn with_mail(mut self, mail: TestMailer) -> Self {
154        self.mail = Some(mail);
155        self
156    }
157
158    /// Inspect real rendered mail. Enable capture on the builder or wire it explicitly.
159    #[cfg(feature = "mail")]
160    pub fn mail(&self) -> &TestMailer {
161        self.mail
162            .as_ref()
163            .expect("Enable TestAppBuilder::capture_mail or attach a capture")
164    }
165
166    /// Build a request with an arbitrary HTTP method.
167    pub fn request(&self, method: Method, uri: &str) -> TestRequest {
168        TestRequest {
169            router: self.router.clone(),
170            builder: Request::builder()
171                .method(method)
172                .uri(uri)
173                .extension(axum::extract::ConnectInfo(self.peer)),
174            body: Body::empty(),
175        }
176    }
177
178    /// Build a GET request.
179    pub fn get(&self, uri: &str) -> TestRequest {
180        self.request(Method::GET, uri)
181    }
182    /// Build a POST request.
183    pub fn post(&self, uri: &str) -> TestRequest {
184        self.request(Method::POST, uri)
185    }
186    /// Build a PUT request.
187    pub fn put(&self, uri: &str) -> TestRequest {
188        self.request(Method::PUT, uri)
189    }
190    /// Build a PATCH request.
191    pub fn patch(&self, uri: &str) -> TestRequest {
192        self.request(Method::PATCH, uri)
193    }
194    /// Build a DELETE request.
195    pub fn delete(&self, uri: &str) -> TestRequest {
196        self.request(Method::DELETE, uri)
197    }
198}
199
200/// A fluent request builder used only in tests; invalid requests panic clearly.
201pub struct TestRequest {
202    router: Router,
203    builder: axum::http::request::Builder,
204    body: Body,
205}
206
207impl TestRequest {
208    /// Supply a simulated socket peer, independent of forwarded headers.
209    pub fn peer_addr(mut self, peer: std::net::SocketAddr) -> Self {
210        self.builder = self.builder.extension(axum::extract::ConnectInfo(peer));
211        self
212    }
213    /// Omit socket metadata to test fail-closed custom-server behavior.
214    pub fn without_peer(mut self) -> Self {
215        if let Some(extensions) = self.builder.extensions_mut() {
216            extensions.remove::<axum::extract::ConnectInfo<std::net::SocketAddr>>();
217        }
218        self
219    }
220    /// Serialize a JSON body and set the content type.
221    pub fn json(mut self, value: impl Serialize) -> Self {
222        self.builder = self.builder.header("content-type", "application/json");
223        self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
224        self
225    }
226
227    /// Set a header, for example authorization or content type.
228    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
229        self.builder = self.builder.header(name, value);
230        self
231    }
232
233    /// Set a session cookie without depending on an application's user model.
234    /// Use TestResponse::cookie to reuse a server-issued cookie.
235    pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
236        cookie.set_sensitive(true);
237        self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
238        self
239    }
240
241    /// Set a raw body, useful for malformed request tests.
242    pub fn body(mut self, body: impl Into<Body>) -> Self {
243        self.body = body.into();
244        self
245    }
246
247    /// Execute the request directly against the service.
248    pub async fn send(self) -> TestResponse {
249        let response = self
250            .router
251            .oneshot(self.builder.body(self.body).expect("invalid test request"))
252            .await
253            .expect("Axum service is infallible");
254        let (parts, body) = response.into_parts();
255        TestResponse {
256            status: parts.status,
257            headers: parts.headers,
258            body: to_bytes(body, 16 * 1024 * 1024)
259                .await
260                .expect("test response exceeds 16 MiB or cannot be read"),
261        }
262    }
263}
264
265/// A fully buffered test response with chainable assertions.
266pub struct TestResponse {
267    /// HTTP response status.
268    pub status: StatusCode,
269    /// HTTP response headers.
270    pub headers: HeaderMap,
271    /// Raw response bytes.
272    pub body: Bytes,
273}
274
275impl std::fmt::Debug for TestResponse {
276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277        f.debug_struct("TestResponse")
278            .field("status", &self.status)
279            .field("body_bytes", &self.body.len())
280            .finish_non_exhaustive()
281    }
282}
283
284impl TestResponse {
285    /// Extract only a named cookie's name/value pair; omit Set-Cookie attributes.
286    /// The returned sensitive header value redacts its Debug output.
287    pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
288        self.headers
289            .get_all(axum::http::header::SET_COOKIE)
290            .iter()
291            .find_map(|value| {
292                let pair = value.to_str().ok()?.split(';').next()?;
293                let (key, _) = pair.split_once('=')?;
294                if key != name {
295                    return None;
296                }
297                let mut value = HeaderValue::from_str(pair).ok()?;
298                value.set_sensitive(true);
299                Some(value)
300            })
301    }
302
303    /// Assert any HTTP status, including custom application error statuses.
304    pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
305        assert_eq!(
306            self.status,
307            status.into(),
308            "response: {}",
309            String::from_utf8_lossy(&self.body)
310        );
311        self
312    }
313    /// Assert HTTP 200.
314    pub fn assert_ok(&self) -> &Self {
315        self.assert_status(StatusCode::OK)
316    }
317    /// Assert HTTP 201.
318    pub fn assert_created(&self) -> &Self {
319        self.assert_status(StatusCode::CREATED)
320    }
321    /// Assert HTTP 204 and an empty response body.
322    pub fn assert_no_content(&self) -> &Self {
323        self.assert_status(StatusCode::NO_CONTENT);
324        assert!(self.body.is_empty(), "204 responses must be empty");
325        self
326    }
327    /// Deserialize the response into a JSON value or application response type.
328    pub fn json<T: DeserializeOwned>(&self) -> T {
329        serde_json::from_slice(&self.body)
330            .expect("response must be valid JSON of the requested type")
331    }
332    /// Assert exact JSON equality, independent of object key order.
333    pub fn assert_json(&self, expected: Value) -> &Self {
334        assert_eq!(self.json::<Value>(), expected);
335        self
336    }
337}
338
339/// Real-persistence job tests. Own an isolated database and apply jobs migrations first.
340#[cfg(feature = "jobs")]
341#[derive(Clone)]
342pub struct TestQueue {
343    queue: capy_jobs::Queue,
344    worker: capy_jobs::Worker,
345}
346#[cfg(feature = "jobs")]
347impl TestQueue {
348    /// Use the application's actual registry, Serde serialization and queue tables.
349    pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
350        Ok(Self {
351            queue: capy_jobs::Queue::new(context.db.clone()),
352            worker: capy_jobs::Worker::new(context, jobs)?,
353        })
354    }
355    /// Select one named queue for both assertions/dispatch and worker execution.
356    /// Use `TestQueue::new(context, registry)?.on_queue("mail")?` for built-in
357    /// queued mail, which uses the `mail` queue by default. Invalid names fail
358    /// before persistence; this starts no background worker.
359    pub fn on_queue(mut self, name: impl Into<String>) -> capy_core::Result<Self> {
360        let name = capy_jobs::QueueName::new(name)?;
361        self.queue = self.queue.named(name.clone());
362        self.worker = self.worker.queues(vec![name])?;
363        Ok(self)
364    }
365    /// Inspect/dispatch through the selected queue (default: `default`).
366    pub fn queue(&self) -> &capy_jobs::Queue {
367        &self.queue
368    }
369    /// Assert that at least one job of this name/version remains queued.
370    pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
371        assert!(
372            self.queue.count::<J>().await? > 0,
373            "Expected a persisted job of type {}",
374            J::NAME
375        );
376        Ok(())
377    }
378    /// Execute one currently available job synchronously with the real worker policy.
379    pub async fn run_next_job(&self) -> capy_core::Result<bool> {
380        self.worker.run_next().await
381    }
382    /// Drain at most `limit` available jobs; never sleep through durable delays.
383    pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
384        let mut processed = 0;
385        while processed < limit && self.worker.run_next().await? {
386            processed += 1;
387        }
388        Ok(processed)
389    }
390}
391
392/// Real-rendering capture transport for mail tests.
393#[cfg(feature = "mail")]
394pub use capy_mail::CaptureTransport as TestMailer;