capy-testing 0.10.0

In-process HTTP testing utilities for Capy applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Integration tests against an Axum service, without TCP or background servers.

mod boot;
mod contracts;
mod factory;
mod session;
pub use boot::{TestAppBuilder, TestApplication, TestDatabase};
pub use factory::{Factory, FactoryBuilder};
pub use session::{SessionRequest, TestSession};

use axum::{
    body::{to_bytes, Body, Bytes},
    http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
    Router,
};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use tower::ServiceExt;

/// An in-process application using the normal factory, isolated data and real middleware.
/// Prefer `TestApp::boot(application())`; `new(router)` remains the low-level adapter.
#[derive(Clone)]
pub struct TestApp {
    contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
    services: capy_core::Services,
    seeds: Option<capy_db::Seeds>,
    router: Router,
    context: Option<capy_core::AppContext>,
    database: Option<std::sync::Arc<boot::DatabaseGuard>>,
    peer: std::net::SocketAddr,
    csrf: bool,
    #[cfg(feature = "jobs")]
    jobs: Option<TestQueue>,
    #[cfg(feature = "mail")]
    mail: Option<TestMailer>,
}

impl TestApp {
    /// Wrap a configured Axum service. The caller owns database isolation.
    pub fn new(router: Router) -> Self {
        Self {
            contracts: None,
            services: capy_core::Services::new(),
            seeds: None,
            router,
            context: None,
            database: None,
            peer: ([127, 0, 0, 1], 12345).into(),
            csrf: false,
            #[cfg(feature = "jobs")]
            jobs: None,
            #[cfg(feature = "mail")]
            mail: None,
        }
    }

    /// Boot the ordinary application builder with an isolated SQLite database and migrations.
    pub async fn boot(application: impl TestApplication) -> capy_core::Result<Self> {
        Self::builder(application).boot().await
    }

    /// Configure database isolation, migrations, configuration and deterministic peer identity.
    pub fn builder<A: TestApplication>(application: A) -> TestAppBuilder<A> {
        TestAppBuilder::new(application)
    }

    /// Attach the context used by the real router. Used by application boot adapters.
    pub fn with_context(mut self, context: capy_core::AppContext) -> Self {
        self.context = Some(context);
        self
    }

    /// Attach the dependencies from the application factory.
    pub fn with_services(mut self, services: capy_core::Services) -> Self {
        self.services = services;
        self
    }

    /// Cache the application's declared response contracts for wire assertions.
    pub fn with_contracts(mut self, document: Value) -> Self {
        self.contracts = Some(std::sync::Arc::new(contracts::ContractRegistry::new(
            document,
        )));
        self
    }

