1use axum::Router;
21use axum::body::Body;
22use axum::http::{Request, StatusCode};
23use axum::response::Response;
24use serde::de::DeserializeOwned;
25use tower::ServiceExt;
26
27pub struct TestClient {
29 router: Router,
30}
31
32impl TestClient {
33 pub fn new(router: Router) -> Self {
35 Self { router }
36 }
37
38 pub async fn get(&self, uri: &str) -> TestResponse {
40 self.send(
41 Request::builder()
42 .uri(uri)
43 .method("GET")
44 .body(Body::empty())
45 .unwrap(),
46 )
47 .await
48 }
49
50 pub async fn post_json(&self, uri: &str, body: &str) -> TestResponse {
52 self.send(
53 Request::builder()
54 .uri(uri)
55 .method("POST")
56 .header("Content-Type", "application/json")
57 .body(Body::from(body.to_string()))
58 .unwrap(),
59 )
60 .await
61 }
62
63 pub async fn put_json(&self, uri: &str, body: &str) -> TestResponse {
65 self.send(
66 Request::builder()
67 .uri(uri)
68 .method("PUT")
69 .header("Content-Type", "application/json")
70 .body(Body::from(body.to_string()))
71 .unwrap(),
72 )
73 .await
74 }
75
76 pub async fn patch_json(&self, uri: &str, body: &str) -> TestResponse {
78 self.send(
79 Request::builder()
80 .uri(uri)
81 .method("PATCH")
82 .header("Content-Type", "application/json")
83 .body(Body::from(body.to_string()))
84 .unwrap(),
85 )
86 .await
87 }
88
89 pub async fn delete(&self, uri: &str) -> TestResponse {
91 self.send(
92 Request::builder()
93 .uri(uri)
94 .method("DELETE")
95 .body(Body::empty())
96 .unwrap(),
97 )
98 .await
99 }
100
101 pub async fn patch(&self, uri: &str) -> TestResponse {
103 self.send(
104 Request::builder()
105 .uri(uri)
106 .method("PATCH")
107 .body(Body::empty())
108 .unwrap(),
109 )
110 .await
111 }
112
113 pub async fn send(&self, request: Request<Body>) -> TestResponse {
115 let response = self.router.clone().oneshot(request).await.unwrap();
116 TestResponse::new(response).await
117 }
118}
119
120pub struct TestResponse {
122 status: StatusCode,
123 body: String,
124}
125
126impl TestResponse {
127 async fn new(response: Response<Body>) -> Self {
128 let status = response.status();
129 let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
130 .await
131 .unwrap_or_default();
132 let body = String::from_utf8_lossy(&body_bytes).to_string();
133 Self { status, body }
134 }
135
136 pub fn status(&self) -> StatusCode {
138 self.status
139 }
140
141 pub fn text(&self) -> &str {
143 &self.body
144 }
145
146 pub fn json<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
148 serde_json::from_str(&self.body)
149 }
150
151 pub fn assert_status(&self, expected: StatusCode) {
153 assert_eq!(
154 self.status, expected,
155 "Expected status {}, got {} (body: {})",
156 expected, self.status, self.body
157 );
158 }
159
160 pub fn assert_see(&self, needle: &str) {
162 assert!(
163 self.body.contains(needle),
164 "Expected body to contain '{}', but body was: {}",
165 needle,
166 self.body
167 );
168 }
169
170 pub fn assert_json(&self, expected: serde_json::Value) {
172 let actual: serde_json::Value = self.json().expect("Response is not valid JSON");
173 assert_eq!(actual, expected, "JSON mismatch");
174 }
175
176 pub fn assert_ok(&self) {
178 self.assert_status(StatusCode::OK);
179 }
180
181 pub fn assert_created(&self) {
183 self.assert_status(StatusCode::CREATED);
184 }
185
186 pub fn assert_redirect(&self) {
188 self.assert_status(StatusCode::FOUND);
189 }
190
191 pub fn assert_unauthorized(&self) {
193 self.assert_status(StatusCode::UNAUTHORIZED);
194 }
195
196 pub fn assert_forbidden(&self) {
198 self.assert_status(StatusCode::FORBIDDEN);
199 }
200
201 pub fn assert_not_found(&self) {
203 self.assert_status(StatusCode::NOT_FOUND);
204 }
205
206 pub fn assert_unprocessable(&self) {
208 self.assert_status(StatusCode::UNPROCESSABLE_ENTITY);
209 }
210
211 pub fn assert_dont_see(&self, needle: &str) {
213 assert!(
214 !self.body.contains(needle),
215 "Expected body NOT to contain '{}', but body was: {}",
216 needle,
217 self.body
218 );
219 }
220
221 pub fn assert_exact(&self, expected: &str) {
223 assert_eq!(
224 self.body, expected,
225 "Expected body to be '{}', but was '{}'",
226 expected, self.body
227 );
228 }
229}
230
231#[cfg(test)]
234mod tests {
235 use super::*;
236 use axum::{Json, routing::get};
237 use serde::Serialize;
238
239 async fn hello() -> &'static str {
240 "Hello, Ravel!"
241 }
242
243 #[derive(Serialize)]
244 struct Health {
245 status: &'static str,
246 }
247
248 async fn health() -> Json<Health> {
249 Json(Health { status: "ok" })
250 }
251
252 async fn login() -> (StatusCode, Json<serde_json::Value>) {
253 (
254 StatusCode::CREATED,
255 Json(serde_json::json!({"token": "abc"})),
256 )
257 }
258
259 fn test_app() -> Router {
260 Router::new()
261 .route("/", get(hello))
262 .route("/health", get(health))
263 .route("/login", get(login))
264 }
265
266 #[tokio::test]
267 async fn test_client_get() {
268 let client = TestClient::new(test_app());
269 let resp = client.get("/").await;
270 resp.assert_ok();
271 resp.assert_see("Hello");
272 }
273
274 #[tokio::test]
275 async fn test_client_json() {
276 let client = TestClient::new(test_app());
277 let resp = client.get("/health").await;
278 resp.assert_ok();
279 resp.assert_json(serde_json::json!({"status": "ok"}));
280 }
281
282 #[tokio::test]
283 async fn test_client_created() {
284 let client = TestClient::new(test_app());
285 let resp = client.get("/login").await;
286 resp.assert_created();
287 let token: String = resp.json::<serde_json::Value>().unwrap()["token"]
288 .as_str()
289 .unwrap()
290 .to_string();
291 assert_eq!(token, "abc");
292 }
293}