1use axum::body::Body;
2use axum::http::Request as AxumRequest;
3use axum_test::{TestResponse as AxumTestResponse, TestServer, TestWebSocket, WsMessage};
4
5pub mod multipart;
6pub use multipart::{MultipartFilePart, build_multipart_body};
7
8pub mod form;
9
10pub mod test_client;
11pub use test_client::TestClient;
12
13use brotli::Decompressor;
14use flate2::read::GzDecoder;
15pub use form::encode_urlencoded_body;
16use http_body_util::BodyExt;
17use serde_json::Value;
18use std::collections::HashMap;
19use std::io::{Cursor, Read};
20
21#[derive(Debug, Clone)]
23pub struct ResponseSnapshot {
24 pub status: u16,
26 pub headers: HashMap<String, String>,
28 pub body: Vec<u8>,
30}
31
32impl ResponseSnapshot {
33 pub fn text(&self) -> Result<String, std::string::FromUtf8Error> {
35 String::from_utf8(self.body.clone())
36 }
37
38 pub fn json(&self) -> Result<Value, serde_json::Error> {
40 serde_json::from_slice(&self.body)
41 }
42
43 pub fn header(&self, name: &str) -> Option<&str> {
45 self.headers.get(&name.to_ascii_lowercase()).map(|s| s.as_str())
46 }
47}
48
49#[derive(Debug)]
51pub enum SnapshotError {
52 InvalidHeader(String),
54 Decompression(String),
56}
57
58impl std::fmt::Display for SnapshotError {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 match self {
61 SnapshotError::InvalidHeader(msg) => write!(f, "Invalid header: {}", msg),
62 SnapshotError::Decompression(msg) => write!(f, "Failed to decode body: {}", msg),
63 }
64 }
65}
66
67impl std::error::Error for SnapshotError {}
68
69pub async fn call_test_server(server: &TestServer, request: AxumRequest<Body>) -> AxumTestResponse {
72 let (parts, body) = request.into_parts();
73
74 let mut path = parts.uri.path().to_string();
75 if let Some(query) = parts.uri.query()
76 && !query.is_empty()
77 {
78 path.push('?');
79 path.push_str(query);
80 }
81
82 let mut test_request = server.method(parts.method.clone(), &path);
83
84 for (name, value) in parts.headers.iter() {
85 test_request = test_request.add_header(name.clone(), value.clone());
86 }
87
88 let collected = body
89 .collect()
90 .await
91 .expect("failed to read request body for test dispatch");
92 let bytes = collected.to_bytes();
93 if !bytes.is_empty() {
94 test_request = test_request.bytes(bytes);
95 }
96
97 test_request.await
98}
99
100pub async fn snapshot_response(response: AxumTestResponse) -> Result<ResponseSnapshot, SnapshotError> {
102 let status = response.status_code().as_u16();
103
104 let mut headers = HashMap::new();
105 for (name, value) in response.headers() {
106 let header_value = value
107 .to_str()
108 .map_err(|e| SnapshotError::InvalidHeader(e.to_string()))?;
109 headers.insert(name.to_string().to_ascii_lowercase(), header_value.to_string());
110 }
111
112 let body = response.into_bytes();
113 let decoded_body = decode_body(&headers, body.to_vec())?;
114
115 Ok(ResponseSnapshot {
116 status,
117 headers,
118 body: decoded_body,
119 })
120}
121
122fn decode_body(headers: &HashMap<String, String>, body: Vec<u8>) -> Result<Vec<u8>, SnapshotError> {
123 let encoding = headers
124 .get("content-encoding")
125 .map(|value| value.trim().to_ascii_lowercase());
126
127 match encoding.as_deref() {
128 Some("gzip" | "x-gzip") => decode_gzip(body),
129 Some("br") => decode_brotli(body),
130 _ => Ok(body),
131 }
132}
133
134fn decode_gzip(body: Vec<u8>) -> Result<Vec<u8>, SnapshotError> {
135 let mut decoder = GzDecoder::new(Cursor::new(body));
136 let mut decoded_bytes = Vec::new();
137 decoder
138 .read_to_end(&mut decoded_bytes)
139 .map_err(|e| SnapshotError::Decompression(e.to_string()))?;
140 Ok(decoded_bytes)
141}
142
143fn decode_brotli(body: Vec<u8>) -> Result<Vec<u8>, SnapshotError> {
144 let mut decoder = Decompressor::new(Cursor::new(body), 4096);
145 let mut decoded_bytes = Vec::new();
146 decoder
147 .read_to_end(&mut decoded_bytes)
148 .map_err(|e| SnapshotError::Decompression(e.to_string()))?;
149 Ok(decoded_bytes)
150}
151
152pub struct WebSocketConnection {
157 inner: TestWebSocket,
158}
159
160impl WebSocketConnection {
161 pub fn new(inner: TestWebSocket) -> Self {
163 Self { inner }
164 }
165
166 pub async fn send_text(&mut self, text: impl std::fmt::Display) {
168 self.inner.send_text(text).await;
169 }
170
171 pub async fn send_json<T: serde::Serialize>(&mut self, value: &T) {
173 self.inner.send_json(value).await;
174 }
175
176 pub async fn send_message(&mut self, msg: WsMessage) {
178 self.inner.send_message(msg).await;
179 }
180
181 pub async fn receive_text(&mut self) -> String {
183 self.inner.receive_text().await
184 }
185
186 pub async fn receive_json<T: serde::de::DeserializeOwned>(&mut self) -> T {
188 self.inner.receive_json().await
189 }
190
191 pub async fn receive_bytes(&mut self) -> bytes::Bytes {
193 self.inner.receive_bytes().await
194 }
195
196 pub async fn receive_message(&mut self) -> WebSocketMessage {
198 let msg = self.inner.receive_message().await;
199 WebSocketMessage::from_ws_message(msg)
200 }
201
202 pub async fn close(self) {
204 self.inner.close().await;
205 }
206}
207
208#[derive(Debug, Clone)]
210pub enum WebSocketMessage {
211 Text(String),
213 Binary(Vec<u8>),
215 Close(Option<String>),
217 Ping(Vec<u8>),
219 Pong(Vec<u8>),
221}
222
223impl WebSocketMessage {
224 fn from_ws_message(msg: WsMessage) -> Self {
225 match msg {
226 WsMessage::Text(text) => WebSocketMessage::Text(text.to_string()),
227 WsMessage::Binary(data) => WebSocketMessage::Binary(data.to_vec()),
228 WsMessage::Close(frame) => WebSocketMessage::Close(frame.map(|f| f.reason.to_string())),
229 WsMessage::Ping(data) => WebSocketMessage::Ping(data.to_vec()),
230 WsMessage::Pong(data) => WebSocketMessage::Pong(data.to_vec()),
231 WsMessage::Frame(_) => WebSocketMessage::Close(None),
232 }
233 }
234
235 pub fn as_text(&self) -> Option<&str> {
237 match self {
238 WebSocketMessage::Text(text) => Some(text),
239 _ => None,
240 }
241 }
242
243 pub fn as_json(&self) -> Result<Value, String> {
245 match self {
246 WebSocketMessage::Text(text) => {
247 serde_json::from_str(text).map_err(|e| format!("Failed to parse JSON: {}", e))
248 }
249 _ => Err("Message is not text".to_string()),
250 }
251 }
252
253 pub fn as_binary(&self) -> Option<&[u8]> {
255 match self {
256 WebSocketMessage::Binary(data) => Some(data),
257 _ => None,
258 }
259 }
260
261 pub fn is_close(&self) -> bool {
263 matches!(self, WebSocketMessage::Close(_))
264 }
265}
266
267pub async fn connect_websocket(server: &TestServer, path: &str) -> WebSocketConnection {
269 let ws = server.get_websocket(path).await.into_websocket().await;
270 WebSocketConnection::new(ws)
271}
272
273#[derive(Debug)]
277pub struct SseStream {
278 body: String,
279 events: Vec<SseEvent>,
280}
281
282impl SseStream {
283 pub fn from_response(response: &ResponseSnapshot) -> Result<Self, String> {
285 let body = response
286 .text()
287 .map_err(|e| format!("Failed to read response body: {}", e))?;
288
289 let events = Self::parse_events(&body);
290
291 Ok(Self { body, events })
292 }
293
294 fn parse_events(body: &str) -> Vec<SseEvent> {
295 let mut events = Vec::new();
296 let lines: Vec<&str> = body.lines().collect();
297 let mut i = 0;
298
299 while i < lines.len() {
300 if lines[i].starts_with("data:") {
301 let data = lines[i].trim_start_matches("data:").trim().to_string();
302 events.push(SseEvent { data });
303 } else if lines[i].starts_with("data") {
304 let data = lines[i].trim_start_matches("data").trim().to_string();
305 if !data.is_empty() || lines[i].len() == 4 {
306 events.push(SseEvent { data });
307 }
308 }
309 i += 1;
310 }
311
312 events
313 }
314
315 pub fn events(&self) -> &[SseEvent] {
317 &self.events
318 }
319
320 pub fn body(&self) -> &str {
322 &self.body
323 }
324
325 pub fn events_as_json(&self) -> Result<Vec<Value>, String> {
327 self.events
328 .iter()
329 .map(|event| event.as_json())
330 .collect::<Result<Vec<_>, _>>()
331 }
332}
333
334#[derive(Debug, Clone)]
336pub struct SseEvent {
337 pub data: String,
339}
340
341impl SseEvent {
342 pub fn as_json(&self) -> Result<Value, String> {
344 serde_json::from_str(&self.data).map_err(|e| format!("Failed to parse JSON: {}", e))
345 }
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 #[test]
353 fn sse_stream_parses_multiple_events() {
354 let mut headers = HashMap::new();
355 headers.insert("content-type".to_string(), "text/event-stream".to_string());
356
357 let snapshot = ResponseSnapshot {
358 status: 200,
359 headers,
360 body: b"data: {\"id\": 1}\n\ndata: \"hello\"\n\n".to_vec(),
361 };
362
363 let stream = SseStream::from_response(&snapshot).expect("stream");
364 assert_eq!(stream.events().len(), 2);
365 assert_eq!(stream.events()[0].as_json().unwrap()["id"], serde_json::json!(1));
366 assert_eq!(stream.events()[1].data, "\"hello\"");
367 assert_eq!(stream.events_as_json().unwrap().len(), 2);
368 }
369
370 #[test]
371 fn sse_event_reports_invalid_json() {
372 let event = SseEvent {
373 data: "not-json".to_string(),
374 };
375 assert!(event.as_json().is_err());
376 }
377}