    /// Inspect a dependency registered for this isolated application.
    pub fn service<T: Send + Sync + 'static>(&self) -> capy_core::Result<std::sync::Arc<T>> {
        self.services.get::<T>()
    }

    /// Attach the same seeds registered by the application factory. Never runs them implicitly.
    pub fn with_seeds(mut self, seeds: Option<capy_db::Seeds>) -> Self {
        self.seeds = seeds;
        self
    }

    /// Run the application's registered seeds against this isolated database.
    pub async fn seed(&self) -> capy_core::Result<()> {
        let seeds = self.seeds.as_ref().ok_or_else(|| {
            capy_core::AppError::Configuration(
                "Register application-owned seeds with App::seeds.".into(),
            )
        })?;
        seeds.run(self.context()).await
    }

    /// Enable real CSRF bootstrap for sessions when the application installs Capy auth.
    pub fn with_csrf(mut self, enabled: bool) -> Self {
        self.csrf = enabled;
        self
    }

    /// Context of a booted application. Low-level `new(router)` has no attached context.
    pub fn context(&self) -> &capy_core::AppContext {
        self.context
            .as_ref()
            .expect("Use TestApp::boot or attach the real application context")
    }

    /// The isolated application database; also usable with native SeaORM transactions.
    pub fn db(&self) -> &sea_orm::DatabaseConnection {
        &self.context().db
    }

    /// Inspect the same private storage service used by HTTP handlers and jobs.
    #[cfg(feature = "storage")]
    pub fn storage(&self) -> capy_core::Result<std::sync::Arc<capy_storage::Storage>> {
        self.service::<capy_storage::Storage>()
    }

    /// Create an independent same-origin browser session. No identity is fabricated.
    pub fn session(&self) -> TestSession {
        TestSession::new(self.clone())
    }

    /// Authenticate through the real login endpoint, including password, throttling and CSRF.
    /// A failed login returns a safe setup error; use `session.login` to assert failures.
    pub async fn login(&self, email: &str, password: &str) -> capy_core::Result<TestSession> {
        let mut session = self.session();
        if !session.login(email, password).await?.status.is_success() {
            return Err(capy_core::AppError::Configuration(
                "Test login failed; inspect it with TestSession::login (credentials redacted)."
                    .into(),
            ));
        }
        Ok(session)
    }

    /// Construct an application-owned factory using this database.
    pub fn factory<F: Factory + Default>(
        &self,
    ) -> FactoryBuilder<'_, F, sea_orm::DatabaseConnection> {
        FactoryBuilder::new(F::default(), self.db())
    }

    /// Explicitly close the test pool and drop a provisioned PostgreSQL database.
    /// Existing sessions/clones become unusable. Drop alone is best-effort cleanup.
    pub async fn cleanup(self) -> capy_core::Result<()> {
        if let Some(database) = &self.database {
            database.cleanup().await?;
        }
        Ok(())
    }

    /// Attach the actual registered job handlers, including captured dependencies.
    #[cfg(feature = "jobs")]
    pub fn with_jobs(mut self, jobs: TestQueue) -> Self {
        self.jobs = Some(jobs);
        self
    }

    /// Run/assert persisted jobs through the application's real worker registry.
    #[cfg(feature = "jobs")]
    pub fn jobs(&self) -> &TestQueue {
        self.jobs
            .as_ref()
            .expect("Register jobs in the application factory")
    }

    /// Attach a capture transport explicitly wired into the actual application factory.
    #[cfg(feature = "mail")]
    pub fn with_mail(mut self, mail: TestMailer) -> Self {
        self.mail = Some(mail);
        self
    }

    /// Inspect real rendered mail. Enable capture on the builder or wire it explicitly.
    #[cfg(feature = "mail")]
    pub fn mail(&self) -> &TestMailer {
        self.mail
            .as_ref()
            .expect("Enable TestAppBuilder::capture_mail or attach a capture")
    }

    /// Build a request with an arbitrary HTTP method.
    pub fn request(&self, method: Method, uri: &str) -> TestRequest {
        TestRequest {
            method: method.clone(),
            path: uri.into(),
            contracts: self.contracts.clone(),
            router: self.router.clone(),
            builder: Request::builder()
                .method(method)
                .uri(uri)
                .extension(axum::extract::ConnectInfo(self.peer)),
            body: Body::empty(),
        }
    }

    /// Build a GET request.
    pub fn get(&self, uri: &str) -> TestRequest {
        self.request(Method::GET, uri)
    }
    /// Build a POST request.
    pub fn post(&self, uri: &str) -> TestRequest {
        self.request(Method::POST, uri)
    }
    /// Build a PUT request.
    pub fn put(&self, uri: &str) -> TestRequest {
        self.request(Method::PUT, uri)
    }
    /// Build a PATCH request.
    pub fn patch(&self, uri: &str) -> TestRequest {
        self.request(Method::PATCH, uri)
    }
    /// Build a DELETE request.
    pub fn delete(&self, uri: &str) -> TestRequest {
        self.request(Method::DELETE, uri)
    }
}

/// A fluent request builder used only in tests; invalid requests panic clearly.
pub struct TestRequest {
    method: Method,
    path: String,
    contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
    router: Router,
    builder: axum::http::request::Builder,
    body: Body,
}

impl TestRequest {
    /// Supply a simulated socket peer, independent of forwarded headers.
    pub fn peer_addr(mut self, peer: std::net::SocketAddr) -> Self {
        self.builder = self.builder.extension(axum::extract::ConnectInfo(peer));
        self
    }
    /// Omit socket metadata to test fail-closed custom-server behavior.
    pub fn without_peer(mut self) -> Self {
        if let Some(extensions) = self.builder.extensions_mut() {
            extensions.remove::<axum::extract::ConnectInfo<std::net::SocketAddr>>();
        }
        self
    }
    /// Serialize a JSON body and set the content type.
    pub fn json(mut self, value: impl Serialize) -> Self {
        self.builder = self.builder.header("content-type", "application/json");
        self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
        self
    }

    /// Set a header, for example authorization or content type.
    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.builder = self.builder.header(name, value);
        self
    }

    /// Set a session cookie without depending on an application's user model.
    /// Use TestResponse::cookie to reuse a server-issued cookie.
    pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
        cookie.set_sensitive(true);
        self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
        self
    }

    /// Set a raw body, useful for malformed request tests.
    pub fn body(mut self, body: impl Into<Body>) -> Self {
        self.body = body.into();
        self
    }

    /// Execute the request directly against the service.
    pub async fn send(self) -> TestResponse {
        let response = self
            .router
            .oneshot(self.builder.body(self.body).expect("invalid test request"))
            .await
            .expect("Axum service is infallible");
        let (parts, body) = response.into_parts();
        TestResponse {
            method: self.method,
            path: self.path,
            contracts: self.contracts,
            status: parts.status,
            headers: parts.headers,
            body: to_bytes(body, 16 * 1024 * 1024)
                .await
                .expect("test response exceeds 16 MiB or cannot be read"),
        }
    }
}

