spikard 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -674
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +13 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +405 -405
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -13
  11. data/lib/spikard/handler_wrapper.rb +113 -113
  12. data/lib/spikard/provide.rb +214 -214
  13. data/lib/spikard/response.rb +173 -173
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -44
  17. data/lib/spikard/testing.rb +256 -256
  18. data/lib/spikard/upload_file.rb +131 -131
  19. data/lib/spikard/version.rb +5 -5
  20. data/lib/spikard/websocket.rb +59 -59
  21. data/lib/spikard.rb +43 -43
  22. data/sig/spikard.rbs +366 -366
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -63
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -132
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -752
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -194
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -246
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -401
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -238
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -24
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -292
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -616
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -305
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -248
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -351
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -454
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -383
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -280
  39. data/vendor/crates/spikard-core/Cargo.toml +40 -40
  40. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
  41. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
  42. data/vendor/crates/spikard-core/src/debug.rs +127 -127
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -702
  44. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
  45. data/vendor/crates/spikard-core/src/di/error.rs +118 -118
  46. data/vendor/crates/spikard-core/src/di/factory.rs +534 -534
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -506
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -405
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -281
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -69
  52. data/vendor/crates/spikard-core/src/http.rs +415 -415
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -1186
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -389
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -2525
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -344
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -1154
  59. data/vendor/crates/spikard-core/src/router.rs +510 -510
  60. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
  61. data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
  62. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +696 -688
  63. data/vendor/crates/spikard-core/src/validation/mod.rs +457 -457
  64. data/vendor/crates/spikard-http/Cargo.toml +62 -64
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -148
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -92
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -296
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -1860
  69. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
  70. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
  71. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
  72. data/vendor/crates/spikard-http/src/cors.rs +1005 -1005
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -128
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -1668
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -901
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +838 -830
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -290
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -534
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -230
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -1193
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +560 -540
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -912
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -513
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +768 -735
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -535
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -1363
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -665
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -793
  90. data/vendor/crates/spikard-http/src/response.rs +720 -720
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -1650
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -234
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1593 -1502
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +789 -770
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +629 -599
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -1409
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -52
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +64 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +311 -283
  100. data/vendor/crates/spikard-http/src/testing.rs +406 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1404 -1375
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -832
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -309
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -26
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -192
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -5
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -1093
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -656
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -314
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -620
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -663
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -48
  113. data/vendor/crates/spikard-rb/build.rs +199 -199
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -5
  116. data/vendor/crates/spikard-rb/src/config/server_config.rs +285 -285
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -554
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -100
  119. data/vendor/crates/spikard-rb/src/di/mod.rs +375 -375
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -618
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -3
  122. data/vendor/crates/spikard-rb/src/lib.rs +1806 -1810
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -275
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -5
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +442 -447
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -5
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -324
  128. data/vendor/crates/spikard-rb/src/server.rs +305 -308
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/testing/client.rs +538 -551
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -7
  132. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +608 -635
  134. data/vendor/crates/spikard-rb/src/websocket.rs +377 -374
  135. metadata +15 -1
