use std::fmt::Write as _;
use std::path::{Path, PathBuf};
pub const UPDATE_GOLDEN: &str = "PETITCARNETS_UPDATE_GOLDEN";
#[must_use]
pub fn golden_path(name: &str) -> PathBuf {
let root = std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(PathBuf::new, PathBuf::from);
root.join("tests")
.join("golden")
.join(format!("{name}.golden"))
}
pub fn assert_golden(name: &str, actual: &str) {
let update = std::env::var_os(UPDATE_GOLDEN).is_some_and(|v| v == "1");
check(&golden_path(name), actual, update);
}
fn check(path: &Path, actual: &str, update: bool) {
if update {
let written = path
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(path, actual));
if let Err(err) = written {
panic!("cannot write {}: {err}", path.display());
}
return;
}
let expected = match std::fs::read_to_string(path) {
Ok(text) => text.replace("\r\n", "\n"),
Err(err) => panic!(
"cannot read {}: {err}; run with {UPDATE_GOLDEN}=1 to write it",
path.display()
),
};
if let Some(report) = difference(&expected, actual) {
panic!(
"{} differs from the actual output; run with {UPDATE_GOLDEN}=1 \
to accept it\n{report}",
path.display()
);
}
}
fn difference(expected: &str, actual: &str) -> Option<String> {
if expected == actual {
return None;
}
let mut want = expected.split('\n');
let mut got = actual.split('\n');
let mut line = 1;
let (want, got) = loop {
match (want.next(), got.next()) {
(w, g) if w == g => line += 1,
other => break other,
}
};
let mut report = format!("line {line}:\n");
let _ = writeln!(report, " expected: {:?}", want.unwrap_or("<end>"));
let _ = writeln!(report, " actual: {:?}", got.unwrap_or("<end>"));
let _ = write!(report, "actual output:\n{actual}");
Some(report)
}
#[must_use]
pub fn escape(bytes: &[u8]) -> String {
let mut out = String::new();
for c in String::from_utf8_lossy(bytes).chars() {
match c {
'\n' => out.push_str("\\n\n"),
'"' | '\'' => out.push(c),
_ => out.extend(c.escape_debug()),
}
}
out
}
#[cfg(test)]
mod tests;