/// A fully buffered test response with chainable assertions.
pub struct TestResponse {
    method: Method,
    path: String,
    contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
    /// HTTP response status.
    pub status: StatusCode,
    /// HTTP response headers.
    pub headers: HeaderMap,
    /// Raw response bytes.
    pub body: Bytes,
}

impl std::fmt::Debug for TestResponse {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TestResponse")
            .field("status", &self.status)
            .field("body_bytes", &self.body.len())
            .finish_non_exhaustive()
    }
}

impl TestResponse {
    /// Validate method, path, status, media type, and JSON response against OpenAPI.
    /// This is an opt-in test assertion with cached contract metadata.
    pub fn validate_contract(&self) -> std::result::Result<(), String> {
        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)?;
        contracts.validate(
            &self.method,
            &self.path,
            self.status,
            &self.headers,
            &self.body,
        )
    }

    /// Assert wire conformance and report the operation and failing JSON location.
    pub fn assert_contract(&self) -> &Self {
        if let Err(error) = self.validate_contract() {
            panic!("{error}");
        }
        self
    }
    /// Extract only a named cookie's name/value pair; omit Set-Cookie attributes.
    /// The returned sensitive header value redacts its Debug output.
    pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
        self.headers
            .get_all(axum::http::header::SET_COOKIE)
            .iter()
            .find_map(|value| {
                let pair = value.to_str().ok()?.split(';').next()?;
                let (key, _) = pair.split_once('=')?;
                if key != name {
                    return None;
                }
                let mut value = HeaderValue::from_str(pair).ok()?;
                value.set_sensitive(true);
                Some(value)
            })
    }

    /// Assert any HTTP status, including custom application error statuses.
    pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
        assert_eq!(
            self.status,
            status.into(),
            "response: {}",
            String::from_utf8_lossy(&self.body)
        );
        self
    }
    /// Assert HTTP 200.
    pub fn assert_ok(&self) -> &Self {
        self.assert_status(StatusCode::OK)
    }
    /// Assert HTTP 201.
    pub fn assert_created(&self) -> &Self {
        self.assert_status(StatusCode::CREATED)
    }
    /// Assert HTTP 204 and an empty response body.
    pub fn assert_no_content(&self) -> &Self {
        self.assert_status(StatusCode::NO_CONTENT);
        assert!(self.body.is_empty(), "204 responses must be empty");
        self
    }
    /// Deserialize the response into a JSON value or application response type.
    pub fn json<T: DeserializeOwned>(&self) -> T {
        serde_json::from_slice(&self.body)
            .expect("response must be valid JSON of the requested type")
    }
    /// Assert exact JSON equality, independent of object key order.
    pub fn assert_json(&self, expected: Value) -> &Self {
        assert_eq!(self.json::<Value>(), expected);
        self
    }
}

/// Real-persistence job tests. Own an isolated database and apply jobs migrations first.
#[cfg(feature = "jobs")]
#[derive(Clone)]
pub struct TestQueue {
    queue: capy_jobs::Queue,
    worker: capy_jobs::Worker,
}
#[cfg(feature = "jobs")]
impl TestQueue {
    /// Use the application's actual registry, Serde serialization and queue tables.
    pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
        Ok(Self {
            queue: capy_jobs::Queue::new(context.db.clone()),
            worker: capy_jobs::Worker::new(context, jobs)?,
        })
    }
    /// Supply the same application dependencies available to HTTP handlers.
    pub fn with_services(mut self, services: capy_core::Services) -> Self {
        self.worker = self.worker.with_services(services);
        self
    }
    /// Select one named queue for both assertions/dispatch and worker execution.
    /// Use `TestQueue::new(context, registry)?.on_queue("mail")?` for built-in
    /// queued mail, which uses the `mail` queue by default. Invalid names fail
    /// before persistence; this starts no background worker.
    pub fn on_queue(mut self, name: impl Into<String>) -> capy_core::Result<Self> {
        let name = capy_jobs::QueueName::new(name)?;
        self.queue = self.queue.named(name.clone());
        self.worker = self.worker.queues(vec![name])?;
        Ok(self)
    }
    /// Inspect/dispatch through the selected queue (default: `default`).
    pub fn queue(&self) -> &capy_jobs::Queue {
        &self.queue
    }
    /// Assert that at least one job of this name/version remains queued.
    pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
        assert!(
            self.queue.count::<J>().await? > 0,
            "Expected a persisted job of type {}",
            J::NAME
        );
        Ok(())
    }
    /// Execute one currently available job synchronously with the real worker policy.
    pub async fn run_next_job(&self) -> capy_core::Result<bool> {
        self.worker.run_next().await
    }
    /// Drain at most `limit` available jobs; never sleep through durable delays.
    pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
        let mut processed = 0;
        while processed < limit && self.worker.run_next().await? {
            processed += 1;
        }
        Ok(processed)
    }
}

/// Real-rendering capture transport for mail tests.
#[cfg(feature = "mail")]
pub use capy_mail::CaptureTransport as TestMailer;