spikard 0.4.0-x86_64-linux

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 (138) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +1 -0
  3. data/README.md +659 -0
  4. data/ext/spikard_rb/Cargo.toml +17 -0
  5. data/ext/spikard_rb/extconf.rb +10 -0
  6. data/ext/spikard_rb/src/lib.rs +6 -0
  7. data/lib/spikard/app.rb +405 -0
  8. data/lib/spikard/background.rb +27 -0
  9. data/lib/spikard/config.rb +396 -0
  10. data/lib/spikard/converters.rb +13 -0
  11. data/lib/spikard/handler_wrapper.rb +113 -0
  12. data/lib/spikard/provide.rb +214 -0
  13. data/lib/spikard/response.rb +173 -0
  14. data/lib/spikard/schema.rb +243 -0
  15. data/lib/spikard/sse.rb +111 -0
  16. data/lib/spikard/streaming_response.rb +44 -0
  17. data/lib/spikard/testing.rb +221 -0
  18. data/lib/spikard/upload_file.rb +131 -0
  19. data/lib/spikard/version.rb +5 -0
  20. data/lib/spikard/websocket.rb +59 -0
  21. data/lib/spikard.rb +43 -0
  22. data/sig/spikard.rbs +366 -0
  23. data/vendor/bundle/ruby/3.4.0/gems/diff-lcs-1.6.2/mise.toml +5 -0
  24. data/vendor/bundle/ruby/3.4.0/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +2 -0
  25. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  26. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +139 -0
  27. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +561 -0
  28. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  29. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  30. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +403 -0
  31. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +274 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lib.rs +25 -0
  33. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +298 -0
  34. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +637 -0
  35. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +309 -0
  36. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  37. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +355 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +502 -0
  39. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +389 -0
  40. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +413 -0
  41. data/vendor/crates/spikard-core/Cargo.toml +40 -0
  42. data/vendor/crates/spikard-core/src/bindings/mod.rs +3 -0
  43. data/vendor/crates/spikard-core/src/bindings/response.rs +133 -0
  44. data/vendor/crates/spikard-core/src/debug.rs +63 -0
  45. data/vendor/crates/spikard-core/src/di/container.rs +726 -0
  46. data/vendor/crates/spikard-core/src/di/dependency.rs +273 -0
  47. data/vendor/crates/spikard-core/src/di/error.rs +118 -0
  48. data/vendor/crates/spikard-core/src/di/factory.rs +538 -0
  49. data/vendor/crates/spikard-core/src/di/graph.rs +545 -0
  50. data/vendor/crates/spikard-core/src/di/mod.rs +192 -0
  51. data/vendor/crates/spikard-core/src/di/resolved.rs +411 -0
  52. data/vendor/crates/spikard-core/src/di/value.rs +283 -0
  53. data/vendor/crates/spikard-core/src/errors.rs +39 -0
  54. data/vendor/crates/spikard-core/src/http.rs +153 -0
  55. data/vendor/crates/spikard-core/src/lib.rs +29 -0
  56. data/vendor/crates/spikard-core/src/lifecycle.rs +422 -0
  57. data/vendor/crates/spikard-core/src/metadata.rs +397 -0
  58. data/vendor/crates/spikard-core/src/parameters.rs +723 -0
  59. data/vendor/crates/spikard-core/src/problem.rs +310 -0
  60. data/vendor/crates/spikard-core/src/request_data.rs +189 -0
  61. data/vendor/crates/spikard-core/src/router.rs +249 -0
  62. data/vendor/crates/spikard-core/src/schema_registry.rs +183 -0
  63. data/vendor/crates/spikard-core/src/type_hints.rs +304 -0
  64. data/vendor/crates/spikard-core/src/validation/error_mapper.rs +689 -0
  65. data/vendor/crates/spikard-core/src/validation/mod.rs +459 -0
  66. data/vendor/crates/spikard-http/Cargo.toml +58 -0
  67. data/vendor/crates/spikard-http/examples/sse-notifications.rs +147 -0
  68. data/vendor/crates/spikard-http/examples/websocket-chat.rs +91 -0
  69. data/vendor/crates/spikard-http/src/auth.rs +247 -0
  70. data/vendor/crates/spikard-http/src/background.rs +1562 -0
  71. data/vendor/crates/spikard-http/src/bindings/mod.rs +3 -0
  72. data/vendor/crates/spikard-http/src/bindings/response.rs +1 -0
  73. data/vendor/crates/spikard-http/src/body_metadata.rs +8 -0
  74. data/vendor/crates/spikard-http/src/cors.rs +490 -0
  75. data/vendor/crates/spikard-http/src/debug.rs +63 -0
  76. data/vendor/crates/spikard-http/src/di_handler.rs +1878 -0
  77. data/vendor/crates/spikard-http/src/handler_response.rs +532 -0
  78. data/vendor/crates/spikard-http/src/handler_trait.rs +861 -0
  79. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +284 -0
  80. data/vendor/crates/spikard-http/src/lib.rs +524 -0
  81. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +149 -0
  82. data/vendor/crates/spikard-http/src/lifecycle.rs +428 -0
  83. data/vendor/crates/spikard-http/src/middleware/mod.rs +285 -0
  84. data/vendor/crates/spikard-http/src/middleware/multipart.rs +930 -0
  85. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +541 -0
  86. data/vendor/crates/spikard-http/src/middleware/validation.rs +287 -0
  87. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -0
  88. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -0
  89. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +867 -0
  90. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +678 -0
  91. data/vendor/crates/spikard-http/src/query_parser.rs +369 -0
  92. data/vendor/crates/spikard-http/src/response.rs +399 -0
  93. data/vendor/crates/spikard-http/src/server/handler.rs +1557 -0
  94. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +98 -0
  95. data/vendor/crates/spikard-http/src/server/mod.rs +806 -0
  96. data/vendor/crates/spikard-http/src/server/request_extraction.rs +630 -0
  97. data/vendor/crates/spikard-http/src/server/routing_factory.rs +497 -0
  98. data/vendor/crates/spikard-http/src/sse.rs +961 -0
  99. data/vendor/crates/spikard-http/src/testing/form.rs +14 -0
  100. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -0
  101. data/vendor/crates/spikard-http/src/testing/test_client.rs +285 -0
  102. data/vendor/crates/spikard-http/src/testing.rs +377 -0
  103. data/vendor/crates/spikard-http/src/websocket.rs +831 -0
  104. data/vendor/crates/spikard-http/tests/background_behavior.rs +918 -0
  105. data/vendor/crates/spikard-http/tests/common/handlers.rs +308 -0
  106. data/vendor/crates/spikard-http/tests/common/mod.rs +21 -0
  107. data/vendor/crates/spikard-http/tests/di_integration.rs +202 -0
  108. data/vendor/crates/spikard-http/tests/doc_snippets.rs +4 -0
  109. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1135 -0
  110. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +688 -0
  111. data/vendor/crates/spikard-http/tests/server_config_builder.rs +324 -0
  112. data/vendor/crates/spikard-http/tests/sse_behavior.rs +728 -0
  113. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +724 -0
  114. data/vendor/crates/spikard-rb/Cargo.toml +43 -0
  115. data/vendor/crates/spikard-rb/build.rs +199 -0
  116. data/vendor/crates/spikard-rb/src/background.rs +63 -0
  117. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  118. data/vendor/crates/spikard-rb/src/config/server_config.rs +283 -0
  119. data/vendor/crates/spikard-rb/src/conversion.rs +459 -0
  120. data/vendor/crates/spikard-rb/src/di/builder.rs +105 -0
  121. data/vendor/crates/spikard-rb/src/di/mod.rs +413 -0
  122. data/vendor/crates/spikard-rb/src/handler.rs +612 -0
  123. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  124. data/vendor/crates/spikard-rb/src/lib.rs +1857 -0
  125. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -0
  126. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +427 -0
  128. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  129. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +326 -0
  130. data/vendor/crates/spikard-rb/src/server.rs +283 -0
  131. data/vendor/crates/spikard-rb/src/sse.rs +231 -0
  132. data/vendor/crates/spikard-rb/src/testing/client.rs +404 -0
  133. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  134. data/vendor/crates/spikard-rb/src/testing/sse.rs +143 -0
  135. data/vendor/crates/spikard-rb/src/testing/websocket.rs +221 -0
  136. data/vendor/crates/spikard-rb/src/websocket.rs +233 -0
  137. data/vendor/crates/spikard-rb/tests/magnus_ffi_tests.rs +14 -0
  138. metadata +213 -0
@@ -0,0 +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
+ }