interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-localhttp / tests / behavior.rs

717 lines · 25275 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Behavior tests against a local tokio TCP server that speaks raw HTTP/1.1,
17//! so every byte on the wire is visible and every failure can be staged.
18
19use aien_localhttp::{Client, Error, DEFAULT_MAX_BODY_BYTES, MAX_HEAD_BYTES};
20use std::future::Future;
21use std::time::{Duration, Instant};
22use tokio::io::{AsyncReadExt, AsyncWriteExt};
23use tokio::net::{TcpListener, TcpStream};
24use tokio::sync::oneshot;
25use tokio::task::JoinHandle;
26
27/// Reads one request: head up to the blank line, then a Content-Length body.
28async fn read_request(stream: &mut TcpStream) -> String {
29 let mut raw = Vec::new();
30 let mut byte = [0u8; 1];
31 while !raw.ends_with(b"\r\n\r\n") {
32 if stream.read(&mut byte).await.unwrap() == 0 {
33 break;
34 }
35 raw.push(byte[0]);
36 }
37 let head = String::from_utf8_lossy(&raw).to_string();
38 let length = head
39 .lines()
40 .find_map(|l| {
41 let (n, v) = l.split_once(':')?;
42 n.eq_ignore_ascii_case("content-length")
43 .then(|| v.trim().parse::<usize>().unwrap())
44 })
45 .unwrap_or(0);
46 let mut body = vec![0u8; length];
47 stream.read_exact(&mut body).await.unwrap();
48 raw.extend_from_slice(&body);
49 String::from_utf8(raw).unwrap()
50}
51
52/// Accepts one connection, captures the request, then hands the stream to `script`.
53async fn serve_once<F, Fut>(script: F) -> (String, JoinHandle<String>)
54where
55 F: FnOnce(TcpStream) -> Fut + Send + 'static,
56 Fut: Future<Output = ()> + Send,
57{
58 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
59 let addr = listener.local_addr().unwrap();
60 let handle = tokio::spawn(async move {
61 let (mut stream, _) = listener.accept().await.unwrap();
62 let request = read_request(&mut stream).await;
63 script(stream).await;
64 request
65 });
66 (format!("http://{addr}"), handle)
67}
68
69/// Writes `bytes` and closes the connection.
70async fn respond(bytes: &'static [u8]) -> (String, JoinHandle<String>) {
71 serve_once(move |mut s| async move {
72 s.write_all(bytes).await.unwrap();
73 s.shutdown().await.ok();
74 })
75 .await
76}
77
78/// Writes the head, then holds the connection open without sending more.
79async fn respond_then_stall(bytes: &'static [u8]) -> (String, JoinHandle<String>) {
80 serve_once(move |mut s| async move {
81 s.write_all(bytes).await.unwrap();
82 tokio::time::sleep(Duration::from_secs(10)).await;
83 })
84 .await
85}
86
87async fn assert_no_connection(listener: &TcpListener) {
88 let accepted = tokio::time::timeout(Duration::from_millis(150), listener.accept()).await;
89 assert!(accepted.is_err(), "the client must not connect");
90}
91
92// ---------------------------------------------------------------- happy paths
93
94#[tokio::test]
95async fn get_writes_a_plain_request_and_reads_a_length_body() {
96 let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello").await;
97 let response = Client::new()
98 .get(format!("{base}/health?x=1"))
99 .send()
100 .await
101 .unwrap();
102 assert_eq!(response.status().as_u16(), 200);
103 assert!(response.status().is_success());
104 assert_eq!(response.content_length(), Some(5));
105 assert_eq!(response.text().await.unwrap(), "hello");
106 let request = server.await.unwrap();
107 let host = base.trim_start_matches("http://");
108 assert_eq!(
109 request,
110 format!(
111 "GET /health?x=1 HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n\r\n"
112 )
113 );
114}
115
116#[tokio::test]
117async fn post_json_sends_bearer_content_type_and_exact_length() {
118 let (base, server) =
119 respond(b"HTTP/1.1 201 Created\r\nContent-Length: 13\r\n\r\n{\"ok\":true}\r\n").await;
120 let response = Client::new()
121 .post(format!("{base}/api/cortex/write"))
122 .bearer_auth("tok-123")
123 .json(&serde_json::json!({"kind": "entity"}))
124 .send()
125 .await
126 .unwrap();
127 assert_eq!(response.status().as_u16(), 201);
128 let value: serde_json::Value = response.json().await.unwrap();
129 assert_eq!(value["ok"], true);
130 let request = server.await.unwrap();
131 assert!(request.starts_with("POST /api/cortex/write HTTP/1.1\r\n"));
132 assert!(request.contains("\r\nAuthorization: Bearer tok-123\r\n"));
133 assert!(request.contains("\r\nContent-Type: application/json\r\n"));
134 assert!(request.contains("\r\nContent-Length: 17\r\n"));
135 assert!(request.ends_with("\r\n\r\n{\"kind\":\"entity\"}"));
136}
137
138#[tokio::test]
139async fn caller_content_type_is_kept_and_not_duplicated() {
140 let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await;
141 Client::new()
142 .post(&base)
143 .header("Content-Type", "application/json")
144 .json(&serde_json::json!({}))
145 .send()
146 .await
147 .unwrap();
148 let request = server.await.unwrap();
149 assert_eq!(request.matches("Content-Type").count(), 1, "{request}");
150}
151
152#[tokio::test]
153async fn raw_body_and_empty_post_send_their_lengths() {
154 let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await;
155 Client::new()
156 .post(&base)
157 .header("content-type", "application/json")
158 .body(b"{\"a\":1}".to_vec())
159 .send()
160 .await
161 .unwrap();
162 let request = server.await.unwrap();
163 assert!(request.contains("\r\nContent-Length: 7\r\n"));
164 assert!(request.ends_with("{\"a\":1}"));
165
166 let (base, server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n").await;
167 Client::new().post(&base).send().await.unwrap();
168 assert!(server.await.unwrap().contains("\r\nContent-Length: 0\r\n"));
169}
170
171#[tokio::test]
172async fn chunked_body_with_extensions_and_trailers_is_decoded() {
173 let (base, _server) = respond(
174 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\
175 5;ext=1\r\nhello\r\n1\r\n \r\n5\r\nworld\r\n0\r\nX-Trailer: t\r\n\r\n",
176 )
177 .await;
178 let response = Client::new().get(&base).send().await.unwrap();
179 assert_eq!(response.content_length(), None);
180 assert_eq!(response.text().await.unwrap(), "hello world");
181}
182
183#[tokio::test]
184async fn close_delimited_body_reads_to_eof() {
185 let (base, _server) = respond(b"HTTP/1.0 200 OK\r\n\r\nuntil the end").await;
186 let body = Client::new().get(&base).send().await.unwrap().bytes().await;
187 assert_eq!(body.unwrap(), b"until the end");
188}
189
190#[tokio::test]
191async fn interim_100_is_skipped_and_204_has_no_body() {
192 let (base, _server) = respond(
193 b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 204 No Content\r\nContent-Length: 9\r\n\r\n",
194 )
195 .await;
196 let response = Client::new().get(&base).send().await.unwrap();
197 assert_eq!(response.status().as_u16(), 204);
198 assert_eq!(response.bytes().await.unwrap(), b"");
199}
200
201#[tokio::test]
202async fn error_status_keeps_its_body_and_reqwest_style_display() {
203 let (base, _server) =
204 respond(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 4\r\nX-Id: 7\r\n\r\nboom")
205 .await;
206 let response = Client::new().get(&base).send().await.unwrap();
207 assert!(!response.status().is_success());
208 assert_eq!(response.status().to_string(), "500 Internal Server Error");
209 assert_eq!(response.header("x-id"), Some("7"));
210 assert_eq!(response.text().await.unwrap(), "boom");
211}
212
213#[tokio::test]
214async fn next_line_yields_each_sse_event_as_it_arrives() {
215 let (release_tx, release_rx) = oneshot::channel::<()>();
216 let (base, _server) = serve_once(move |mut s| async move {
217 s.write_all(
218 b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n",
219 )
220 .await
221 .unwrap();
222 s.write_all(b"13\r\ndata: {\"t\":\"one\"}\n\n\r\n")
223 .await
224 .unwrap();
225 // The second event is only sent after the client has seen the first.
226 release_rx.await.unwrap();
227 s.write_all(b"13\r\ndata: {\"t\":\"two\"}\n\n\r\ne\r\ndata: [DONE]\n\n\r\n0\r\n\r\n")
228 .await
229 .unwrap();
230 })
231 .await;
232 let mut response = Client::new().post(&base).send().await.unwrap();
233 assert_eq!(
234 response.next_line().await.unwrap().as_deref(),
235 Some("data: {\"t\":\"one\"}")
236 );
237 assert_eq!(response.next_line().await.unwrap().as_deref(), Some(""));
238 release_tx.send(()).unwrap();
239 let mut rest = Vec::new();
240 while let Some(line) = response.next_line().await.unwrap() {
241 rest.push(line);
242 }
243 assert_eq!(rest, ["data: {\"t\":\"two\"}", "", "data: [DONE]", ""]);
244}
245
246#[tokio::test]
247async fn next_line_joins_a_line_split_across_chunks_and_strips_crlf() {
248 let (base, _server) = respond(
249 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\
250 4\r\ndata\r\n7\r\n: half\r\r\n5\r\n\nlast\r\n0\r\n\r\n",
251 )
252 .await;
253 let mut response = Client::new().get(&base).send().await.unwrap();
254 assert_eq!(
255 response.next_line().await.unwrap().as_deref(),
256 Some("data: half")
257 );
258 assert_eq!(response.next_line().await.unwrap().as_deref(), Some("last"));
259 assert_eq!(response.next_line().await.unwrap(), None);
260}
261
262#[tokio::test]
263async fn chunk_hands_out_body_pieces_in_order() {
264 let (base, _server) = respond(
265 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n2\r\nde\r\n0\r\n\r\n",
266 )
267 .await;
268 let mut response = Client::new().get(&base).send().await.unwrap();
269 let mut all = Vec::new();
270 while let Some(piece) = response.chunk().await.unwrap() {
271 all.extend(piece);
272 }
273 assert_eq!(all, b"abcde");
274}
275
276// ------------------------------------------------------------- refusals (no I/O)
277
278#[tokio::test]
279async fn https_is_refused_before_any_connection() {
280 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
281 let port = listener.local_addr().unwrap().port();
282 let error = Client::new()
283 .get(format!("https://127.0.0.1:{port}/health"))
284 .send()
285 .await
286 .unwrap_err();
287 assert!(matches!(error, Error::HttpsRefused { .. }), "{error:?}");
288 assert!(error.to_string().contains("https is refused"));
289 assert_no_connection(&listener).await;
290}
291
292#[tokio::test]
293async fn other_schemes_and_bad_urls_are_refused() {
294 let error = Client::new()
295 .get("ftp://127.0.0.1/")
296 .send()
297 .await
298 .unwrap_err();
299 assert!(
300 matches!(error, Error::UnsupportedScheme { .. }),
301 "{error:?}"
302 );
303 let error = Client::new().get("127.0.0.1:80").send().await.unwrap_err();
304 assert!(matches!(error, Error::InvalidUrl { .. }), "{error:?}");
305}
306
307#[tokio::test]
308async fn header_injection_and_framing_overrides_are_refused() {
309 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
310 let base = format!("http://{}", listener.local_addr().unwrap());
311 for (name, value) in [
312 ("X-A", "a\r\nX-Injected: 1"),
313 ("X-A", "a\nb"),
314 ("Bad Name", "v"),
315 ("", "v"),
316 ("Content-Length", "1"),
317 ("transfer-encoding", "chunked"),
318 ("Host", "evil"),
319 ("Connection", "keep-alive"),
320 ] {
321 let error = Client::new()
322 .get(&base)
323 .header(name, value)
324 .send()
325 .await
326 .unwrap_err();
327 assert!(
328 matches!(error, Error::InvalidHeader { .. }),
329 "{name}: {error:?}"
330 );
331 }
332 let error = Client::new()
333 .get(&base)
334 .bearer_auth("tok\r\nX: y")
335 .send()
336 .await
337 .unwrap_err();
338 assert!(matches!(error, Error::InvalidHeader { .. }));
339 assert_no_connection(&listener).await;
340}
341
342#[tokio::test]
343async fn connect_refused_is_a_connect_error() {
344 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
345 let port = listener.local_addr().unwrap().port();
346 drop(listener);
347 let error = Client::builder()
348 .connect_timeout(Duration::from_secs(2))
349 .build()
350 .get(format!("http://127.0.0.1:{port}/"))
351 .send()
352 .await
353 .unwrap_err();
354 assert!(error.is_connect(), "{error:?}");
355 assert!(!error.is_timeout());
356}
357
358// ------------------------------------------------------------------- size caps
359
360#[tokio::test]
361async fn oversize_content_length_is_refused() {
362 let (base, _server) =
363 respond_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 11\r\n\r\nhello").await;
364 let client = Client::builder().max_body_bytes(10).build();
365 let error = client.get(&base).send().await.unwrap().bytes().await;
366 assert!(
367 matches!(error, Err(Error::BodyTooLarge { limit: 10 })),
368 "{error:?}"
369 );
370}
371
372#[tokio::test]
373async fn oversize_chunked_body_is_refused() {
374 let (base, _server) = respond(
375 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nabcdef\r\n6\r\nghijkl\r\n0\r\n\r\n",
376 )
377 .await;
378 let client = Client::builder().max_body_bytes(10).build();
379 let error = client.get(&base).send().await.unwrap().bytes().await;
380 assert!(
381 matches!(error, Err(Error::BodyTooLarge { limit: 10 })),
382 "{error:?}"
383 );
384}
385
386#[tokio::test]
387async fn oversize_close_delimited_body_is_refused() {
388 let (base, _server) = respond(b"HTTP/1.1 200 OK\r\n\r\n0123456789abc").await;
389 let client = Client::builder().max_body_bytes(10).build();
390 let error = client.get(&base).send().await.unwrap().text().await;
391 assert!(
392 matches!(error, Err(Error::BodyTooLarge { limit: 10 })),
393 "{error:?}"
394 );
395}
396
397#[tokio::test]
398async fn body_exactly_at_the_cap_is_accepted() {
399 let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n0123456789").await;
400 let client = Client::builder().max_body_bytes(10).build();
401 let body = client
402 .get(&base)
403 .send()
404 .await
405 .unwrap()
406 .bytes()
407 .await
408 .unwrap();
409 assert_eq!(body.len(), 10);
410 assert_eq!(DEFAULT_MAX_BODY_BYTES, 16 * 1024 * 1024);
411}
412
413#[tokio::test]
414async fn oversize_response_head_is_refused() {
415 let (base, _server) = serve_once(|mut s| async move {
416 let mut head = b"HTTP/1.1 200 OK\r\nX-Big: ".to_vec();
417 head.extend(std::iter::repeat_n(b'a', MAX_HEAD_BYTES));
418 head.extend_from_slice(b"\r\n\r\n");
419 let _ = s.write_all(&head).await;
420 })
421 .await;
422 let error = Client::new().get(&base).send().await.unwrap_err();
423 assert!(matches!(error, Error::HeadTooLarge { .. }), "{error:?}");
424}
425
426// -------------------------------------------------------------------- timeouts
427
428#[tokio::test]
429async fn silent_server_hits_the_total_timeout() {
430 let (base, _server) = serve_once(|s| async move {
431 let _hold = s;
432 tokio::time::sleep(Duration::from_secs(10)).await;
433 })
434 .await;
435 let started = Instant::now();
436 let error = Client::builder()
437 .timeout(Duration::from_millis(200))
438 .build()
439 .get(&base)
440 .send()
441 .await
442 .unwrap_err();
443 assert!(
444 matches!(error, Error::Timeout(d) if d == Duration::from_millis(200)),
445 "{error:?}"
446 );
447 assert!(error.is_timeout());
448 assert!(started.elapsed() < Duration::from_secs(3));
449}
450
451#[tokio::test]
452async fn request_timeout_overrides_the_client_timeout() {
453 let (base, _server) = serve_once(|s| async move {
454 let _hold = s;
455 tokio::time::sleep(Duration::from_secs(10)).await;
456 })
457 .await;
458 let error = Client::builder()
459 .timeout(Duration::from_secs(30))
460 .build()
461 .get(&base)
462 .timeout(Duration::from_millis(150))
463 .send()
464 .await
465 .unwrap_err();
466 assert!(
467 matches!(error, Error::Timeout(d) if d == Duration::from_millis(150)),
468 "{error:?}"
469 );
470}
471
472#[tokio::test]
473async fn stalled_body_hits_the_total_timeout() {
474 let (base, _server) =
475 respond_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial").await;
476 let response = Client::builder()
477 .timeout(Duration::from_millis(250))
478 .build()
479 .get(&base)
480 .send()
481 .await
482 .unwrap();
483 let error = response.bytes().await.unwrap_err();
484 assert!(matches!(error, Error::Timeout(_)), "{error:?}");
485}
486
487#[tokio::test]
488async fn stalled_stream_line_hits_the_total_timeout() {
489 let (base, _server) =
490 respond_then_stall(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n6\r\ndata: \r\n")
491 .await;
492 let mut response = Client::builder()
493 .timeout(Duration::from_millis(250))
494 .build()
495 .get(&base)
496 .send()
497 .await
498 .unwrap();
499 let error = response.next_line().await.unwrap_err();
500 assert!(matches!(error, Error::Timeout(_)), "{error:?}");
501}
502
503// ----------------------------------------------------- malformed and early close
504
505#[tokio::test]
506async fn malformed_chunk_size_is_refused() {
507 let (base, _server) =
508 respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\nhello\r\n0\r\n\r\n")
509 .await;
510 let error = Client::new().get(&base).send().await.unwrap().bytes().await;
511 assert!(matches!(error, Err(Error::MalformedChunk(_))), "{error:?}");
512}
513
514#[tokio::test]
515async fn chunk_without_trailing_crlf_is_refused() {
516 let (base, _server) =
517 respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhelloXX0\r\n\r\n")
518 .await;
519 let error = Client::new().get(&base).send().await.unwrap().bytes().await;
520 assert!(matches!(error, Err(Error::MalformedChunk(_))), "{error:?}");
521}
522
523#[tokio::test]
524async fn oversized_chunk_size_number_is_refused() {
525 let (base, _server) =
526 respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n10000000000000000\r\nx\r\n")
527 .await;
528 let error = Client::new().get(&base).send().await.unwrap().bytes().await;
529 assert!(matches!(error, Err(Error::MalformedChunk(_))), "{error:?}");
530}
531
532#[tokio::test]
533async fn early_close_before_the_status_line() {
534 let (base, _server) = serve_once(|s| async move { drop(s) }).await;
535 let error = Client::new().get(&base).send().await.unwrap_err();
536 assert!(matches!(error, Error::EarlyClose(_)), "{error:?}");
537}
538
539#[tokio::test]
540async fn early_close_inside_the_head() {
541 let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Len").await;
542 let error = Client::new().get(&base).send().await.unwrap_err();
543 assert!(matches!(error, Error::EarlyClose(_)), "{error:?}");
544}
545
546#[tokio::test]
547async fn early_close_inside_a_length_body() {
548 let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabcd").await;
549 let error = Client::new().get(&base).send().await.unwrap().bytes().await;
550 match error {
551 Err(Error::EarlyClose(why)) => assert!(why.contains("4 of 10"), "{why}"),
552 other => panic!("expected EarlyClose, got {other:?}"),
553 }
554}
555
556#[tokio::test]
557async fn early_close_inside_a_chunk() {
558 let (base, _server) =
559 respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\na\r\nabc").await;
560 let error = Client::new().get(&base).send().await.unwrap().bytes().await;
561 assert!(matches!(error, Err(Error::EarlyClose(_))), "{error:?}");
562}
563
564#[tokio::test]
565async fn early_close_before_the_last_chunk() {
566 let (base, _server) =
567 respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n").await;
568 let mut response = Client::new().get(&base).send().await.unwrap();
569 assert_eq!(response.chunk().await.unwrap().unwrap(), b"abc");
570 let error = response.chunk().await;
571 assert!(matches!(error, Err(Error::EarlyClose(_))), "{error:?}");
572}
573
574#[tokio::test]
575async fn malformed_heads_are_refused() {
576 for raw in [
577 &b"HTTP/2 200 OK\r\n\r\n"[..],
578 b"HTTP/1.1 2x0 OK\r\n\r\n",
579 b"HTTP/1.1 200 OK\r\nNo colon here\r\n\r\n",
580 b"HTTP/1.1 200 OK\r\nA: b\r\n folded\r\n\r\n",
581 b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\nabc",
582 b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Length: 4\r\n\r\nabc",
583 b"HTTP/1.1 101 Switching Protocols\r\n\r\n",
584 ] {
585 let (base, _server) = respond(raw).await;
586 let error = Client::new().get(&base).send().await.unwrap_err();
587 assert!(
588 matches!(error, Error::MalformedResponse(_)),
589 "{:?}: {error:?}",
590 String::from_utf8_lossy(raw)
591 );
592 }
593}
594
595#[tokio::test]
596async fn invalid_json_body_is_a_decode_error() {
597 let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\nnot").await;
598 let error = Client::new()
599 .get(&base)
600 .send()
601 .await
602 .unwrap()
603 .json::<serde_json::Value>()
604 .await;
605 assert!(matches!(error, Err(Error::Decode(_))), "{error:?}");
606}
607
608// -------------------------------------------------------------------- blocking
609
610#[test]
611fn send_blocking_works_from_a_plain_thread() {
612 // The server runs on its own runtime; the caller thread has none.
613 let runtime = tokio::runtime::Runtime::new().unwrap();
614 let (base, handle) =
615 runtime.block_on(respond(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"));
616 let response = Client::builder()
617 .timeout(Duration::from_secs(5))
618 .build()
619 .post(format!("{base}/v1/probe"))
620 .header("content-type", "application/json")
621 .body(b"{}".to_vec())
622 .send_blocking()
623 .unwrap();
624 assert!(response.status().is_success());
625 assert_eq!(response.text(), "ok");
626 let request = runtime.block_on(handle).unwrap();
627 assert!(request.starts_with("POST /v1/probe HTTP/1.1\r\n"));
628}
629
630#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
631async fn send_blocking_works_inside_a_runtime() {
632 let (base, _server) = respond(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 2\r\n\r\nno").await;
633 let response = Client::new().get(&base).send_blocking().unwrap();
634 assert_eq!(response.status().as_u16(), 403);
635 assert_eq!(response.bytes(), b"no");
636}
637
638#[test]
639fn send_blocking_refuses_https_and_reports_timeouts() {
640 let error = Client::new()
641 .post("https://127.0.0.1:1/v1/probe")
642 .send_blocking()
643 .unwrap_err();
644 assert!(matches!(error, Error::HttpsRefused { .. }), "{error:?}");
645
646 let runtime = tokio::runtime::Runtime::new().unwrap();
647 let (base, _server) = runtime.block_on(serve_once(|s| async move {
648 let _hold = s;
649 tokio::time::sleep(Duration::from_secs(10)).await;
650 }));
651 let error = Client::builder()
652 .timeout(Duration::from_millis(200))
653 .build()
654 .get(&base)
655 .send_blocking()
656 .unwrap_err();
657 assert!(matches!(error, Error::Timeout(_)), "{error:?}");
658}
659
660// ------------------------------------------------- review round 1 regressions
661
662#[tokio::test]
663async fn empty_transfer_encoding_with_content_length_is_refused() {
664 let (base, _server) =
665 respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: \r\nContent-Length: 3\r\n\r\nabc").await;
666 let error = Client::new().get(&base).send().await.unwrap_err();
667 assert!(
668 matches!(&error, Error::MalformedResponse(m) if m.contains("both")),
669 "{error:?}"
670 );
671}
672
673#[tokio::test]
674async fn empty_transfer_encoding_alone_is_refused() {
675 let (base, _server) = respond(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: \r\n\r\nabc").await;
676 let error = Client::new().get(&base).send().await.unwrap_err();
677 assert!(
678 matches!(&error, Error::MalformedResponse(m) if m.contains("unsupported")),
679 "{error:?}"
680 );
681}
682
683#[tokio::test(flavor = "multi_thread")]
684async fn blocking_status_returns_before_a_stalled_body() {
685 let (base, _server) =
686 respond_then_stall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 100\r\n\r\npartial").await;
687 let started = Instant::now();
688 let status = tokio::task::spawn_blocking(move || {
689 Client::builder()
690 .timeout(Duration::from_secs(5))
691 .build()
692 .get(&base)
693 .send_blocking_status()
694 })
695 .await
696 .unwrap()
697 .unwrap();
698 assert_eq!(status.as_u16(), 403);
699 assert!(started.elapsed() < Duration::from_secs(2));
700}
701
702#[tokio::test(flavor = "multi_thread")]
703async fn blocking_full_read_of_a_stalled_body_times_out() {
704 let (base, _server) =
705 respond_then_stall(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial").await;
706 let error = tokio::task::spawn_blocking(move || {
707 Client::builder()
708 .timeout(Duration::from_millis(250))
709 .build()
710 .get(&base)
711 .send_blocking()
712 })
713 .await
714 .unwrap()
715 .unwrap_err();
716 assert!(matches!(error, Error::Timeout(_)), "{error:?}");
717}