1use std::convert::Infallible;
8
9use anvil_core::Application;
10use axum::body::{Body, Bytes};
11use axum::Router;
12use http::{HeaderMap, Method, Request, StatusCode};
13use http_body_util::BodyExt;
14use serde::de::DeserializeOwned;
15use tower::ServiceExt;
16
17pub struct TestClient {
18 router: Router,
19 base_headers: HeaderMap,
20}
21
22impl TestClient {
23 pub async fn new(app: Application) -> Self {
24 let _ = anvil_core::config::load_dotenv();
30 Self {
31 router: app.into_router(),
32 base_headers: HeaderMap::new(),
33 }
34 }
35
36 pub fn from_router(router: Router) -> Self {
37 let _ = anvil_core::config::load_dotenv();
38 Self {
39 router,
40 base_headers: HeaderMap::new(),
41 }
42 }
43
44 pub fn with_header(mut self, name: &str, value: &str) -> Self {
46 if let (Ok(name), Ok(val)) = (
47 http::HeaderName::try_from(name),
48 http::HeaderValue::try_from(value),
49 ) {
50 self.base_headers.insert(name, val);
51 }
52 self
53 }
54
55 pub fn with_bearer(self, token: &str) -> Self {
57 self.with_header("authorization", &format!("Bearer {token}"))
58 }
59
60 pub fn with_ajax(self) -> Self {
62 self.with_header("x-requested-with", "XMLHttpRequest")
63 }
64
65 pub async fn get(&self, path: &str) -> TestResponse {
66 self.request(Method::GET, path, None, &[]).await
67 }
68
69 pub async fn post(&self, path: &str, body: serde_json::Value) -> TestResponse {
70 self.request(Method::POST, path, Some(body), &[]).await
71 }
72
73 pub async fn put(&self, path: &str, body: serde_json::Value) -> TestResponse {
74 self.request(Method::PUT, path, Some(body), &[]).await
75 }
76
77 pub async fn patch(&self, path: &str, body: serde_json::Value) -> TestResponse {
78 self.request(Method::PATCH, path, Some(body), &[]).await
79 }
80
81 pub async fn delete(&self, path: &str) -> TestResponse {
82 self.request(Method::DELETE, path, None, &[]).await
83 }
84
85 pub async fn post_form(&self, path: &str, form: &[(&str, &str)]) -> TestResponse {
87 let body = serde_urlencoded::to_string(form).unwrap_or_default();
88 let req = Request::builder()
89 .method(Method::POST)
90 .uri(path)
91 .header("content-type", "application/x-www-form-urlencoded")
92 .body(Body::from(body))
93 .unwrap();
94 self.send(req).await
95 }
96
97 pub async fn post_bytes(
101 &self,
102 path: &str,
103 body: impl Into<Bytes>,
104 content_type: &str,
105 ) -> TestResponse {
106 self.bytes_request(Method::POST, path, body.into(), content_type)
107 .await
108 }
109
110 pub async fn put_bytes(
112 &self,
113 path: &str,
114 body: impl Into<Bytes>,
115 content_type: &str,
116 ) -> TestResponse {
117 self.bytes_request(Method::PUT, path, body.into(), content_type)
118 .await
119 }
120
121 pub async fn patch_bytes(
123 &self,
124 path: &str,
125 body: impl Into<Bytes>,
126 content_type: &str,
127 ) -> TestResponse {
128 self.bytes_request(Method::PATCH, path, body.into(), content_type)
129 .await
130 }
131
132 async fn bytes_request(
133 &self,
134 method: Method,
135 path: &str,
136 body: Bytes,
137 content_type: &str,
138 ) -> TestResponse {
139 let req = Request::builder()
140 .method(method)
141 .uri(path)
142 .header("content-type", content_type)
143 .body(Body::from(body))
144 .unwrap();
145 self.send(req).await
146 }
147
148 async fn request(
149 &self,
150 method: Method,
151 path: &str,
152 body: Option<serde_json::Value>,
153 extra_headers: &[(&str, &str)],
154 ) -> TestResponse {
155 let mut req = Request::builder().method(method).uri(path);
156 let body = match body {
157 Some(v) => {
158 req = req.header("content-type", "application/json");
159 Body::from(serde_json::to_vec(&v).unwrap())
160 }
161 None => Body::empty(),
162 };
163 for (n, v) in extra_headers {
164 req = req.header(*n, *v);
165 }
166 let mut http_req = req.body(body).unwrap();
167 for (name, value) in &self.base_headers {
168 http_req.headers_mut().insert(name.clone(), value.clone());
169 }
170 self.send(http_req).await
171 }
172
173 async fn send(&self, req: Request<Body>) -> TestResponse {
174 let mut req = req;
175 for (name, value) in &self.base_headers {
176 req.headers_mut()
177 .entry(name.clone())
178 .or_insert_with(|| value.clone());
179 }
180 let response = self.router.clone().oneshot(req).await.unwrap();
181
182 let status = response.status();
183 let headers = response.headers().clone();
184 let bytes = response
185 .into_body()
186 .collect()
187 .await
188 .map(|c| c.to_bytes())
189 .unwrap_or_default();
190
191 TestResponse {
192 status,
193 headers,
194 body: bytes.to_vec(),
195 }
196 }
197}
198
199pub struct TestResponse {
200 pub status: StatusCode,
201 pub headers: HeaderMap,
202 pub body: Vec<u8>,
203}
204
205impl TestResponse {
206 pub fn assert_status(&self, expected: u16) -> &Self {
209 assert_eq!(
210 self.status.as_u16(),
211 expected,
212 "expected status {expected}, got {} — body: {}",
213 self.status,
214 self.body_text()
215 );
216 self
217 }
218
219 pub fn assert_ok(&self) -> &Self {
220 assert!(
221 self.status.is_success(),
222 "expected success, got {} — body: {}",
223 self.status,
224 self.body_text()
225 );
226 self
227 }
228
229 pub fn assert_created(&self) -> &Self {
230 self.assert_status(201)
231 }
232 pub fn assert_no_content(&self) -> &Self {
233 self.assert_status(204)
234 }
235 pub fn assert_bad_request(&self) -> &Self {
236 self.assert_status(400)
237 }
238 pub fn assert_unauthorized(&self) -> &Self {
239 self.assert_status(401)
240 }
241 pub fn assert_forbidden(&self) -> &Self {
242 self.assert_status(403)
243 }
244 pub fn assert_not_found(&self) -> &Self {
245 self.assert_status(404)
246 }
247 pub fn assert_unprocessable(&self) -> &Self {
248 self.assert_status(422)
249 }
250 pub fn assert_too_many_requests(&self) -> &Self {
251 self.assert_status(429)
252 }
253 pub fn assert_server_error(&self) -> &Self {
254 assert!(
255 self.status.is_server_error(),
256 "expected 5xx, got {} — body: {}",
257 self.status,
258 self.body_text()
259 );
260 self
261 }
262
263 pub fn assert_redirect(&self) -> &Self {
264 assert!(
265 self.status.is_redirection(),
266 "expected 3xx redirect, got {} — body: {}",
267 self.status,
268 self.body_text()
269 );
270 self
271 }
272
273 pub fn assert_redirect_to(&self, location: &str) -> &Self {
274 self.assert_redirect();
275 let actual = self
276 .headers
277 .get("location")
278 .and_then(|v| v.to_str().ok())
279 .unwrap_or("");
280 assert_eq!(actual, location, "redirect Location mismatch");
281 self
282 }
283
284 pub fn assert_header(&self, name: &str, value: &str) -> &Self {
287 let actual = self
288 .headers
289 .get(name)
290 .and_then(|v| v.to_str().ok())
291 .unwrap_or("");
292 assert_eq!(actual, value, "header `{name}` mismatch");
293 self
294 }
295
296 pub fn assert_header_present(&self, name: &str) -> &Self {
297 assert!(
298 self.headers.contains_key(name),
299 "expected header `{name}` to be present"
300 );
301 self
302 }
303
304 pub fn assert_header_missing(&self, name: &str) -> &Self {
305 assert!(
306 !self.headers.contains_key(name),
307 "expected header `{name}` NOT to be present"
308 );
309 self
310 }
311
312 pub fn header(&self, name: &str) -> Option<String> {
313 self.headers
314 .get(name)
315 .and_then(|v| v.to_str().ok().map(String::from))
316 }
317
318 pub fn body_text(&self) -> String {
321 String::from_utf8_lossy(&self.body).to_string()
322 }
323
324 pub fn json<T: DeserializeOwned>(&self) -> T {
325 serde_json::from_slice(&self.body).expect("response was not valid JSON")
326 }
327
328 pub fn json_value(&self) -> serde_json::Value {
329 serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null)
330 }
331
332 pub fn assert_contains(&self, needle: &str) -> &Self {
333 let body = self.body_text();
334 assert!(
335 body.contains(needle),
336 "expected response body to contain '{needle}', got: {body}"
337 );
338 self
339 }
340 pub fn assert_dont_contain(&self, needle: &str) -> &Self {
341 let body = self.body_text();
342 assert!(
343 !body.contains(needle),
344 "expected response body NOT to contain '{needle}', got: {body}"
345 );
346 self
347 }
348 pub fn assert_see(&self, text: &str) -> &Self {
350 self.assert_contains(text)
351 }
352 pub fn assert_dont_see(&self, text: &str) -> &Self {
353 self.assert_dont_contain(text)
354 }
355
356 pub fn assert_json(&self, expected: serde_json::Value) -> &Self {
360 let actual = self.json_value();
361 assert_eq!(actual, expected, "JSON body mismatch");
362 self
363 }
364
365 pub fn assert_json_path(&self, path: &str, expected: serde_json::Value) -> &Self {
368 let actual = json_dig(&self.json_value(), path);
369 assert_eq!(
370 actual.as_ref(),
371 Some(&expected),
372 "JSON path `{path}` mismatch — full body: {}",
373 self.body_text()
374 );
375 self
376 }
377
378 pub fn assert_json_fragment(&self, subset: serde_json::Value) -> &Self {
381 let actual = self.json_value();
382 assert!(
383 json_contains(&actual, &subset),
384 "JSON body missing fragment {subset} — got {actual}"
385 );
386 self
387 }
388
389 pub fn assert_validation_error(&self, field: &str) -> &Self {
392 let v = self.json_value();
393 let arr = v
394 .get("errors")
395 .and_then(|e| e.get(field))
396 .and_then(|f| f.as_array());
397 assert!(
398 arr.map(|a| !a.is_empty()).unwrap_or(false),
399 "expected validation error on field `{field}` — body: {}",
400 self.body_text()
401 );
402 self
403 }
404}
405
406fn json_contains(actual: &serde_json::Value, expected: &serde_json::Value) -> bool {
409 use serde_json::Value::*;
410 match (actual, expected) {
411 (Object(a), Object(e)) => e
412 .iter()
413 .all(|(k, ev)| a.get(k).is_some_and(|av| json_contains(av, ev))),
414 (Array(a), Array(e)) => e.iter().all(|ev| a.iter().any(|av| json_contains(av, ev))),
415 (a, e) => a == e,
416 }
417}
418
419fn json_dig(v: &serde_json::Value, path: &str) -> Option<serde_json::Value> {
421 let mut current = v;
422 for segment in path.split('.') {
423 current = if let Ok(idx) = segment.parse::<usize>() {
424 current.get(idx)?
425 } else {
426 current.get(segment)?
427 };
428 }
429 Some(current.clone())
430}
431
432fn _force_link() {
434 let _ = std::any::type_name::<Infallible>();
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440 use axum::routing::post;
441
442 async fn echo(body: Bytes) -> Bytes {
445 body
446 }
447
448 #[tokio::test]
449 async fn post_bytes_round_trips_arbitrary_bytes() {
450 let router = Router::new().route("/echo", post(echo));
451 let client = TestClient::from_router(router);
452
453 let cbor = vec![0xA1, 0x62, 0x6F, 0x6B, 0xF5];
455 let resp = client
456 .post_bytes("/echo", cbor.clone(), "application/cbor")
457 .await;
458
459 resp.assert_ok();
460 assert_eq!(resp.body, cbor);
461 }
462
463 #[tokio::test]
464 async fn post_bytes_sets_content_type_header_for_handler_dispatch() {
465 async fn ct(headers: http::HeaderMap) -> String {
468 headers
469 .get("content-type")
470 .and_then(|v| v.to_str().ok())
471 .unwrap_or("missing")
472 .to_string()
473 }
474 let router = Router::new().route("/ct", post(ct));
475 let client = TestClient::from_router(router);
476
477 let resp = client
478 .post_bytes("/ct", b"x".to_vec(), "application/x-protobuf")
479 .await;
480 resp.assert_ok();
481 assert_eq!(resp.body_text(), "application/x-protobuf");
482 }
483
484 #[tokio::test]
485 async fn put_and_patch_bytes_dispatch_correctly() {
486 async fn method_name(method: Method) -> String {
487 method.as_str().to_string()
488 }
489 let router = Router::new()
490 .route("/m", axum::routing::put(method_name))
491 .route("/m", axum::routing::patch(method_name));
492 let client = TestClient::from_router(router);
493
494 let resp = client
495 .put_bytes("/m", b"_".to_vec(), "application/octet-stream")
496 .await;
497 resp.assert_ok();
498 assert_eq!(resp.body_text(), "PUT");
499
500 let resp = client
501 .patch_bytes("/m", b"_".to_vec(), "application/octet-stream")
502 .await;
503 resp.assert_ok();
504 assert_eq!(resp.body_text(), "PATCH");
505 }
506}