Skip to main content

capy_testing/
lib.rs

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