use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use fallow_config::EnvSnapshot;
use serde::Deserialize;
use serde_json::Value;
use super::ResolvedRun;
const ROW_PLACEHOLDER: &str = "<row>";
fn cases_dir() -> PathBuf {
let Some(manifest_dir) = std::env::var_os("CARGO_MANIFEST_DIR") else {
panic!("cargo sets CARGO_MANIFEST_DIR");
};
Path::new(&manifest_dir).join("../../tests/fixtures/run-parity/cases")
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Case {
pub name: String,
#[serde(default)]
pub files: BTreeMap<String, String>,
#[serde(default)]
pub env: BTreeMap<String, String>,
pub inputs: BTreeMap<String, Value>,
pub expected: BTreeMap<String, Expected>,
#[serde(default)]
pub deviations: BTreeMap<String, Deviation>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum Expected {
Decision {
value: Value,
source: String,
},
Plain(Value),
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Deviation {
pub reason: String,
pub expected: BTreeMap<String, Expected>,
}
pub enum RowResult {
Run(Box<ResolvedRun>),
NotExpressible,
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RowFailure {
pub case: String,
pub key: String,
pub message: String,
}
#[must_use]
pub fn load_cases() -> Vec<Case> {
let dir = cases_dir();
let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
.unwrap_or_else(|err| panic!("cannot read {}: {err}", dir.display()))
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "json"))
.collect();
paths.sort();
paths
.iter()
.map(|path| {
let text = std::fs::read_to_string(path)
.unwrap_or_else(|err| panic!("cannot read {}: {err}", path.display()));
let case: Case = serde_json::from_str(&text)
.unwrap_or_else(|err| panic!("cannot parse {}: {err}", path.display()));
let stem = path.file_stem().and_then(|stem| stem.to_str());
assert_eq!(stem, Some(case.name.as_str()), "{}", path.display());
case
})
.collect()
}
fn write_case(dir: &Path, case: &Case) {
std::fs::create_dir_all(dir.join(".git")).unwrap_or_else(|err| panic!("git marker: {err}"));
for (name, content) in &case.files {
let path = dir.join(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).unwrap_or_else(|err| panic!("case file folder: {err}"));
}
std::fs::write(&path, content).unwrap_or_else(|err| panic!("case file: {err}"));
}
}
pub fn assert_rows(
row: &str,
cases: &[Case],
translate: impl Fn(&Case, &Path, EnvSnapshot) -> RowResult,
) -> Vec<RowFailure> {
let mut failures = Vec::new();
for case in cases {
let failure = |key: &str, message: String| RowFailure {
case: case.name.clone(),
key: key.to_owned(),
message,
};
let Some(input) = case.inputs.get(row) else {
failures.push(failure(
"input",
format!("the case has no input for `{row}`"),
));
continue;
};
let project = tempfile::tempdir().unwrap_or_else(|err| panic!("case root: {err}"));
let cwd = tempfile::tempdir().unwrap_or_else(|err| panic!("case cwd: {err}"));
let root = dunce::canonicalize(project.path())
.unwrap_or_else(|err| panic!("canonical case root: {err}"));
write_case(&root, case);
let pairs: Vec<(&str, &str)> = case
.env
.iter()
.map(|(name, value)| (name.as_str(), value.as_str()))
.collect();
let env = EnvSnapshot::from_pairs(&pairs, Some(cwd.path()));
match translate(case, &root, env) {
RowResult::NotExpressible => {
let reason = input.get("not_expressible").and_then(Value::as_str);
if reason.is_none_or(str::is_empty) {
failures.push(failure(
"input",
"the row is not expressible, and the case gives no reason".to_owned(),
));
}
}
RowResult::Failed(message) => failures.push(failure("run", message)),
RowResult::Run(run) => {
failures.extend(
compare(row, case, &run)
.into_iter()
.map(|(key, message)| failure(&key, message)),
);
}
}
}
failures
}
fn expected_for(row: &str, case: &Case) -> Result<BTreeMap<String, Expected>, String> {
let mut expected = case.expected.clone();
if let Some(deviation) = case.deviations.get(row) {
if deviation.reason.trim().is_empty() {
return Err(format!("the deviation of `{row}` has no reason"));
}
expected.extend(deviation.expected.clone());
}
Ok(expected)
}
fn compare(row: &str, case: &Case, run: &ResolvedRun) -> Vec<(String, String)> {
let expected = match expected_for(row, case) {
Ok(expected) => expected,
Err(message) => return vec![("deviations".to_owned(), message)],
};
let view = match serde_json::to_value(run.view()) {
Ok(view) => view,
Err(err) => return vec![("view".to_owned(), err.to_string())],
};
expected
.iter()
.filter_map(|(key, expected)| {
let actual = key
.split('.')
.try_fold(&view, |value, part| value.get(part));
let Some(actual) = actual else {
return Some((key.clone(), "the view has no such field".to_owned()));
};
compare_value(row, expected, actual).map(|message| (key.clone(), message))
})
.collect()
}
fn compare_value(row: &str, expected: &Expected, actual: &Value) -> Option<String> {
match expected {
Expected::Plain(Value::String(text)) if text == ROW_PLACEHOLDER => {
(actual.as_str() != Some(row)).then(|| format!("expected `{row}`, got {actual}"))
}
Expected::Plain(value) => {
(value != actual).then(|| format!("expected {value}, got {actual}"))
}
Expected::Decision { value, source } => {
let actual_value = actual.get("value").unwrap_or(&Value::Null);
let actual_source = actual.get("source").map(source_label);
if actual_value == value && actual_source.as_deref() == Some(source.as_str()) {
None
} else {
Some(format!(
"expected {value} from {source}, got {actual_value} from {}",
actual_source.as_deref().unwrap_or("no source")
))
}
}
}
}
fn source_label(source: &Value) -> String {
let kind = source.get("kind").and_then(Value::as_str).unwrap_or("");
let field = |name| source.get(name).and_then(Value::as_str).unwrap_or("");
let name = match kind {
"default" => field("rule"),
"derived" => field("from"),
"config-file" => field("key"),
"environment" => field("name"),
"given" => source
.get("origin")
.and_then(|origin| origin.get("name"))
.and_then(Value::as_str)
.unwrap_or(""),
_ => "",
};
format!("{kind}:{name}")
}
#[must_use]
pub fn normalize_mcp_cli_argv(argv: &[String]) -> Vec<String> {
let mut normalized = Vec::with_capacity(argv.len());
let mut args = argv.iter().peekable();
while let Some(arg) = args.next() {
match arg.as_str() {
"--quiet" | "--explain" | "--format=json" => {}
"--format" if args.peek().is_some_and(|next| *next == "json") => {
args.next();
}
_ => normalized.push(arg.clone()),
}
}
normalized
}
#[cfg(test)]
#[path = "parity_tests.rs"]
mod tests;