1mod 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#[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 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 pub async fn boot(application: impl TestApplication) -> capy_core::Result<Self> {
54 Self::builder(application).boot().await
55 }
56
57 pub fn builder<A: TestApplication>(application: A) -> TestAppBuilder<A> {
59 TestAppBuilder::new(application)
60 }
61
62 pub fn with_context(mut self, context: capy_core::AppContext) -> Self {
64 self.context = Some(context);
65 self
66 }
67
68 pub fn with_seeds(mut self, seeds: Option<capy_db::Seeds>) -> Self {
70 self.seeds = seeds;
71 self
72 }
73
74 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 pub fn with_csrf(mut self, enabled: bool) -> Self {
86 self.csrf = enabled;
87 self
88 }
89
90 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 pub fn db(&self) -> &sea_orm::DatabaseConnection {
99 &self.context().db
100 }
101
102 pub fn session(&self) -> TestSession {
104 TestSession::new(self.clone())
105 }
106
107 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 pub fn factory<F: Factory + Default>(
122 &self,
123 ) -> FactoryBuilder<'_, F, sea_orm::DatabaseConnection> {
124 FactoryBuilder::new(F::default(), self.db())
125 }
126
127 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 #[cfg(feature = "jobs")]
138 pub fn with_jobs(mut self, jobs: TestQueue) -> Self {
139 self.jobs = Some(jobs);
140 self
141 }
142
143 #[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 #[cfg(feature = "mail")]
153 pub fn with_mail(mut self, mail: TestMailer) -> Self {
154 self.mail = Some(mail);
155 self
156 }
157
158 #[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 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 pub fn get(&self, uri: &str) -> TestRequest {
180 self.request(Method::GET, uri)
181 }
182 pub fn post(&self, uri: &str) -> TestRequest {
184 self.request(Method::POST, uri)
185 }
186 pub fn put(&self, uri: &str) -> TestRequest {
188 self.request(Method::PUT, uri)
189 }
190 pub fn patch(&self, uri: &str) -> TestRequest {
192 self.request(Method::PATCH, uri)
193 }
194 pub fn delete(&self, uri: &str) -> TestRequest {
196 self.request(Method::DELETE, uri)
197 }
198}
199
200pub struct TestRequest {
202 router: Router,
203 builder: axum::http::request::Builder,
204 body: Body,
205}
206
207impl TestRequest {
208 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 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 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 pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
229 self.builder = self.builder.header(name, value);
230 self
231 }
232
233 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 pub fn body(mut self, body: impl Into<Body>) -> Self {
243 self.body = body.into();
244 self
245 }
246
247 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
265pub struct TestResponse {
267 pub status: StatusCode,
269 pub headers: HeaderMap,
271 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 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 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 pub fn assert_ok(&self) -> &Self {
315 self.assert_status(StatusCode::OK)
316 }
317 pub fn assert_created(&self) -> &Self {
319 self.assert_status(StatusCode::CREATED)
320 }
321 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 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 pub fn assert_json(&self, expected: Value) -> &Self {
334 assert_eq!(self.json::<Value>(), expected);
335 self
336 }
337}
338
339#[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 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 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 pub fn queue(&self) -> &capy_jobs::Queue {
367 &self.queue
368 }
369 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 pub async fn run_next_job(&self) -> capy_core::Result<bool> {
380 self.worker.run_next().await
381 }
382 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#[cfg(feature = "mail")]
394pub use capy_mail::CaptureTransport as TestMailer;