Skip to main content

ravel_test/
lib.rs

1//! Test utilities for Ravel applications.
2//!
3//! Provides helpers for HTTP and application-level testing:
4//! - `TestClient` — send requests to your Axum router without a running server
5//! - `assert_status` / `assert_see` / `assert_json` — response assertions
6//!
7//! # Usage
8//!
9//! ```rust,ignore
10//! use ravel_test::TestClient;
11//!
12//! let app = my_ravel_app();
13//! let client = TestClient::new(app);
14//!
15//! let resp = client.get("/").await;
16//! assert_eq!(resp.status(), 200);
17//! assert!(resp.text().contains("Hello"));
18//! ```
19
20use axum::Router;
21use axum::body::Body;
22use axum::http::{Request, StatusCode};
23use axum::response::Response;
24use serde::de::DeserializeOwned;
25use tower::ServiceExt;
26
27/// A test client for sending HTTP requests to an Axum [`Router`].
28pub struct TestClient {
29    router: Router,
30}
31
32impl TestClient {
33    /// Create a test client wrapping the given router.
34    pub fn new(router: Router) -> Self {
35        Self { router }
36    }
37
38    /// Send a GET request to `uri`.
39    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    /// Send a POST request with a JSON body.
51    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    /// Send a PUT request with a JSON body.
64    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    /// Send a PATCH request with a JSON body.
77    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    /// Send a DELETE request.
90    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    /// Send a PATCH request.
102    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    /// Send a raw request.
114    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
120/// Wrapper around an Axum [`Response`] with convenience assertions.
121pub 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    /// HTTP status code.
137    pub fn status(&self) -> StatusCode {
138        self.status
139    }
140
141    /// Response body as a string.
142    pub fn text(&self) -> &str {
143        &self.body
144    }
145
146    /// Parse the body as JSON.
147    pub fn json<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
148        serde_json::from_str(&self.body)
149    }
150
151    /// Assert the response has a specific status.
152    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    /// Assert the response body contains the given string.
161    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    /// Assert the response body matches the expected JSON value.
171    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    /// Assert the response status is 200 OK.
177    pub fn assert_ok(&self) {
178        self.assert_status(StatusCode::OK);
179    }
180
181    /// Assert the response status is 201 Created.
182    pub fn assert_created(&self) {
183        self.assert_status(StatusCode::CREATED);
184    }
185
186    /// Assert the response status is 302 Found (redirect).
187    pub fn assert_redirect(&self) {
188        self.assert_status(StatusCode::FOUND);
189    }
190
191    /// Assert the response status is 401 Unauthorized.
192    pub fn assert_unauthorized(&self) {
193        self.assert_status(StatusCode::UNAUTHORIZED);
194    }
195
196    /// Assert the response status is 403 Forbidden.
197    pub fn assert_forbidden(&self) {
198        self.assert_status(StatusCode::FORBIDDEN);
199    }
200
201    /// Assert the response status is 404 Not Found.
202    pub fn assert_not_found(&self) {
203        self.assert_status(StatusCode::NOT_FOUND);
204    }
205
206    /// Assert the response status is 422 Unprocessable Entity.
207    pub fn assert_unprocessable(&self) {
208        self.assert_status(StatusCode::UNPROCESSABLE_ENTITY);
209    }
210
211    /// Assert the response body does NOT contain the given string.
212    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    /// Assert the response body is exactly the given string.
222    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// ── Tests ──────────────────────────────────────────────────────────
232
233#[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}