1use axum::{
4 body::{to_bytes, Body, Bytes},
5 http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
6 Router,
7};
8use serde::{de::DeserializeOwned, Serialize};
9use serde_json::Value;
10use tower::ServiceExt;
11
12#[derive(Clone)]
14pub struct TestApp {
15 router: Router,
16}
17
18impl TestApp {
19 pub fn new(router: Router) -> Self {
21 Self { router }
22 }
23
24 pub fn request(&self, method: Method, uri: &str) -> TestRequest {
26 TestRequest {
27 router: self.router.clone(),
28 builder: Request::builder().method(method).uri(uri),
29 body: Body::empty(),
30 }
31 }
32
33 pub fn get(&self, uri: &str) -> TestRequest {
35 self.request(Method::GET, uri)
36 }
37 pub fn post(&self, uri: &str) -> TestRequest {
39 self.request(Method::POST, uri)
40 }
41 pub fn put(&self, uri: &str) -> TestRequest {
43 self.request(Method::PUT, uri)
44 }
45 pub fn patch(&self, uri: &str) -> TestRequest {
47 self.request(Method::PATCH, uri)
48 }
49 pub fn delete(&self, uri: &str) -> TestRequest {
51 self.request(Method::DELETE, uri)
52 }
53}
54
55pub struct TestRequest {
57 router: Router,
58 builder: axum::http::request::Builder,
59 body: Body,
60}
61
62impl TestRequest {
63 pub fn json(mut self, value: impl Serialize) -> Self {
65 self.builder = self.builder.header("content-type", "application/json");
66 self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
67 self
68 }
69
70 pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
72 self.builder = self.builder.header(name, value);
73 self
74 }
75
76 pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
79 cookie.set_sensitive(true);
80 self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
81 self
82 }
83
84 pub fn body(mut self, body: impl Into<Body>) -> Self {
86 self.body = body.into();
87 self
88 }
89
90 pub async fn send(self) -> TestResponse {
92 let response = self
93 .router
94 .oneshot(self.builder.body(self.body).expect("invalid test request"))
95 .await
96 .expect("Axum service is infallible");
97 let (parts, body) = response.into_parts();
98 TestResponse {
99 status: parts.status,
100 headers: parts.headers,
101 body: to_bytes(body, 16 * 1024 * 1024)
102 .await
103 .expect("test response exceeds 16 MiB or cannot be read"),
104 }
105 }
106}
107
108pub struct TestResponse {
110 pub status: StatusCode,
112 pub headers: HeaderMap,
114 pub body: Bytes,
116}
117
118impl std::fmt::Debug for TestResponse {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 f.debug_struct("TestResponse")
121 .field("status", &self.status)
122 .field("body_bytes", &self.body.len())
123 .finish_non_exhaustive()
124 }
125}
126
127impl TestResponse {
128 pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
131 self.headers
132 .get_all(axum::http::header::SET_COOKIE)
133 .iter()
134 .find_map(|value| {
135 let pair = value.to_str().ok()?.split(';').next()?;
136 let (key, _) = pair.split_once('=')?;
137 if key != name {
138 return None;
139 }
140 let mut value = HeaderValue::from_str(pair).ok()?;
141 value.set_sensitive(true);
142 Some(value)
143 })
144 }
145
146 pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
148 assert_eq!(
149 self.status,
150 status.into(),
151 "response: {}",
152 String::from_utf8_lossy(&self.body)
153 );
154 self
155 }
156 pub fn assert_ok(&self) -> &Self {
158 self.assert_status(StatusCode::OK)
159 }
160 pub fn assert_created(&self) -> &Self {
162 self.assert_status(StatusCode::CREATED)
163 }
164 pub fn assert_no_content(&self) -> &Self {
166 self.assert_status(StatusCode::NO_CONTENT);
167 assert!(self.body.is_empty(), "204 responses must be empty");
168 self
169 }
170 pub fn json<T: DeserializeOwned>(&self) -> T {
172 serde_json::from_slice(&self.body)
173 .expect("response must be valid JSON of the requested type")
174 }
175 pub fn assert_json(&self, expected: Value) -> &Self {
177 assert_eq!(self.json::<Value>(), expected);
178 self
179 }
180}
181
182#[cfg(feature = "jobs")]
184pub struct TestQueue {
185 queue: capy_jobs::Queue,
186 worker: capy_jobs::Worker,
187}
188#[cfg(feature = "jobs")]
189impl TestQueue {
190 pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
192 Ok(Self {
193 queue: capy_jobs::Queue::new(context.db.clone()),
194 worker: capy_jobs::Worker::new(context, jobs)?,
195 })
196 }
197 pub fn queue(&self) -> &capy_jobs::Queue {
199 &self.queue
200 }
201 pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
203 assert!(
204 self.queue.count::<J>().await? > 0,
205 "Expected a persisted job of type {}",
206 J::NAME
207 );
208 Ok(())
209 }
210 pub async fn run_next_job(&self) -> capy_core::Result<bool> {
212 self.worker.run_next().await
213 }
214 pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
216 let mut processed = 0;
217 while processed < limit && self.worker.run_next().await? {
218 processed += 1;
219 }
220 Ok(processed)
221 }
222}
223
224#[cfg(feature = "mail")]
226pub use capy_mail::CaptureTransport as TestMailer;