spikard 0.3.5 → 0.5.0

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 (142) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +1 -1
  3. data/README.md +674 -659
  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 +405 -386
  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 -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 +366 -360
  23. data/vendor/crates/spikard-bindings-shared/Cargo.toml +63 -0
  24. data/vendor/crates/spikard-bindings-shared/examples/config_extraction.rs +132 -0
  25. data/vendor/crates/spikard-bindings-shared/src/config_extractor.rs +752 -0
  26. data/vendor/crates/spikard-bindings-shared/src/conversion_traits.rs +194 -0
  27. data/vendor/crates/spikard-bindings-shared/src/di_traits.rs +246 -0
  28. data/vendor/crates/spikard-bindings-shared/src/error_response.rs +401 -0
  29. data/vendor/crates/spikard-bindings-shared/src/handler_base.rs +238 -0
  30. data/vendor/crates/spikard-bindings-shared/src/lib.rs +24 -0
  31. data/vendor/crates/spikard-bindings-shared/src/lifecycle_base.rs +292 -0
  32. data/vendor/crates/spikard-bindings-shared/src/lifecycle_executor.rs +616 -0
  33. data/vendor/crates/spikard-bindings-shared/src/response_builder.rs +305 -0
  34. data/vendor/crates/spikard-bindings-shared/src/test_client_base.rs +248 -0
  35. data/vendor/crates/spikard-bindings-shared/src/validation_helpers.rs +351 -0
  36. data/vendor/crates/spikard-bindings-shared/tests/comprehensive_coverage.rs +454 -0
  37. data/vendor/crates/spikard-bindings-shared/tests/error_response_edge_cases.rs +383 -0
  38. data/vendor/crates/spikard-bindings-shared/tests/handler_base_integration.rs +280 -0
  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 -63
  43. data/vendor/crates/spikard-core/src/di/container.rs +702 -726
  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 -538
  47. data/vendor/crates/spikard-core/src/di/graph.rs +506 -545
  48. data/vendor/crates/spikard-core/src/di/mod.rs +192 -192
  49. data/vendor/crates/spikard-core/src/di/resolved.rs +405 -411
  50. data/vendor/crates/spikard-core/src/di/value.rs +281 -283
  51. data/vendor/crates/spikard-core/src/errors.rs +69 -39
  52. data/vendor/crates/spikard-core/src/http.rs +415 -153
  53. data/vendor/crates/spikard-core/src/lib.rs +29 -29
  54. data/vendor/crates/spikard-core/src/lifecycle.rs +1186 -422
  55. data/vendor/crates/spikard-core/src/metadata.rs +389 -0
  56. data/vendor/crates/spikard-core/src/parameters.rs +2525 -722
  57. data/vendor/crates/spikard-core/src/problem.rs +344 -310
  58. data/vendor/crates/spikard-core/src/request_data.rs +1154 -189
  59. data/vendor/crates/spikard-core/src/router.rs +510 -249
  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 +688 -0
  63. data/vendor/crates/spikard-core/src/{validation.rs → validation/mod.rs} +457 -699
  64. data/vendor/crates/spikard-http/Cargo.toml +64 -68
  65. data/vendor/crates/spikard-http/examples/sse-notifications.rs +148 -0
  66. data/vendor/crates/spikard-http/examples/websocket-chat.rs +92 -0
  67. data/vendor/crates/spikard-http/src/auth.rs +296 -247
  68. data/vendor/crates/spikard-http/src/background.rs +1860 -249
  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 -490
  73. data/vendor/crates/spikard-http/src/debug.rs +128 -63
  74. data/vendor/crates/spikard-http/src/di_handler.rs +1668 -423
  75. data/vendor/crates/spikard-http/src/handler_response.rs +901 -190
  76. data/vendor/crates/spikard-http/src/handler_trait.rs +830 -228
  77. data/vendor/crates/spikard-http/src/handler_trait_tests.rs +290 -284
  78. data/vendor/crates/spikard-http/src/lib.rs +534 -529
  79. data/vendor/crates/spikard-http/src/lifecycle/adapter.rs +230 -149
  80. data/vendor/crates/spikard-http/src/lifecycle.rs +1193 -428
  81. data/vendor/crates/spikard-http/src/middleware/mod.rs +540 -285
  82. data/vendor/crates/spikard-http/src/middleware/multipart.rs +912 -86
  83. data/vendor/crates/spikard-http/src/middleware/urlencoded.rs +513 -147
  84. data/vendor/crates/spikard-http/src/middleware/validation.rs +735 -287
  85. data/vendor/crates/spikard-http/src/openapi/mod.rs +309 -309
  86. data/vendor/crates/spikard-http/src/openapi/parameter_extraction.rs +535 -190
  87. data/vendor/crates/spikard-http/src/openapi/schema_conversion.rs +1363 -308
  88. data/vendor/crates/spikard-http/src/openapi/spec_generation.rs +665 -195
  89. data/vendor/crates/spikard-http/src/query_parser.rs +793 -369
  90. data/vendor/crates/spikard-http/src/response.rs +720 -399
  91. data/vendor/crates/spikard-http/src/server/handler.rs +1650 -87
  92. data/vendor/crates/spikard-http/src/server/lifecycle_execution.rs +234 -98
  93. data/vendor/crates/spikard-http/src/server/mod.rs +1502 -805
  94. data/vendor/crates/spikard-http/src/server/request_extraction.rs +770 -119
  95. data/vendor/crates/spikard-http/src/server/routing_factory.rs +599 -0
  96. data/vendor/crates/spikard-http/src/sse.rs +1409 -447
  97. data/vendor/crates/spikard-http/src/testing/form.rs +52 -14
  98. data/vendor/crates/spikard-http/src/testing/multipart.rs +60 -60
  99. data/vendor/crates/spikard-http/src/testing/test_client.rs +283 -285
  100. data/vendor/crates/spikard-http/src/testing.rs +377 -377
  101. data/vendor/crates/spikard-http/src/websocket.rs +1375 -324
  102. data/vendor/crates/spikard-http/tests/background_behavior.rs +832 -0
  103. data/vendor/crates/spikard-http/tests/common/handlers.rs +309 -0
  104. data/vendor/crates/spikard-http/tests/common/mod.rs +26 -0
  105. data/vendor/crates/spikard-http/tests/di_integration.rs +192 -0
  106. data/vendor/crates/spikard-http/tests/doc_snippets.rs +5 -0
  107. data/vendor/crates/spikard-http/tests/lifecycle_execution.rs +1093 -0
  108. data/vendor/crates/spikard-http/tests/multipart_behavior.rs +656 -0
  109. data/vendor/crates/spikard-http/tests/server_config_builder.rs +314 -0
  110. data/vendor/crates/spikard-http/tests/sse_behavior.rs +620 -0
  111. data/vendor/crates/spikard-http/tests/websocket_behavior.rs +663 -0
  112. data/vendor/crates/spikard-rb/Cargo.toml +48 -42
  113. data/vendor/crates/spikard-rb/build.rs +199 -8
  114. data/vendor/crates/spikard-rb/src/background.rs +63 -63
  115. data/vendor/crates/spikard-rb/src/config/mod.rs +5 -0
  116. data/vendor/crates/spikard-rb/src/{config.rs → config/server_config.rs} +285 -294
  117. data/vendor/crates/spikard-rb/src/conversion.rs +554 -453
  118. data/vendor/crates/spikard-rb/src/di/builder.rs +100 -0
  119. data/vendor/crates/spikard-rb/src/{di.rs → di/mod.rs} +375 -409
  120. data/vendor/crates/spikard-rb/src/handler.rs +618 -625
  121. data/vendor/crates/spikard-rb/src/integration/mod.rs +3 -0
  122. data/vendor/crates/spikard-rb/src/lib.rs +1810 -2771
  123. data/vendor/crates/spikard-rb/src/lifecycle.rs +275 -274
  124. data/vendor/crates/spikard-rb/src/metadata/mod.rs +5 -0
  125. data/vendor/crates/spikard-rb/src/metadata/route_extraction.rs +447 -0
  126. data/vendor/crates/spikard-rb/src/runtime/mod.rs +5 -0
  127. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +324 -0
  128. data/vendor/crates/spikard-rb/src/server.rs +308 -283
  129. data/vendor/crates/spikard-rb/src/sse.rs +231 -231
  130. data/vendor/crates/spikard-rb/src/{test_client.rs → testing/client.rs} +551 -404
  131. data/vendor/crates/spikard-rb/src/testing/mod.rs +7 -0
  132. data/vendor/crates/spikard-rb/src/{test_sse.rs → testing/sse.rs} +143 -143
  133. data/vendor/crates/spikard-rb/src/testing/websocket.rs +635 -0
  134. data/vendor/crates/spikard-rb/src/websocket.rs +374 -233
  135. metadata +46 -13
  136. data/vendor/crates/spikard-http/src/parameters.rs +0 -1
  137. data/vendor/crates/spikard-http/src/problem.rs +0 -1
  138. data/vendor/crates/spikard-http/src/router.rs +0 -1
  139. data/vendor/crates/spikard-http/src/schema_registry.rs +0 -1
  140. data/vendor/crates/spikard-http/src/type_hints.rs +0 -1
  141. data/vendor/crates/spikard-http/src/validation.rs +0 -1
  142. data/vendor/crates/spikard-rb/src/test_websocket.rs +0 -221
