spikard 0.2.5 → 0.3.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 (103) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +659 -626
  4. data/ext/spikard_rb/Cargo.toml +17 -17
  5. data/ext/spikard_rb/extconf.rb +10 -10
  6. data/ext/spikard_rb/src/lib.rs +6 -6
  7. data/lib/spikard/app.rb +386 -374
  8. data/lib/spikard/background.rb +27 -27
  9. data/lib/spikard/config.rb +396 -396
  10. data/lib/spikard/converters.rb +13 -85
  11. data/lib/spikard/handler_wrapper.rb +113 -116
  12. data/lib/spikard/provide.rb +214 -228
  13. data/lib/spikard/response.rb +173 -109
  14. data/lib/spikard/schema.rb +243 -243
  15. data/lib/spikard/sse.rb +111 -111
  16. data/lib/spikard/streaming_response.rb +44 -21
  17. data/lib/spikard/testing.rb +221 -221
  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 +360 -349
  23. data/vendor/bundle/ruby/3.4.0/gems/rake-compiler-dock-1.10.0/build/buildkitd.toml +2 -0
  24. metadata +5 -85
  25. data/vendor/crates/spikard-core/Cargo.toml +0 -40
  26. data/vendor/crates/spikard-core/src/bindings/mod.rs +0 -3
  27. data/vendor/crates/spikard-core/src/bindings/response.rs +0 -133
  28. data/vendor/crates/spikard-core/src/debug.rs +0 -63
  29. data/vendor/crates/spikard-core/src/di/container.rs +0 -726
  30. data/vendor/crates/spikard-core/src/di/dependency.rs +0 -273
  31. data/vendor/crates/spikard-core/src/di/error.rs +0 -118
  32. data/vendor/crates/spikard-core/src/di/factory.rs +0 -538
  33. data/vendor/crates/spikard-core/src/di/graph.rs +0 -545
  34. data/vendor/crates/spikard-core/src/di/mod.rs +0 -192
  35. data/vendor/crates/spikard-core/src/di/resolved.rs +0 -411
  36. data/vendor/crates/spikard-core/src/di/value.rs +0 -283
  37. data/vendor/crates/spikard-core/src/http.rs +0 -153
  38. data/vendor/crates/spikard-core/src/lib.rs +0 -28
  39. data/vendor/crates/spikard-core/src/lifecycle.rs +0 -422
  40. data/vendor/crates/spikard-core/src/parameters.rs +0 -719
  41. data/vendor/crates/spikard-core/src/problem.rs +0 -310
  42. data/vendor/crates/spikard-core/src/request_data.rs +0 -189
  43. data/vendor/crates/spikard-core/src/router.rs +0 -249
  44. data/vendor/crates/spikard-core/src/schema_registry.rs +0 -183
  45. data/vendor/crates/spikard-core/src/type_hints.rs +0 -304
  46. data/vendor/crates/spikard-core/src/validation.rs +0 -699
  47. data/vendor/crates/spikard-http/Cargo.toml +0 -58
  48. data/vendor/crates/spikard-http/src/auth.rs +0 -247
  49. data/vendor/crates/spikard-http/src/background.rs +0 -249
  50. data/vendor/crates/spikard-http/src/bindings/mod.rs +0 -3
  51. data/vendor/crates/spikard-http/src/bindings/response.rs +0 -1
  52. data/vendor/crates/spikard-http/src/body_metadata.rs +0 -8
  53. data/vendor/crates/spikard-http/src/cors.rs +0 -490
  54. data/vendor/crates/spikard-http/src/debug.rs +0 -63
  55. data/vendor/crates/spikard-http/src/di_handler.rs +0 -423
  56. data/vendor/crates/spikard-http/src/handler_response.rs +0 -190
  57. data/vendor/crates/spikard-http/src/handler_trait.rs +0 -228
  58. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +0 -284
  59. data/vendor/crates/spikard-http/src/lib.rs +0 -529
  60. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +0 -149
  61. data/vendor/crates/spikard-http/src/lifecycle.rs +0 -428
  62. data/vendor/crates/spikard-http/src/middleware/mod.rs +0 -285
  63. data/vendor/crates/spikard-http/src/middleware/multipart.rs +0 -86
  64. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +0 -147
  65. data/vendor/crates/spikard-http/src/middleware/validation.rs +0 -287
  66. data/vendor/crates/spikard-http/src/openapi/mod.rs +0 -309
  67. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +0 -190
  68. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +0 -308
  69. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +0 -195
  70. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  71. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  72. data/vendor/crates/spikard-http/src/query_parser.rs +0 -369
  73. data/vendor/crates/spikard-http/src/response.rs +0 -399
  74. data/vendor/crates/spikard-http/src/router.rs +0 -1
  75. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  76. data/vendor/crates/spikard-http/src/server/handler.rs +0 -80
  77. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +0 -98
  78. data/vendor/crates/spikard-http/src/server/mod.rs +0 -805
  79. data/vendor/crates/spikard-http/src/server/request_extraction.rs +0 -119
  80. data/vendor/crates/spikard-http/src/sse.rs +0 -447
  81. data/vendor/crates/spikard-http/src/testing/form.rs +0 -14
  82. data/vendor/crates/spikard-http/src/testing/multipart.rs +0 -60
  83. data/vendor/crates/spikard-http/src/testing/test_client.rs +0 -285
  84. data/vendor/crates/spikard-http/src/testing.rs +0 -377
  85. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  86. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  87. data/vendor/crates/spikard-http/src/websocket.rs +0 -324
  88. data/vendor/crates/spikard-rb/Cargo.toml +0 -42
  89. data/vendor/crates/spikard-rb/build.rs +0 -8
  90. data/vendor/crates/spikard-rb/src/background.rs +0 -63
  91. data/vendor/crates/spikard-rb/src/config.rs +0 -294
  92. data/vendor/crates/spikard-rb/src/conversion.rs +0 -392
  93. data/vendor/crates/spikard-rb/src/di.rs +0 -409
  94. data/vendor/crates/spikard-rb/src/handler.rs +0 -534
  95. data/vendor/crates/spikard-rb/src/lib.rs +0 -2020
  96. data/vendor/crates/spikard-rb/src/lifecycle.rs +0 -267
  97. data/vendor/crates/spikard-rb/src/server.rs +0 -283
  98. data/vendor/crates/spikard-rb/src/sse.rs +0 -231
  99. data/vendor/crates/spikard-rb/src/test_client.rs +0 -404
  100. data/vendor/crates/spikard-rb/src/test_sse.rs +0 -143
  101. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
  102. data/vendor/crates/spikard-rb/src/websocket.rs +0 -233
  103. /data/vendor/bundle/ruby/{3.3.0 → 3.4.0}/gems/diff-lcs-1.6.2/mise.toml +0 -0
