Skip to main content

rust_web_server/test_client/
mod.rs

1#[cfg(test)]
2mod tests;
3
4use crate::application::Application;
5use crate::header::Header;
6use crate::http::VERSION;
7use crate::mime_type::MimeType;
8use crate::range::Range;
9use crate::request::{METHOD, Request};
10use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
11use crate::server::{Address, ConnectionInfo};
12
13/// An in-process HTTP test client that dispatches requests directly through an
14/// [`Application`] without opening a TCP socket.
15///
16/// Use this in unit and integration tests to exercise controllers and routing
17/// without starting the server.
18///
19/// # Example
20///
21/// ```rust,no_run
22/// use rust_web_server::app::App;
23/// use rust_web_server::core::New;
24/// use rust_web_server::test_client::TestClient;
25///
26/// let client = TestClient::new(App::new());
27///
28/// let res = client.get("/healthz").send();
29/// assert_eq!(200, res.status());
30///
31/// let res = client.post("/echo")
32///     .header("Content-Type", "text/plain")
33///     .body_text("hello")
34///     .send();
35/// assert_eq!(200, res.status());
36/// ```
37pub struct TestClient<A: Application> {
38    app: A,
39    connection: ConnectionInfo,
40}
41
42impl<A: Application> TestClient<A> {
43    /// Create a test client wrapping `app`. Requests are dispatched on a
44    /// synthetic `127.0.0.1:12345 → 127.0.0.1:7878` connection.
45    pub fn new(app: A) -> Self {
46        TestClient {
47            app,
48            connection: ConnectionInfo {
49                client: Address { ip: "127.0.0.1".to_string(), port: 12345 },
50                server: Address { ip: "127.0.0.1".to_string(), port: 7878 },
51                request_size: 16000,
52                sni_hostname: None,
53            },
54        }
55    }
56
57    /// Build a `GET` request to `path`.
58    pub fn get(&self, path: &str) -> TestRequest<'_, A> {
59        TestRequest::new(METHOD.get.to_string(), path, self)
60    }
61
62    /// Build a `POST` request to `path`.
63    pub fn post(&self, path: &str) -> TestRequest<'_, A> {
64        TestRequest::new(METHOD.post.to_string(), path, self)
65    }
66
67    /// Build a `PUT` request to `path`.
68    pub fn put(&self, path: &str) -> TestRequest<'_, A> {
69        TestRequest::new(METHOD.put.to_string(), path, self)
70    }
71
72    /// Build a `PATCH` request to `path`.
73    pub fn patch(&self, path: &str) -> TestRequest<'_, A> {
74        TestRequest::new(METHOD.patch.to_string(), path, self)
75    }
76
77    /// Build a `DELETE` request to `path`.
78    pub fn delete(&self, path: &str) -> TestRequest<'_, A> {
79        TestRequest::new(METHOD.delete.to_string(), path, self)
80    }
81
82    /// Build an `OPTIONS` request to `path`.
83    pub fn options(&self, path: &str) -> TestRequest<'_, A> {
84        TestRequest::new(METHOD.options.to_string(), path, self)
85    }
86}
87
88/// A pending test request. Chain builder methods then call [`TestRequest::send`].
89pub struct TestRequest<'a, A: Application> {
90    method: String,
91    path: String,
92    headers: Vec<Header>,
93    body: Vec<u8>,
94    client: &'a TestClient<A>,
95}
96
97impl<'a, A: Application> TestRequest<'a, A> {
98    fn new(method: String, path: &str, client: &'a TestClient<A>) -> Self {
99        TestRequest {
100            method,
101            path: path.to_string(),
102            headers: vec![],
103            body: vec![],
104            client,
105        }
106    }
107
108    /// Add a request header.
109    pub fn header(mut self, name: &str, value: &str) -> Self {
110        self.headers.push(Header { name: name.to_string(), value: value.to_string() });
111        self
112    }
113
114    /// Set the request body to raw bytes.
115    pub fn body_bytes(mut self, body: Vec<u8>) -> Self {
116        self.body = body;
117        self
118    }
119
120    /// Set the request body to a UTF-8 string.
121    pub fn body_text(mut self, text: &str) -> Self {
122        self.body = text.as_bytes().to_vec();
123        self
124    }
125
126    /// Set the request body to a JSON string, with
127    /// `Content-Type: application/json`.
128    pub fn body_json(mut self, json: &str) -> Self {
129        self.headers.push(Header { name: "Content-Type".to_string(), value: "application/json".to_string() });
130        self.body = json.as_bytes().to_vec();
131        self
132    }
133
134    /// Dispatch the request and return the response.
135    pub fn send(self) -> TestResponse {
136        let request = Request {
137            method: self.method,
138            request_uri: self.path,
139            http_version: VERSION.http_1_1.to_string(),
140            headers: self.headers,
141            body: self.body,
142        };
143
144        let response = self.client.app.execute(&request, &self.client.connection)
145            .unwrap_or_else(|msg| {
146                let dummy = Request {
147                    method: "GET".to_string(),
148                    request_uri: "/".to_string(),
149                    http_version: VERSION.http_1_1.to_string(),
150                    headers: vec![],
151                    body: vec![],
152                };
153                let header_list = Header::get_header_list(&dummy);
154                let body = msg.into_bytes();
155                let cr = Range::get_content_range(body, MimeType::TEXT_PLAIN.to_string());
156                Response::get_response(
157                    STATUS_CODE_REASON_PHRASE.n500_internal_server_error,
158                    Some(header_list),
159                    Some(vec![cr]),
160                )
161            });
162
163        TestResponse::from_response(response)
164    }
165}
166
167/// The result of a dispatched test request.
168pub struct TestResponse {
169    status: i16,
170    reason: String,
171    headers: Vec<Header>,
172    body: Vec<u8>,
173}
174
175impl TestResponse {
176    fn from_response(mut r: Response) -> Self {
177        let body: Vec<u8> = r.content_range_list.iter()
178            .flat_map(|cr| cr.body.iter().copied())
179            .collect();
180
181        // Mirror Response::generate_response, which only adds these headers
182        // at HTTP/1.1 write time — TestClient bypasses that path entirely.
183        if r.content_range_list.len() == 1 {
184            let content_range = r.content_range_list.get(0).unwrap();
185            r.headers.push(Header {
186                name: Header::_CONTENT_TYPE.to_string(),
187                value: content_range.content_type.to_string(),
188            });
189            if let Some(value) = crate::response::content_range_header_value(r.status_code, content_range) {
190                r.headers.push(Header {
191                    name: Header::_CONTENT_RANGE.to_string(),
192                    value,
193                });
194            }
195            r.headers.push(Header {
196                name: Header::_CONTENT_LENGTH.to_string(),
197                value: content_range.body.len().to_string(),
198            });
199        }
200
201        TestResponse {
202            status: r.status_code,
203            reason: r.reason_phrase,
204            headers: r.headers,
205            body,
206        }
207    }
208
209    /// HTTP status code, e.g. `200`.
210    pub fn status(&self) -> i16 {
211        self.status
212    }
213
214    /// HTTP reason phrase, e.g. `"OK"`.
215    pub fn reason(&self) -> &str {
216        &self.reason
217    }
218
219    /// Return the value of the first header matching `name` (case-insensitive).
220    pub fn header(&self, name: &str) -> Option<&str> {
221        let lower = name.to_lowercase();
222        self.headers
223            .iter()
224            .find(|h| h.name.to_lowercase() == lower)
225            .map(|h| h.value.as_str())
226    }
227
228    /// All response headers.
229    pub fn headers(&self) -> &[Header] {
230        &self.headers
231    }
232
233    /// Raw response body bytes.
234    pub fn body_bytes(&self) -> &[u8] {
235        &self.body
236    }
237
238    /// Response body decoded as UTF-8. Panics if the body is not valid UTF-8.
239    pub fn body_text(&self) -> &str {
240        std::str::from_utf8(&self.body).expect("response body is not valid UTF-8")
241    }
242
243    /// `true` if the status code is 2xx.
244    pub fn is_success(&self) -> bool {
245        (200..300).contains(&self.status)
246    }
247}