Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! `obligations fallbacks`: the journal the front door writes, sorted entry by entry, stored by
//! `--write`, and what the stored file blocks in `standing` and in `lift`.
//!
//! Each test builds a small repository in a temporary folder, copied from an `obligations-*`
//! fixture, with the front door's state written by hand (the kind of the application) and recorded
//! cases written by hand: the rules are tested without the front door or the recorders. The real
//! front door is in `obligations_fallbacks_door.rs`.
mod common;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use rust_anything::obligations::standing::{
ADR_FILE, FALLBACKS_FILE, FALLBACKS_SCHEMA, FallbacksOptions, FallbacksReport, lift_blockers,
run_fallbacks, standing, standing_text, waive,
};
use serde_json::{Value, json};
const CLI: &str = env!("CARGO_BIN_EXE_rust-anything");
fn fixture(name: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures")
.join(name)
}
fn copy_dir(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for entry in std::fs::read_dir(from).unwrap() {
let entry = entry.unwrap();
let dest = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_dir(&entry.path(), &dest);
} else {
std::fs::copy(entry.path(), &dest).unwrap();
}
}
}
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"rust-anything-fallbacks-it-{}-{tag}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn put(root: &Path, rel: &str, text: &str) {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
fn get(root: &Path, rel: &str) -> String {
std::fs::read_to_string(root.join(rel)).unwrap()
}
/// A copy of the `obligations-<name>` fixture, with the front door's state of kind `kind`.
fn repo(name: &str, kind: &str, tag: &str) -> PathBuf {
let root = scratch(tag);
copy_dir(&fixture(&format!("obligations-{name}")), &root);
put(
&root,
"rust/app/rust-anything.json",
&format!("{{\"schema\":\"t\",\"name\":\"t\",\"commands\":[],\"kind\":\"{kind}\"}}"),
);
root
}
fn cli_repo(tag: &str) -> PathBuf {
repo("ts-cli", "cli", tag)
}
fn http_repo(tag: &str) -> PathBuf {
let root = repo("ts-server", "http", tag);
// Only literal routes: the routes family is read in full, which the fixture (a prefix taken
// from the environment) does not allow.
put(
&root,
"src/server.ts",
"import express from \"express\";
const app = express();
app.get(\"/health\", (_req, res) => res.send(\"ok\"));
app.get(\"/users/:id\", getUser);
app.post(\"/users\", createUser);
function getUser(_req: unknown, res: { send(s: string): void }) {
res.send(\"user\");
}
function createUser(_req: unknown, res: { send(s: string): void }) {
res.send(\"created\");
}
app.listen(3000);
",
);
root
}
/// A recorded CLI case, as `app record` writes it (exit 0).
fn cli_case(root: &Path, name: &str, args: &[&str]) {
let list: Vec<String> = args
.iter()
.map(|a| serde_json::to_string(a).unwrap())
.collect();
put(
root,
&format!("rust/app-cases/{name}.toml"),
&format!("args = [{}]\n", list.join(", ")),
);
}
/// A recorded HTTP case, as `app record --http` writes it.
fn http_case(root: &Path, name: &str, method: &str, path: &str, status: u16) {
put(
root,
&format!("rust/app-cases/http/{name}.toml"),
&format!(
"[request]\nmethod = {}\npath = {}\n\n[response]\nstatus = {status}\n",
serde_json::to_string(method).unwrap(),
serde_json::to_string(path).unwrap()
),
);
}
/// FNV-1a 64, written a second time here: the test does not depend on the function it judges.
fn fnv(bytes: &[u8]) -> String {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in bytes {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
format!("{h:016x}")
}
fn cli_line(args: &[&str], status: u16, stdin: Option<&[u8]>) -> String {
let mut v = json!({"v": 1, "kind": "cli", "args": args, "status": status});
if let Some(bytes) = stdin {
v["stdin_bytes"] = json!(bytes.len());
v["stdin_fnv"] = json!(fnv(bytes));
}
v.to_string()
}
fn http_line(method: &str, path: &str, status: Option<u16>, body: Option<&[u8]>) -> String {
let mut v = json!({"v": 1, "kind": "http", "method": method, "path": path});
if let Some(s) = status {
v["status"] = json!(s);
}
if let Some(bytes) = body {
v["body_bytes"] = json!(bytes.len());
v["body_fnv"] = json!(fnv(bytes));
}
v.to_string()
}
fn journal(root: &Path, name: &str, lines: &[String]) -> PathBuf {
let path = root.join(name);
std::fs::write(&path, lines.join("\n") + "\n").unwrap();
path
}
fn fallbacks(
root: &Path,
journals: &[PathBuf],
write: bool,
inputs: Option<&Path>,
) -> anyhow::Result<FallbacksReport> {
run_fallbacks(&FallbacksOptions {
repo: root,
journals,
write,
inputs,
})
}
fn report(root: &Path, journals: &[PathBuf]) -> FallbacksReport {
fallbacks(root, journals, false, None).unwrap()
}
/// Waives everything that has no case and attests every family: the repository is decided, except
/// the fallbacks added afterwards.
fn decide(root: &Path) {
common::decide_obligations(root);
}
fn run(args: &[&str]) -> Output {
Command::new(CLI).args(args).output().unwrap()
}
fn out(o: &Output) -> String {
format!(
"{}{}",
String::from_utf8_lossy(&o.stdout),
String::from_utf8_lossy(&o.stderr)
)
}
fn err(r: anyhow::Result<FallbacksReport>) -> String {
format!("{:#}", r.expect_err("the command should have refused"))
}
fn ids(items: &[rust_anything::obligations::standing::FallbackItem]) -> Vec<String> {
items.iter().map(|i| i.id.clone()).collect()
}
fn stored_lines(root: &Path) -> Vec<Value> {
get(root, FALLBACKS_FILE)
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect()
}
// ---------------------------------------------------------------------------------------------
// The journal is read strictly.
#[test]
fn every_fault_of_every_journal_is_listed_at_once_and_nothing_is_applied() {
let root = cli_repo("faults");
let bad = journal(
&root,
"bad.jsonl",
&[
cli_line(&["build"], 0, None),
"{\"v\":2,\"kind\":\"cli\",\"args\":[],\"status\":0}".to_string(),
"not json".to_string(),
"{\"v\":1,\"kind\":\"cli\",\"args\":[\"a\"],\"status\":0,\"extra\":1}".to_string(),
"{\"v\":1,\"kind\":\"cli\",\"args\":[\"a\"],\"stdin_bytes\":3,\"stdin_fnv\":\"ABCDEF0123456789\",\"status\":0}".to_string(),
"{\"v\":1,\"kind\":\"cli\",\"args\":[\"a\"],\"stdin_bytes\":3,\"stdin_fnv\":\"abc\",\"status\":0}".to_string(),
http_line("GET", "/a", Some(200), None),
"{\"v\":1,\"kind\":\"mystery\"}".to_string(),
],
);
let worse = journal(
&root,
"worse.jsonl",
&[
cli_line(&["serve", "x"], 0, None),
"{\"v\":1,\"kind\":\"cli\",\"status\":0}".to_string(),
],
);
let inputs = root.join("inputs.jsonl");
let message = err(fallbacks(
&root,
&[bad.clone(), worse.clone()],
true,
Some(&inputs),
));
assert!(
message.contains("invalid journal, nothing was applied"),
"{message}"
);
for line in [2, 3, 4, 5, 6, 7, 8] {
assert!(
message.contains(&format!("{}:{line}", bad.display())),
"line {line} of bad.jsonl: {message}"
);
}
assert!(
!message.contains(&format!("{}:1:", bad.display())),
"line 1 is good: {message}"
);
assert!(
message.contains(&format!("{}:2", worse.display())),
"the second journal is read too: {message}"
);
assert!(!root.join(FALLBACKS_FILE).exists(), "no store");
assert!(!inputs.exists(), "no inputs");
}
#[test]
fn a_journal_that_is_not_a_regular_file_or_too_big_or_missing_is_refused() {
let root = cli_repo("refused-files");
let good = journal(&root, "good.jsonl", &[cli_line(&["build"], 0, None)]);
let dir = root.join("a-folder");
std::fs::create_dir_all(&dir).unwrap();
let message = err(fallbacks(&root, &[good.clone(), dir.clone()], false, None));
assert!(message.contains("not a regular file"), "{message}");
let message = err(fallbacks(&root, &[root.join("absent.jsonl")], false, None));
assert!(message.contains("absent.jsonl"), "{message}");
// Over 16 MiB: not read, and without reading it.
let big = root.join("big.jsonl");
let file = std::fs::File::create(&big).unwrap();
file.set_len(17 * 1024 * 1024).unwrap();
drop(file);
let message = err(fallbacks(&root, &[big], false, None));
assert!(message.contains("16 MiB"), "{message}");
// No journal: nothing to read.
let message = err(fallbacks(&root, &[], false, None));
assert!(message.contains("nothing to read"), "{message}");
// A journal that is not text.
let binary = root.join("binary.jsonl");
std::fs::write(&binary, [0xff, 0xfe, b'\n']).unwrap();
let message = err(fallbacks(&root, &[binary], false, None));
assert!(message.contains("not UTF-8"), "{message}");
}
#[test]
fn a_line_of_the_other_kind_and_a_library_are_refused() {
let root = cli_repo("kind");
let j = journal(&root, "j.jsonl", &[http_line("GET", "/a", Some(200), None)]);
let message = err(fallbacks(&root, &[j], false, None));
assert!(
message.contains("a `http` line, but this is a CLI application"),
"{message}"
);
let lib = repo("ts-cli", "library", "kind-lib");
let j = journal(&lib, "j.jsonl", &[cli_line(&["a"], 0, None)]);
let message = err(fallbacks(&lib, &[j], false, None));
assert!(message.contains("library"), "{message}");
// No front door: nothing to read.
let none = scratch("kind-none");
copy_dir(&fixture("obligations-ts-cli"), &none);
let j = journal(&none, "j.jsonl", &[cli_line(&["a"], 0, None)]);
let message = err(fallbacks(&none, &[j], false, None));
assert!(message.contains("front-door"), "{message}");
}
#[test]
fn a_journal_that_reached_its_bound_and_the_skipped_lines_are_warned_about() {
let root = cli_repo("warn");
// A journal of one megabyte of valid lines, then a skipped line.
let line = cli_line(&["build", "--out", "d"], 0, None);
let mut text = String::new();
while text.len() < 1024 * 1024 {
text.push_str(&line);
text.push('\n');
}
text.push_str("{\"v\":1,\"kind\":\"skipped\",\"bytes\":70000,\"fnv\":\"af63dc4c8601ec8c\"}\n");
let path = root.join("big.jsonl");
std::fs::write(&path, &text).unwrap();
let r = report(&root, &[path]);
assert_eq!(r.distinct, 3, "{r:#?}");
assert_eq!(r.skipped, 1);
assert!(r.lines > 1000, "{}", r.lines);
assert!(
r.warnings.iter().any(|w| w.contains("reached 1 MiB")),
"{:?}",
r.warnings
);
assert!(
r.warnings
.iter()
.any(|w| w.contains("too long to be written")),
"{:?}",
r.warnings
);
}
// ---------------------------------------------------------------------------------------------
// The sorting.
/// A CLI repository with one recorded case and a journal that has one entry of each class.
fn sorted_cli(tag: &str) -> (PathBuf, PathBuf) {
let root = cli_repo(tag);
cli_case(&root, "c-serve", &["serve", "dir"]);
let j = journal(
&root,
"j.jsonl",
&[
cli_line(&["serve", "dir"], 0, None), // already recorded
cli_line(&["build", "--out", "d"], 0, None), // explained, and covers an obligation
cli_line(&["nope"], 0, None), // outside the registry
cli_line(&["build", "--bogus"], 2, None), // refused by the original
cli_line(&["nope"], 0, None), // the same one, twice
],
);
(root, j)
}
#[test]
fn each_entry_is_sorted_refusal_first_and_the_same_line_twice_counts_once() {
let (root, j) = sorted_cli("classes");
let r = report(&root, &[j]);
assert_eq!(r.schema, FALLBACKS_SCHEMA);
assert_eq!(r.kind, "cli");
assert_eq!((r.lines, r.distinct), (5, 4), "{r:#?}");
assert_eq!(r.refused, 1, "{r:#?}");
assert_eq!(r.recorded, 1, "{r:#?}");
assert_eq!(r.outside.len(), 1, "{r:#?}");
assert_eq!(r.outside[0].entry, "nope");
assert!(
r.outside[0].id.starts_with("fallback:cli#"),
"{}",
r.outside[0].id
);
assert_eq!(r.outside[0].id.len(), "fallback:cli#".len() + 16);
// `build --out d` is read by the registry and moves `build` to `matched`.
assert_eq!(r.candidates.len() + r.explained, 1, "{r:#?}");
assert_eq!(r.candidates.len(), 1, "{r:#?}");
assert!(
r.candidates[0].covers.iter().any(|c| c.contains("build")),
"{:?}",
r.candidates[0]
);
// Nothing was written without being asked.
assert!(!root.join(FALLBACKS_FILE).exists());
}
#[test]
fn an_entry_the_original_refused_is_counted_and_never_blocks_or_is_stored() {
let root = cli_repo("refused");
let j = journal(
&root,
"j.jsonl",
&[
cli_line(&["nope"], 1, None),
cli_line(&["nope2"], 127, None),
],
);
let r = fallbacks(&root, &[j], true, None).unwrap();
assert_eq!(
(r.refused, r.outside.len(), r.recorded),
(2, 0, 0),
"{r:#?}"
);
assert!(!root.join(FALLBACKS_FILE).exists(), "nothing to store");
assert_eq!(r.stored.as_ref().map(|s| (s.total, s.added)), Some((0, 0)));
decide(&root);
assert!(!standing(&root).unwrap().blocks());
}
#[test]
fn an_entry_with_a_stdin_is_recorded_only_by_a_case_with_the_same_stdin() {
let root = cli_repo("stdin");
cli_case(&root, "c-fmt", &["build"]);
put(&root, "rust/app-cases/c-fmt.stdin", "hello\n");
let same = cli_line(&["build"], 0, Some(b"hello\n"));
let other = cli_line(&["build"], 0, Some(b"different\n"));
let r = report(&root, &[journal(&root, "a.jsonl", &[same])]);
assert_eq!(
(r.recorded, r.outside.len(), r.candidates.len()),
(1, 0, 0),
"{r:#?}"
);
// Another stdin: not recorded. The arguments are those of a command the registry reads, so
// explained (and not outside): the stdin is what separates the two.
let r = report(&root, &[journal(&root, "b.jsonl", &[other])]);
assert_eq!(r.recorded, 0, "{r:#?}");
assert_eq!(
r.outside.len() + r.candidates.len() + r.explained,
1,
"{r:#?}"
);
// An empty stdin is not the stdin of `hello`.
let empty = cli_line(&["build"], 0, Some(b""));
let r = report(&root, &[journal(&root, "c.jsonl", &[empty])]);
assert_eq!(r.recorded, 0, "{r:#?}");
}
#[test]
fn a_lossy_entry_is_never_recorded_and_can_only_be_waived() {
let root = cli_repo("lossy");
cli_case(&root, "c-nope", &["nope"]);
// The arguments of the line are those of a recorded case, but `lossy` says they are not what
// ran.
let line = "{\"v\":1,\"kind\":\"cli\",\"args\":[\"nope\"],\"lossy\":true,\"status\":0}";
let j = journal(&root, "j.jsonl", &[line.to_string()]);
let r = report(&root, std::slice::from_ref(&j));
assert_eq!((r.recorded, r.outside.len()), (0, 1), "{r:#?}");
assert!(r.outside[0].lossy);
assert!(
r.outside[0].note.contains("not UTF-8"),
"{}",
r.outside[0].note
);
// `--inputs` does not write it, and says why.
let inputs = root.join("inputs.jsonl");
let r = fallbacks(&root, &[j], true, Some(&inputs)).unwrap();
let i = r.inputs.expect("inputs report");
assert_eq!(i.written, 0);
assert_eq!(i.not_written.len(), 1, "{i:#?}");
assert!(i.not_written[0].why.contains("not UTF-8"));
assert!(!inputs.exists(), "nothing to write");
// Stored, it blocks despite the case, and only a waiver lets it through.
decide(&root);
// `decide` waives the fallbacks too: the blocker is checked in a second repository, before
// any waiver.
let root2 = cli_repo("lossy-2");
cli_case(&root2, "c-nope", &["nope"]);
put(&root2, FALLBACKS_FILE, &format!("{line}\n"));
let before = standing(&root2).unwrap();
assert_eq!(before.blocking.fallbacks.len(), 1, "{before:#?}");
assert!(before.blocking.fallbacks[0].why.contains("not UTF-8"));
let id = before.blocking.fallbacks[0].id.clone();
waive(&root2, std::slice::from_ref(&id), "the byte is a fixture's").unwrap();
let after = standing(&root2).unwrap();
assert!(after.blocking.fallbacks.is_empty(), "{after:#?}");
assert!(after.waived.iter().any(|w| w.id == id), "{after:#?}");
}
#[test]
fn an_http_request_is_sorted_by_method_path_and_body() {
let root = http_repo("http-classes");
http_case(&root, "h-health", "GET", "/health", 200);
let j = journal(
&root,
"j.jsonl",
&[
http_line("GET", "/health", Some(200), None), // recorded
http_line("POST", "/users", Some(201), Some(b"{\"n\":1}")), // explained
http_line("GET", "/users/7", Some(200), None), // explained
http_line("GET", "/nothing/here", Some(200), None), // outside the registry
http_line("GET", "/users/9", Some(404), None), // refused
http_line("GET", "/slow", None, None), // the original did not answer
],
);
let r = report(&root, &[j]);
assert_eq!(r.kind, "http");
assert_eq!(r.distinct, 6, "{r:#?}");
assert_eq!(r.recorded, 1, "{r:#?}");
assert_eq!(r.refused, 2, "{r:#?}");
assert_eq!(r.outside.len(), 1, "{r:#?}");
assert_eq!(r.outside[0].entry, "GET /nothing/here");
assert!(r.outside[0].id.starts_with("fallback:http#"));
assert_eq!(r.candidates.len() + r.explained, 2, "{r:#?}");
// The same path with a body the case does not have is not recorded.
let j = journal(
&root,
"j2.jsonl",
&[http_line("GET", "/health", Some(200), Some(b"x"))],
);
let r = report(&root, &[j]);
assert_eq!(r.recorded, 0, "{r:#?}");
}
// ---------------------------------------------------------------------------------------------
// `--write`.
#[test]
fn write_merges_sorts_and_dedupes_the_entries_outside_the_registry() {
let root = cli_repo("write");
let a = journal(
&root,
"a.jsonl",
&[
cli_line(&["zeta"], 0, None),
cli_line(&["alpha"], 0, None),
cli_line(&["build", "--out", "d"], 0, None),
cli_line(&["refused"], 3, None),
],
);
// Without `--write`, nothing.
let r = fallbacks(&root, std::slice::from_ref(&a), false, None).unwrap();
assert!(r.stored.is_none());
assert!(!root.join(FALLBACKS_FILE).exists());
let r = fallbacks(&root, std::slice::from_ref(&a), true, None).unwrap();
let s = r.stored.expect("stored");
assert_eq!((s.added, s.total), (2, 2), "{s:?}");
assert_eq!(s.path, FALLBACKS_FILE);
let lines = stored_lines(&root);
assert_eq!(lines.len(), 2);
let order: Vec<String> = get(&root, FALLBACKS_FILE)
.lines()
.map(str::to_string)
.collect();
let mut sorted = order.clone();
sorted.sort();
assert_eq!(order, sorted, "the file is sorted");
// Only the identity and the status: no journal path, no date.
for l in &lines {
let keys: Vec<&String> = l.as_object().unwrap().keys().collect();
assert!(
keys.iter()
.all(|k| ["v", "kind", "args", "status"].contains(&k.as_str())),
"{l}"
);
}
// A second time, with a journal that repeats one entry and brings one: merge.
let b = journal(
&root,
"b.jsonl",
&[
cli_line(&["alpha"], 0, None),
cli_line(&["middle"], 0, None),
],
);
let r = fallbacks(&root, std::slice::from_ref(&b), true, None).unwrap();
let s = r.stored.expect("stored");
assert_eq!((s.added, s.total), (1, 3), "{s:?}");
let args: Vec<String> = stored_lines(&root)
.iter()
.map(|l| l["args"][0].as_str().unwrap().to_string())
.collect();
assert_eq!(args.len(), 3);
assert!(args.contains(&"alpha".to_string()) && args.contains(&"middle".to_string()));
// A third time: nothing new, the file is not rewritten.
let before = get(&root, FALLBACKS_FILE);
let r = fallbacks(&root, &[a, b], true, None).unwrap();
assert_eq!(r.stored.map(|s| (s.added, s.total)), Some((0, 3)));
assert_eq!(get(&root, FALLBACKS_FILE), before);
// No temporary file is left next to it.
let names: Vec<String> = std::fs::read_dir(root.join("rust"))
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(
names
.iter()
.all(|n| !n.contains(".tmp") && !n.contains("tmp-")),
"{names:?}"
);
}
#[test]
fn the_text_report_says_to_review_the_stored_file_before_committing() {
let root = cli_repo("text");
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 0, None)]);
let r = fallbacks(&root, std::slice::from_ref(&j), false, None).unwrap();
let text = rust_anything::obligations::standing::fallbacks_text(&r);
assert!(text.contains("outside the registry: 1"), "{text}");
assert!(text.contains("--write"), "{text}");
let r = fallbacks(&root, &[j], true, None).unwrap();
let text = rust_anything::obligations::standing::fallbacks_text(&r);
assert!(text.contains("review them before committing"), "{text}");
assert!(text.contains(FALLBACKS_FILE), "{text}");
}
#[cfg(unix)]
#[test]
fn write_refuses_a_stored_file_that_is_a_link_going_outside_the_repository() {
use std::os::unix::fs::symlink;
let root = cli_repo("link");
let outside = scratch("link-outside");
let target = outside.join("elsewhere.jsonl");
std::fs::write(&target, "").unwrap();
std::fs::create_dir_all(root.join("rust")).unwrap();
symlink(&target, root.join(FALLBACKS_FILE)).unwrap();
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 0, None)]);
let message = err(fallbacks(&root, std::slice::from_ref(&j), true, None));
assert!(message.contains(FALLBACKS_FILE), "{message}");
assert_eq!(
std::fs::read_to_string(&target).unwrap(),
"",
"nothing went through the link"
);
// A `rust/` folder that is a link: the same.
let root = cli_repo("link-dir");
let real = scratch("link-dir-real");
std::fs::create_dir_all(real.join("app")).unwrap();
std::fs::copy(
root.join("rust/app/rust-anything.json"),
real.join("app/rust-anything.json"),
)
.unwrap();
std::fs::remove_dir_all(root.join("rust")).unwrap();
symlink(&real, root.join("rust")).unwrap();
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 0, None)]);
let _ = fallbacks(&root, &[j], true, None);
assert!(
!real.join("obligations-fallbacks.jsonl").exists(),
"nothing was written through the linked folder"
);
}
// ---------------------------------------------------------------------------------------------
// `--inputs`.
#[test]
fn inputs_are_the_lines_app_record_reads_and_a_stdin_is_listed_to_be_added_by_hand() {
let root = cli_repo("inputs");
let j = journal(
&root,
"j.jsonl",
&[
cli_line(&["nope", "say \"hi\""], 0, None),
cli_line(&["build", "--out", "d"], 0, None),
cli_line(&["words"], 0, Some(b"twelve bytes")),
cli_line(&["empty"], 0, Some(b"")),
cli_line(&["refused"], 1, None),
],
);
let inputs = root.join("out").join("inputs.jsonl");
std::fs::create_dir_all(inputs.parent().unwrap()).unwrap();
let r = fallbacks(&root, &[j], false, Some(&inputs)).unwrap();
let i = r.inputs.clone().expect("inputs report");
// `nope`, `words`, `empty` (outside the registry) and `build --out d` (covers an obligation).
assert_eq!(i.written, 4, "{i:#?}");
assert_eq!(i.by_hand.len(), 1, "{i:#?}");
assert!(
i.by_hand[0]
.todo
.contains("add its stdin (12 bytes) by hand"),
"{i:#?}"
);
let text = std::fs::read_to_string(&inputs).unwrap();
let lines: Vec<Value> = text
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(lines.len(), 4);
for l in &lines {
let name = l["name"].as_str().unwrap();
assert!(
name.starts_with("fallback-")
&& name["fallback-".len()..].len() == 16
&& name["fallback-".len()..]
.chars()
.all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()),
"{name}"
);
assert!(l["args"].is_array());
assert!(l.get("stdin").is_none(), "no stdin is invented: {l}");
}
assert!(
lines
.iter()
.any(|l| l["args"] == json!(["nope", "say \"hi\""])),
"{text}"
);
// The name is the digest of the id.
let outside = &r
.outside
.iter()
.find(|o| o.entry.starts_with("nope"))
.unwrap()
.id;
let digest = outside.rsplit('#').next().unwrap();
assert!(
lines
.iter()
.any(|l| l["name"] == format!("fallback-{digest}")),
"{outside}: {text}"
);
// What `app record` does not read is not there: the line refused by the original.
assert!(!text.contains("refused"), "{text}");
let message = rust_anything::obligations::standing::fallbacks_text(&r);
assert!(message.contains("app record --inputs"), "{message}");
assert!(
message.contains("add its stdin (12 bytes) by hand"),
"{message}"
);
}
#[test]
fn http_inputs_hold_the_method_and_the_path_and_a_body_is_listed_by_hand() {
let root = http_repo("inputs-http");
let j = journal(
&root,
"j.jsonl",
&[
http_line("GET", "/nothing/here?x=1", Some(200), None),
http_line("POST", "/users", Some(201), Some(b"{\"n\":1}")),
],
);
let inputs = root.join("inputs.jsonl");
let r = fallbacks(&root, &[j], false, Some(&inputs)).unwrap();
let i = r.inputs.expect("inputs report");
assert_eq!(i.written, 2, "{i:#?}");
assert_eq!(i.by_hand.len(), 1, "{i:#?}");
assert!(
i.by_hand[0].todo.contains("add its body (7 bytes) by hand"),
"{i:#?}"
);
let lines: Vec<Value> = std::fs::read_to_string(&inputs)
.unwrap()
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert!(
lines
.iter()
.any(|l| l["method"] == "GET" && l["path"] == "/nothing/here?x=1")
);
assert!(
lines
.iter()
.any(|l| l["method"] == "POST" && l["path"] == "/users")
);
assert!(lines.iter().all(|l| l.get("body").is_none()), "{lines:?}");
}
// ---------------------------------------------------------------------------------------------
// What the stored file blocks.
/// A decided repository, where `--write` stores `nope` (outside the registry) and `build --out d`
/// is nothing.
fn blocked(tag: &str) -> (PathBuf, String) {
let root = cli_repo(tag);
decide(&root);
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 0, None)]);
let r = fallbacks(&root, &[j], true, None).unwrap();
let id = r.outside[0].id.clone();
(root, id)
}
#[test]
fn a_stored_entry_blocks_standing_and_is_the_fourth_line_of_lift() {
let (root, id) = blocked("blocks");
let s = standing(&root).unwrap();
assert!(s.blocks(), "{s:#?}");
assert_eq!(ids_of(&s), std::slice::from_ref(&id));
assert_eq!(s.blocking.fallbacks[0].kind, "cli");
assert_eq!(s.blocking.fallbacks[0].entry, "nope");
assert_eq!(s.blocking.fallbacks[0].status, Some(0));
assert_eq!(s.blocking_count(), 1);
let lines = lift_blockers(&s, "my-repo");
assert_eq!(lines.len(), 1, "{lines:#?}");
assert!(
lines[0].contains("1 fallback the front door handed back to the original")
&& lines[0].contains(&id)
&& lines[0].contains(
"rust-anything obligations fallbacks <journal> --repo my-repo --inputs <file>"
)
&& lines[0].contains("rust-anything obligations waive <id>")
&& lines[0].contains("--check"),
"{}",
lines[0]
);
let text = standing_text(&s);
assert!(text.contains(&id) && text.contains("nope"), "{text}");
let json = serde_json::to_value(&s).unwrap();
assert_eq!(json["blocking"]["fallbacks"][0]["id"], id);
// In a repository where the rest blocks too, it is the last line, after the other three.
let raw = cli_repo("blocks-all");
put(&raw, FALLBACKS_FILE, &get(&root, FALLBACKS_FILE));
let s = standing(&raw).unwrap();
let lines = lift_blockers(&s, "r");
assert!(lines.len() >= 3, "{lines:#?}");
assert!(
lines.last().unwrap().contains("fallback"),
"the fallbacks are the last line: {lines:#?}"
);
assert!(
lines[..lines.len() - 1]
.iter()
.all(|l| !l.contains("handed back")),
"{lines:#?}"
);
}
fn ids_of(s: &rust_anything::obligations::standing::Standing) -> Vec<String> {
ids(&s.blocking.fallbacks)
}
#[test]
fn the_first_way_out_is_a_recorded_case_with_the_same_arguments() {
let (root, id) = blocked("out-recorded");
assert!(standing(&root).unwrap().blocks());
cli_case(&root, "c-nope", &["nope"]);
let s = standing(&root).unwrap();
assert!(!s.blocks(), "{s:#?}");
assert!(
s.notes
.iter()
.any(|n| n.contains(&id) && n.contains("has a recorded case now")),
"{:?}",
s.notes
);
// The same arguments with another word are not enough.
let (root, _) = blocked("out-recorded-near");
cli_case(&root, "c-near", &["nope", "extra"]);
assert!(standing(&root).unwrap().blocks());
cli_case(&root, "c-near2", &["NOPE"]);
assert!(standing(&root).unwrap().blocks());
}
#[test]
fn a_recorded_case_that_failed_does_not_record_the_entry() {
let (root, _) = blocked("out-recorded-failed");
put(
&root,
"rust/app-cases/c-nope.toml",
"args = [\"nope\"]\nstatus = \"failed\"\n",
);
assert!(
standing(&root).unwrap().blocks(),
"a case that exits 1 says nothing about a line the original served"
);
}
#[test]
fn the_second_way_out_is_the_registry_explaining_the_entry_and_it_says_so() {
let root = cli_repo("out-explained");
decide(&root);
// A file stored by hand with a line the registry reads.
put(
&root,
FALLBACKS_FILE,
&(cli_line(&["build", "--out", "d"], 0, None) + "\n"),
);
let s = standing(&root).unwrap();
assert!(!s.blocks(), "{s:#?}");
assert!(
s.notes
.iter()
.any(|n| n.contains("is explained by the registry now")),
"{:?}",
s.notes
);
}
#[test]
fn the_third_way_out_is_waive_and_it_writes_an_adr_and_refuses_what_does_not_block() {
let (root, id) = blocked("out-waive");
let done = waive(&root, std::slice::from_ref(&id), "the original handles it").unwrap();
assert_eq!(done.items, std::slice::from_ref(&id));
let s = standing(&root).unwrap();
assert!(!s.blocks(), "{s:#?}");
assert!(s.waived.iter().any(|w| w.id == id), "{s:#?}");
let adr = get(&root, ADR_FILE);
assert!(
adr.contains(&id) && adr.contains("the original handles it"),
"{adr}"
);
assert!(adr.contains("fallback"), "{adr}");
// An entry that does not block is not waived: nothing is written.
let root = cli_repo("out-waive-refused");
decide(&root);
put(
&root,
FALLBACKS_FILE,
&(cli_line(&["build", "--out", "d"], 0, None) + "\n"),
);
let explained = get(&root, FALLBACKS_FILE);
let first = serde_json::from_str::<Value>(explained.lines().next().unwrap()).unwrap();
assert_eq!(first["args"][0], "build");
let j = journal(
&root,
"j.jsonl",
&[cli_line(&["build", "--out", "d"], 0, None)],
);
let r = report(&root, &[j]);
let known = r
.candidates
.iter()
.chain(&r.outside)
.map(|i| i.id.clone())
.next();
let known = known.expect("an id");
let before_adr = root.join(ADR_FILE).exists();
let message = format!(
"{:#}",
waive(&root, std::slice::from_ref(&known), "no").expect_err("an entry that does not block")
);
assert!(
message.contains(&known) || message.contains("nothing to waive"),
"{message}"
);
assert_eq!(root.join(ADR_FILE).exists(), before_adr, "nothing written");
let message = format!(
"{:#}",
waive(
&root,
&["fallback:cli#0000000000000000".to_string()],
"no because"
)
.expect_err("an unknown id")
);
assert!(message.contains("nothing to waive"), "{message}");
}
#[test]
fn a_pattern_waives_every_fallback_it_matches_and_only_those() {
let root = cli_repo("out-pattern");
decide(&root);
let j = journal(
&root,
"j.jsonl",
&[cli_line(&["nope"], 0, None), cli_line(&["other"], 0, None)],
);
let r = fallbacks(&root, &[j], true, None).unwrap();
assert_eq!(r.outside.len(), 2);
let done = waive(
&root,
&["fallback:cli#*".to_string()],
"all of these are the demo's",
)
.unwrap();
assert_eq!(done.items.len(), 2, "{done:?}");
assert_eq!(done.pattern.as_deref(), Some("fallback:cli#*"));
assert!(!standing(&root).unwrap().blocks());
let message = format!(
"{:#}",
waive(&root, &["fallback:http#*".to_string()], "nothing matches").expect_err("no match")
);
assert!(
message.contains("matches no obligation that blocks"),
"{message}"
);
}
#[test]
fn an_entry_with_another_stdin_than_the_recorded_case_still_blocks() {
let root = cli_repo("stdin-blocks");
decide(&root);
let stored = cli_line(&["nope"], 0, Some(b"input A\n"));
put(&root, FALLBACKS_FILE, &(stored + "\n"));
cli_case(&root, "c-nope", &["nope"]);
put(&root, "rust/app-cases/c-nope.stdin", "input B\n");
let s = standing(&root).unwrap();
assert_eq!(s.blocking.fallbacks.len(), 1, "{s:#?}");
// The same stdin lifts the blocker.
put(&root, "rust/app-cases/c-nope.stdin", "input A\n");
assert!(!standing(&root).unwrap().blocks());
// An entry without stdin (the terminal) makes do with the arguments.
put(
&root,
FALLBACKS_FILE,
&(cli_line(&["nope"], 0, None) + "\n"),
);
put(&root, "rust/app-cases/c-nope.stdin", "anything\n");
assert!(!standing(&root).unwrap().blocks());
}
#[test]
fn a_stored_entry_the_original_refused_still_blocks_because_a_hand_may_have_written_it() {
let root = cli_repo("stored-refused");
decide(&root);
// The journal would have counted this line as refused; stored, it is no longer judged by its
// status.
put(
&root,
FALLBACKS_FILE,
&(cli_line(&["nope"], 2, None) + "\n"),
);
let s = standing(&root).unwrap();
assert_eq!(s.blocking.fallbacks.len(), 1, "{s:#?}");
assert_eq!(s.blocking.fallbacks[0].status, Some(2));
}
#[test]
fn an_invalid_stored_file_is_an_error_that_lift_reports_as_not_checked() {
let root = cli_repo("stored-invalid");
put(
&root,
FALLBACKS_FILE,
&format!(
"{}\n{{\"v\":3}}\nnot json\n{}\n",
cli_line(&["nope"], 0, None),
http_line("GET", "/a", Some(200), None)
),
);
let message = format!("{:#}", standing(&root).expect_err("an invalid stored file"));
assert!(
message.contains("invalid rust/obligations-fallbacks.jsonl"),
"{message}"
);
for line in [2, 3, 4] {
assert!(
message.contains(&format!("{FALLBACKS_FILE}:{line}")),
"{message}"
);
}
// The other commands that read the state do not say "nothing blocks" either.
let o = run(&["obligations", root.to_str().unwrap(), "--check"]);
assert!(!o.status.success(), "{}", out(&o));
assert!(
out(&o).contains("invalid rust/obligations-fallbacks.jsonl"),
"{}",
out(&o)
);
let o = run(&[
"obligations",
"waive",
"x",
"--reason",
"long enough reason",
"--repo",
root.to_str().unwrap(),
]);
assert!(!o.status.success(), "{}", out(&o));
assert!(!root.join(ADR_FILE).exists());
}
#[test]
fn a_stored_file_that_is_a_folder_is_not_read_as_empty() {
let root = cli_repo("stored-dir");
std::fs::create_dir_all(root.join(FALLBACKS_FILE)).unwrap();
let message = format!(
"{:#}",
standing(&root).expect_err("a folder is not a stored file")
);
assert!(message.contains(FALLBACKS_FILE), "{message}");
}
// ---------------------------------------------------------------------------------------------
// HTTP, and the binary.
#[test]
fn an_http_entry_outside_the_registry_blocks_and_a_recorded_request_lifts_it() {
let root = http_repo("http-blocks");
decide(&root);
let j = journal(
&root,
"j.jsonl",
&[
http_line("GET", "/nothing/here", Some(200), None),
http_line("GET", "/health", Some(200), None),
],
);
let r = fallbacks(&root, &[j], true, None).unwrap();
assert_eq!(r.outside.len(), 1, "{r:#?}");
let id = r.outside[0].id.clone();
assert!(id.starts_with("fallback:http#"));
let s = standing(&root).unwrap();
assert_eq!(ids_of(&s), std::slice::from_ref(&id), "{s:#?}");
assert_eq!(s.blocking.fallbacks[0].kind, "http");
assert_eq!(s.blocking.fallbacks[0].entry, "GET /nothing/here");
http_case(&root, "h-nothing", "GET", "/nothing/here", 200);
assert!(!standing(&root).unwrap().blocks());
// A case that answers 404 does not record what the original served as 200.
let root = http_repo("http-blocks-404");
decide(&root);
put(
&root,
FALLBACKS_FILE,
&(http_line("GET", "/nothing/here", Some(200), None) + "\n"),
);
http_case(&root, "h-nothing", "GET", "/nothing/here", 404);
assert!(standing(&root).unwrap().blocks());
}
#[test]
fn the_binary_prints_the_report_as_json_and_the_text_and_refuses_a_bad_journal() {
let (root, j) = sorted_cli("binary");
let o = run(&[
"obligations",
"fallbacks",
j.to_str().unwrap(),
"--repo",
root.to_str().unwrap(),
"--json",
]);
assert!(o.status.success(), "{}", out(&o));
let v: Value = serde_json::from_slice(&o.stdout).unwrap();
assert_eq!(v["schema"], FALLBACKS_SCHEMA);
assert_eq!(v["kind"], "cli");
assert_eq!(v["distinct"], 4);
assert_eq!(v["outside"][0]["entry"], "nope");
assert!(v.get("stored").is_none() && v.get("inputs").is_none());
let o = run(&[
"obligations",
"fallbacks",
j.to_str().unwrap(),
"--repo",
root.to_str().unwrap(),
"--write",
]);
assert!(o.status.success(), "{}", out(&o));
let text = out(&o);
assert!(
text.contains("outside the registry: 1") && text.contains("review them before committing"),
"{text}"
);
assert_eq!(stored_lines(&root).len(), 1);
let bad = root.join("bad.jsonl");
std::fs::write(&bad, "nonsense\n").unwrap();
let o = run(&[
"obligations",
"fallbacks",
bad.to_str().unwrap(),
"--repo",
root.to_str().unwrap(),
]);
assert!(!o.status.success());
assert!(
out(&o).contains("invalid journal, nothing was applied"),
"{}",
out(&o)
);
// `--check` shows it, and `waive` waives it by id.
let o = run(&["obligations", root.to_str().unwrap(), "--check"]);
assert!(out(&o).contains("fallback:cli#"), "{}", out(&o));
let id = stored_id(&root);
let o = run(&[
"obligations",
"waive",
&id,
"--reason",
"the original keeps this one",
"--repo",
root.to_str().unwrap(),
]);
assert!(o.status.success(), "{}", out(&o));
let s = standing(&root).unwrap();
assert!(s.blocking.fallbacks.is_empty(), "{s:#?}");
}
fn stored_id(root: &Path) -> String {
let r = report(
root,
&[journal(
root,
"again.jsonl",
&[cli_line(&["nope"], 0, None)],
)],
);
r.outside[0].id.clone()
}
#[test]
fn a_route_family_that_is_only_partly_read_explains_nothing() {
// The fixture takes a prefix from the environment: the family is partial, and when in doubt no
// request is explained, not even `GET /health`, which the source declares.
let root = repo("ts-server", "http", "http-partial");
let j = journal(
&root,
"j.jsonl",
&[
http_line("GET", "/health", Some(200), None),
http_line("POST", "/users", Some(201), None),
],
);
let r = report(&root, &[j]);
assert_eq!(
(r.explained, r.candidates.len(), r.outside.len()),
(0, 0, 2),
"{r:#?}"
);
assert!(
r.outside.iter().all(|o| o.note.contains("partial")),
"{:?}",
r.outside
);
}
// ---------------------------------------------------------------------------------------------
// What is known only by its size: a `skipped` line and a full journal block.
const SKIPPED: &str = "{\"v\":1,\"kind\":\"skipped\",\"bytes\":70000,\"fnv\":\"af63dc4c8601ec8c\"}";
/// A journal of more than one megabyte of valid lines: the front door stopped writing.
fn full_journal(root: &Path, line: &str) -> PathBuf {
let mut text = String::new();
while text.len() < 1024 * 1024 {
text.push_str(line);
text.push('\n');
}
let path = root.join("full.jsonl");
std::fs::write(&path, &text).unwrap();
path
}
/// The entry of kind `kind` among those that block, for this repository.
fn blocking_of(root: &Path, kind: &str) -> Vec<rust_anything::obligations::standing::FallbackItem> {
standing(root)
.unwrap()
.blocking
.fallbacks
.into_iter()
.filter(|f| f.kind == kind)
.collect()
}
#[test]
fn a_skipped_line_blocks_is_never_recorded_or_explained_and_only_a_waiver_lifts_it() {
let root = cli_repo("skipped");
decide(&root);
let j = journal(&root, "j.jsonl", &[SKIPPED.to_string()]);
let r = fallbacks(&root, &[j], true, None).unwrap();
assert_eq!(
(r.recorded, r.explained, r.candidates.len(), r.refused),
(0, 0, 0, 0),
"{r:#?}"
);
assert_eq!(r.outside.len(), 1, "{r:#?}");
let id = r.outside[0].id.clone();
assert!(id.starts_with("fallback:skipped#"), "{id}");
assert!(r.outside[0].note.contains("fresh journal"), "{r:#?}");
// Stored with its size, and nothing else.
let lines = stored_lines(&root);
assert_eq!(
lines,
[json!({"v": 1, "kind": "skipped", "bytes": 70000, "fnv": "af63dc4c8601ec8c"})]
);
// It blocks `standing` and `lift`, and says what to do.
let s = standing(&root).unwrap();
assert!(s.blocks(), "{s:#?}");
let items = blocking_of(&root, "skipped");
assert_eq!(ids(&items), std::slice::from_ref(&id));
assert!(items[0].entry.contains("70000"), "{:?}", items[0]);
let lift = lift_blockers(&s, "my-repo");
assert!(
lift.len() == 1 && lift[0].contains(&id) && lift[0].contains("fresh journal"),
"{lift:#?}"
);
assert!(standing_text(&s).contains("fresh journal"));
let json = serde_json::to_value(&s).unwrap();
assert_eq!(json["blocking"]["fallbacks"][0]["kind"], "skipped");
// No case and no rule of the registry records or explains it: neither the arguments of a
// command the registry reads, nor a case of any shape.
cli_case(&root, "c-any", &["build", "--out", "d"]);
http_case(&root, "h-any", "GET", "/health", 200);
assert!(standing(&root).unwrap().blocks());
// Only a waiver lets it through.
waive(&root, std::slice::from_ref(&id), "a fixture's long line").unwrap();
let after = standing(&root).unwrap();
assert!(!after.blocks(), "{after:#?}");
assert!(after.waived.iter().any(|w| w.id == id), "{after:#?}");
}
#[test]
fn a_journal_that_reached_its_bound_leaves_a_truncated_entry_that_blocks_until_it_is_waived() {
let root = cli_repo("truncated");
decide(&root);
let path = full_journal(&root, &cli_line(&["build", "--out", "d"], 0, None));
let size = std::fs::metadata(&path).unwrap().len();
let digest = fnv(&std::fs::read(&path).unwrap());
let r = fallbacks(&root, &[path], true, None).unwrap();
let truncated: Vec<_> = r
.outside
.iter()
.filter(|o| o.id.starts_with("fallback:truncated#"))
.collect();
assert_eq!(truncated.len(), 1, "{r:#?}");
assert!(truncated[0].note.contains("fresh journal"), "{truncated:?}");
assert!(
truncated[0].entry.contains(&size.to_string()),
"{truncated:?}"
);
assert_eq!((r.recorded, r.refused), (0, 0), "{r:#?}");
assert!(
stored_lines(&root)
.iter()
.any(|l| l == &json!({"v": 1, "kind": "truncated", "bytes": size, "fnv": digest})),
"{}",
get(&root, FALLBACKS_FILE)
);
let items = blocking_of(&root, "truncated");
assert_eq!(items.len(), 1);
let id = items[0].id.clone();
let s = standing(&root).unwrap();
assert!(s.blocks());
assert!(
lift_blockers(&s, "r")
.iter()
.any(|l| l.contains(&id) && l.contains("fresh journal"))
);
// A case with the same arguments as the repeated line does not erase what is missing after.
cli_case(&root, "c-build", &["build", "--out", "d"]);
assert!(!blocking_of(&root, "truncated").is_empty());
waive(
&root,
&[id],
"the journal was cut and the rest was read by hand",
)
.unwrap();
assert!(blocking_of(&root, "truncated").is_empty());
}
#[test]
fn a_skipped_and_a_truncated_entry_of_an_http_application_block_too() {
let root = http_repo("http-unreadable");
decide(&root);
let path = full_journal(&root, &http_line("GET", "/health", Some(200), None));
let mut text = std::fs::read_to_string(&path).unwrap();
text.push_str(SKIPPED);
text.push('\n');
std::fs::write(&path, text).unwrap();
let r = fallbacks(&root, &[path], true, None).unwrap();
let kinds: Vec<&str> = r
.outside
.iter()
.map(|o| o.id.split('#').next().unwrap())
.collect();
assert!(
kinds.contains(&"fallback:skipped") && kinds.contains(&"fallback:truncated"),
"{kinds:?}"
);
let s = standing(&root).unwrap();
assert_eq!(s.blocking.fallbacks.len(), 2, "{s:#?}");
let ids: Vec<String> = ids_of(&s);
waive(&root, &ids, "both belong to a fixture").unwrap();
assert!(!standing(&root).unwrap().blocks());
}
#[test]
fn a_stored_file_accepts_skipped_and_truncated_lines_and_a_journal_refuses_a_truncated_one() {
for (kind, repo_of) in [
("cli", cli_repo as fn(&str) -> PathBuf),
("http", http_repo),
] {
let root = repo_of(&format!("stored-unreadable-{kind}"));
decide(&root);
put(
&root,
FALLBACKS_FILE,
&format!(
"{SKIPPED}
{{\"v\":1,\"kind\":\"truncated\",\"bytes\":1048600,\"fnv\":\"af63dc4c8601ec8c\"}}
"
),
);
assert_eq!(
standing(&root).unwrap().blocking.fallbacks.len(),
2,
"{kind}"
);
// In a journal, nobody writes `truncated`: it is a fault.
let j = journal(
&root,
"j.jsonl",
&["{\"v\":1,\"kind\":\"truncated\",\"bytes\":9}".to_string()],
);
let message = err(fallbacks(&root, &[j], false, None));
assert!(
message.contains("expected cli, http or skipped"),
"{message}"
);
}
}
#[test]
fn inputs_do_not_write_a_skipped_or_truncated_entry_and_say_why() {
let root = cli_repo("inputs-unreadable");
let j = journal(&root, "j.jsonl", &[SKIPPED.to_string()]);
let inputs = root.join("inputs.jsonl");
let r = fallbacks(&root, &[j], false, Some(&inputs)).unwrap();
let i = r.inputs.expect("inputs report");
assert_eq!((i.written, i.not_written.len()), (0, 1), "{i:#?}");
assert!(i.not_written[0].why.contains("fresh journal"), "{i:#?}");
assert!(i.not_written[0].why.contains("waive"), "{i:#?}");
assert!(!inputs.exists(), "nothing to write: no file");
}
// ---------------------------------------------------------------------------------------------
// `--inputs` creates a file: it does not replace one, and it does not create a folder.
/// A journal with one entry that `--inputs` writes (outside the registry) and a decided
/// repository.
fn writable(tag: &str) -> (PathBuf, PathBuf) {
let root = cli_repo(tag);
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 0, None)]);
(root, j)
}
#[test]
fn an_inputs_target_that_exists_is_never_replaced() {
let (root, j) = writable("inputs-exists");
put(&root, "src/cli.ts", "the source\n");
let target = root.join("src/cli.ts");
let message = err(fallbacks(
&root,
std::slice::from_ref(&j),
true,
Some(&target),
));
assert!(
message.contains("already exists: remove it or name another file"),
"{message}"
);
assert_eq!(get(&root, "src/cli.ts"), "the source\n");
// Nothing was stored either: the target is judged before any write.
assert!(!root.join(FALLBACKS_FILE).exists());
// A link (even a dangling one) exists too: it is not followed.
#[cfg(unix)]
{
let link = root.join("link.jsonl");
std::os::unix::fs::symlink(root.join("nowhere"), &link).unwrap();
let message = err(fallbacks(&root, &[j], false, Some(&link)));
assert!(message.contains("already exists"), "{message}");
assert!(!root.join("nowhere").exists());
}
}
#[test]
fn an_inputs_target_in_a_folder_that_does_not_exist_makes_no_folder() {
let (root, j) = writable("inputs-parent");
let target = root.join("not").join("there").join("inputs.jsonl");
let message = err(fallbacks(&root, &[j], true, Some(&target)));
assert!(message.contains("does not exist"), "{message}");
assert!(!root.join("not").exists(), "no folder is created");
assert!(!root.join(FALLBACKS_FILE).exists());
}
#[test]
fn with_nothing_to_write_no_file_is_created_and_the_report_does_not_name_one() {
let root = cli_repo("inputs-nothing");
// An entry refused by the original: nothing to record.
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 2, None)]);
let inputs = root.join("inputs.jsonl");
let r = fallbacks(&root, &[j], false, Some(&inputs)).unwrap();
let i = r.inputs.clone().expect("inputs report");
assert_eq!(i.written, 0);
assert!(!inputs.exists(), "no file");
let text = rust_anything::obligations::standing::fallbacks_text(&r);
assert!(text.contains("no file was created"), "{text}");
assert!(!text.contains("inputs.jsonl"), "{text}");
let json = serde_json::to_value(&r).unwrap();
assert!(json["inputs"].get("path").is_none(), "{json}");
// A target that exists, when there is nothing to write to it, is no problem.
std::fs::write(&inputs, "mine\n").unwrap();
let r = fallbacks(
&root,
&[journal(&root, "k.jsonl", &[cli_line(&["x"], 2, None)])],
false,
Some(&inputs),
)
.unwrap();
assert_eq!(r.inputs.unwrap().written, 0);
assert_eq!(std::fs::read_to_string(&inputs).unwrap(), "mine\n");
}
#[test]
fn the_inputs_file_that_is_written_is_new_and_named_in_the_report() {
let (root, j) = writable("inputs-new");
let inputs = root.join("fresh.jsonl");
let r = fallbacks(&root, &[j], false, Some(&inputs)).unwrap();
let i = r.inputs.expect("inputs report");
assert_eq!(i.written, 1);
assert_eq!(
i.path.as_deref(),
Some(inputs.display().to_string().as_str())
);
assert!(inputs.exists());
}
// ---------------------------------------------------------------------------------------------
// Warnings are in the JSON, and when `--inputs` writes.
const REVIEW: &str = "review them before committing";
fn warnings_of(o: &Output) -> Vec<String> {
let v: Value = serde_json::from_slice(&o.stdout).unwrap();
v["warnings"]
.as_array()
.unwrap()
.iter()
.map(|w| w.as_str().unwrap().to_string())
.collect()
}
#[test]
fn the_review_warning_is_in_the_json_and_when_inputs_writes_and_only_when_something_is_written() {
let (root, j) = writable("warn-review");
let base = [
"obligations",
"fallbacks",
j.to_str().unwrap(),
"--repo",
root.to_str().unwrap(),
"--json",
];
// Nothing is written: no warning.
let o = run(&base);
assert!(o.status.success(), "{}", out(&o));
assert!(
warnings_of(&o).iter().all(|w| !w.contains(REVIEW)),
"{:?}",
warnings_of(&o)
);
// `--inputs` writes, without `--write`.
let inputs = root.join("i.jsonl");
let mut args = base.to_vec();
args.extend(["--inputs", inputs.to_str().unwrap()]);
let o = run(&args);
assert!(o.status.success(), "{}", out(&o));
assert!(
warnings_of(&o).iter().any(|w| w.contains(REVIEW)),
"{}",
out(&o)
);
// `--write` stores something.
let mut args = base.to_vec();
args.push("--write");
let o = run(&args);
assert!(o.status.success(), "{}", out(&o));
assert!(
warnings_of(&o).iter().any(|w| w.contains(REVIEW)),
"{}",
out(&o)
);
// `--write` a second time: nothing new, nothing written, no warning.
let o = run(&args);
assert!(o.status.success(), "{}", out(&o));
assert!(warnings_of(&o).iter().all(|w| !w.contains(REVIEW)));
}
// ---------------------------------------------------------------------------------------------
// What records an entry.
#[test]
fn a_case_that_adds_environment_variables_does_not_record_the_entry() {
let root = cli_repo("env-case");
let j = journal(&root, "j.jsonl", &[cli_line(&["nope"], 0, None)]);
put(
&root,
"rust/app-cases/c-env.toml",
"args = [\"nope\"]\n\n[env.add]\nMODE = \"other\"\n",
);
let r = report(&root, std::slice::from_ref(&j));
assert_eq!((r.recorded, r.outside.len()), (0, 1), "{r:#?}");
// The same case without the variable records it.
put(&root, "rust/app-cases/c-env.toml", "args = [\"nope\"]\n");
let r = report(&root, &[j]);
assert_eq!((r.recorded, r.outside.len()), (1, 0), "{r:#?}");
}
#[test]
fn a_recorded_request_with_a_body_does_not_record_an_entry_without_one() {
let root = http_repo("body-case-only");
put(
&root,
"rust/app-cases/http/h-body.toml",
"[request]\nmethod = \"POST\"\npath = \"/nothing/here\"\nbody = \"payload\"\n\n[response]\nstatus = 200\n",
);
let j = journal(
&root,
"j.jsonl",
&[http_line("POST", "/nothing/here", Some(200), None)],
);
let r = report(&root, &[j]);
assert_eq!((r.recorded, r.outside.len()), (0, 1), "{r:#?}");
// With the same body on both sides, it is recorded.
let j = journal(
&root,
"k.jsonl",
&[http_line(
"POST",
"/nothing/here",
Some(200),
Some(b"payload"),
)],
);
let r = report(&root, &[j]);
assert_eq!((r.recorded, r.outside.len()), (1, 0), "{r:#?}");
}
/// A case also states its body as base64 (`body_base64`: bytes that are not UTF-8) or by a file
/// (`body_file`, in a case written by hand). Such a case sends a body: read as "no body", it
/// recorded a fallback that has none.
#[test]
fn a_recorded_request_with_a_base64_or_a_file_body_does_not_record_an_entry_without_one() {
let root = http_repo("body-other-forms");
let case = |body: &str| {
format!(
"[request]\nmethod = \"POST\"\npath = \"/nothing/here\"\n{body}\n\n[response]\nstatus = 200\n"
)
};
let counts = |journal: &PathBuf| {
let r = report(&root, std::slice::from_ref(journal));
(r.recorded, r.outside.len())
};
let line = |body: Option<&[u8]>| http_line("POST", "/nothing/here", Some(200), body);
// 0xff 0xfe 0x00 0x01 is not UTF-8: `app record` writes it as base64 (`//4AAQ==`).
let raw: &[u8] = &[0xff, 0xfe, 0x00, 0x01];
let without = journal(&root, "none.jsonl", &[line(None)]);
let same = journal(&root, "same.jsonl", &[line(Some(raw))]);
let other = journal(
&root,
"other.jsonl",
&[line(Some(&[0xff, 0xfe, 0x00, 0x02]))],
);
let text = journal(&root, "text.jsonl", &[line(Some(b"payload"))]);
let toml = "rust/app-cases/http/h-body.toml";
put(&root, toml, &case("body_base64 = \"//4AAQ==\""));
assert_eq!(counts(&without), (0, 1), "a base64 body is a body");
assert_eq!(counts(&other), (0, 1), "other bytes are another request");
assert_eq!(counts(&same), (1, 0), "the same bytes are the same request");
// A body that the case's header does not give is the body of no fallback: neither "no
// body" nor the bytes of the file, which this read does not open.
put(&root, "rust/app-cases/http/payload.txt", "payload");
for unread in [
"body_file = \"payload.txt\"",
"body_base64 = \"not base64\"",
"body = \"payload\"\nbody_base64 = \"cGF5bG9hZA==\"",
"body = 7",
] {
put(&root, toml, &case(unread));
assert_eq!(counts(&without), (0, 1), "{unread}");
assert_eq!(counts(&text), (0, 1), "{unread}");
}
// An empty body is the same as no body, in both spellings.
for empty in ["body = \"\"", "body_base64 = \"\""] {
put(&root, toml, &case(empty));
assert_eq!(counts(&without), (1, 0), "{empty}");
}
}
// ---------------------------------------------------------------------------------------------
// A size does not identify: what was not written is identified by its digest too.
fn skipped_line(bytes: u64, fnv: &str) -> String {
format!("{{\"v\":1,\"kind\":\"skipped\",\"bytes\":{bytes},\"fnv\":\"{fnv}\"}}")
}
#[test]
fn a_waiver_of_a_skipped_line_does_not_cover_another_one_of_the_same_size() {
let root = cli_repo("skipped-same-size");
decide(&root);
let first = journal(&root, "a.jsonl", &[skipped_line(70000, "0000000000000001")]);
let r = fallbacks(&root, &[first], true, None).unwrap();
let old = r.outside[0].id.clone();
waive(&root, std::slice::from_ref(&old), "a fixture's long line").unwrap();
assert!(!standing(&root).unwrap().blocks());
// Another fallback that is too long, of the same size, with another digest.
let second = journal(&root, "b.jsonl", &[skipped_line(70000, "0000000000000002")]);
let r = fallbacks(&root, &[second], true, None).unwrap();
assert_eq!(r.outside.len(), 1, "{r:#?}");
let new = r.outside[0].id.clone();
assert_ne!(new, old, "the same size is not the same fallback");
let s = standing(&root).unwrap();
assert!(s.blocks(), "{s:#?}");
assert_eq!(
ids(&blocking_of(&root, "skipped")),
std::slice::from_ref(&new)
);
assert!(s.waived.iter().any(|w| w.id == old), "{s:#?}");
assert!(!s.waived.iter().any(|w| w.id == new), "{s:#?}");
assert!(lift_blockers(&s, "r").iter().any(|l| l.contains(&new)));
// The journal read a second time creates no duplicate and the waiver holds.
waive(&root, std::slice::from_ref(&new), "the second one too").unwrap();
let again = journal(
&root,
"c.jsonl",
&[
skipped_line(70000, "0000000000000001"),
skipped_line(70000, "0000000000000002"),
],
);
let r = fallbacks(&root, &[again.clone(), again], true, None).unwrap();
assert_eq!(r.outside.len(), 2, "{r:#?}");
assert!(r.outside.iter().all(|o| o.waived.is_some()), "{r:#?}");
assert!(!standing(&root).unwrap().blocks());
assert_eq!(
stored_lines(&root).len(),
2,
"{}",
get(&root, FALLBACKS_FILE)
);
}
#[test]
fn two_skipped_lines_of_one_size_and_two_digests_are_two_entries() {
let root = cli_repo("skipped-two-digests");
decide(&root);
let j = journal(
&root,
"j.jsonl",
&[
skipped_line(70000, "0000000000000001"),
skipped_line(70000, "0000000000000002"),
skipped_line(70000, "0000000000000002"),
],
);
let r = fallbacks(&root, &[j], true, None).unwrap();
assert_eq!(r.outside.len(), 2, "{r:#?}");
assert_ne!(r.outside[0].id, r.outside[1].id);
assert_eq!(stored_lines(&root).len(), 2);
}
#[test]
fn a_waiver_of_a_full_journal_does_not_cover_another_full_journal_of_the_same_size() {
let root = cli_repo("truncated-same-size");
decide(&root);
let a = full_journal(&root, &cli_line(&["build", "--out", "d"], 0, None));
let size = std::fs::metadata(&a).unwrap().len();
let r = fallbacks(&root, std::slice::from_ref(&a), true, None).unwrap();
let old = r
.outside
.iter()
.find(|o| o.id.starts_with("fallback:truncated#"))
.unwrap()
.id
.clone();
waive(
&root,
std::slice::from_ref(&old),
"the journal was read by hand",
)
.unwrap();
assert!(blocking_of(&root, "truncated").is_empty());
// Another full journal, of the same size but other content: same line length.
let a_copy = root.join("full-a.jsonl");
std::fs::copy(&a, &a_copy).unwrap();
let b = full_journal(&root, &cli_line(&["build", "--out", "e"], 0, None));
assert_eq!(std::fs::metadata(&b).unwrap().len(), size);
let r = fallbacks(&root, &[b], true, None).unwrap();
let new = r
.outside
.iter()
.find(|o| o.id.starts_with("fallback:truncated#"))
.unwrap()
.id
.clone();
assert_ne!(new, old);
assert_eq!(
ids(&blocking_of(&root, "truncated")),
std::slice::from_ref(&new)
);
let s = standing(&root).unwrap();
assert!(
s.blocks() && !s.waived.iter().any(|w| w.id == new),
"{s:#?}"
);
// The same journal read twice: a single entry, still waived.
waive(&root, std::slice::from_ref(&new), "this one too").unwrap();
let r = fallbacks(&root, &[a_copy.clone(), a_copy], true, None).unwrap();
let trunc: Vec<_> = r
.outside
.iter()
.filter(|o| o.id.starts_with("fallback:truncated#"))
.collect();
assert_eq!(trunc.len(), 1, "{r:#?}");
assert!(trunc[0].waived.is_some(), "{r:#?}");
assert!(!standing(&root).unwrap().blocks());
}
#[test]
fn a_skipped_or_truncated_line_without_its_digest_is_a_fault_in_a_journal_and_in_the_stored_file() {
let root = cli_repo("no-digest");
for (name, line) in [
("skipped", "{\"v\":1,\"kind\":\"skipped\",\"bytes\":70000}"),
(
"skipped-fnv-only",
"{\"v\":1,\"kind\":\"skipped\",\"fnv\":\"0000000000000001\"}",
),
(
"skipped-upper",
"{\"v\":1,\"kind\":\"skipped\",\"bytes\":1,\"fnv\":\"ABCDEF0123456789\"}",
),
] {
let j = journal(&root, &format!("{name}.jsonl"), &[line.to_string()]);
assert!(
fallbacks(&root, &[j], false, None).is_err(),
"{name}: {line}"
);
}
put(
&root,
FALLBACKS_FILE,
"{\"v\":1,\"kind\":\"truncated\",\"bytes\":1048600}\n",
);
assert!(
standing(&root).is_err(),
"a stored truncated line needs its digest"
);
}
// ---------------------------------------------------------------------------------------------
// The MCP tool `obligations_fallbacks`: the same command, and it writes when asked to.
/// A tool call as the server makes it: the result of `tools/call`.
fn tool(arguments: Value) -> Value {
rust_anything::mcp::handle(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": { "name": "obligations_fallbacks", "arguments": arguments } }))
.unwrap()["result"]
.clone()
}
#[test]
fn the_mcp_tool_sorts_writes_the_stored_file_and_creates_the_inputs_file_but_never_overwrites() {
let (root, j) = sorted_cli("mcp-tool");
// A skipped line: the warning must reach the tool's answer.
let mut text = std::fs::read_to_string(&j).unwrap();
text.push_str("{\"v\":1,\"kind\":\"skipped\",\"bytes\":70000,\"fnv\":\"af63dc4c8601ec8c\"}\n");
std::fs::write(&j, text).unwrap();
let inputs = root.join("inputs.jsonl");
// Without `write` or `inputs`: it reads and stores nothing.
let read = tool(json!({ "repo": root, "journals": [j] }));
assert_eq!(read["isError"], false, "{read}");
assert!(!root.join(FALLBACKS_FILE).exists() && !inputs.exists());
let s = &read["structuredContent"];
assert_eq!(s["schema"], FALLBACKS_SCHEMA, "{s}");
assert_eq!(s["outside"].as_array().unwrap().len(), 2, "{s}");
assert_eq!(s["refused"], 1, "{s}");
assert!(
s["warnings"]
.as_array()
.unwrap()
.iter()
.any(|w| w.as_str().unwrap().contains("too long to be written")),
"{s}"
);
// With `write` and `inputs`: the stored file and the inputs file are written.
let done = tool(json!({ "repo": root, "journals": [j], "write": true, "inputs": inputs }));
assert_eq!(done["isError"], false, "{done}");
let s = &done["structuredContent"];
assert_eq!(s["stored"]["path"], FALLBACKS_FILE, "{s}");
assert_eq!(s["stored"]["added"], 2, "{s}");
let stored = stored_lines(&root);
assert_eq!(stored.len(), 2);
assert!(
stored.iter().any(|l| l["args"] == json!(["nope"])),
"{stored:?}"
);
assert!(s["inputs"]["written"].as_u64().unwrap() >= 1, "{s}");
assert!(inputs.is_file(), "the inputs file is created");
let created = std::fs::read_to_string(&inputs).unwrap();
assert!(created.contains("\"nope\""), "{created}");
assert!(
s["warnings"]
.as_array()
.unwrap()
.iter()
.any(|w| w.as_str().unwrap().contains("too long to be written")),
"{s}"
);
// An inputs target that exists is refused, and nothing is rewritten.
let before_inputs = std::fs::read_to_string(&inputs).unwrap();
let again = tool(json!({ "repo": root, "journals": [j], "inputs": inputs }));
assert_eq!(again["isError"], true, "{again}");
assert_eq!(std::fs::read_to_string(&inputs).unwrap(), before_inputs);
}