@@ -1,285 +0,0 @@
1
- //! Core test client for Spikard applications
2
- //!
3
- //! This module provides a language-agnostic TestClient that can be wrapped by
4
- //! language bindings (PyO3, napi-rs, magnus) to provide Pythonic, JavaScripty, and
5
- //! Ruby-like APIs respectively.
6
- //!
7
- //! The core client handles all HTTP method dispatch, query params, header management,
8
- //! body encoding (JSON, form-data, multipart), and response snapshot capture.
9
-
10
- use super::{ResponseSnapshot, SnapshotError, snapshot_response};
11
- use axum::http::{HeaderName, HeaderValue, Method};
12
- use axum_test::TestServer;
13
- use bytes::Bytes;
14
- use serde_json::Value;
15
- use std::sync::Arc;
16
- use urlencoding::encode;
17
-
18
- type MultipartPayload = Option<(Vec<(String, String)>, Vec<super::MultipartFilePart>)>;
19
-
20
- /// Core test client for making HTTP requests to a Spikard application.
21
- ///
22
- /// This struct wraps axum-test's TestServer and provides a language-agnostic
23
- /// interface for making HTTP requests, sending WebSocket connections, and
24
- /// handling Server-Sent Events. Language bindings wrap this to provide
25
- /// native API surfaces.
26
- pub struct TestClient {
27
- server: Arc<TestServer>,
28
- }
29
-
30
- impl TestClient {
31
- /// Create a new test client from an Axum router
32
- pub fn from_router(router: axum::Router) -> Result<Self, String> {
33
- let server = TestServer::new(router).map_err(|e| format!("Failed to create test server: {}", e))?;
34
-
35
- Ok(Self {
36
- server: Arc::new(server),
37
- })
38
- }
39
-
40
- /// Get the underlying test server (for WebSocket and SSE connections)
41
- pub fn server(&self) -> &TestServer {
42
- &self.server
43
- }
44
-
45
- /// Make a GET request
46
- pub async fn get(
47
- &self,
48
- path: &str,
49
- query_params: Option<Vec<(String, String)>>,
50
- headers: Option<Vec<(String, String)>>,
51
- ) -> Result<ResponseSnapshot, SnapshotError> {
52
- let full_path = build_full_path(path, query_params.as_deref());
53
- let mut request = self.server.get(&full_path);
54
-
55
- if let Some(headers_vec) = headers {
56
- request = self.add_headers(request, headers_vec)?;
57
- }
58
-
59
- let response = request.await;
60
- snapshot_response(response).await
61
- }
62
-
63
- /// Make a POST request
64
- pub async fn post(
65
- &self,
66
- path: &str,
67
- json: Option<Value>,
68
- form_data: Option<Vec<(String, String)>>,
69
- multipart: MultipartPayload,
70
- query_params: Option<Vec<(String, String)>>,
71
- headers: Option<Vec<(String, String)>>,
72
- ) -> Result<ResponseSnapshot, SnapshotError> {
73
- let full_path = build_full_path(path, query_params.as_deref());
74
- let mut request = self.server.post(&full_path);
75
-
76
- // Apply headers first
77
- if let Some(headers_vec) = headers {
78
- request = self.add_headers(request, headers_vec.clone())?;
79
- }
80
-
81
- // Determine body and content-type
82
- if let Some((form_fields, files)) = multipart {
83
- let (body, boundary) = super::build_multipart_body(&form_fields, &files);
84
- let content_type = format!("multipart/form-data; boundary={}", boundary);
85
- request = request.add_header("content-type", &content_type);
86
- request = request.bytes(Bytes::from(body));
87
- } else if let Some(form_fields) = form_data {
88
- let encoded = super::encode_urlencoded_body(&serde_json::to_value(&form_fields).unwrap_or(Value::Null))
89
- .map_err(|e| SnapshotError::Decompression(format!("Form encoding failed: {}", e)))?;
90
- request = request.add_header("content-type", "application/x-www-form-urlencoded");
91
- request = request.bytes(Bytes::from(encoded));
92
- } else if let Some(json_value) = json {
93
- request = request.json(&json_value);
94
- }
95
-
96
- let response = request.await;
97
- snapshot_response(response).await
98
- }
99
-
100
- /// Make a PUT request
101
- pub async fn put(
102
- &self,
103
- path: &str,
104
- json: Option<Value>,
105
- query_params: Option<Vec<(String, String)>>,
106
- headers: Option<Vec<(String, String)>>,
107
- ) -> Result<ResponseSnapshot, SnapshotError> {
108
- let full_path = build_full_path(path, query_params.as_deref());
109
- let mut request = self.server.put(&full_path);
110
-
111
- if let Some(headers_vec) = headers {
112
- request = self.add_headers(request, headers_vec)?;
113
- }
114
-
115
- if let Some(json_value) = json {
116
- request = request.json(&json_value);
117
- }
118
-
119
- let response = request.await;
120
- snapshot_response(response).await
121
- }
122
-
123
- /// Make a PATCH request
124
- pub async fn patch(
125
- &self,
126
- path: &str,
127
- json: Option<Value>,
128
- query_params: Option<Vec<(String, String)>>,
129
- headers: Option<Vec<(String, String)>>,
130
- ) -> Result<ResponseSnapshot, SnapshotError> {
131
- let full_path = build_full_path(path, query_params.as_deref());
132
- let mut request = self.server.patch(&full_path);
133
-
134
- if let Some(headers_vec) = headers {
135
- request = self.add_headers(request, headers_vec)?;
136
- }
137
-
138
- if let Some(json_value) = json {
139
- request = request.json(&json_value);
140
- }
141
-
142
- let response = request.await;
143
- snapshot_response(response).await
144
- }
145
-
146
- /// Make a DELETE request
147
- pub async fn delete(
148
- &self,
149
- path: &str,
150
- query_params: Option<Vec<(String, String)>>,
151
- headers: Option<Vec<(String, String)>>,
152
- ) -> Result<ResponseSnapshot, SnapshotError> {
153
- let full_path = build_full_path(path, query_params.as_deref());
154
- let mut request = self.server.delete(&full_path);
155
-
156
- if let Some(headers_vec) = headers {
157
- request = self.add_headers(request, headers_vec)?;
158
- }
159
-
160
- let response = request.await;
161
- snapshot_response(response).await
162
- }
163
-
164
- /// Make an OPTIONS request
165
- pub async fn options(
166
- &self,
167
- path: &str,
168
- query_params: Option<Vec<(String, String)>>,
169
- headers: Option<Vec<(String, String)>>,
170
- ) -> Result<ResponseSnapshot, SnapshotError> {
171
- let full_path = build_full_path(path, query_params.as_deref());
172
- let mut request = self.server.method(Method::OPTIONS, &full_path);
173
-
174
- if let Some(headers_vec) = headers {
175
- request = self.add_headers(request, headers_vec)?;
176
- }
177
-
178
- let response = request.await;
179
- snapshot_response(response).await
180
- }
181
-
182
- /// Make a HEAD request
183
- pub async fn head(
184
- &self,
185
- path: &str,
186
- query_params: Option<Vec<(String, String)>>,
187
- headers: Option<Vec<(String, String)>>,
188
- ) -> Result<ResponseSnapshot, SnapshotError> {
189
- let full_path = build_full_path(path, query_params.as_deref());
190
- let mut request = self.server.method(Method::HEAD, &full_path);
191
-
192
- if let Some(headers_vec) = headers {
193
- request = self.add_headers(request, headers_vec)?;
194
- }
195
-
196
- let response = request.await;
197
- snapshot_response(response).await
198
- }
199
-
200
- /// Make a TRACE request
201
- pub async fn trace(
202
- &self,
203
- path: &str,
204
- query_params: Option<Vec<(String, String)>>,
205
- headers: Option<Vec<(String, String)>>,
206
- ) -> Result<ResponseSnapshot, SnapshotError> {
207
- let full_path = build_full_path(path, query_params.as_deref());
208
- let mut request = self.server.method(Method::TRACE, &full_path);
209
-
210
- if let Some(headers_vec) = headers {
211
- request = self.add_headers(request, headers_vec)?;
212
- }
213
-
214
- let response = request.await;
215
- snapshot_response(response).await
216
- }
217
-
218
- /// Add headers to a test request builder
219
- fn add_headers(
220
- &self,
221
- mut request: axum_test::TestRequest,
222
- headers: Vec<(String, String)>,
223
- ) -> Result<axum_test::TestRequest, SnapshotError> {
224
- for (key, value) in headers {
225
- let header_name = HeaderName::from_bytes(key.as_bytes())
226
- .map_err(|e| SnapshotError::InvalidHeader(format!("Invalid header name: {}", e)))?;
227
- let header_value = HeaderValue::from_str(&value)
228
- .map_err(|e| SnapshotError::InvalidHeader(format!("Invalid header value: {}", e)))?;
229
- request = request.add_header(header_name, header_value);
230
- }
231
- Ok(request)
232
- }
233
- }
234
-
235
- /// Build a full path with query parameters
236
- fn build_full_path(path: &str, query_params: Option<&[(String, String)]>) -> String {
237
- match query_params {
238
- None | Some(&[]) => path.to_string(),
239
- Some(params) => {
240
- let query_string: Vec<String> = params
241
- .iter()
242
- .map(|(k, v)| format!("{}={}", encode(k), encode(v)))
243
- .collect();
244
-
245
- if path.contains('?') {
246
- format!("{}&{}", path, query_string.join("&"))
247
- } else {
248
- format!("{}?{}", path, query_string.join("&"))
249
- }
250
- }
251
- }
252
- }
253
-
254
- #[cfg(test)]
255
- mod tests {
256
- use super::*;
257
-
258
- #[test]
259
- fn build_full_path_no_params() {
260
- let path = "/users";
261
- assert_eq!(build_full_path(path, None), "/users");
262
- assert_eq!(build_full_path(path, Some(&[])), "/users");
263
- }
264
-
265
- #[test]
266
- fn build_full_path_with_params() {
267
- let path = "/users";
268
- let params = vec![
269
- ("id".to_string(), "123".to_string()),
270
- ("name".to_string(), "test user".to_string()),
271
- ];
272
- let result = build_full_path(path, Some(&params));
273
- assert!(result.starts_with("/users?"));
274
- assert!(result.contains("id=123"));
275
- assert!(result.contains("name=test%20user"));
276
- }
277
-
278
- #[test]
279
- fn build_full_path_existing_query() {
280
- let path = "/users?active=true";
281
- let params = vec![("id".to_string(), "123".to_string())];
282
- let result = build_full_path(path, Some(&params));
283
- assert_eq!(result, "/users?active=true&id=123");
284
- }
285
- }
@@ -1,377 +0,0 @@
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 +0,0 @@
1
- pub use spikard_core::type_hints::*;
@@ -1 +0,0 @@
1
- pub use spikard_core::validation::*;