@@ -1,377 +1,406 @@
1
- use axum::body::Body;
2
- use axum::http::Request as AxumRequest;
3
- use axum_test::{TestResponse as AxumTestResponse, TestServer, TestWebSocket, WsMessage};
4
-
5
- pub mod multipart;
6
- pub use multipart::{MultipartFilePart, build_multipart_body};
7
-
8
- pub mod form;
9
-
10
- pub mod test_client;
11
- pub use test_client::TestClient;
12
-
13
- use brotli::Decompressor;
14
- use flate2::read::GzDecoder;
15
- pub use form::encode_urlencoded_body;
16
- use http_body_util::BodyExt;
17
- use serde_json::Value;
18
- use std::collections::HashMap;
19
- use std::io::{Cursor, Read};
20
-
21
- /// Snapshot of an Axum response used by higher-level language bindings.
22
- #[derive(Debug, Clone)]
23
- pub struct ResponseSnapshot {
24
- /// HTTP status code.
25
- pub status: u16,
26
- /// Response headers (lowercase keys for predictable lookups).
27
- pub headers: HashMap<String, String>,
28
- /// Response body bytes (decoded for supported encodings).
29
- pub body: Vec<u8>,
30
- }
31
-
32
- impl ResponseSnapshot {
33
- /// Return response body as UTF-8 string.
34
- pub fn text(&self) -> Result<String, std::string::FromUtf8Error> {
35
- String::from_utf8(self.body.clone())
36
- }
37
-
38
- /// Parse response body as JSON.
39
- pub fn json(&self) -> Result<Value, serde_json::Error> {
40
- serde_json::from_slice(&self.body)
41
- }
42
-
43
- /// Lookup header by case-insensitive name.
44
- 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
- /// Possible errors while converting an Axum response into a snapshot.
50
- #[derive(Debug)]
51
- pub enum SnapshotError {
52
- /// Response header could not be decoded to UTF-8.
53
- InvalidHeader(String),
54
- /// Body decompression failed.
55
- Decompression(String),
56
- }
57
-
58
- impl 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
-
67
- impl std::error::Error for SnapshotError {}
68
-
69
- /// Execute an HTTP request against an Axum [`TestServer`] by rehydrating it
70
- /// into the server's own [`axum_test::TestRequest`] builder.
71
- pub 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
-
100
- /// Convert an `AxumTestResponse` into a reusable [`ResponseSnapshot`].
101
- pub 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
-
122
- fn 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
-
134
- fn 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
-
143
- fn 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
-
152
- /// WebSocket connection wrapper for testing.
153
- ///
154
- /// Provides a simple interface for sending and receiving WebSocket messages
155
- /// during tests without needing a real network connection.
156
- pub struct WebSocketConnection {
157
- inner: TestWebSocket,
158
- }
159
-
160
- impl WebSocketConnection {
161
- /// Create a new WebSocket connection from an axum-test TestWebSocket.
162
- pub fn new(inner: TestWebSocket) -> Self {
163
- Self { inner }
164
- }
165
-
166
- /// Send a text message over the WebSocket.
167
- pub async fn send_text(&mut self, text: impl std::fmt::Display) {
168
- self.inner.send_text(text).await;
169
- }
170
-
171
- /// Send a JSON message over the WebSocket.
172
- pub async fn send_json<T: serde::Serialize>(&mut self, value: &T) {
173
- self.inner.send_json(value).await;
174
- }
175
-
176
- /// Send a raw WebSocket message.
177
- pub async fn send_message(&mut self, msg: WsMessage) {
178
- self.inner.send_message(msg).await;
179
- }
180
-
181
- /// Receive the next text message from the WebSocket.
182
- pub async fn receive_text(&mut self) -> String {
183
- self.inner.receive_text().await
184
- }
185
-
186
- /// Receive and parse a JSON message from the WebSocket.
187
- pub async fn receive_json<T: serde::de::DeserializeOwned>(&mut self) -> T {
188
- self.inner.receive_json().await
189
- }
190
-
191
- /// Receive raw bytes from the WebSocket.
192
- pub async fn receive_bytes(&mut self) -> bytes::Bytes {
193
- self.inner.receive_bytes().await
194
- }
195
-
196
- /// Receive the next raw message from the WebSocket.
197
- 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
- /// Close the WebSocket connection.
203
- pub async fn close(self) {
204
- self.inner.close().await;
205
- }
206
- }
207
-
208
- /// A WebSocket message that can be text or binary.
209
- #[derive(Debug, Clone)]
210
- pub enum WebSocketMessage {
211
- /// A text message.
212
- Text(String),
213
- /// A binary message.
214
- Binary(Vec<u8>),
215
- /// A close message.
216
- Close(Option<String>),
217
- /// A ping message.
218
- Ping(Vec<u8>),
219
- /// A pong message.
220
- Pong(Vec<u8>),
221
- }
222
-
223
- impl 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
- /// Get the message as text, if it's a text message.
236
- pub fn as_text(&self) -> Option<&str> {
237
- match self {
238
- WebSocketMessage::Text(text) => Some(text),
239
- _ => None,
240
- }
241
- }
242
-
243
- /// Get the message as JSON, if it's a text message containing JSON.
244
- 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
- /// Get the message as binary, if it's a binary message.
254
- pub fn as_binary(&self) -> Option<&[u8]> {
255
- match self {
256
- WebSocketMessage::Binary(data) => Some(data),
257
- _ => None,
258
- }
259
- }
260
-
261
- /// Check if this is a close message.
262
- pub fn is_close(&self) -> bool {
263
- matches!(self, WebSocketMessage::Close(_))
264
- }
265
- }
266
-
267
- /// Connect to a WebSocket endpoint on the test server.
268
- pub 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
- /// Server-Sent Events (SSE) stream for testing.
274
- ///
275
- /// Wraps a response body and provides methods to parse SSE events.
276
- #[derive(Debug)]
277
- pub struct SseStream {
278
- body: String,
279
- events: Vec<SseEvent>,
280
- }
281
-
282
- impl SseStream {
283
- /// Create a new SSE stream from a response.
284
- 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
- /// Get all events from the stream.
316
- pub fn events(&self) -> &[SseEvent] {
317
- &self.events
318
- }
319
-
320
- /// Get the raw body of the SSE response.
321
- pub fn body(&self) -> &str {
322
- &self.body
323
- }
324
-
325
- /// Get events as JSON values.
326
- 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
- /// A single Server-Sent Event.
335
- #[derive(Debug, Clone)]
336
- pub struct SseEvent {
337
- /// The data field of the event.
338
- pub data: String,
339
- }
340
-
341
- impl SseEvent {
342
- /// Parse the event data as JSON.
343
- 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)]
349
- mod 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
- }
1
+ use axum::body::Body;
2
+ use axum::http::Request as AxumRequest;
3
+ use axum_test::{TestResponse as AxumTestResponse, TestServer, TestWebSocket, WsMessage};
4
+
5
+ pub mod multipart;
6
+ pub use multipart::{MultipartFilePart, build_multipart_body};
7
+
8
+ pub mod form;
9
+
10
+ pub mod test_client;
11
+ pub use test_client::TestClient;
12
+
13
+ use brotli::Decompressor;
14
+ use flate2::read::GzDecoder;
15
+ pub use form::encode_urlencoded_body;
16
+ use http_body_util::BodyExt;
17
+ use serde_json::Value;
18
+ use std::collections::HashMap;
19
+ use std::io::{Cursor, Read};
20
+
21
+ /// Snapshot of an Axum response used by higher-level language bindings.
22
+ #[derive(Debug, Clone)]
23
+ pub struct ResponseSnapshot {
24
+ /// HTTP status code.
25
+ pub status: u16,
26
+ /// Response headers (lowercase keys for predictable lookups).
27
+ pub headers: HashMap<String, String>,
28
+ /// Response body bytes (decoded for supported encodings).
29
+ pub body: Vec<u8>,
30
+ }
31
+
32
+ impl ResponseSnapshot {
33
+ /// Return response body as UTF-8 string.
34
+ pub fn text(&self) -> Result<String, std::string::FromUtf8Error> {
35
+ String::from_utf8(self.body.clone())
36
+ }
37
+
38
+ /// Parse response body as JSON.
39
+ pub fn json(&self) -> Result<Value, serde_json::Error> {
40
+ serde_json::from_slice(&self.body)
41
+ }
42
+
43
+ /// Lookup header by case-insensitive name.
44
+ 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
+ /// Possible errors while converting an Axum response into a snapshot.
50
+ #[derive(Debug)]
51
+ pub enum SnapshotError {
52
+ /// Response header could not be decoded to UTF-8.
53
+ InvalidHeader(String),
54
+ /// Body decompression failed.
55
+ Decompression(String),
56
+ }
57
+
58
+ impl 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
+
67
+ impl std::error::Error for SnapshotError {}
68
+
69
+ /// Execute an HTTP request against an Axum [`TestServer`] by rehydrating it
70
+ /// into the server's own [`axum_test::TestRequest`] builder.
71
+ pub 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
+
100
+ /// Convert an `AxumTestResponse` into a reusable [`ResponseSnapshot`].
101
+ pub 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
+
122
+ /// Convert an Axum response into a reusable [`ResponseSnapshot`].
123
+ pub async fn snapshot_http_response(
124
+ response: axum::response::Response<Body>,
125
+ ) -> Result<ResponseSnapshot, SnapshotError> {
126
+ let (parts, body) = response.into_parts();
127
+ let status = parts.status.as_u16();
128
+
129
+ let mut headers = HashMap::new();
130
+ for (name, value) in parts.headers.iter() {
131
+ let header_value = value
132
+ .to_str()
133
+ .map_err(|e| SnapshotError::InvalidHeader(e.to_string()))?;
134
+ headers.insert(name.to_string().to_ascii_lowercase(), header_value.to_string());
135
+ }
136
+
137
+ let collected = body
138
+ .collect()
139
+ .await
140
+ .map_err(|e| SnapshotError::Decompression(e.to_string()))?;
141
+ let bytes = collected.to_bytes();
142
+ let decoded_body = decode_body(&headers, bytes.to_vec())?;
143
+
144
+ Ok(ResponseSnapshot {
145
+ status,
146
+ headers,
147
+ body: decoded_body,
148
+ })
149
+ }
150
+
151
+ fn decode_body(headers: &HashMap<String, String>, body: Vec<u8>) -> Result<Vec<u8>, SnapshotError> {
152
+ let encoding = headers
153
+ .get("content-encoding")
154
+ .map(|value| value.trim().to_ascii_lowercase());
155
+
156
+ match encoding.as_deref() {
157
+ Some("gzip" | "x-gzip") => decode_gzip(body),
158
+ Some("br") => decode_brotli(body),
159
+ _ => Ok(body),
160
+ }
161
+ }
162
+
163
+ fn decode_gzip(body: Vec<u8>) -> Result<Vec<u8>, SnapshotError> {
164
+ let mut decoder = GzDecoder::new(Cursor::new(body));
165
+ let mut decoded_bytes = Vec::new();
166
+ decoder
167
+ .read_to_end(&mut decoded_bytes)
168
+ .map_err(|e| SnapshotError::Decompression(e.to_string()))?;
169
+ Ok(decoded_bytes)
170
+ }
171
+
172
+ fn decode_brotli(body: Vec<u8>) -> Result<Vec<u8>, SnapshotError> {
173
+ let mut decoder = Decompressor::new(Cursor::new(body), 4096);
174
+ let mut decoded_bytes = Vec::new();
175
+ decoder
176
+ .read_to_end(&mut decoded_bytes)
177
+ .map_err(|e| SnapshotError::Decompression(e.to_string()))?;
178
+ Ok(decoded_bytes)
179
+ }
180
+
181
+ /// WebSocket connection wrapper for testing.
182
+ ///
183
+ /// Provides a simple interface for sending and receiving WebSocket messages
184
+ /// during tests without needing a real network connection.
185
+ pub struct WebSocketConnection {
186
+ inner: TestWebSocket,
187
+ }
188
+
189
+ impl WebSocketConnection {
190
+ /// Create a new WebSocket connection from an axum-test TestWebSocket.
191
+ pub fn new(inner: TestWebSocket) -> Self {
192
+ Self { inner }
193
+ }
194
+
195
+ /// Send a text message over the WebSocket.
196
+ pub async fn send_text(&mut self, text: impl std::fmt::Display) {
197
+ self.inner.send_text(text).await;
198
+ }
199
+
200
+ /// Send a JSON message over the WebSocket.
201
+ pub async fn send_json<T: serde::Serialize>(&mut self, value: &T) {
202
+ self.inner.send_json(value).await;
203
+ }
204
+
205
+ /// Send a raw WebSocket message.
206
+ pub async fn send_message(&mut self, msg: WsMessage) {
207
+ self.inner.send_message(msg).await;
208
+ }
209
+
210
+ /// Receive the next text message from the WebSocket.
211
+ pub async fn receive_text(&mut self) -> String {
212
+ self.inner.receive_text().await
213
+ }
214
+
215
+ /// Receive and parse a JSON message from the WebSocket.
216
+ pub async fn receive_json<T: serde::de::DeserializeOwned>(&mut self) -> T {
217
+ self.inner.receive_json().await
218
+ }
219
+
220
+ /// Receive raw bytes from the WebSocket.
221
+ pub async fn receive_bytes(&mut self) -> bytes::Bytes {
222
+ self.inner.receive_bytes().await
223
+ }
224
+
225
+ /// Receive the next raw message from the WebSocket.
226
+ pub async fn receive_message(&mut self) -> WebSocketMessage {
227
+ let msg = self.inner.receive_message().await;
228
+ WebSocketMessage::from_ws_message(msg)
229
+ }
230
+
231
+ /// Close the WebSocket connection.
232
+ pub async fn close(self) {
233
+ self.inner.close().await;
234
+ }
235
+ }
236
+
237
+ /// A WebSocket message that can be text or binary.
238
+ #[derive(Debug, Clone)]
239
+ pub enum WebSocketMessage {
240
+ /// A text message.
241
+ Text(String),
242
+ /// A binary message.
243
+ Binary(Vec<u8>),
244
+ /// A close message.
245
+ Close(Option<String>),
246
+ /// A ping message.
247
+ Ping(Vec<u8>),
248
+ /// A pong message.
249
+ Pong(Vec<u8>),
250
+ }
251
+
252
+ impl WebSocketMessage {
253
+ fn from_ws_message(msg: WsMessage) -> Self {
254
+ match msg {
255
+ WsMessage::Text(text) => WebSocketMessage::Text(text.to_string()),
256
+ WsMessage::Binary(data) => WebSocketMessage::Binary(data.to_vec()),
257
+ WsMessage::Close(frame) => WebSocketMessage::Close(frame.map(|f| f.reason.to_string())),
258
+ WsMessage::Ping(data) => WebSocketMessage::Ping(data.to_vec()),
259
+ WsMessage::Pong(data) => WebSocketMessage::Pong(data.to_vec()),
260
+ WsMessage::Frame(_) => WebSocketMessage::Close(None),
261
+ }
262
+ }
263
+
264
+ /// Get the message as text, if it's a text message.
265
+ pub fn as_text(&self) -> Option<&str> {
266
+ match self {
267
+ WebSocketMessage::Text(text) => Some(text),
268
+ _ => None,
269
+ }
270
+ }
271
+
272
+ /// Get the message as JSON, if it's a text message containing JSON.
273
+ pub fn as_json(&self) -> Result<Value, String> {
274
+ match self {
275
+ WebSocketMessage::Text(text) => {
276
+ serde_json::from_str(text).map_err(|e| format!("Failed to parse JSON: {}", e))
277
+ }
278
+ _ => Err("Message is not text".to_string()),
279
+ }
280
+ }
281
+
282
+ /// Get the message as binary, if it's a binary message.
283
+ pub fn as_binary(&self) -> Option<&[u8]> {
284
+ match self {
285
+ WebSocketMessage::Binary(data) => Some(data),
286
+ _ => None,
287
+ }
288
+ }
289
+
290
+ /// Check if this is a close message.
291
+ pub fn is_close(&self) -> bool {
292
+ matches!(self, WebSocketMessage::Close(_))
293
+ }
294
+ }
295
+
296
+ /// Connect to a WebSocket endpoint on the test server.
297
+ pub async fn connect_websocket(server: &TestServer, path: &str) -> WebSocketConnection {
298
+ let ws = server.get_websocket(path).await.into_websocket().await;
299
+ WebSocketConnection::new(ws)
300
+ }
301
+
302
+ /// Server-Sent Events (SSE) stream for testing.
303
+ ///
304
+ /// Wraps a response body and provides methods to parse SSE events.
305
+ #[derive(Debug)]
306
+ pub struct SseStream {
307
+ body: String,
308
+ events: Vec<SseEvent>,
309
+ }
310
+
311
+ impl SseStream {
312
+ /// Create a new SSE stream from a response.
313
+ pub fn from_response(response: &ResponseSnapshot) -> Result<Self, String> {
314
+ let body = response
315
+ .text()
316
+ .map_err(|e| format!("Failed to read response body: {}", e))?;
317
+
318
+ let events = Self::parse_events(&body);
319
+
320
+ Ok(Self { body, events })
321
+ }
322
+
323
+ fn parse_events(body: &str) -> Vec<SseEvent> {
324
+ let mut events = Vec::new();
325
+ let lines: Vec<&str> = body.lines().collect();
326
+ let mut i = 0;
327
+
328
+ while i < lines.len() {
329
+ if lines[i].starts_with("data:") {
330
+ let data = lines[i].trim_start_matches("data:").trim().to_string();
331
+ events.push(SseEvent { data });
332
+ } else if lines[i].starts_with("data") {
333
+ let data = lines[i].trim_start_matches("data").trim().to_string();
334
+ if !data.is_empty() || lines[i].len() == 4 {
335
+ events.push(SseEvent { data });
336
+ }
337
+ }
338
+ i += 1;
339
+ }
340
+
341
+ events
342
+ }
343
+
344
+ /// Get all events from the stream.
345
+ pub fn events(&self) -> &[SseEvent] {
346
+ &self.events
347
+ }
348
+
349
+ /// Get the raw body of the SSE response.
350
+ pub fn body(&self) -> &str {
351
+ &self.body
352
+ }
353
+
354
+ /// Get events as JSON values.
355
+ pub fn events_as_json(&self) -> Result<Vec<Value>, String> {
356
+ self.events
357
+ .iter()
358
+ .map(|event| event.as_json())
359
+ .collect::<Result<Vec<_>, _>>()
360
+ }
361
+ }
362
+
363
+ /// A single Server-Sent Event.
364
+ #[derive(Debug, Clone)]
365
+ pub struct SseEvent {
366
+ /// The data field of the event.
367
+ pub data: String,
368
+ }
369
+
370
+ impl SseEvent {
371
+ /// Parse the event data as JSON.
372
+ pub fn as_json(&self) -> Result<Value, String> {
373
+ serde_json::from_str(&self.data).map_err(|e| format!("Failed to parse JSON: {}", e))
374
+ }
375
+ }
376
+
377
+ #[cfg(test)]
378
+ mod tests {
379
+ use super::*;
380
+
381
+ #[test]
382
+ fn sse_stream_parses_multiple_events() {
383
+ let mut headers = HashMap::new();
384
+ headers.insert("content-type".to_string(), "text/event-stream".to_string());
385
+
386
+ let snapshot = ResponseSnapshot {
387
+ status: 200,
388
+ headers,
389
+ body: b"data: {\"id\": 1}\n\ndata: \"hello\"\n\n".to_vec(),
390
+ };
391
+
392
+ let stream = SseStream::from_response(&snapshot).expect("stream");
393
+ assert_eq!(stream.events().len(), 2);
394
+ assert_eq!(stream.events()[0].as_json().unwrap()["id"], serde_json::json!(1));
395
+ assert_eq!(stream.events()[1].data, "\"hello\"");
396
+ assert_eq!(stream.events_as_json().unwrap().len(), 2);
397
+ }
398
+
399
+ #[test]
400
+ fn sse_event_reports_invalid_json() {
401
+ let event = SseEvent {
402
+ data: "not-json".to_string(),
403
+ };
404
+ assert!(event.as_json().is_err());
405
+ }
406
+ }