spikard 0.3.2 → 0.3.4
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.
- checksums.yaml +4 -4
- data/LICENSE +1 -1
- data/README.md +659 -659
- data/ext/spikard_rb/Cargo.toml +17 -17
- data/ext/spikard_rb/extconf.rb +10 -10
- data/ext/spikard_rb/src/lib.rs +6 -6
- data/lib/spikard/app.rb +386 -386
- data/lib/spikard/background.rb +27 -27
- data/lib/spikard/config.rb +396 -396
- data/lib/spikard/converters.rb +13 -13
- data/lib/spikard/handler_wrapper.rb +113 -113
- data/lib/spikard/provide.rb +214 -214
- data/lib/spikard/response.rb +173 -173
- data/lib/spikard/schema.rb +243 -243
- data/lib/spikard/sse.rb +111 -111
- data/lib/spikard/streaming_response.rb +44 -44
- data/lib/spikard/testing.rb +221 -221
- data/lib/spikard/upload_file.rb +131 -131
- data/lib/spikard/version.rb +5 -5
- data/lib/spikard/websocket.rb +59 -59
- data/lib/spikard.rb +43 -43
- data/sig/spikard.rbs +360 -360
- data/vendor/crates/spikard-core/Cargo.toml +40 -40
- data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -3
- data/vendor/crates/spikard-core/src/bindings/response.rs +133 -133
- data/vendor/crates/spikard-core/src/debug.rs +63 -63
- data/vendor/crates/spikard-core/src/di/container.rs +726 -726
- data/vendor/crates/spikard-core/src/di/dependency.rs +273 -273
- data/vendor/crates/spikard-core/src/di/error.rs +118 -118
- data/vendor/crates/spikard-core/src/di/factory.rs +538 -538
- data/vendor/crates/spikard-core/src/di/graph.rs +545 -545
- data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
- data/vendor/crates/spikard-core/src/di/resolved.rs +411 -411
- data/vendor/crates/spikard-core/src/di/value.rs +283 -283
- data/vendor/crates/spikard-core/src/errors.rs +39 -39
- data/vendor/crates/spikard-core/src/http.rs +153 -153
- data/vendor/crates/spikard-core/src/lib.rs +29 -29
- data/vendor/crates/spikard-core/src/lifecycle.rs +422 -422
- data/vendor/crates/spikard-core/src/parameters.rs +722 -722
- data/vendor/crates/spikard-core/src/problem.rs +310 -310
- data/vendor/crates/spikard-core/src/request_data.rs +189 -189
- data/vendor/crates/spikard-core/src/router.rs +249 -249
- data/vendor/crates/spikard-core/src/schema_registry.rs +183 -183
- data/vendor/crates/spikard-core/src/type_hints.rs +304 -304
- data/vendor/crates/spikard-core/src/validation.rs +699 -699
- data/vendor/crates/spikard-http/Cargo.toml +58 -58
- data/vendor/crates/spikard-http/src/auth.rs +247 -247
- data/vendor/crates/spikard-http/src/background.rs +249 -249
- data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -3
- data/vendor/crates/spikard-http/src/bindings/response.rs +1 -1
- data/vendor/crates/spikard-http/src/body_metadata.rs +8 -8
- data/vendor/crates/spikard-http/src/cors.rs +490 -490
- data/vendor/crates/spikard-http/src/debug.rs +63 -63
- data/vendor/crates/spikard-http/src/di_handler.rs +423 -423
- data/vendor/crates/spikard-http/src/handler_response.rs +190 -190
- data/vendor/crates/spikard-http/src/handler_trait.rs +228 -228
- data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -284
- data/vendor/crates/spikard-http/src/lib.rs +529 -529
- data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -149
- data/vendor/crates/spikard-http/src/lifecycle.rs +428 -428
- data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -285
- data/vendor/crates/spikard-http/src/middleware/multipart.rs +86 -86
- data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +147 -147
- data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -287
- data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
- data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +190 -190
- data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +308 -308
- data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +195 -195
- data/vendor/crates/spikard-http/src/parameters.rs +1 -1
- data/vendor/crates/spikard-http/src/problem.rs +1 -1
- data/vendor/crates/spikard-http/src/query_parser.rs +369 -369
- data/vendor/crates/spikard-http/src/response.rs +399 -399
- data/vendor/crates/spikard-http/src/router.rs +1 -1
- data/vendor/crates/spikard-http/src/schema_registry.rs +1 -1
- data/vendor/crates/spikard-http/src/server/handler.rs +87 -87
- data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -98
- data/vendor/crates/spikard-http/src/server/mod.rs +805 -805
- data/vendor/crates/spikard-http/src/server/request_extraction.rs +119 -119
- data/vendor/crates/spikard-http/src/sse.rs +447 -447
- data/vendor/crates/spikard-http/src/testing/form.rs +14 -14
- data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
- data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -285
- data/vendor/crates/spikard-http/src/testing.rs +377 -377
- data/vendor/crates/spikard-http/src/type_hints.rs +1 -1
- data/vendor/crates/spikard-http/src/validation.rs +1 -1
- data/vendor/crates/spikard-http/src/websocket.rs +324 -324
- data/vendor/crates/spikard-rb/Cargo.toml +42 -42
- data/vendor/crates/spikard-rb/build.rs +8 -8
- data/vendor/crates/spikard-rb/src/background.rs +63 -63
- data/vendor/crates/spikard-rb/src/config.rs +294 -294
- data/vendor/crates/spikard-rb/src/conversion.rs +453 -453
- data/vendor/crates/spikard-rb/src/di.rs +409 -409
- data/vendor/crates/spikard-rb/src/handler.rs +625 -625
- data/vendor/crates/spikard-rb/src/lib.rs +2771 -2771
- data/vendor/crates/spikard-rb/src/lifecycle.rs +274 -274
- data/vendor/crates/spikard-rb/src/server.rs +283 -283
- data/vendor/crates/spikard-rb/src/sse.rs +231 -231
- data/vendor/crates/spikard-rb/src/test_client.rs +404 -404
- data/vendor/crates/spikard-rb/src/test_sse.rs +143 -143
- data/vendor/crates/spikard-rb/src/test_websocket.rs +221 -221
- data/vendor/crates/spikard-rb/src/websocket.rs +233 -233
- data/vendor/spikard-core/Cargo.toml +40 -40
- data/vendor/spikard-core/src/bindings/mod.rs +3 -3
- data/vendor/spikard-core/src/bindings/response.rs +133 -133
- data/vendor/spikard-core/src/debug.rs +63 -63
- data/vendor/spikard-core/src/di/container.rs +726 -726
- data/vendor/spikard-core/src/di/dependency.rs +273 -273
- data/vendor/spikard-core/src/di/error.rs +118 -118
- data/vendor/spikard-core/src/di/factory.rs +538 -538
- data/vendor/spikard-core/src/di/graph.rs +545 -545
- data/vendor/spikard-core/src/di/mod.rs +192 -192
- data/vendor/spikard-core/src/di/resolved.rs +411 -411
- data/vendor/spikard-core/src/di/value.rs +283 -283
- data/vendor/spikard-core/src/http.rs +153 -153
- data/vendor/spikard-core/src/lib.rs +28 -28
- data/vendor/spikard-core/src/lifecycle.rs +422 -422
- data/vendor/spikard-core/src/parameters.rs +719 -719
- data/vendor/spikard-core/src/problem.rs +310 -310
- data/vendor/spikard-core/src/request_data.rs +189 -189
- data/vendor/spikard-core/src/router.rs +249 -249
- data/vendor/spikard-core/src/schema_registry.rs +183 -183
- data/vendor/spikard-core/src/type_hints.rs +304 -304
- data/vendor/spikard-core/src/validation.rs +699 -699
- data/vendor/spikard-http/Cargo.toml +58 -58
- data/vendor/spikard-http/src/auth.rs +247 -247
- data/vendor/spikard-http/src/background.rs +249 -249
- data/vendor/spikard-http/src/bindings/mod.rs +3 -3
- data/vendor/spikard-http/src/bindings/response.rs +1 -1
- data/vendor/spikard-http/src/body_metadata.rs +8 -8
- data/vendor/spikard-http/src/cors.rs +490 -490
- data/vendor/spikard-http/src/debug.rs +63 -63
- data/vendor/spikard-http/src/di_handler.rs +423 -423
- data/vendor/spikard-http/src/handler_response.rs +190 -190
- data/vendor/spikard-http/src/handler_trait.rs +228 -228
- data/vendor/spikard-http/src/handler_trait_tests.rs +284 -284
- data/vendor/spikard-http/src/lib.rs +529 -529
- data/vendor/spikard-http/src/lifecycle/adapter.rs +149 -149
- data/vendor/spikard-http/src/lifecycle.rs +428 -428
- data/vendor/spikard-http/src/middleware/mod.rs +285 -285
- data/vendor/spikard-http/src/middleware/multipart.rs +86 -86
- data/vendor/spikard-http/src/middleware/urlencoded.rs +147 -147
- data/vendor/spikard-http/src/middleware/validation.rs +287 -287
- data/vendor/spikard-http/src/openapi/mod.rs +309 -309
- data/vendor/spikard-http/src/openapi/parameter_extraction.rs +190 -190
- data/vendor/spikard-http/src/openapi/schema_conversion.rs +308 -308
- data/vendor/spikard-http/src/openapi/spec_generation.rs +195 -195
- data/vendor/spikard-http/src/parameters.rs +1 -1
- data/vendor/spikard-http/src/problem.rs +1 -1
- data/vendor/spikard-http/src/query_parser.rs +369 -369
- data/vendor/spikard-http/src/response.rs +399 -399
- data/vendor/spikard-http/src/router.rs +1 -1
- data/vendor/spikard-http/src/schema_registry.rs +1 -1
- data/vendor/spikard-http/src/server/handler.rs +80 -80
- data/vendor/spikard-http/src/server/lifecycle_execution.rs +98 -98
- data/vendor/spikard-http/src/server/mod.rs +805 -805
- data/vendor/spikard-http/src/server/request_extraction.rs +119 -119
- data/vendor/spikard-http/src/sse.rs +447 -447
- data/vendor/spikard-http/src/testing/form.rs +14 -14
- data/vendor/spikard-http/src/testing/multipart.rs +60 -60
- data/vendor/spikard-http/src/testing/test_client.rs +285 -285
- data/vendor/spikard-http/src/testing.rs +377 -377
- data/vendor/spikard-http/src/type_hints.rs +1 -1
- data/vendor/spikard-http/src/validation.rs +1 -1
- data/vendor/spikard-http/src/websocket.rs +324 -324
- data/vendor/spikard-rb/Cargo.toml +42 -42
- data/vendor/spikard-rb/build.rs +8 -8
- data/vendor/spikard-rb/src/background.rs +63 -63
- data/vendor/spikard-rb/src/config.rs +294 -294
- data/vendor/spikard-rb/src/conversion.rs +392 -392
- data/vendor/spikard-rb/src/di.rs +409 -409
- data/vendor/spikard-rb/src/handler.rs +534 -534
- data/vendor/spikard-rb/src/lib.rs +2020 -2020
- data/vendor/spikard-rb/src/lifecycle.rs +267 -267
- data/vendor/spikard-rb/src/server.rs +283 -283
- data/vendor/spikard-rb/src/sse.rs +231 -231
- data/vendor/spikard-rb/src/test_client.rs +404 -404
- data/vendor/spikard-rb/src/test_sse.rs +143 -143
- data/vendor/spikard-rb/src/test_websocket.rs +221 -221
- data/vendor/spikard-rb/src/websocket.rs +233 -233
- metadata +1 -1
|
@@ -1,377 +1,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
|
-
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") | Some("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 = Vec::new();
|
|
137
|
-
decoder
|
|
138
|
-
.read_to_end(&mut decoded)
|
|
139
|
-
.map_err(|e| SnapshotError::Decompression(e.to_string()))?;
|
|
140
|
-
Ok(decoded)
|
|
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 = Vec::new();
|
|
146
|
-
decoder
|
|
147
|
-
.read_to_end(&mut decoded)
|
|
148
|
-
.map_err(|e| SnapshotError::Decompression(e.to_string()))?;
|
|
149
|
-
Ok(decoded)
|
|
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
|
+
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") | Some("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 = Vec::new();
|
|
137
|
+
decoder
|
|
138
|
+
.read_to_end(&mut decoded)
|
|
139
|
+
.map_err(|e| SnapshotError::Decompression(e.to_string()))?;
|
|
140
|
+
Ok(decoded)
|
|
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 = Vec::new();
|
|
146
|
+
decoder
|
|
147
|
+
.read_to_end(&mut decoded)
|
|
148
|
+
.map_err(|e| SnapshotError::Decompression(e.to_string()))?;
|
|
149
|
+
Ok(decoded)
|
|
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
|
+
}
|