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).extension(
29 axum::extract::ConnectInfo(std::net::SocketAddr::from(([127, 0, 0, 1], 12345))),
30 ),
31 body: Body::empty(),
32 }
33 }
34
35 pub fn get(&self, uri: &str) -> TestRequest {
37 self.request(Method::GET, uri)
38 }
39 pub fn post(&self, uri: &str) -> TestRequest {
41 self.request(Method::POST, uri)
42 }
43 pub fn put(&self, uri: &str) -> TestRequest {
45 self.request(Method::PUT, uri)
46 }
47 pub fn patch(&self, uri: &str) -> TestRequest {
49 self.request(Method::PATCH, uri)
50 }
51 pub fn delete(&self, uri: &str) -> TestRequest {
53 self.request(Method::DELETE, uri)
54 }
55}
56
57pub struct TestRequest {
59 router: Router,
60 builder: axum::http::request::Builder,
61 body: Body,
62}
63
64impl TestRequest {
65 pub fn peer_addr(mut self, peer: std::net::SocketAddr) -> Self {
67 self.builder = self.builder.extension(axum::extract::ConnectInfo(peer));
68 self
69 }
70 pub fn without_peer(mut self) -> Self {
72 if let Some(extensions) = self.builder.extensions_mut() {
73 extensions.remove::<axum::extract::ConnectInfo<std::net::SocketAddr>>();
74 }
75 self
76 }
77 pub fn json(mut self, value: impl Serialize) -> Self {
79 self.builder = self.builder.header("content-type", "application/json");
80 self.body = Body::from(serde_json::to_vec(&value).expect("test JSON must serialize"));
81 self
82 }
83
84 pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
86 self.builder = self.builder.header(name, value);
87 self
88 }
89
90 pub fn cookie(mut self, mut cookie: HeaderValue) -> Self {
93 cookie.set_sensitive(true);
94 self.builder = self.builder.header(axum::http::header::COOKIE, cookie);
95 self
96 }
97
98 pub fn body(mut self, body: impl Into<Body>) -> Self {
100 self.body = body.into();
101 self
102 }
103
104 pub async fn send(self) -> TestResponse {
106 let response = self
107 .router
108 .oneshot(self.builder.body(self.body).expect("invalid test request"))
109 .await
110 .expect("Axum service is infallible");
111 let (parts, body) = response.into_parts();
112 TestResponse {
113 status: parts.status,
114 headers: parts.headers,
115 body: to_bytes(body, 16 * 1024 * 1024)
116 .await
117 .expect("test response exceeds 16 MiB or cannot be read"),
118 }
119 }
120}
121
122pub struct TestResponse {
124 pub status: StatusCode,
126 pub headers: HeaderMap,
128 pub body: Bytes,
130}
131
132impl std::fmt::Debug for TestResponse {
133 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134 f.debug_struct("TestResponse")
135 .field("status", &self.status)
136 .field("body_bytes", &self.body.len())
137 .finish_non_exhaustive()
138 }
139}
140
141impl TestResponse {
142 pub fn cookie(&self, name: &str) -> Option<HeaderValue> {
145 self.headers
146 .get_all(axum::http::header::SET_COOKIE)
147 .iter()
148 .find_map(|value| {
149 let pair = value.to_str().ok()?.split(';').next()?;
150 let (key, _) = pair.split_once('=')?;
151 if key != name {
152 return None;
153 }
154 let mut value = HeaderValue::from_str(pair).ok()?;
155 value.set_sensitive(true);
156 Some(value)
157 })
158 }
159
160 pub fn assert_status(&self, status: impl Into<StatusCode>) -> &Self {
162 assert_eq!(
163 self.status,
164 status.into(),
165 "response: {}",
166 String::from_utf8_lossy(&self.body)
167 );
168 self
169 }
170 pub fn assert_ok(&self) -> &Self {
172 self.assert_status(StatusCode::OK)
173 }
174 pub fn assert_created(&self) -> &Self {
176 self.assert_status(StatusCode::CREATED)
177 }
178 pub fn assert_no_content(&self) -> &Self {
180 self.assert_status(StatusCode::NO_CONTENT);
181 assert!(self.body.is_empty(), "204 responses must be empty");
182 self
183 }
184 pub fn json<T: DeserializeOwned>(&self) -> T {
186 serde_json::from_slice(&self.body)
187 .expect("response must be valid JSON of the requested type")
188 }
189 pub fn assert_json(&self, expected: Value) -> &Self {
191 assert_eq!(self.json::<Value>(), expected);
192 self
193 }
194}
195
196#[cfg(feature = "jobs")]
198pub struct TestQueue {
199 queue: capy_jobs::Queue,
200 worker: capy_jobs::Worker,
201}
202#[cfg(feature = "jobs")]
203impl TestQueue {
204 pub fn new(context: capy_core::AppContext, jobs: capy_jobs::Jobs) -> capy_core::Result<Self> {
206 Ok(Self {
207 queue: capy_jobs::Queue::new(context.db.clone()),
208 worker: capy_jobs::Worker::new(context, jobs)?,
209 })
210 }
211 pub fn on_queue(mut self, name: impl Into<String>) -> capy_core::Result<Self> {
216 let name = capy_jobs::QueueName::new(name)?;
217 self.queue = self.queue.named(name.clone());
218 self.worker = self.worker.queues(vec![name])?;
219 Ok(self)
220 }
221 pub fn queue(&self) -> &capy_jobs::Queue {
223 &self.queue
224 }
225 pub async fn assert_dispatched<J: capy_jobs::Job>(&self) -> capy_core::Result<()> {
227 assert!(
228 self.queue.count::<J>().await? > 0,
229 "Expected a persisted job of type {}",
230 J::NAME
231 );
232 Ok(())
233 }
234 pub async fn run_next_job(&self) -> capy_core::Result<bool> {
236 self.worker.run_next().await
237 }
238 pub async fn drain(&self, limit: usize) -> capy_core::Result<usize> {
240 let mut processed = 0;
241 while processed < limit && self.worker.run_next().await? {
242 processed += 1;
243 }
244 Ok(processed)
245 }
246}
247
248#[cfg(feature = "mail")]
250pub use capy_mail::CaptureTransport as TestMailer;