1use std::collections::{BTreeMap, BTreeSet};
5use std::io::{Read, Write};
6use std::net::{SocketAddr, TcpListener, TcpStream};
7use std::path::{Path, PathBuf};
8use std::process::{Child, Command, Stdio};
9use std::time::{Duration, Instant};
10
11use anyhow::{Context, Result, bail, ensure};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use toml_edit::{DocumentMut, Item, Table, value};
15
16use crate::app::{
17 self, Config, Failure, Fallback, Normalizers, Problem, RecordOptions, RecordOutcome,
18 ReplayOutcome,
19};
20
21pub const HTTP_DIR: &str = "http";
22const READY: Duration = Duration::from_secs(60);
23const SKIP_HEADERS: [&str; 12] = [
24 "date",
25 "host",
26 "server",
27 "connection",
28 "keep-alive",
29 "transfer-encoding",
30 "content-length",
31 "x-powered-by",
32 "etag",
33 "last-modified",
34 "age",
35 "via",
36];
37const LOCAL_HOSTS: [&str; 4] = ["localhost", "127.0.0.1", "0.0.0.0", "[::1]"];
38
39#[derive(Debug, Clone, Default, Serialize, Deserialize)]
41pub struct HttpConfig {
42 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub port: Option<u16>,
46 #[serde(default, skip_serializing_if = "Vec::is_empty")]
48 pub args: Vec<String>,
49 #[serde(default, skip_serializing_if = "Vec::is_empty")]
52 pub fresh: Vec<String>,
53 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub pace_ms: Option<u64>,
56}
57
58pub(crate) fn merge_config(saved: Option<HttpConfig>, opts: &RecordOptions) -> Option<HttpConfig> {
60 let asked =
61 opts.http || opts.port.is_some() || !opts.server_args.is_empty() || opts.pace_ms.is_some();
62 let mut config = match (saved, asked) {
63 (Some(c), _) => c,
64 (None, true) => HttpConfig::default(),
65 (None, false) => return None,
66 };
67 if opts.port.is_some() {
68 config.port = opts.port;
69 }
70 if !opts.server_args.is_empty() {
71 config.args = opts.server_args.to_vec();
72 }
73 if !opts.fresh.is_empty() {
74 config.fresh = opts.fresh.to_vec();
75 }
76 if let Some(pace) = opts.pace_ms {
77 config.pace_ms = (pace > 0).then_some(pace);
78 }
79 Some(config)
80}
81
82pub(crate) const FILES_DIR: &str = "files";
83
84pub(crate) fn copy_tree(from: &Path, to: &Path) -> Result<()> {
85 if from.is_dir() {
86 std::fs::create_dir_all(to)?;
87 for entry in std::fs::read_dir(from)?.flatten() {
88 copy_tree(&entry.path(), &to.join(entry.file_name()))?;
89 }
90 } else {
91 if let Some(parent) = to.parent() {
92 std::fs::create_dir_all(parent)?;
93 }
94 std::fs::copy(from, to)
95 .with_context(|| format!("copying {} to {}", from.display(), to.display()))?;
96 }
97 Ok(())
98}
99
100fn snapshot(repo: &Path, fresh: &[String]) -> Result<Option<PathBuf>> {
102 let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
103 snapshot_to(repo, fresh, &dir)
104}
105
106pub(crate) fn snapshot_to(repo: &Path, fresh: &[String], dir: &Path) -> Result<Option<PathBuf>> {
108 if fresh.is_empty() {
109 return Ok(None);
110 }
111 let dir = dir.to_path_buf();
112 let _ = std::fs::remove_dir_all(&dir);
113 for path in fresh {
114 let rel = Path::new(path);
115 ensure!(
116 rel.is_relative()
117 && rel
118 .components()
119 .all(|c| matches!(c, std::path::Component::Normal(_))),
120 "--fresh `{path}`: give a path inside the repository, relative to it"
121 );
122 let from = repo.join(rel);
123 ensure!(from.exists(), "--fresh `{path}`: no such file or folder");
124 let to = if path.ends_with('/') && from.is_dir() {
125 dir.clone()
126 } else {
127 dir.join(rel)
128 };
129 copy_tree(&from, &to)?;
130 }
131 Ok(Some(dir))
132}
133
134fn saved_snapshot(repo: &Path, config: &Config) -> Result<Option<PathBuf>> {
136 if config.http.as_ref().is_none_or(|h| h.fresh.is_empty()) {
137 return Ok(None);
138 }
139 let dir = app::cases_dir(repo).join(HTTP_DIR).join(FILES_DIR);
140 ensure!(
141 dir.is_dir(),
142 "no {}: record again to snapshot the fresh files",
143 dir.display()
144 );
145 Ok(Some(dir))
146}
147
148fn get() -> String {
149 "GET".to_string()
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
154pub struct Req {
155 #[serde(default = "get")]
156 pub method: String,
157 pub path: String,
158 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
159 pub headers: BTreeMap<String, String>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub body: Option<String>,
162}
163
164#[derive(Debug, Deserialize)]
165struct HttpInput {
166 #[serde(default)]
167 name: Option<String>,
168 #[serde(flatten)]
169 req: Req,
170}
171
172#[derive(Debug, Clone)]
173struct Resp {
174 status: u16,
175 headers: BTreeMap<String, String>,
176 body: Vec<u8>,
177}
178
179pub fn free_port() -> Result<u16> {
180 Ok(TcpListener::bind("127.0.0.1:0")?.local_addr()?.port())
181}
182
183fn local(port: u16) -> SocketAddr {
184 SocketAddr::from(([127, 0, 0, 1], port))
185}
186
187fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
188 haystack.windows(needle.len()).position(|w| w == needle)
189}
190
191fn fill(stream: &mut impl Read, buf: &mut Vec<u8>, need: usize) -> Result<()> {
192 let mut chunk = [0u8; 8192];
193 while buf.len() < need {
194 let n = stream.read(&mut chunk)?;
195 ensure!(n > 0, "the connection closed in the middle of the response");
196 buf.extend_from_slice(&chunk[..n]);
197 }
198 Ok(())
199}
200
201fn chunk_line_end(stream: &mut impl Read, buf: &mut Vec<u8>) -> Result<usize> {
202 loop {
203 if let Some(end) = find(buf, b"\r\n") {
204 return Ok(end);
205 }
206 let need = buf.len() + 1;
207 fill(stream, buf, need)?;
208 }
209}
210
211fn read_chunked(stream: &mut impl Read, mut buf: Vec<u8>) -> Result<Vec<u8>> {
212 let mut body = Vec::new();
213 loop {
214 let line_end = chunk_line_end(stream, &mut buf)?;
215 let size_text = String::from_utf8_lossy(&buf[..line_end]).into_owned();
216 let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
217 .with_context(|| format!("bad chunk size `{size_text}`"))?;
218 buf.drain(..line_end + 2);
219 if size == 0 {
220 loop {
221 let line_end = chunk_line_end(stream, &mut buf)?;
222 if line_end == 0 {
223 return Ok(body);
224 }
225 buf.drain(..line_end + 2);
226 }
227 }
228 let end = size.checked_add(2).context("chunk size is too large")?;
229 fill(stream, &mut buf, end)?;
230 ensure!(&buf[size..end] == b"\r\n", "bad chunk terminator");
231 body.extend_from_slice(&buf[..size]);
232 buf.drain(..end);
233 }
234}
235
236fn read_response(stream: &mut impl Read, head_only: bool) -> Result<Resp> {
237 let mut buf = Vec::new();
238 let mut chunk = [0u8; 8192];
239 let (status, head, mut rest) = loop {
240 let header_end = loop {
241 if let Some(i) = find(&buf, b"\r\n\r\n") {
242 break i;
243 }
244 let n = stream.read(&mut chunk)?;
245 ensure!(n > 0, "the connection closed before a full response");
246 buf.extend_from_slice(&chunk[..n]);
247 };
248 let head = String::from_utf8_lossy(&buf[..header_end]).into_owned();
249 let status_line = head.split("\r\n").next().unwrap_or_default();
250 let status: u16 = status_line
251 .split_whitespace()
252 .nth(1)
253 .and_then(|s| s.parse().ok())
254 .with_context(|| format!("not an HTTP response: `{status_line}`"))?;
255 let rest = buf.split_off(header_end + 4);
256 if status == 101 || !(100..200).contains(&status) {
257 break (status, head, rest);
258 }
259 buf = rest;
260 };
261 let lines = head.split("\r\n").skip(1);
262 let mut headers: BTreeMap<String, String> = BTreeMap::new();
263 for line in lines {
264 if let Some((k, v)) = line.split_once(':') {
265 let v = v.trim().to_string();
266 headers
267 .entry(k.trim().to_ascii_lowercase())
268 .and_modify(|e| {
269 e.push_str(", ");
270 e.push_str(&v);
271 })
272 .or_insert(v);
273 }
274 }
275 let chunked = headers
276 .get("transfer-encoding")
277 .is_some_and(|t| t.to_ascii_lowercase().contains("chunked"));
278 let body = if head_only || status == 204 || status == 304 || (100..200).contains(&status) {
279 Vec::new()
280 } else if chunked {
281 read_chunked(stream, rest)?
282 } else if let Some(lengths) = headers.get("content-length") {
283 let parse = |value: &str| -> Result<usize> {
284 let value = value.trim();
285 ensure!(
286 !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()),
287 "invalid Content-Length"
288 );
289 value.parse().context("invalid Content-Length")
290 };
291 let mut lengths = lengths.split(',');
292 let len = parse(lengths.next().unwrap_or_default())?;
293 for other in lengths {
294 ensure!(parse(other)? == len, "conflicting Content-Length headers");
295 }
296 fill(stream, &mut rest, len)?;
297 rest.truncate(len);
298 rest
299 } else {
300 stream
301 .read_to_end(&mut rest)
302 .context("reading close-delimited HTTP body")?;
303 rest
304 };
305 Ok(Resp {
306 status,
307 headers,
308 body,
309 })
310}
311
312fn send(port: u16, req: &Req, timeout: Duration) -> Result<Resp> {
313 let mut stream = TcpStream::connect_timeout(&local(port), timeout)?;
314 stream.set_read_timeout(Some(timeout))?;
315 stream.set_write_timeout(Some(timeout))?;
316 let body = req.body.as_deref().unwrap_or("").as_bytes();
317 let mut head = format!(
318 "{} {} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n",
319 req.method, req.path
320 );
321 for (k, v) in &req.headers {
322 if !matches!(
323 k.to_ascii_lowercase().as_str(),
324 "host" | "connection" | "content-length"
325 ) {
326 head += &format!("{k}: {v}\r\n");
327 }
328 }
329 if req.body.is_some() || matches!(req.method.as_str(), "POST" | "PUT" | "PATCH") {
330 head += &format!("Content-Length: {}\r\n", body.len());
331 }
332 head += "\r\n";
333 stream.write_all(head.as_bytes())?;
334 stream.write_all(body)?;
335 read_response(&mut stream, req.method == "HEAD")
336}
337
338struct Server {
340 child: Child,
341 port: u16,
342 dir: PathBuf,
343 cwd: PathBuf,
344 log: PathBuf,
345 stopped: bool,
346 sinks: Option<crate::effects::Sinks>,
347}
348
349impl Server {
350 fn start(command: &[String], launch: &Launch, repo: &Path, port: u16) -> Result<Server> {
351 let dir = app::temp_dir("server")?;
352 let words: Vec<String> = command
353 .iter()
354 .map(|w| app::resolve_word(repo, &w.replace("{port}", &port.to_string())))
355 .collect();
356 let (program, rest) = words.split_first().context("empty command")?;
357 let log = dir.join("fallback.log");
358 let cwd = match launch.files {
359 Some(files) => {
360 let cwd = dir.join("cwd");
361 copy_tree(files, &cwd)?;
362 cwd
363 }
364 None => repo.to_path_buf(),
365 };
366 let sinks = launch
367 .effects
368 .map(|config| -> Result<_> {
369 let sinks = crate::effects::Sinks::start(config)?;
370 sinks.reset(&cwd)?;
371 Ok(sinks)
372 })
373 .transpose()?;
374 let mut child = Command::new(program)
375 .args(rest)
376 .args(
377 launch
378 .args
379 .iter()
380 .map(|a| a.replace("{port}", &port.to_string())),
381 )
382 .current_dir(&cwd)
383 .envs(sinks.iter().flat_map(crate::effects::Sinks::env))
384 .env("PORT", port.to_string())
385 .env(app::FALLBACK_ENV, &log)
386 .stdin(Stdio::null())
387 .stdout(std::fs::File::create(dir.join("stdout"))?)
388 .stderr(std::fs::File::create(dir.join("stderr"))?)
389 .spawn()
390 .with_context(|| format!("starting `{}`", command.join(" ")))?;
391 let deadline = Instant::now() + READY;
392 loop {
393 if TcpStream::connect_timeout(&local(port), Duration::from_millis(200)).is_ok() {
394 break;
395 }
396 let failure = if let Some(status) = child.try_wait()? {
397 Some(format!("exited ({status}) before listening"))
398 } else if Instant::now() > deadline {
399 Some(format!("did not listen within {}s", READY.as_secs()))
400 } else {
401 None
402 };
403 if let Some(failure) = failure {
404 let _ = child.kill();
405 let _ = child.wait();
406 let stderr = std::fs::read_to_string(dir.join("stderr")).unwrap_or_default();
407 let tail: Vec<&str> = stderr.lines().rev().take(15).collect();
408 let tail: Vec<&str> = tail.into_iter().rev().collect();
409 let _ = std::fs::remove_dir_all(&dir);
410 bail!(
411 "`{}` {failure} on port {port}{}",
412 command.join(" "),
413 if tail.is_empty() {
414 String::new()
415 } else {
416 format!(":\n{}", tail.join("\n"))
417 }
418 );
419 }
420 std::thread::sleep(Duration::from_millis(50));
421 }
422 Ok(Server {
423 child,
424 port,
425 dir,
426 cwd,
427 log,
428 stopped: false,
429 sinks,
430 })
431 }
432
433 fn fallbacks(&self) -> Option<usize> {
434 std::fs::read_to_string(&self.log)
435 .ok()
436 .map(|t| t.lines().count())
437 }
438
439 fn stop(&mut self) {
440 if self.stopped {
441 return;
442 }
443 self.stopped = true;
444 #[cfg(unix)]
445 {
446 let _ = Command::new("kill")
447 .args(["-TERM", &self.child.id().to_string()])
448 .stderr(Stdio::null())
449 .status();
450 let deadline = Instant::now() + Duration::from_secs(5);
451 while Instant::now() < deadline {
452 if let Ok(Some(_)) = self.child.try_wait() {
453 break;
454 }
455 std::thread::sleep(Duration::from_millis(20));
456 }
457 }
458 let _ = self.child.kill();
459 let _ = self.child.wait();
460 let _ = std::fs::remove_dir_all(&self.dir);
461 }
462}
463
464impl Drop for Server {
465 fn drop(&mut self) {
466 self.stop();
467 }
468}
469
470type Answer = (
471 std::result::Result<Resp, String>,
472 Option<bool>,
473 Option<Vec<u8>>,
474);
475
476struct Launch<'a> {
478 args: &'a [String],
479 files: Option<&'a Path>,
480 pace: Option<Duration>,
481 effects: Option<&'a crate::effects::EffectsConfig>,
482}
483
484fn run_all(
486 command: &[String],
487 launch: &Launch,
488 repo: &Path,
489 port: u16,
490 reqs: &[&Req],
491 timeout: Duration,
492) -> Result<Vec<Answer>> {
493 let mut server = Server::start(command, launch, repo, port)?;
494 let mut out = Vec::new();
495 for req in reqs {
496 let before = server.fallbacks().unwrap_or(0);
497 let resp = send(server.port, req, timeout).map_err(|e| format!("{e:#}"));
498 if let Some(pace) = launch.pace {
499 std::thread::sleep(pace);
500 }
501 let fell_back = server.fallbacks().map(|after| after > before);
502 let effects = server.sinks.as_ref().map(|s| s.take(&server.cwd));
503 out.push((resp, fell_back, effects));
504 }
505 server.stop();
506 Ok(out)
507}
508
509fn percent_decode(text: &str) -> String {
510 let bytes = text.as_bytes();
511 let mut out = Vec::new();
512 let mut i = 0;
513 while i < bytes.len() {
514 if bytes[i] == b'%'
515 && let Some(hex) = text.get(i + 1..i + 3)
516 && hex.len() == 2
519 && hex.bytes().all(|b| b.is_ascii_hexdigit())
520 {
521 out.push(u8::from_str_radix(hex, 16).unwrap_or(0));
522 i += 3;
523 continue;
524 }
525 out.push(bytes[i]);
526 i += 1;
527 }
528 String::from_utf8_lossy(&out).into_owned()
529}
530
531fn percent_encode(text: &str) -> String {
532 let mut out = String::new();
533 for b in text.bytes() {
534 if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
535 out.push(char::from(b));
536 } else {
537 out += &format!("%{b:02X}");
538 }
539 }
540 out
541}
542
543fn parse_curl(line: &str, repo: &Path, doc_dir: &Path) -> Option<Req> {
544 let toks = app::shell_tokens(line)?;
545 if toks.iter().any(|t| t.op) {
546 return None;
547 }
548 let words: Vec<String> = toks.into_iter().map(|t| t.text).collect();
549 let (first, args) = words.split_first()?;
550 if first != "curl" {
551 return None;
552 }
553 let mut method: Option<String> = None;
554 let mut headers = BTreeMap::new();
555 let mut data: Vec<String> = Vec::new();
556 let mut url: Option<String> = None;
557 let mut i = 0;
558 let read_file = |name: &str| -> Option<String> {
559 let name = name.strip_prefix('@')?;
560 [repo.join(name), doc_dir.join(name)]
561 .iter()
562 .find(|p| p.is_file())
563 .and_then(|p| std::fs::read_to_string(p).ok())
564 };
565 while i < args.len() {
566 let arg = &args[i];
567 let mut next = || -> Option<String> {
568 i += 1;
569 args.get(i).cloned()
570 };
571 match arg.as_str() {
572 "-X" | "--request" => method = Some(next()?),
573 "-H" | "--header" => {
574 let h = next()?;
575 let (k, v) = h.split_once(':')?;
576 headers.insert(k.trim().to_string(), v.trim().to_string());
577 }
578 "-d" | "--data" | "--data-raw" | "--data-binary" | "--data-ascii" => {
579 let d = next()?;
580 data.push(if d.starts_with('@') && arg != "--data-raw" {
581 let mut contents = read_file(&d)?;
582 if arg != "--data-binary" {
583 contents.retain(|c| !matches!(c, '\r' | '\n' | '\0'));
584 }
585 contents
586 } else {
587 d
588 });
589 }
590 "--json" => {
591 let d = next()?;
592 data.push(if d.starts_with('@') {
593 read_file(&d)?
594 } else {
595 d
596 });
597 headers
598 .entry("Content-Type".to_string())
599 .or_insert_with(|| "application/json".to_string());
600 headers
601 .entry("Accept".to_string())
602 .or_insert_with(|| "application/json".to_string());
603 }
604 "-A" | "--user-agent" => {
605 headers.insert("User-Agent".to_string(), next()?);
606 }
607 "-b" | "--cookie" => {
608 headers.insert("Cookie".to_string(), next()?);
609 }
610 "-e" | "--referer" => {
611 headers.insert("Referer".to_string(), next()?);
612 }
613 "-o" | "--output" | "-w" | "--write-out" | "-m" | "--max-time"
614 | "--connect-timeout" => {
615 next()?;
616 }
617 "--silent"
618 | "--show-error"
619 | "--include"
620 | "--verbose"
621 | "--location"
622 | "--fail"
623 | "--insecure"
624 | "--no-progress-meter" => {}
625 other if other.starts_with("-X") && other.len() > 2 => {
626 method = Some(other[2..].to_string());
627 }
628 other if other.starts_with("-H") && other.len() > 2 => {
629 let (k, v) = other[2..].split_once(':')?;
630 headers.insert(k.trim().to_string(), v.trim().to_string());
631 }
632 other
633 if other.starts_with('-')
634 && other.len() > 1
635 && !other.starts_with("--")
636 && other[1..].chars().all(|c| "sSivLfk".contains(c)) => {}
637 other if other.starts_with('-') => return None,
638 other => url = Some(other.to_string()),
639 }
640 i += 1;
641 }
642 let url = url?;
643 let (scheme, rest) = url.split_once("://").unwrap_or(("http", &url));
644 if !matches!(scheme, "http" | "https") {
645 return None;
646 }
647 let rest = rest.split('#').next()?;
648 let (host, target) = rest.split_at(rest.find(['/', '?']).unwrap_or(rest.len()));
649 let path = if target.starts_with('/') {
650 target.to_string()
651 } else {
652 format!("/{target}")
653 };
654 let host = if host.starts_with('[') {
655 host.split_inclusive(']').next().unwrap_or(host)
656 } else {
657 host.split(':').next().unwrap_or(host)
658 };
659 if !LOCAL_HOSTS.contains(&host) {
660 return None;
661 }
662 let body = (!data.is_empty()).then(|| data.join("&"));
663 if body.is_some()
664 && !headers
665 .keys()
666 .any(|k| k.eq_ignore_ascii_case("content-type"))
667 {
668 headers.insert(
669 "Content-Type".to_string(),
670 "application/x-www-form-urlencoded".to_string(),
671 );
672 }
673 let method = method.unwrap_or_else(|| if body.is_some() { "POST" } else { "GET" }.to_string());
674 Some(Req {
675 method,
676 path,
677 headers,
678 body,
679 })
680}
681
682fn read_inputs(path: &Path) -> Result<Vec<(Option<String>, Req)>> {
683 let text =
684 std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
685 let mut out = Vec::new();
686 for (n, line) in text.lines().enumerate() {
687 if line.trim().is_empty() {
688 continue;
689 }
690 let input: HttpInput = serde_json::from_str(line).with_context(|| {
691 format!(
692 "{}:{}: expected {{\"method\", \"path\", \"headers\": {{...}}, \"body\"}}",
693 path.display(),
694 n + 1
695 )
696 })?;
697 ensure!(
698 input.req.path.starts_with('/'),
699 "{}:{}: `path` must start with /",
700 path.display(),
701 n + 1
702 );
703 out.push((input.name, input.req));
704 }
705 Ok(out)
706}
707
708fn trap_values(raw: &str) -> Vec<&'static str> {
709 if raw.parse::<i128>().is_ok() {
710 app::INT_TRAPS.to_vec()
711 } else if raw.parse::<f64>().is_ok() && raw.contains(['.', 'e', 'E']) {
712 app::FLOAT_TRAPS.to_vec()
713 } else {
714 app::STRING_TRAPS.to_vec()
715 }
716}
717
718fn traps(bases: &[Req]) -> Vec<Req> {
719 let mut out = Vec::new();
720 for base in bases {
721 let (path, query) = match base.path.split_once('?') {
722 Some((p, q)) => (p, Some(q)),
723 None => (base.path.as_str(), None),
724 };
725 let segments: Vec<&str> = path.split('/').collect();
726 for i in 2..segments.len() {
727 let raw = percent_decode(segments[i]);
728 for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
729 let mut parts: Vec<String> = segments.iter().map(|s| s.to_string()).collect();
730 parts[i] = percent_encode(v);
731 let mut req = base.clone();
732 req.path = parts.join("/") + &query.map(|q| format!("?{q}")).unwrap_or_default();
733 out.push(req);
734 }
735 }
736 if let Some(query) = query {
737 let pairs: Vec<&str> = query.split('&').collect();
738 for (i, pair) in pairs.iter().enumerate() {
739 let Some((key, raw)) = pair.split_once('=') else {
740 continue;
741 };
742 let raw = percent_decode(raw);
743 for v in trap_values(&raw).into_iter().filter(|v| *v != raw) {
744 let mut new: Vec<String> = pairs.iter().map(|p| p.to_string()).collect();
745 new[i] = format!("{key}={}", percent_encode(v));
746 let mut req = base.clone();
747 req.path = format!("{path}?{}", new.join("&"));
748 out.push(req);
749 }
750 }
751 }
752 if let Some(body) = &base.body {
753 let json =
754 serde_json::from_str::<Value>(body).is_ok_and(|v| v.is_object() || v.is_array());
755 let values: &[&str] = if json {
756 &app::JSON_TRAPS
757 } else {
758 &app::STDIN_TRAPS
759 };
760 for v in values {
761 let mut req = base.clone();
762 req.body = Some(v.to_string());
763 out.push(req);
764 }
765 }
766 }
767 out.push(Req {
768 method: "GET".to_string(),
769 path: "/rust-anything-missing".to_string(),
770 headers: BTreeMap::new(),
771 body: None,
772 });
773 out.truncate(app::MAX_TRAPS);
774 out
775}
776
777fn case_slug(req: &Req) -> String {
778 let first = req
779 .path
780 .split(['/', '?'])
781 .find(|s| !s.is_empty())
782 .unwrap_or("root");
783 app::slug(&format!("{} {first}", req.method))
784}
785
786fn settle_headers(
787 norm: &Normalizers,
788 a: &BTreeMap<String, String>,
789 b: &BTreeMap<String, String>,
790) -> (BTreeMap<String, String>, bool) {
791 let mut out = BTreeMap::new();
792 let mut noisy = false;
793 for (k, va) in a {
794 if SKIP_HEADERS.contains(&k.as_str()) {
795 continue;
796 }
797 let Some(vb) = b.get(k) else {
798 noisy = true;
799 continue;
800 };
801 let (va, vb) = (norm.apply(va), norm.apply(vb));
802 if va == vb {
803 out.insert(k.clone(), va);
804 } else {
805 noisy = true;
806 out.insert(k.clone(), app::merge_line(&va, &vb));
807 }
808 }
809 noisy |= b
810 .keys()
811 .any(|k| !a.contains_key(k) && !SKIP_HEADERS.contains(&k.as_str()));
812 (out, noisy)
813}
814
815fn table(entries: &BTreeMap<String, String>) -> Table {
816 let mut t = Table::new();
817 for (k, v) in entries {
818 t[k.as_str()] = value(v.as_str());
819 }
820 t
821}
822
823fn write_case(
824 dir: &Path,
825 name: &str,
826 req: &Req,
827 status: u16,
828 headers: &BTreeMap<String, String>,
829 body: &[u8],
830 binary: bool,
831) -> Result<()> {
832 let mut doc = DocumentMut::new();
833 let mut request = Table::new();
834 request["method"] = value(req.method.as_str());
835 request["path"] = value(req.path.as_str());
836 if let Some(body) = &req.body {
837 request["body"] = value(body.as_str());
838 }
839 if !req.headers.is_empty() {
840 request.insert("headers", Item::Table(table(&req.headers)));
841 }
842 doc.insert("request", Item::Table(request));
843 let mut response = Table::new();
844 response["status"] = value(i64::from(status));
845 if binary {
846 response["binary"] = value(true);
847 }
848 if !headers.is_empty() {
849 response.insert("headers", Item::Table(table(headers)));
850 }
851 doc.insert("response", Item::Table(response));
852 std::fs::write(dir.join(format!("{name}.toml")), doc.to_string())?;
853 std::fs::write(dir.join(format!("{name}.body")), body)?;
854 Ok(())
855}
856
857pub(crate) fn record(
858 repo: &Path,
859 config: &Config,
860 norm: &Normalizers,
861 opts: &RecordOptions,
862) -> Result<RecordOutcome> {
863 let examples = app::scan_examples(repo, |line, doc_dir| parse_curl(line, repo, doc_dir));
864 let inputs = match opts.inputs {
865 Some(path) => read_inputs(path)?,
866 None => Vec::new(),
867 };
868 let mut planned: Vec<(String, Req)> = Vec::new();
869 let mut seen = BTreeSet::new();
870 let mut taken = BTreeSet::new();
871 let mut counts = [0usize; 3];
872 let mut bases = Vec::new();
873 let mut push = |kind: usize, given: Option<String>, req: Req| -> bool {
874 let key = serde_json::to_string(&req).unwrap_or_default();
875 if !seen.insert(key) {
876 return false;
877 }
878 counts[kind] += 1;
879 let prefix = ["example", "input", "trap"][kind];
880 let name = match given.map(|g| app::given_slug(&g)).filter(|g| !g.is_empty()) {
881 Some(g) => g,
882 None => format!("{prefix}-{:03}-{}", counts[kind], case_slug(&req)),
883 };
884 let name = app::reserve_case_name(&mut taken, name, counts[kind]);
885 planned.push((name, req));
886 true
887 };
888 for req in examples {
889 if push(0, None, req.clone()) {
890 bases.push(req);
891 }
892 }
893 for (given, req) in inputs {
894 if push(1, given, req.clone()) {
895 bases.push(req);
896 }
897 }
898 if bases.is_empty() {
899 let root = Req {
900 method: "GET".to_string(),
901 path: "/".to_string(),
902 headers: BTreeMap::new(),
903 body: None,
904 };
905 push(0, None, root.clone());
906 bases.push(root);
907 }
908 if opts.traps {
909 for req in traps(&bases) {
910 push(2, None, req);
911 }
912 }
913 planned.sort_by(|a, b| a.0.cmp(&b.0));
914
915 let timeout = Duration::from_secs(config.timeout_secs);
916 let fixed = config.http.as_ref().and_then(|h| h.port);
917 let reqs: Vec<&Req> = planned.iter().map(|(_, r)| r).collect();
918 let http = config.http.clone().unwrap_or_default();
919 let files = snapshot(repo, &http.fresh)?;
920 let launch = Launch {
921 args: &http.args,
922 files: files.as_deref(),
923 pace: http.pace_ms.map(Duration::from_millis),
924 effects: config.effects.as_ref(),
925 };
926 let one = run_all(
927 &config.run,
928 &launch,
929 repo,
930 fixed.map_or_else(free_port, Ok)?,
931 &reqs,
932 timeout,
933 )?;
934 let two = run_all(
935 &config.run,
936 &launch,
937 repo,
938 fixed.map_or_else(free_port, Ok)?,
939 &reqs,
940 timeout,
941 )?;
942
943 let dir = app::cases_dir(repo).join(HTTP_DIR);
944 std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
945 let mut outcome = RecordOutcome {
946 dir: dir.clone(),
947 run: config.run.clone(),
948 cases: 0,
949 examples: counts[0],
950 inputs: counts[1],
951 traps: counts[2],
952 noisy: Vec::new(),
953 noise: Vec::new(),
954 unstable: Vec::new(),
955 timed_out: Vec::new(),
956 };
957 for (((name, req), (a, _, fx_a)), (b, _, fx_b)) in planned.iter().zip(one).zip(two) {
958 let (Ok(a), Ok(b)) = (a, b) else {
959 outcome.timed_out.push(name.clone());
960 continue;
961 };
962 let (body, body_noise, binary) = app::settle_text(norm, &a.body, &b.body);
963 let (headers, header_noisy) = settle_headers(norm, &a.headers, &b.headers);
964 write_case(&dir, name, req, a.status, &headers, &body, binary)?;
965 let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
966 let _ = std::fs::remove_file(&effects_file);
967 let mut fx_noise = None;
968 if let (Some(fa), Some(fb)) = (&fx_a, &fx_b) {
969 let (fx, noise, _) = app::settle_text(norm, fa, fb);
970 std::fs::write(&effects_file, fx)?;
971 fx_noise = noise;
972 }
973 outcome.cases += 1;
974 if body_noise.is_some() || header_noisy || fx_noise.is_some() {
975 outcome.noisy.push(name.clone());
976 }
977 for (field, kind) in [
978 ("body", body_noise),
979 ("headers", header_noisy.then_some(app::NoiseKind::Values)),
980 (crate::effects::EXT, fx_noise),
981 ] {
982 if let Some(kind) = kind {
983 outcome.noise.push(app::Noise {
984 case: name.clone(),
985 field: field.to_string(),
986 kind,
987 });
988 }
989 }
990 if a.status != b.status || (binary && body_noise.is_some()) {
991 outcome.unstable.push(name.clone());
992 }
993 }
994 Ok(outcome)
995}
996
997struct Spec {
998 name: String,
999 req: Req,
1000 status: u16,
1001 headers: BTreeMap<String, String>,
1002 body: Option<Vec<u8>>,
1003 binary: bool,
1004 effects: Option<Vec<u8>>,
1005}
1006
1007fn strings(item: Option<&Item>) -> BTreeMap<String, String> {
1008 item.and_then(Item::as_table_like)
1009 .map(|t| {
1010 t.iter()
1011 .map(|(k, v)| (k.to_string(), v.as_str().unwrap_or_default().to_string()))
1012 .collect()
1013 })
1014 .unwrap_or_default()
1015}
1016
1017fn load_spec(dir: &Path, path: &Path) -> Result<Spec> {
1018 let name = path
1019 .file_stem()
1020 .map(|s| s.to_string_lossy().into_owned())
1021 .unwrap_or_default();
1022 let doc: DocumentMut = std::fs::read_to_string(path)
1023 .with_context(|| format!("reading {}", path.display()))?
1024 .parse()
1025 .with_context(|| format!("parsing {}", path.display()))?;
1026 let request = doc.get("request").context("no [request]")?;
1027 let response = doc.get("response").context("no [response]")?;
1028 let body_file = dir.join(format!("{name}.body"));
1029 let effects_file = dir.join(format!("{name}.{}", crate::effects::EXT));
1030 Ok(Spec {
1031 effects: if effects_file.exists() {
1032 Some(std::fs::read(&effects_file)?)
1033 } else {
1034 None
1035 },
1036 req: Req {
1037 method: request
1038 .get("method")
1039 .and_then(Item::as_str)
1040 .unwrap_or("GET")
1041 .to_string(),
1042 path: request
1043 .get("path")
1044 .and_then(Item::as_str)
1045 .with_context(|| format!("{}: no request.path", path.display()))?
1046 .to_string(),
1047 headers: strings(request.get("headers")),
1048 body: request
1049 .get("body")
1050 .and_then(Item::as_str)
1051 .map(str::to_string),
1052 },
1053 status: response
1054 .get("status")
1055 .and_then(Item::as_integer)
1056 .and_then(|s| u16::try_from(s).ok())
1057 .with_context(|| format!("{}: no response.status", path.display()))?,
1058 headers: strings(response.get("headers")),
1059 body: if body_file.exists() {
1060 Some(std::fs::read(&body_file)?)
1061 } else {
1062 None
1063 },
1064 binary: response
1065 .get("binary")
1066 .and_then(Item::as_bool)
1067 .unwrap_or(false),
1068 name,
1069 })
1070}
1071
1072pub(crate) fn recorded_routes(repo: &Path) -> Result<Vec<String>> {
1074 let mut seen = BTreeSet::new();
1075 let mut out = Vec::new();
1076 for spec in load_specs(&app::cases_dir(repo).join(HTTP_DIR))? {
1077 let path = spec.req.path.split('?').next().unwrap_or("/").to_string();
1078 let route = format!("{} {path}", spec.req.method);
1079 if seen.insert(route.clone()) {
1080 out.push(route);
1081 }
1082 }
1083 Ok(out)
1084}
1085
1086fn load_specs(dir: &Path) -> Result<Vec<Spec>> {
1087 let mut paths: Vec<PathBuf> = std::fs::read_dir(dir)
1088 .with_context(|| {
1089 format!(
1090 "no HTTP cases in {}: run `rust-anything app record` first",
1091 dir.display()
1092 )
1093 })?
1094 .flatten()
1095 .map(|e| e.path())
1096 .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "toml"))
1097 .collect();
1098 paths.sort();
1099 let specs = paths
1100 .iter()
1101 .map(|p| load_spec(dir, p))
1102 .collect::<Result<Vec<_>>>()?;
1103 ensure!(!specs.is_empty(), "no HTTP cases in {}", dir.display());
1104 Ok(specs)
1105}
1106
1107pub(crate) fn replay(
1108 repo: &Path,
1109 config: &Config,
1110 norm: &Normalizers,
1111 command: &[String],
1112 port: Option<u16>,
1113 case: Option<&str>,
1114 timeout: Duration,
1115) -> Result<ReplayOutcome> {
1116 let dir = app::cases_dir(repo);
1117 let specs = app::only_case(load_specs(&dir.join(HTTP_DIR))?, case, |s| &s.name)?;
1118 let port = match port.or(config.http.as_ref().and_then(|h| h.port)) {
1119 Some(p) => p,
1120 None => free_port()?,
1121 };
1122 let reqs: Vec<&Req> = specs.iter().map(|s| &s.req).collect();
1123 let files = saved_snapshot(repo, config)?;
1124 let http = config.http.clone().unwrap_or_default();
1125 let launch = Launch {
1126 args: &http.args,
1127 files: files.as_deref(),
1128 pace: http.pace_ms.map(Duration::from_millis),
1129 effects: config.effects.as_ref(),
1130 };
1131 let answers = run_all(command, &launch, repo, port, &reqs, timeout)?;
1132 let mut outcome = ReplayOutcome {
1133 build: command.to_vec(),
1134 passed: 0,
1135 total: 0,
1136 skipped: 0,
1137 failures: Vec::new(),
1138 fallback: None,
1139 report: dir.join(app::REPORT_FILE),
1140 };
1141 let (mut reported, mut fell_back) = (false, Vec::new());
1142 for (spec, (answer, fallback, effects)) in specs.iter().zip(answers) {
1143 outcome.total += 1;
1144 reported |= fallback.is_some();
1145 if fallback == Some(true) {
1146 fell_back.push(spec.name.clone());
1147 }
1148 let mut problems = Vec::new();
1149 match answer {
1150 Err(e) => problems.push(Problem {
1151 field: "response".to_string(),
1152 detail: format!("no response: {e}\n"),
1153 }),
1154 Ok(resp) => {
1155 if resp.status != spec.status {
1156 problems.push(Problem {
1157 field: "status".to_string(),
1158 detail: format!("expected {}, got {}\n", spec.status, resp.status),
1159 });
1160 }
1161 for (k, expected) in &spec.headers {
1162 let field = format!("header {k}");
1163 let key = k.to_ascii_lowercase();
1164 match resp.headers.get(&key) {
1165 None => problems.push(Problem {
1166 field,
1167 detail: format!("- {expected}\n(missing)\n"),
1168 }),
1169 Some(actual) => {
1170 let (e, a) = (norm.apply(expected), norm.apply(actual));
1171 if !app::line_matches(&e, &a) {
1172 problems.push(Problem {
1173 field,
1174 detail: format!("- {e}\n+ {a}\n"),
1175 });
1176 }
1177 }
1178 }
1179 }
1180 if let Some(expected) = &spec.body
1181 && let Some(detail) = app::compare(
1182 norm,
1183 expected,
1184 &resp.body,
1185 spec.binary,
1186 norm.unordered(&spec.name, "body"),
1187 )
1188 {
1189 problems.push(Problem {
1190 field: "body".to_string(),
1191 detail,
1192 });
1193 }
1194 }
1195 }
1196 if let Some(expected) = &spec.effects
1197 && let Some(detail) = app::compare(
1198 norm,
1199 expected,
1200 effects.as_deref().unwrap_or_default(),
1201 false,
1202 norm.unordered(&spec.name, crate::effects::EXT),
1203 )
1204 {
1205 problems.push(Problem {
1206 field: crate::effects::EXT.to_string(),
1207 detail,
1208 });
1209 }
1210 if problems.is_empty() {
1211 outcome.passed += 1;
1212 } else {
1213 outcome.failures.push(Failure {
1214 case: spec.name.clone(),
1215 args: vec![spec.req.method.clone(), spec.req.path.clone()],
1216 problems,
1217 });
1218 }
1219 }
1220 if reported {
1221 outcome.fallback = Some(Fallback {
1222 cases: fell_back.len(),
1223 total: outcome.total,
1224 rate: fell_back.len() as f64 / outcome.total.max(1) as f64,
1225 names: fell_back,
1226 });
1227 }
1228 std::fs::write(&outcome.report, app::report_markdown(&outcome))
1229 .with_context(|| format!("writing {}", outcome.report.display()))?;
1230 Ok(outcome)
1231}
1232
1233#[cfg(test)]
1234mod tests {
1235 use super::*;
1236
1237 #[test]
1238 fn curl_lines_become_requests() {
1239 let here = Path::new(".");
1240 let r = parse_curl(
1241 "curl -sS -X POST -H 'Content-Type: text/plain' -d 'hello world' http://localhost:8080/upper?x=1",
1242 here,
1243 here,
1244 )
1245 .unwrap();
1246 assert_eq!(r.method, "POST");
1247 assert_eq!(r.path, "/upper?x=1");
1248 assert_eq!(r.body.as_deref(), Some("hello world"));
1249 assert_eq!(r.headers["Content-Type"], "text/plain");
1250 let g = parse_curl("curl 127.0.0.1:3000", here, here).unwrap();
1251 assert_eq!((g.method.as_str(), g.path.as_str()), ("GET", "/"));
1252 let form = parse_curl("curl -d a=1 http://[::1]:80/f", here, here).unwrap();
1253 assert_eq!(form.method, "POST");
1254 assert_eq!(
1255 form.headers["Content-Type"],
1256 "application/x-www-form-urlencoded"
1257 );
1258 assert!(parse_curl("curl https://example.com/x", here, here).is_none());
1259 let query = parse_curl("curl 'http://localhost?x=y#section'", here, here).unwrap();
1260 assert_eq!(query.path, "/?x=y");
1261 let fragment = parse_curl("curl 'http://[::1]:8080/path#section'", here, here).unwrap();
1262 assert_eq!(fragment.path, "/path");
1263 assert!(parse_curl("curl ftp://localhost/file", here, here).is_none());
1264 assert!(parse_curl("curl --unknown x http://localhost/", here, here).is_none());
1265 assert!(parse_curl("curl http://localhost/ | jq .", here, here).is_none());
1266 }
1267
1268 #[test]
1269 fn a_curl_example_wrapped_over_lines_is_one_request() {
1270 let repo = std::env::temp_dir().join(format!("ra-curl-wrapped-{}", std::process::id()));
1271 let _ = std::fs::remove_dir_all(&repo);
1272 std::fs::create_dir_all(&repo).unwrap();
1273 std::fs::write(
1274 repo.join("README.md"),
1275 "```sh\ncurl -X POST http://localhost:8080/users \\\n -H 'Content-Type: application/json' \\\n -d '{\"name\":\"ada\"}'\n```\n",
1276 )
1277 .unwrap();
1278 let reqs = app::scan_examples(&repo, |line, doc_dir| parse_curl(line, &repo, doc_dir));
1279 std::fs::remove_dir_all(&repo).unwrap();
1280 assert_eq!(reqs.len(), 1, "{reqs:?}");
1281 assert_eq!(
1282 (reqs[0].method.as_str(), reqs[0].path.as_str()),
1283 ("POST", "/users")
1284 );
1285 assert_eq!(reqs[0].body.as_deref(), Some("{\"name\":\"ada\"}"));
1286 assert_eq!(reqs[0].headers["Content-Type"], "application/json");
1287 }
1288
1289 #[test]
1290 fn curl_data_and_binary_file_inputs_match_curl_file_semantics() {
1291 let root = app::temp_dir("curl-data").unwrap();
1292 std::fs::write(root.join("body.txt"), b"one\r\ntwo\0\nthree").unwrap();
1293 let body = |flag| {
1294 parse_curl(
1295 &format!("curl {flag} @body.txt http://localhost/upper"),
1296 &root,
1297 &root,
1298 )
1299 .unwrap()
1300 .body
1301 .unwrap()
1302 };
1303 let data = body("--data");
1304 let binary = body("--data-binary");
1305 std::fs::remove_dir_all(root).unwrap();
1306 assert_eq!(data, "onetwothree");
1307 assert_eq!(binary, "one\r\ntwo\0\nthree");
1308 }
1309
1310 #[test]
1311 fn informational_responses_do_not_replace_the_final_response() {
1312 let raw = b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </app.js>\r\n\r\nHTTP/1.1 201 Created\r\nContent-Length: 2\r\n\r\nok";
1313 let response = read_response(&mut &raw[..], false).unwrap();
1314 assert_eq!(response.status, 201);
1315 assert_eq!(response.body, b"ok");
1316 assert!(!response.headers.contains_key("link"));
1317
1318 let switching = b"HTTP/1.1 101 Switching Protocols\r\n\r\n";
1319 assert_eq!(
1320 read_response(&mut &switching[..], false).unwrap().status,
1321 101
1322 );
1323 }
1324
1325 #[test]
1326 fn responses_parse_with_length_chunks_or_close() {
1327 let fixed =
1328 b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
1329 let r = read_response(&mut &fixed[..], false).unwrap();
1330 assert_eq!((r.status, r.body.as_slice()), (200, &b"hello"[..]));
1331 assert_eq!(r.headers["content-type"], "text/plain");
1332 let chunked = b"HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n4\r\nnot \r\n5;x=y\r\nfound\r\n0\r\n\r\n";
1333 let r = read_response(&mut &chunked[..], false).unwrap();
1334 assert_eq!((r.status, r.body.as_slice()), (404, &b"not found"[..]));
1335 let close = b"HTTP/1.0 500 Oops\r\n\r\nbye";
1336 assert_eq!(read_response(&mut &close[..], false).unwrap().body, b"bye");
1337 }
1338
1339 #[test]
1340 fn malformed_http_chunks_are_errors() {
1341 let mut bad_ending = &b"1\r\naXX0\r\n\r\n"[..];
1342 assert!(read_chunked(&mut bad_ending, Vec::new()).is_err());
1343 let max = format!("{:x}\r\n", usize::MAX);
1344 assert!(read_chunked(&mut max.as_bytes(), Vec::new()).is_err());
1345 let mut truncated = &b"1\r\na\r\n0\r\n"[..];
1346 assert!(read_chunked(&mut truncated, Vec::new()).is_err());
1347 let mut trailers = &b"1\r\na\r\n0\r\nX-Trailer: present\r\n\r\n"[..];
1348 assert_eq!(read_chunked(&mut trailers, Vec::new()).unwrap(), b"a");
1349 }
1350
1351 #[test]
1352 fn fixed_body_rejects_malformed_lengths_and_accepts_equal_duplicates() {
1353 let response = |lengths| {
1354 let msg = format!("HTTP/1.1 200 OK\r\n{lengths}\r\n\r\nabc trailing");
1355 read_response(&mut msg.as_bytes(), false)
1356 };
1357 assert!(response("Content-Length: invalid").is_err());
1358 assert!(response("Content-Length: 3\r\nContent-Length: 4").is_err());
1359 let matching = response("Content-Length: 3\r\nContent-Length: 03").unwrap();
1360 assert_eq!(matching.body, b"abc");
1361 }
1362
1363 #[test]
1364 fn interrupted_close_delimited_body_is_an_error() {
1365 struct BrokenBody;
1366
1367 impl Read for BrokenBody {
1368 fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
1369 Err(std::io::ErrorKind::TimedOut.into())
1370 }
1371 }
1372
1373 let response = &b"HTTP/1.0 200 OK\r\n\r\npartial"[..];
1374 assert!(read_response(&mut response.chain(BrokenBody), false).is_err());
1375 }
1376
1377 #[test]
1378 fn traps_change_path_segments_queries_and_bodies() {
1379 let base = Req {
1380 method: "POST".into(),
1381 path: "/div/7/2?name=bob".into(),
1382 headers: BTreeMap::new(),
1383 body: Some("{\"a\":1}".into()),
1384 };
1385 let t = traps(&[base]);
1386 assert!(t.iter().any(|r| r.path == "/div/-7/2?name=bob"));
1387 assert!(t.iter().any(|r| r.path == "/div/7/0?name=bob"));
1388 assert!(
1389 t.iter()
1390 .any(|r| r.path == "/div/7/2?name=%F0%9F%91%8D%F0%9F%8F%BD%20thumbs")
1391 );
1392 assert!(
1393 t.iter()
1394 .all(|r| r.path.starts_with("/div/") || r.path == "/rust-anything-missing")
1395 );
1396 assert!(
1397 t.iter()
1398 .any(|r| r.body.as_deref() == Some(app::JSON_TRAPS[0]))
1399 );
1400 assert_eq!(percent_decode("a%20b%zz"), "a b%zz");
1401 assert_eq!(percent_decode("%+1"), "%+1");
1403 assert_eq!(percent_decode("%-1"), "%-1");
1404 assert_eq!(percent_decode("%2b"), "+");
1405 assert_eq!(percent_decode("%2B"), "+");
1406 assert_eq!(percent_decode("%4"), "%4");
1407 }
1408}