1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! In-memory test client (spec §4.1 "Test client"): no sockets, no network.
//! `override_dep` is THE testing seam — fake any dependency, run real requests.
//!
//! Panics in handlers propagate in tests by design — the serve path converts them to 500 JC0500.
use crate::App;
use crate::app::{BuiltApp, Policy};
use crate::clock::Clock;
use crate::error::Error;
use crate::response::{IntoResponse, Response};
use bytes::Bytes;
use http::{Method, StatusCode, header};
use http_body_util::BodyExt;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::any::TypeId;
use std::sync::Arc;
/// One part for [`TestApp::post_multipart`].
pub struct TestPart {
name: String,
filename: Option<String>,
content_type: Option<String>,
data: Bytes,
}
impl TestPart {
/// A simple form field.
pub fn text(name: &str, value: &str) -> Self {
Self {
name: name.to_string(),
filename: None,
content_type: None,
data: Bytes::copy_from_slice(value.as_bytes()),
}
}
/// A file-upload field.
pub fn file(name: &str, filename: &str, content_type: &str, data: &[u8]) -> Self {
Self {
name: name.to_string(),
filename: Some(filename.to_string()),
content_type: Some(content_type.to_string()),
data: Bytes::copy_from_slice(data),
}
}
}
/// Deterministic boundary (determinism is a framework invariant — no
/// randomness in generated bytes). Part data containing the wire delimiter
/// would silently corrupt the assembled request, so the helper debug-asserts
/// against it instead of trusting improbability.
const TEST_BOUNDARY: &str = "jerrycan-test-boundary-7f3a";
impl App {
/// Build for testing. Panics on build errors — a test should fail loudly.
///
/// Swaps the default real [`Clock`] for a controllable [`Clock::test`] via
/// the override seam (overrides outrank the app's `Clock::system` singleton)
/// and keeps a handle on the same clock — [`TestApp::clock`] returns it, so
/// `advance`/`set` move the very clock handlers resolve.
pub fn into_test(self) -> TestApp {
let mut built = self.build().expect("app failed to build");
let clock = Clock::test();
let mut overrides = (*built.overrides).clone();
overrides.insert(
TypeId::of::<Clock>(),
Arc::new(clock.clone()) as crate::dep::AnyArc,
);
built.overrides = Arc::new(overrides);
TestApp { built, clock }
}
}
pub struct TestApp {
built: BuiltApp,
/// The test clock handed to handlers via the override above. Shares its
/// offset with the resolved copy (`Clock` clones share one `Arc`), so
/// `clock().advance(..)` is observable through real requests.
clock: Clock,
}
impl TestApp {
/// Replace the provider for `T` everywhere (values AND factories) for all
/// subsequent requests. Chainable.
pub fn override_dep<T: Send + Sync + 'static>(mut self, value: T) -> Self {
let mut map = (*self.built.overrides).clone();
map.insert(TypeId::of::<T>(), Arc::new(value) as crate::dep::AnyArc);
self.built.overrides = Arc::new(map);
self
}
/// The controllable [`Clock`] injected for this test. `advance`/`set` it to
/// move domain time (rate windows, schedules, expiry) under the app; the
/// change is visible to every subsequent request and task context.
pub fn clock(&self) -> Clock {
self.clock.clone()
}
/// A [`TaskContext`](crate::TaskContext) for resolving app-level dependencies
/// outside a request, honoring any `override_dep` fakes set on this `TestApp`.
///
/// Only **app-level** dependencies (those registered with `App::provide` /
/// `App::provide_dep`) are resolvable; module-scoped providers are not in
/// scope here.
pub fn task_context(&self) -> crate::TaskContext {
self.built.task_context()
}
pub async fn get(&self, path: &str) -> TestResponse {
self.request_json(Method::GET, path, None).await
}
pub async fn delete(&self, path: &str) -> TestResponse {
self.request_json(Method::DELETE, path, None).await
}
pub async fn post_json<B: Serialize>(&self, path: &str, body: &B) -> TestResponse {
self.request_json(
Method::POST,
path,
Some(serde_json::to_vec(body).expect("serialize")),
)
.await
}
pub async fn put_json<B: Serialize>(&self, path: &str, body: &B) -> TestResponse {
self.request_json(
Method::PUT,
path,
Some(serde_json::to_vec(body).expect("serialize")),
)
.await
}
pub async fn patch_json<B: Serialize>(&self, path: &str, body: &B) -> TestResponse {
self.request_json(
Method::PATCH,
path,
Some(serde_json::to_vec(body).expect("serialize")),
)
.await
}
/// A CORS preflight (`OPTIONS`) request with headers.
pub async fn options_with(&self, path: &str, headers: &[(&str, &str)]) -> TestResponse {
self.request(http::Method::OPTIONS, path, headers, None)
.await
}
/// A by-method request with headers and an optional body. The generic seam the
/// `*_with` helpers don't cover (OPTIONS, HEAD, custom flows). No simulated
/// peer address — use `request_from` for the IP-partition rate-limit tier.
pub async fn request(
&self,
method: http::Method,
path: &str,
headers: &[(&str, &str)],
body: Option<&[u8]>,
) -> TestResponse {
self.send(
method,
path,
body.map(Bytes::copy_from_slice),
None,
headers,
None,
)
.await
}
/// POST a raw byte body (content-type `application/octet-stream`). Routes
/// and per-route body limits apply exactly as they do over a socket.
pub async fn post_bytes(&self, path: &str, bytes: &[u8]) -> TestResponse {
self.post_bytes_with(path, bytes, &[]).await
}
/// POST a raw byte body with explicit request headers.
pub async fn post_bytes_with(
&self,
path: &str,
bytes: &[u8],
headers: &[(&str, &str)],
) -> TestResponse {
self.send(
Method::POST,
path,
Some(Bytes::copy_from_slice(bytes)),
Some("application/octet-stream"),
headers,
None,
)
.await
}
/// POSTs a `multipart/form-data` request assembled from `parts`.
pub async fn post_multipart(&self, path: &str, parts: &[TestPart]) -> TestResponse {
self.post_multipart_with(path, parts, &[]).await
}
/// `post_multipart` with extra request headers (e.g. auth cookies).
pub async fn post_multipart_with(
&self,
path: &str,
parts: &[TestPart],
headers: &[(&str, &str)],
) -> TestResponse {
let mut body = Vec::new();
for part in parts {
debug_assert!(
!part
.data
.windows(TEST_BOUNDARY.len() + 4)
.any(|w| w[..4] == *b"\r\n--" && &w[4..] == TEST_BOUNDARY.as_bytes()),
"TestPart data contains the multipart delimiter — the assembled request would corrupt"
);
body.extend_from_slice(format!("--{TEST_BOUNDARY}\r\n").as_bytes());
match &part.filename {
Some(filename) => body.extend_from_slice(
format!(
"content-disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
part.name, filename
)
.as_bytes(),
),
None => body.extend_from_slice(
format!("content-disposition: form-data; name=\"{}\"\r\n", part.name)
.as_bytes(),
),
}
if let Some(content_type) = &part.content_type {
body.extend_from_slice(format!("content-type: {content_type}\r\n").as_bytes());
}
body.extend_from_slice(b"\r\n");
body.extend_from_slice(&part.data);
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(format!("--{TEST_BOUNDARY}--\r\n").as_bytes());
let content_type = format!("multipart/form-data; boundary={TEST_BOUNDARY}");
self.send(
Method::POST,
path,
Some(Bytes::from(body)),
Some(&content_type),
headers,
None,
)
.await
}
/// GET with explicit request headers (auth tests, content negotiation).
pub async fn get_with(&self, path: &str, headers: &[(&str, &str)]) -> TestResponse {
self.request_with(Method::GET, path, None, headers).await
}
/// Like `get`, but also sets the simulated client socket address (for the
/// rate-limiter's IP partition tier).
pub async fn get_from(&self, path: &str, peer: std::net::SocketAddr) -> TestResponse {
self.send(Method::GET, path, None, None, &[], Some(peer))
.await
}
/// A by-method request with headers AND a simulated peer address.
pub async fn request_from(
&self,
method: http::Method,
path: &str,
headers: &[(&str, &str)],
peer: std::net::SocketAddr,
) -> TestResponse {
self.send(method, path, None, None, headers, Some(peer))
.await
}
/// POST JSON with explicit request headers.
pub async fn post_json_with<B: Serialize>(
&self,
path: &str,
body: &B,
headers: &[(&str, &str)],
) -> TestResponse {
self.request_with(
Method::POST,
path,
Some(serde_json::to_vec(body).expect("serialize")),
headers,
)
.await
}
/// DELETE with explicit request headers (guarded-route auth tests).
pub async fn delete_with(&self, path: &str, headers: &[(&str, &str)]) -> TestResponse {
self.request_with(Method::DELETE, path, None, headers).await
}
/// PUT JSON with explicit request headers.
pub async fn put_json_with<B: Serialize>(
&self,
path: &str,
body: &B,
headers: &[(&str, &str)],
) -> TestResponse {
self.request_with(
Method::PUT,
path,
Some(serde_json::to_vec(body).expect("serialize")),
headers,
)
.await
}
/// PATCH JSON with explicit request headers.
pub async fn patch_json_with<B: Serialize>(
&self,
path: &str,
body: &B,
headers: &[(&str, &str)],
) -> TestResponse {
self.request_with(
Method::PATCH,
path,
Some(serde_json::to_vec(body).expect("serialize")),
headers,
)
.await
}
async fn request_json(
&self,
method: Method,
path: &str,
json: Option<Vec<u8>>,
) -> TestResponse {
self.request_with(method, path, json, &[]).await
}
async fn request_with(
&self,
method: Method,
path: &str,
json: Option<Vec<u8>>,
headers: &[(&str, &str)],
) -> TestResponse {
let content_type = json.as_ref().map(|_| "application/json");
self.send(
method,
path,
json.map(Bytes::from),
content_type,
headers,
None,
)
.await
}
/// The single test request path: build the head, run the SAME two-phase
/// policy the live server runs (route before body, per-route limit), then
/// dispatch. Stream routes get a real framed lane with the route's `Limited`
/// cap inside it (the equivalent of `Limited` over a socket); buffered routes
/// keep the upfront length check on the already-buffered bytes. Either way
/// this keeps 404-before-read and per-route 413 honest in tests.
async fn send(
&self,
method: Method,
path: &str,
body: Option<Bytes>,
content_type: Option<&str>,
headers: &[(&str, &str)],
peer: Option<std::net::SocketAddr>,
) -> TestResponse {
let mut builder = http::Request::builder().method(method).uri(path);
// Apply the helper's default content-type only when the explicit headers
// don't already set one — otherwise an explicit `content-type` (e.g. a
// `multipart/form-data` boundary) would be shadowed by the default, since
// `HeaderMap::get` returns the first value inserted.
let explicit_ct = headers
.iter()
.any(|(name, _)| name.eq_ignore_ascii_case("content-type"));
if let Some(ct) = content_type
&& !explicit_ct
{
builder = builder.header(header::CONTENT_TYPE, ct);
}
for (name, value) in headers {
builder = builder.header(*name, *value);
}
let req = builder.body(()).expect("test request build");
let (mut parts, ()) = req.into_parts();
// Inject the simulated peer the same way the serve loop does, so IP-based
// rate-limit tests run in-memory with the address already on the request.
if let Some(peer) = peer {
parts.extensions.insert(crate::extract::ClientAddr(peer));
}
let body = body.unwrap_or_default();
// Capture the request Origin before `parts` is moved into dispatch, so the
// in-process 413 path mirrors serve.rs's `finish_error` and CORS-decorates
// a cross-origin over-limit response.
let cors_origin = parts.headers.get(http::header::ORIGIN).cloned();
// Phase 1: route on the head alone — a reject answers without reading the body.
let (limit, stream) = match self.built.route_policy(&parts) {
Policy::Reject(response) => return TestResponse::collect(response).await,
Policy::Route { limit, stream } => (limit, stream),
};
// Phase 2: stream routes get a REAL stream lane — frames + the route's
// `Limited` cap inside it, exactly like the live socket path, so the
// cumulative cap (and frame straddling) are honest in tests too. The
// buffered path keeps its upfront length check.
let lane = if stream {
crate::extract::BodyLane::Stream(Some(test_stream_lane(body, limit)))
} else {
if body.len() > limit {
let mut response = Error::payload_too_large().into_response();
if self.built.security_headers {
crate::app::apply_security_headers(&mut response);
}
if let Some(config) = &self.built.cors {
crate::cors::apply_cors(&mut response, cors_origin.as_ref(), config);
}
return TestResponse::collect(response).await;
}
crate::extract::BodyLane::Buffered(body)
};
TestResponse::collect(self.built.dispatch(parts, lane).await).await
}
}
/// A test-only stream lane: chop the buffered body into 13-byte frames so every
/// test on a stream route exercises frame straddling for free, then wrap in the
/// route's `Limited` cap so the cumulative cap trips in-process exactly as it
/// does over a socket.
fn test_stream_lane(body: Bytes, limit: usize) -> crate::extract::StreamLane {
struct Frames(std::collections::VecDeque<Bytes>);
impl http_body::Body for Frames {
type Data = Bytes;
type Error = Box<dyn std::error::Error + Send + Sync>;
fn poll_frame(
mut self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Result<http_body::Frame<Bytes>, Self::Error>>> {
std::task::Poll::Ready(self.0.pop_front().map(|b| Ok(http_body::Frame::data(b))))
}
}
let frames = body.chunks(13).map(Bytes::copy_from_slice).collect();
// `Limited<Frames>::Error` is already `Box<dyn Error + Send + Sync>` (Frames'
// error type), so the cap maps straight into the lane's error channel.
let limited = http_body_util::Limited::new(Frames(frames), limit);
http_body_util::combinators::UnsyncBoxBody::new(limited)
}
pub struct TestResponse {
status: StatusCode,
headers: http::HeaderMap,
body: Bytes,
}
impl TestResponse {
async fn collect(res: Response) -> Self {
let (parts, body) = res.into_parts();
let body = body
.collect()
// A buffered body cannot fail; a streaming one can fail mid-stream.
.await
.unwrap_or_else(|e| panic!("response body failed mid-stream: {e}"))
.to_bytes();
Self {
status: parts.status,
headers: parts.headers,
body,
}
}
pub fn status(&self) -> StatusCode {
self.status
}
pub fn headers(&self) -> &http::HeaderMap {
&self.headers
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
/// The raw response body — for binary downloads where `text()` would mangle.
pub fn bytes(&self) -> &[u8] {
&self.body
}
/// Deserialize the JSON body, with a readable panic on mismatch.
pub fn json<T: DeserializeOwned>(&self) -> T {
serde_json::from_slice(&self.body).unwrap_or_else(|e| {
panic!(
"response body is not the expected JSON shape: {e}\nbody: {}",
self.text()
)
})
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
#[tokio::test]
async fn post_multipart_builds_a_parseable_request() {
use crate::multipart::Multipart;
async fn upload(mut mp: Multipart) -> Result<Json<Vec<String>>> {
let mut seen = Vec::new();
while let Some(part) = mp.next_part().await? {
let label = match part.filename() {
Some(f) => format!("{}:{}", part.name(), f),
None => part.name().to_string(),
};
let len = part.bytes().await?.len();
seen.push(format!("{label}({len})"));
}
Ok(Json(seen))
}
let t = App::new()
.route("/upload", post(upload).stream_body())
.into_test();
let res = t
.post_multipart(
"/upload",
&[
TestPart::text("title", "Q3 leads"),
TestPart::file("csv", "leads.csv", "text/csv", b"a,b\n1,2\n"),
],
)
.await;
assert_eq!(res.status().as_u16(), 200, "body: {}", res.text());
assert_eq!(
res.json::<Vec<String>>(),
vec!["title(8)".to_string(), "csv:leads.csv(8)".to_string()]
);
}
#[tokio::test]
async fn test_response_exposes_raw_bytes() {
async fn download() -> StreamBody {
let (body, tx) = StreamBody::channel();
tokio::spawn(async move {
let _ = tx.send(&b"\x00\x01binary"[..]).await;
});
body.content_type("application/octet-stream")
}
let t = App::new().route("/dl", get(download)).into_test();
let res = t.get("/dl").await;
assert_eq!(res.bytes(), b"\x00\x01binary");
}
/// `post_multipart_with` must carry extra request headers alongside the
/// generated multipart body: the handler sees `x-auth` AND parses the parts.
#[tokio::test]
async fn post_multipart_with_carries_extra_headers() {
use crate::multipart::Multipart;
async fn upload(headers: Headers, mut mp: Multipart) -> Result<Json<(bool, usize)>> {
let authed = headers.get("x-auth").is_some();
let mut parts = 0;
while let Some(part) = mp.next_part().await? {
let _ = part.bytes().await?;
parts += 1;
}
Ok(Json((authed, parts)))
}
let t = App::new()
.route("/upload", post(upload).stream_body())
.into_test();
let res = t
.post_multipart_with(
"/upload",
&[TestPart::text("field", "value")],
&[("x-auth", "token")],
)
.await;
assert_eq!(res.status().as_u16(), 200, "body: {}", res.text());
assert_eq!(res.json::<(bool, usize)>(), (true, 1));
}
/// `into_test` injects the SAME clock `TestApp::clock()` returns: advancing
/// the handle must be visible to a dep resolved through a task context —
/// the path background jobs use to read domain time.
#[tokio::test]
async fn test_clock_handle_drives_resolved_clock_in_task_context() {
let t = App::new().into_test();
let mut ctx = t.task_context();
let resolved = ctx.resolve::<Clock>().await.unwrap();
let before = resolved.now();
t.clock().advance(std::time::Duration::from_secs(60));
assert_eq!(
resolved.now().duration_since(before).unwrap(),
std::time::Duration::from_secs(60),
"TestApp::clock() and the resolved Clock share one offset",
);
}
}