1mod 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#[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 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 pub async fn boot(application: impl TestApplication) -> capy_core::Result<Self> {
59 Self::builder(application).boot().await
60 }
61
62 pub fn builder<A: TestApplication>(application: A) -> TestAppBuilder<A> {
64 TestAppBuilder::new(application)
65 }
66
67 pub fn with_context(mut self, context: capy_core::AppContext) -> Self {
69 self.context = Some(context);
70 self
71 }
72
73 pub fn with_services(mut self, services: capy_core::Services) -> Self {
75 self.services = services;
76 self
77 }
78
79 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 pub fn service<T: Send + Sync + 'static>(&self) -> capy_core::Result<std::sync::Arc<T>> {
89 self.services.get::<T>()
90 }
91
92 pub fn with_seeds(mut self, seeds: Option<capy_db::Seeds>) -> Self {
94 self.seeds = seeds;
95 self
96 }
97
98 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 pub fn with_csrf(mut self, enabled: bool) -> Self {
110 self.csrf = enabled;
111 self
112 }
113
114 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 pub fn db(&self) -> &sea_orm::DatabaseConnection {
123 &self.context().db
124 }
125
126 #[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 pub fn session(&self) -> TestSession {
134 TestSession::new(self.clone())
135 }
136
137 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 pub fn factory<F: Factory + Default>(
152 &self,
153 ) -> FactoryBuilder<'_, F, sea_orm::DatabaseConnection> {
154 FactoryBuilder::new(F::default(), self.db())
155 }
156
157 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 #[cfg(feature = "jobs")]
168 pub fn with_jobs(mut self, jobs: TestQueue) -> Self {
169 self.jobs = Some(jobs);
170 self
171 }
172
173 #[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 #[cfg(feature = "mail")]
183 pub fn with_mail(mut self, mail: TestMailer) -> Self {
184 self.mail = Some(mail);
185 self
186 }
187
188 #[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 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 pub fn get(&self, uri: &str) -> TestRequest {
213 self.request(Method::GET, uri)
214 }
215 pub fn post(&self, uri: &str) -> TestRequest {
217 self.request(Method::POST, uri)
218 }
219 pub fn put(&self, uri: &str) -> TestRequest {
221 self.request(Method::PUT, uri)
222 }
223 pub fn patch(&self, uri: &str) -> TestRequest {
225 self.request(Method::PATCH, uri)
226 }
227 pub fn delete(&self, uri: &str) -> TestRequest {
229 self.request(Method::DELETE, uri)
230 }
231}
232
233pub 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 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 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 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 pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
265 self.builder = self.builder.header(name, value);
266 self
267 }
268
269 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 pub fn body(mut self, body: impl Into<Body>) -> Self {
279 self.body = body.into();
280 self
281 }
282
283 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
304pub struct TestResponse {
306 method: Method,
307 path: String,
308 contracts: Option<std::sync::Arc<std::result::Result<contracts::ContractRegistry, String>>>,
309 pub status: StatusCode,
311 pub headers: HeaderMap,
313 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 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 pub fn assert_contract(&self) -> &Self {
342 if let Err(error) = self.validate_contract() {
343 panic!("{error}");
344 }
345 self
346 }
347 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 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 pub fn assert_ok(&self) -> &Self {
377 self.assert_status(StatusCode::OK)
378 }
379 pub fn assert_created(&self) -> &Self {
381 self.assert_status(StatusCode::CREATED)
382 }
383 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 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 pub fn assert_json(&self, expected: Value) -> &Self {
396 assert_eq!(self.json::<Value>(), expected);
397 self
398 }
399}
400
401#[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 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 pub fn with_services(mut self, services: capy_core::Services) -> Self {
419 self.worker = self.worker.with_services(services);
420 self
421 }
422 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 pub fn queue(&self) -> &capy_jobs::Queue {
434 &self.queue
435 }
436 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 pub async fn run_next_job(&self) -> capy_core::Result<bool> {
447 self.worker.run_next().await
448 }
449 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#[cfg(feature = "mail")]
461pub use capy_mail::CaptureTransport as TestMailer;