@@ -1,404 +1,551 @@
1
- //! Native Ruby test client for HTTP testing.
2
- //!
3
- //! This module implements `NativeTestClient`, a wrapped Ruby class that provides
4
- //! HTTP testing capabilities against a Spikard server. It manages test servers
5
- //! for both HTTP and WebSocket/SSE transports.
6
-
7
- #![allow(dead_code)]
8
-
9
- use axum::http::Method;
10
- use axum_test::{TestServer, TestServerConfig, Transport};
11
- use bytes::Bytes;
12
- use cookie::Cookie;
13
- use magnus::prelude::*;
14
- use magnus::{Error, RHash, Ruby, Value, gc::Marker};
15
- use serde_json::Value as JsonValue;
16
- use spikard_http::testing::{
17
- MultipartFilePart, SnapshotError, build_multipart_body, encode_urlencoded_body, snapshot_response,
18
- };
19
- use spikard_http::{Route, RouteMetadata};
20
- use std::cell::RefCell;
21
- use std::collections::HashMap;
22
- use std::sync::Arc;
23
-
24
- use crate::conversion::{parse_request_config, response_to_ruby};
25
- use crate::handler::RubyHandler;
26
- use crate::server::GLOBAL_RUNTIME;
27
-
28
- /// Request configuration built from Ruby options hash.
29
- pub struct RequestConfig {
30
- pub query: Option<JsonValue>,
31
- pub headers: HashMap<String, String>,
32
- pub cookies: HashMap<String, String>,
33
- pub body: Option<RequestBody>,
34
- }
35
-
36
- /// HTTP request body variants.
37
- pub enum RequestBody {
38
- Json(JsonValue),
39
- Form(JsonValue),
40
- Raw(String),
41
- Multipart {
42
- form_data: Vec<(String, String)>,
43
- files: Vec<MultipartFilePart>,
44
- },
45
- }
46
-
47
- /// Snapshot of an HTTP response.
48
- pub struct TestResponseData {
49
- pub status: u16,
50
- pub headers: HashMap<String, String>,
51
- pub body_text: Option<String>,
52
- }
53
-
54
- /// Error wrapper for native request failures.
55
- #[derive(Debug)]
56
- pub struct NativeRequestError(pub String);
57
-
58
- /// Inner client state containing the test servers and handlers.
59
- pub struct ClientInner {
60
- pub http_server: Arc<TestServer>,
61
- pub transport_server: Arc<TestServer>,
62
- /// Keep Ruby handler closures alive for GC; accessed via the `mark` hook.
63
- #[allow(dead_code)]
64
- pub handlers: Vec<RubyHandler>,
65
- }
66
-
67
- /// Native Ruby TestClient wrapper for integration testing.
68
- ///
69
- /// Wraps an optional `ClientInner` that holds the HTTP test servers
70
- /// and keeps handler references alive for Ruby's garbage collector.
71
- #[derive(Default)]
72
- #[magnus::wrap(class = "Spikard::Native::TestClient", free_immediately, mark)]
73
- pub struct NativeTestClient {
74
- pub inner: RefCell<Option<ClientInner>>,
75
- }
76
-
77
- impl NativeTestClient {
78
- /// Initialize the test client with routes, handlers, and server config.
79
- ///
80
- /// # Arguments
81
- ///
82
- /// * `ruby` - Ruby VM reference
83
- /// * `this` - The wrapped NativeTestClient instance
84
- /// * `routes_json` - JSON string containing route metadata
85
- /// * `handlers` - Ruby Hash mapping handler_name => Proc
86
- /// * `config_value` - Ruby ServerConfig object
87
- /// * `ws_handlers` - Ruby Hash of WebSocket handlers (optional)
88
- /// * `sse_producers` - Ruby Hash of SSE producers (optional)
89
- pub fn initialize(
90
- ruby: &Ruby,
91
- this: &Self,
92
- routes_json: String,
93
- handlers: Value,
94
- config_value: Value,
95
- ws_handlers: Value,
96
- sse_producers: Value,
97
- ) -> Result<(), Error> {
98
- let metadata: Vec<RouteMetadata> = serde_json::from_str(&routes_json)
99
- .map_err(|err| Error::new(ruby.exception_arg_error(), format!("Invalid routes JSON: {err}")))?;
100
-
101
- let handlers_hash = RHash::from_value(handlers).ok_or_else(|| {
102
- Error::new(
103
- ruby.exception_arg_error(),
104
- "handlers parameter must be a Hash of handler_name => Proc",
105
- )
106
- })?;
107
-
108
- let json_module = ruby
109
- .class_object()
110
- .const_get("JSON")
111
- .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
112
-
113
- let server_config = crate::config::extract_server_config(ruby, config_value)?;
114
-
115
- let schema_registry = spikard_http::SchemaRegistry::new();
116
- let mut prepared_routes = Vec::with_capacity(metadata.len());
117
- let mut handler_refs = Vec::with_capacity(metadata.len());
118
- let mut route_metadata_vec = Vec::with_capacity(metadata.len());
119
-
120
- for meta in metadata.clone() {
121
- let handler_value = crate::conversion::fetch_handler(ruby, &handlers_hash, &meta.handler_name)?;
122
- let route = Route::from_metadata(meta.clone(), &schema_registry)
123
- .map_err(|err| Error::new(ruby.exception_runtime_error(), format!("Failed to build route: {err}")))?;
124
-
125
- let handler = RubyHandler::new(&route, handler_value, json_module)?;
126
- prepared_routes.push((route, Arc::new(handler.clone()) as Arc<dyn spikard_http::Handler>));
127
- handler_refs.push(handler);
128
- route_metadata_vec.push(meta);
129
- }
130
-
131
- let mut router = spikard_http::server::build_router_with_handlers_and_config(
132
- prepared_routes,
133
- server_config,
134
- route_metadata_vec,
135
- )
136
- .map_err(|err| Error::new(ruby.exception_runtime_error(), format!("Failed to build router: {err}")))?;
137
-
138
- let mut ws_endpoints = Vec::new();
139
- if !ws_handlers.is_nil() {
140
- let ws_hash = RHash::from_value(ws_handlers)
141
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "WebSocket handlers must be a Hash"))?;
142
-
143
- ws_hash.foreach(
144
- |path: String, factory: Value| -> Result<magnus::r_hash::ForEach, Error> {
145
- let handler_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
146
- Error::new(
147
- ruby.exception_runtime_error(),
148
- format!("Failed to create WebSocket handler: {}", e),
149
- )
150
- })?;
151
-
152
- let ws_state = crate::websocket::create_websocket_state(ruby, handler_instance)?;
153
-
154
- ws_endpoints.push((path, ws_state));
155
-
156
- Ok(magnus::r_hash::ForEach::Continue)
157
- },
158
- )?;
159
- }
160
-
161
- let mut sse_endpoints = Vec::new();
162
- if !sse_producers.is_nil() {
163
- let sse_hash = RHash::from_value(sse_producers)
164
- .ok_or_else(|| Error::new(ruby.exception_arg_error(), "SSE producers must be a Hash"))?;
165
-
166
- sse_hash.foreach(
167
- |path: String, factory: Value| -> Result<magnus::r_hash::ForEach, Error> {
168
- let producer_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
169
- Error::new(
170
- ruby.exception_runtime_error(),
171
- format!("Failed to create SSE producer: {}", e),
172
- )
173
- })?;
174
-
175
- let sse_state = crate::sse::create_sse_state(ruby, producer_instance)?;
176
-
177
- sse_endpoints.push((path, sse_state));
178
-
179
- Ok(magnus::r_hash::ForEach::Continue)
180
- },
181
- )?;
182
- }
183
-
184
- use axum::routing::get;
185
- for (path, ws_state) in ws_endpoints {
186
- router = router.route(
187
- &path,
188
- get(spikard_http::websocket_handler::<crate::websocket::RubyWebSocketHandler>).with_state(ws_state),
189
- );
190
- }
191
-
192
- for (path, sse_state) in sse_endpoints {
193
- router = router.route(
194
- &path,
195
- get(spikard_http::sse_handler::<crate::sse::RubySseEventProducer>).with_state(sse_state),
196
- );
197
- }
198
-
199
- let http_server = GLOBAL_RUNTIME
200
- .block_on(async { TestServer::new(router.clone()) })
201
- .map_err(|err| {
202
- Error::new(
203
- ruby.exception_runtime_error(),
204
- format!("Failed to initialise test server: {err}"),
205
- )
206
- })?;
207
-
208
- let ws_config = TestServerConfig {
209
- transport: Some(Transport::HttpRandomPort),
210
- ..Default::default()
211
- };
212
- let transport_server = GLOBAL_RUNTIME
213
- .block_on(async { TestServer::new_with_config(router, ws_config) })
214
- .map_err(|err| {
215
- Error::new(
216
- ruby.exception_runtime_error(),
217
- format!("Failed to initialise WebSocket transport server: {err}"),
218
- )
219
- })?;
220
-
221
- *this.inner.borrow_mut() = Some(ClientInner {
222
- http_server: Arc::new(http_server),
223
- transport_server: Arc::new(transport_server),
224
- handlers: handler_refs,
225
- });
226
-
227
- Ok(())
228
- }
229
-
230
- /// Execute an HTTP request against the test server.
231
- ///
232
- /// # Arguments
233
- ///
234
- /// * `ruby` - Ruby VM reference
235
- /// * `this` - The wrapped NativeTestClient instance
236
- /// * `method` - HTTP method (GET, POST, etc.)
237
- /// * `path` - URL path
238
- /// * `options` - Ruby Hash with query, headers, cookies, body, etc.
239
- pub fn request(ruby: &Ruby, this: &Self, method: String, path: String, options: Value) -> Result<Value, Error> {
240
- let inner_borrow = this.inner.borrow();
241
- let inner = inner_borrow
242
- .as_ref()
243
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
244
- let method_upper = method.to_ascii_uppercase();
245
- let http_method = Method::from_bytes(method_upper.as_bytes()).map_err(|err| {
246
- Error::new(
247
- ruby.exception_arg_error(),
248
- format!("Unsupported method {method_upper}: {err}"),
249
- )
250
- })?;
251
-
252
- let request_config = parse_request_config(ruby, options)?;
253
-
254
- let response = GLOBAL_RUNTIME
255
- .block_on(execute_request(
256
- inner.http_server.clone(),
257
- http_method,
258
- path.clone(),
259
- request_config,
260
- ))
261
- .map_err(|err| {
262
- Error::new(
263
- ruby.exception_runtime_error(),
264
- format!("Request failed for {method_upper} {path}: {}", err.0),
265
- )
266
- })?;
267
-
268
- response_to_ruby(ruby, response)
269
- }
270
-
271
- /// Close the test client and clean up resources.
272
- pub fn close(&self) -> Result<(), Error> {
273
- *self.inner.borrow_mut() = None;
274
- Ok(())
275
- }
276
-
277
- /// Connect to a WebSocket endpoint on the test server.
278
- pub fn websocket(ruby: &Ruby, this: &Self, path: String) -> Result<Value, Error> {
279
- let inner_borrow = this.inner.borrow();
280
- let inner = inner_borrow
281
- .as_ref()
282
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
283
-
284
- let server = Arc::clone(&inner.transport_server);
285
-
286
- drop(inner_borrow);
287
-
288
- let handle =
289
- GLOBAL_RUNTIME.spawn(async move { spikard_http::testing::connect_websocket(&server, &path).await });
290
-
291
- let ws = GLOBAL_RUNTIME.block_on(async {
292
- handle
293
- .await
294
- .map_err(|e| Error::new(ruby.exception_runtime_error(), format!("WebSocket task failed: {}", e)))
295
- })?;
296
-
297
- let ws_conn = crate::test_websocket::WebSocketTestConnection::new(ws);
298
- Ok(ruby.obj_wrap(ws_conn).as_value())
299
- }
300
-
301
- /// Connect to an SSE endpoint on the test server.
302
- pub fn sse(ruby: &Ruby, this: &Self, path: String) -> Result<Value, Error> {
303
- let inner_borrow = this.inner.borrow();
304
- let inner = inner_borrow
305
- .as_ref()
306
- .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
307
-
308
- let response = GLOBAL_RUNTIME
309
- .block_on(async {
310
- let axum_response = inner.transport_server.get(&path).await;
311
- snapshot_response(axum_response).await
312
- })
313
- .map_err(|e| Error::new(ruby.exception_runtime_error(), format!("SSE request failed: {}", e)))?;
314
-
315
- crate::test_sse::sse_stream_from_response(ruby, &response)
316
- }
317
-
318
- /// GC mark hook so Ruby keeps handler closures alive.
319
- #[allow(dead_code)]
320
- pub fn mark(&self, marker: &Marker) {
321
- let inner_ref = self.inner.borrow();
322
- if let Some(inner) = inner_ref.as_ref() {
323
- for handler in &inner.handlers {
324
- handler.mark(marker);
325
- }
326
- }
327
- }
328
- }
329
-
330
- /// Execute an HTTP request against a test server.
331
- ///
332
- /// Handles method routing, query params, headers, cookies, and various body formats.
333
- pub async fn execute_request(
334
- server: Arc<TestServer>,
335
- method: Method,
336
- path: String,
337
- config: RequestConfig,
338
- ) -> Result<TestResponseData, NativeRequestError> {
339
- let mut request = match method {
340
- Method::GET => server.get(&path),
341
- Method::POST => server.post(&path),
342
- Method::PUT => server.put(&path),
343
- Method::PATCH => server.patch(&path),
344
- Method::DELETE => server.delete(&path),
345
- Method::HEAD => server.method(Method::HEAD, &path),
346
- Method::OPTIONS => server.method(Method::OPTIONS, &path),
347
- Method::TRACE => server.method(Method::TRACE, &path),
348
- other => return Err(NativeRequestError(format!("Unsupported HTTP method {other}"))),
349
- };
350
-
351
- if let Some(query) = config.query {
352
- request = request.add_query_params(&query);
353
- }
354
-
355
- for (name, value) in config.headers {
356
- request = request.add_header(name.as_str(), value.as_str());
357
- }
358
-
359
- for (name, value) in config.cookies {
360
- request = request.add_cookie(Cookie::new(name, value));
361
- }
362
-
363
- if let Some(body) = config.body {
364
- match body {
365
- RequestBody::Json(json_value) => {
366
- request = request.json(&json_value);
367
- }
368
- RequestBody::Form(form_value) => {
369
- let encoded = encode_urlencoded_body(&form_value)
370
- .map_err(|err| NativeRequestError(format!("Failed to encode form body: {err}")))?;
371
- request = request
372
- .content_type("application/x-www-form-urlencoded")
373
- .bytes(Bytes::from(encoded));
374
- }
375
- RequestBody::Raw(raw) => {
376
- request = request.bytes(Bytes::from(raw));
377
- }
378
- RequestBody::Multipart { form_data, files } => {
379
- let (multipart_body, boundary) = build_multipart_body(&form_data, &files);
380
- request = request
381
- .content_type(&format!("multipart/form-data; boundary={}", boundary))
382
- .bytes(Bytes::from(multipart_body));
383
- }
384
- }
385
- }
386
-
387
- let response = request.await;
388
- let snapshot = snapshot_response(response).await.map_err(snapshot_err_to_native)?;
389
- let body_text = if snapshot.body.is_empty() {
390
- None
391
- } else {
392
- Some(String::from_utf8_lossy(&snapshot.body).into_owned())
393
- };
394
-
395
- Ok(TestResponseData {
396
- status: snapshot.status,
397
- headers: snapshot.headers,
398
- body_text,
399
- })
400
- }
401
-
402
- fn snapshot_err_to_native(err: SnapshotError) -> NativeRequestError {
403
- NativeRequestError(err.to_string())
404
- }
1
+ //! Native Ruby test client for HTTP testing.
2
+ //!
3
+ //! This module implements `NativeTestClient`, a wrapped Ruby class that provides
4
+ //! HTTP testing capabilities against a Spikard server. It manages test servers
5
+ //! for both HTTP and WebSocket/SSE transports.
6
+
7
+ #![allow(dead_code)]
8
+
9
+ use axum::http::Method;
10
+ use axum::Router;
11
+ use axum_test::{TestServer, TestServerConfig, Transport};
12
+ use bytes::Bytes;
13
+ use cookie::Cookie;
14
+ use magnus::prelude::*;
15
+ use magnus::{Error, RHash, Ruby, Value, gc::Marker};
16
+ use serde_json::Value as JsonValue;
17
+ use spikard_http::testing::{
18
+ MultipartFilePart,
19
+ ResponseSnapshot,
20
+ SnapshotError,
21
+ build_multipart_body,
22
+ encode_urlencoded_body,
23
+ snapshot_response,
24
+ };
25
+ use spikard_http::{Route, RouteMetadata};
26
+ use std::cell::RefCell;
27
+ use std::collections::HashMap;
28
+ use std::sync::Arc;
29
+ use std::time::Duration;
30
+ use url::Url;
31
+
32
+ use crate::conversion::{parse_request_config, response_to_ruby};
33
+ use crate::handler::RubyHandler;
34
+
35
+ /// Request configuration built from Ruby options hash.
36
+ pub struct RequestConfig {
37
+ pub query: Option<JsonValue>,
38
+ pub headers: HashMap<String, String>,
39
+ pub cookies: HashMap<String, String>,
40
+ pub body: Option<RequestBody>,
41
+ }
42
+
43
+ /// HTTP request body variants.
44
+ pub enum RequestBody {
45
+ Json(JsonValue),
46
+ Form(JsonValue),
47
+ Raw(String),
48
+ Multipart {
49
+ form_data: Vec<(String, String)>,
50
+ files: Vec<MultipartFilePart>,
51
+ },
52
+ }
53
+
54
+ /// Snapshot of an HTTP response.
55
+ pub struct TestResponseData {
56
+ pub status: u16,
57
+ pub headers: HashMap<String, String>,
58
+ pub body_text: Option<String>,
59
+ }
60
+
61
+ /// Error wrapper for native request failures.
62
+ #[derive(Debug)]
63
+ pub struct NativeRequestError(pub String);
64
+
65
+ #[derive(Debug)]
66
+ enum WebSocketConnectError {
67
+ Timeout,
68
+ Other(String),
69
+ }
70
+
71
+ /// Inner client state containing the test servers and handlers.
72
+ pub struct ClientInner {
73
+ pub http_server: Arc<TestServer>,
74
+ pub transport_server: Arc<TestServer>,
75
+ /// Keep Ruby handler closures alive for GC; accessed via the `mark` hook.
76
+ #[allow(dead_code)]
77
+ pub handlers: Vec<RubyHandler>,
78
+ }
79
+
80
+ /// Native Ruby TestClient wrapper for integration testing.
81
+ ///
82
+ /// Wraps an optional `ClientInner` that holds the HTTP test servers
83
+ /// and keeps handler references alive for Ruby's garbage collector.
84
+ #[derive(Default)]
85
+ #[magnus::wrap(class = "Spikard::Native::TestClient", free_immediately, mark)]
86
+ pub struct NativeTestClient {
87
+ pub inner: RefCell<Option<ClientInner>>,
88
+ }
89
+
90
+ impl NativeTestClient {
91
+ /// Initialize the test client with routes, handlers, and server config.
92
+ ///
93
+ /// # Arguments
94
+ ///
95
+ /// * `ruby` - Ruby VM reference
96
+ /// * `this` - The wrapped NativeTestClient instance
97
+ /// * `routes_json` - JSON string containing route metadata
98
+ /// * `handlers` - Ruby Hash mapping handler_name => Proc
99
+ /// * `config_value` - Ruby ServerConfig object
100
+ /// * `ws_handlers` - Ruby Hash of WebSocket handlers (optional)
101
+ /// * `sse_producers` - Ruby Hash of SSE producers (optional)
102
+ pub fn initialize(
103
+ ruby: &Ruby,
104
+ this: &Self,
105
+ routes_json: String,
106
+ handlers: Value,
107
+ config_value: Value,
108
+ ws_handlers: Value,
109
+ sse_producers: Value,
110
+ ) -> Result<(), Error> {
111
+ trace_step("initialize:start");
112
+ let metadata: Vec<RouteMetadata> = serde_json::from_str(&routes_json)
113
+ .map_err(|err| Error::new(ruby.exception_arg_error(), format!("Invalid routes JSON: {err}")))?;
114
+
115
+ let handlers_hash = RHash::from_value(handlers).ok_or_else(|| {
116
+ Error::new(
117
+ ruby.exception_arg_error(),
118
+ "handlers parameter must be a Hash of handler_name => Proc",
119
+ )
120
+ })?;
121
+
122
+ let json_module = ruby
123
+ .class_object()
124
+ .const_get("JSON")
125
+ .map_err(|_| Error::new(ruby.exception_runtime_error(), "JSON module not available"))?;
126
+
127
+ let server_config = crate::config::extract_server_config(ruby, config_value)?;
128
+
129
+ let schema_registry = spikard_http::SchemaRegistry::new();
130
+ let mut prepared_routes = Vec::with_capacity(metadata.len());
131
+ let mut handler_refs = Vec::with_capacity(metadata.len());
132
+ let mut route_metadata_vec = Vec::with_capacity(metadata.len());
133
+
134
+ for meta in metadata.clone() {
135
+ let handler_value = crate::conversion::fetch_handler(ruby, &handlers_hash, &meta.handler_name)?;
136
+ let route = Route::from_metadata(meta.clone(), &schema_registry)
137
+ .map_err(|err| Error::new(ruby.exception_runtime_error(), format!("Failed to build route: {err}")))?;
138
+
139
+ let handler = RubyHandler::new(&route, handler_value, json_module)?;
140
+ prepared_routes.push((route, Arc::new(handler.clone()) as Arc<dyn spikard_http::Handler>));
141
+ handler_refs.push(handler);
142
+ route_metadata_vec.push(meta);
143
+ }
144
+
145
+ trace_step("initialize:build_router");
146
+ let mut router = spikard_http::server::build_router_with_handlers_and_config(
147
+ prepared_routes,
148
+ server_config,
149
+ route_metadata_vec,
150
+ )
151
+ .map_err(|err| Error::new(ruby.exception_runtime_error(), format!("Failed to build router: {err}")))?;
152
+
153
+ let mut ws_endpoints = Vec::new();
154
+ if !ws_handlers.is_nil() {
155
+ trace_step("initialize:ws_handlers");
156
+ let ws_hash = RHash::from_value(ws_handlers)
157
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "WebSocket handlers must be a Hash"))?;
158
+
159
+ ws_hash.foreach(
160
+ |path: String, factory: Value| -> Result<magnus::r_hash::ForEach, Error> {
161
+ let handler_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
162
+ Error::new(
163
+ ruby.exception_runtime_error(),
164
+ format!("Failed to create WebSocket handler: {}", e),
165
+ )
166
+ })?;
167
+
168
+ let ws_state = crate::websocket::create_websocket_state(ruby, handler_instance)?;
169
+
170
+ ws_endpoints.push((path, ws_state));
171
+
172
+ Ok(magnus::r_hash::ForEach::Continue)
173
+ },
174
+ )?;
175
+ }
176
+
177
+ let mut sse_endpoints = Vec::new();
178
+ if !sse_producers.is_nil() {
179
+ trace_step("initialize:sse_producers");
180
+ let sse_hash = RHash::from_value(sse_producers)
181
+ .ok_or_else(|| Error::new(ruby.exception_arg_error(), "SSE producers must be a Hash"))?;
182
+
183
+ sse_hash.foreach(
184
+ |path: String, factory: Value| -> Result<magnus::r_hash::ForEach, Error> {
185
+ let producer_instance = factory.funcall::<_, _, Value>("call", ()).map_err(|e| {
186
+ Error::new(
187
+ ruby.exception_runtime_error(),
188
+ format!("Failed to create SSE producer: {}", e),
189
+ )
190
+ })?;
191
+
192
+ let sse_state = crate::sse::create_sse_state(ruby, producer_instance)?;
193
+
194
+ sse_endpoints.push((path, sse_state));
195
+
196
+ Ok(magnus::r_hash::ForEach::Continue)
197
+ },
198
+ )?;
199
+ }
200
+
201
+ use axum::routing::get;
202
+ for (path, ws_state) in ws_endpoints {
203
+ router = router.route(
204
+ &path,
205
+ get(spikard_http::websocket_handler::<crate::websocket::RubyWebSocketHandler>).with_state(ws_state),
206
+ );
207
+ }
208
+
209
+ for (path, sse_state) in sse_endpoints {
210
+ router = router.route(
211
+ &path,
212
+ get(spikard_http::sse_handler::<crate::sse::RubySseEventProducer>).with_state(sse_state),
213
+ );
214
+ }
215
+
216
+ trace_step("initialize:test_server_http");
217
+ let timeout_duration = test_server_timeout();
218
+ let http_server = init_test_server(router.clone(), timeout_duration, "test server", ruby)?;
219
+
220
+ trace_step("initialize:test_server_ws");
221
+ let ws_config = TestServerConfig {
222
+ transport: Some(Transport::HttpRandomPort),
223
+ ..Default::default()
224
+ };
225
+ let transport_server =
226
+ init_test_server_with_config(router, ws_config, timeout_duration, "WebSocket transport server", ruby)?;
227
+
228
+ trace_step("initialize:done");
229
+ *this.inner.borrow_mut() = Some(ClientInner {
230
+ http_server: Arc::new(http_server),
231
+ transport_server: Arc::new(transport_server),
232
+ handlers: handler_refs,
233
+ });
234
+
235
+ Ok(())
236
+ }
237
+
238
+ /// Execute an HTTP request against the test server.
239
+ ///
240
+ /// # Arguments
241
+ ///
242
+ /// * `ruby` - Ruby VM reference
243
+ /// * `this` - The wrapped NativeTestClient instance
244
+ /// * `method` - HTTP method (GET, POST, etc.)
245
+ /// * `path` - URL path
246
+ /// * `options` - Ruby Hash with query, headers, cookies, body, etc.
247
+ pub fn request(ruby: &Ruby, this: &Self, method: String, path: String, options: Value) -> Result<Value, Error> {
248
+ let inner_borrow = this.inner.borrow();
249
+ let inner = inner_borrow
250
+ .as_ref()
251
+ .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
252
+ let method_upper = method.to_ascii_uppercase();
253
+ let http_method = Method::from_bytes(method_upper.as_bytes()).map_err(|err| {
254
+ Error::new(
255
+ ruby.exception_arg_error(),
256
+ format!("Unsupported method {method_upper}: {err}"),
257
+ )
258
+ })?;
259
+
260
+ let request_config = parse_request_config(ruby, options)?;
261
+
262
+ let runtime = crate::server::global_runtime(ruby)?;
263
+ let server = inner.http_server.clone();
264
+ let path_value = path.clone();
265
+ let request_config_value = request_config;
266
+ let response = crate::call_without_gvl!(
267
+ block_on_request,
268
+ args: (
269
+ runtime, &tokio::runtime::Runtime,
270
+ server, Arc<TestServer>,
271
+ http_method, Method,
272
+ path_value, String,
273
+ request_config_value, RequestConfig
274
+ ),
275
+ return_type: Result<TestResponseData, NativeRequestError>
276
+ )
277
+ .map_err(|err| {
278
+ Error::new(
279
+ ruby.exception_runtime_error(),
280
+ format!("Request failed for {method_upper} {path}: {}", err.0),
281
+ )
282
+ })?;
283
+
284
+ response_to_ruby(ruby, response)
285
+ }
286
+
287
+ /// Close the test client and clean up resources.
288
+ pub fn close(&self) -> Result<(), Error> {
289
+ *self.inner.borrow_mut() = None;
290
+ Ok(())
291
+ }
292
+
293
+ /// Connect to a WebSocket endpoint on the test server.
294
+ pub fn websocket(ruby: &Ruby, this: &Self, path: String) -> Result<Value, Error> {
295
+ let inner_borrow = this.inner.borrow();
296
+ let inner = inner_borrow
297
+ .as_ref()
298
+ .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
299
+
300
+ let server = Arc::clone(&inner.transport_server);
301
+
302
+ drop(inner_borrow);
303
+
304
+ let timeout_duration = websocket_timeout();
305
+ let ws = crate::call_without_gvl!(
306
+ block_on_websocket_connect,
307
+ args: (
308
+ server, Arc<TestServer>,
309
+ path, String,
310
+ timeout_duration, Duration
311
+ ),
312
+ return_type: Result<crate::testing::websocket::WebSocketConnection, WebSocketConnectError>
313
+ )
314
+ .map_err(|err| match err {
315
+ WebSocketConnectError::Timeout => Error::new(
316
+ ruby.exception_runtime_error(),
317
+ format!(
318
+ "WebSocket connect timed out after {}ms",
319
+ timeout_duration.as_millis()
320
+ ),
321
+ ),
322
+ WebSocketConnectError::Other(message) => Error::new(
323
+ ruby.exception_runtime_error(),
324
+ format!("WebSocket connect failed: {}", message),
325
+ ),
326
+ })?;
327
+
328
+ let ws_conn = crate::testing::websocket::WebSocketTestConnection::new(ws);
329
+ Ok(ruby.obj_wrap(ws_conn).as_value())
330
+ }
331
+
332
+ /// Connect to an SSE endpoint on the test server.
333
+ pub fn sse(ruby: &Ruby, this: &Self, path: String) -> Result<Value, Error> {
334
+ let inner_borrow = this.inner.borrow();
335
+ let inner = inner_borrow
336
+ .as_ref()
337
+ .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "TestClient not initialised"))?;
338
+
339
+ let runtime = crate::server::global_runtime(ruby)?;
340
+ let server = inner.http_server.clone();
341
+ let http_method = Method::GET;
342
+ let request_config = RequestConfig {
343
+ query: None,
344
+ headers: HashMap::new(),
345
+ cookies: HashMap::new(),
346
+ body: None,
347
+ };
348
+ let response = crate::call_without_gvl!(
349
+ block_on_request,
350
+ args: (
351
+ runtime, &tokio::runtime::Runtime,
352
+ server, Arc<TestServer>,
353
+ http_method, Method,
354
+ path, String,
355
+ request_config, RequestConfig
356
+ ),
357
+ return_type: Result<TestResponseData, NativeRequestError>
358
+ )
359
+ .map_err(|err| {
360
+ Error::new(
361
+ ruby.exception_runtime_error(),
362
+ format!("SSE request failed: {}", err.0),
363
+ )
364
+ })?;
365
+
366
+ let body = response.body_text.unwrap_or_default().into_bytes();
367
+ let snapshot = ResponseSnapshot {
368
+ status: response.status,
369
+ headers: response.headers,
370
+ body,
371
+ };
372
+
373
+ crate::testing::sse::sse_stream_from_response(ruby, &snapshot)
374
+ }
375
+
376
+ /// GC mark hook so Ruby keeps handler closures alive.
377
+ #[allow(dead_code)]
378
+ pub fn mark(&self, marker: &Marker) {
379
+ let inner_ref = self.inner.borrow();
380
+ if let Some(inner) = inner_ref.as_ref() {
381
+ for handler in &inner.handlers {
382
+ handler.mark(marker);
383
+ }
384
+ }
385
+ }
386
+ }
387
+
388
+ fn websocket_timeout() -> Duration {
389
+ const DEFAULT_TIMEOUT_MS: u64 = 30_000;
390
+ let timeout_ms = std::env::var("SPIKARD_RB_WS_TIMEOUT_MS")
391
+ .ok()
392
+ .and_then(|value| value.parse::<u64>().ok())
393
+ .unwrap_or(DEFAULT_TIMEOUT_MS);
394
+ Duration::from_millis(timeout_ms)
395
+ }
396
+
397
+ fn block_on_request(
398
+ runtime: &tokio::runtime::Runtime,
399
+ server: Arc<TestServer>,
400
+ method: Method,
401
+ path: String,
402
+ config: RequestConfig,
403
+ ) -> Result<TestResponseData, NativeRequestError> {
404
+ runtime.block_on(execute_request(server, method, path, config))
405
+ }
406
+
407
+ fn block_on_websocket_connect(
408
+ server: Arc<TestServer>,
409
+ path: String,
410
+ timeout_duration: Duration,
411
+ ) -> Result<crate::testing::websocket::WebSocketConnection, WebSocketConnectError> {
412
+ let url = server
413
+ .server_url(&path)
414
+ .map_err(|err| WebSocketConnectError::Other(err.to_string()))?;
415
+ let ws_url = to_ws_url(url)?;
416
+
417
+ match crate::testing::websocket::WebSocketConnection::connect(ws_url, timeout_duration) {
418
+ Ok(ws) => Ok(ws),
419
+ Err(crate::testing::websocket::WebSocketIoError::Timeout) => Err(WebSocketConnectError::Timeout),
420
+ Err(err) => Err(WebSocketConnectError::Other(format!("{:?}", err))),
421
+ }
422
+ }
423
+
424
+ fn to_ws_url(mut url: Url) -> Result<Url, WebSocketConnectError> {
425
+ let scheme = match url.scheme() {
426
+ "https" => "wss",
427
+ _ => "ws",
428
+ };
429
+ url.set_scheme(scheme)
430
+ .map_err(|_| WebSocketConnectError::Other("Failed to set WebSocket scheme".to_string()))?;
431
+ Ok(url)
432
+ }
433
+
434
+ fn test_server_timeout() -> Duration {
435
+ const DEFAULT_TIMEOUT_MS: u64 = 30_000;
436
+ let timeout_ms = std::env::var("SPIKARD_RB_TESTSERVER_TIMEOUT_MS")
437
+ .ok()
438
+ .and_then(|value| value.parse::<u64>().ok())
439
+ .unwrap_or(DEFAULT_TIMEOUT_MS);
440
+ Duration::from_millis(timeout_ms)
441
+ }
442
+
443
+ fn trace_step(message: &str) {
444
+ if std::env::var("SPIKARD_RB_TEST_TRACE").ok().as_deref() == Some("1") {
445
+ eprintln!("[spikard-rb-test] {}", message);
446
+ }
447
+ }
448
+
449
+ fn init_test_server(router: Router, _timeout: Duration, label: &str, ruby: &Ruby) -> Result<TestServer, Error> {
450
+ let runtime = crate::server::global_runtime(ruby)?;
451
+ let _guard = runtime.enter();
452
+ TestServer::new(router).map_err(|err| {
453
+ Error::new(
454
+ ruby.exception_runtime_error(),
455
+ format!("Failed to initialise {label}: {err}"),
456
+ )
457
+ })
458
+ }
459
+
460
+ fn init_test_server_with_config(
461
+ router: Router,
462
+ config: TestServerConfig,
463
+ _timeout: Duration,
464
+ label: &str,
465
+ ruby: &Ruby,
466
+ ) -> Result<TestServer, Error> {
467
+ let runtime = crate::server::global_runtime(ruby)?;
468
+ let _guard = runtime.enter();
469
+ TestServer::new_with_config(router, config).map_err(|err| {
470
+ Error::new(
471
+ ruby.exception_runtime_error(),
472
+ format!("Failed to initialise {label}: {err}"),
473
+ )
474
+ })
475
+ }
476
+
477
+ /// Execute an HTTP request against a test server.
478
+ ///
479
+ /// Handles method routing, query params, headers, cookies, and various body formats.
480
+ pub async fn execute_request(
481
+ server: Arc<TestServer>,
482
+ method: Method,
483
+ path: String,
484
+ config: RequestConfig,
485
+ ) -> Result<TestResponseData, NativeRequestError> {
486
+ let mut request = match method {
487
+ Method::GET => server.get(&path),
488
+ Method::POST => server.post(&path),
489
+ Method::PUT => server.put(&path),
490
+ Method::PATCH => server.patch(&path),
491
+ Method::DELETE => server.delete(&path),
492
+ Method::HEAD => server.method(Method::HEAD, &path),
493
+ Method::OPTIONS => server.method(Method::OPTIONS, &path),
494
+ Method::TRACE => server.method(Method::TRACE, &path),
495
+ other => return Err(NativeRequestError(format!("Unsupported HTTP method {other}"))),
496
+ };
497
+
498
+ if let Some(query) = config.query {
499
+ request = request.add_query_params(&query);
500
+ }
501
+
502
+ for (name, value) in config.headers {
503
+ request = request.add_header(name.as_str(), value.as_str());
504
+ }
505
+
506
+ for (name, value) in config.cookies {
507
+ request = request.add_cookie(Cookie::new(name, value));
508
+ }
509
+
510
+ if let Some(body) = config.body {
511
+ match body {
512
+ RequestBody::Json(json_value) => {
513
+ request = request.json(&json_value);
514
+ }
515
+ RequestBody::Form(form_value) => {
516
+ let encoded = encode_urlencoded_body(&form_value)
517
+ .map_err(|err| NativeRequestError(format!("Failed to encode form body: {err}")))?;
518
+ request = request
519
+ .content_type("application/x-www-form-urlencoded")
520
+ .bytes(Bytes::from(encoded));
521
+ }
522
+ RequestBody::Raw(raw) => {
523
+ request = request.bytes(Bytes::from(raw));
524
+ }
525
+ RequestBody::Multipart { form_data, files } => {
526
+ let (multipart_body, boundary) = build_multipart_body(&form_data, &files);
527
+ request = request
528
+ .content_type(&format!("multipart/form-data; boundary={}", boundary))
529
+ .bytes(Bytes::from(multipart_body));
530
+ }
531
+ }
532
+ }
533
+
534
+ let response = request.await;
535
+ let snapshot = snapshot_response(response).await.map_err(snapshot_err_to_native)?;
536
+ let body_text = if snapshot.body.is_empty() {
537
+ None
538
+ } else {
539
+ Some(String::from_utf8_lossy(&snapshot.body).into_owned())
540
+ };
541
+
542
+ Ok(TestResponseData {
543
+ status: snapshot.status,
544
+ headers: snapshot.headers,
545
+ body_text,
546
+ })
547
+ }
548
+
549
+ fn snapshot_err_to_native(err: SnapshotError) -> NativeRequestError {
550
+ NativeRequestError(err.to_string())
551
+ }