Skip to main content

rtce_testkit/
lib.rs

1//! `rtce-testkit` — golden-fixture harness for `rtce` and its consumer
2//! games.
3//!
4//! This crate carries no test logic of its own; it's the small set of
5//! house rules every `rtce`-based game's test suite is expected to share,
6//! inherited from `diablo4-calc`'s M1 milestone:
7//!
8//! - **Golden fixtures live in JSON files, one case per file.**
9//!   [`for_each_fixture`] walks a directory, parses each `*.json` as a
10//!   `serde_json::Value`, and hands it to your callback in sorted-by-name
11//!   order (deterministic test output, deterministic diffs).
12//! - **An empty suite is a bug, not a pass.** If the fixture directory is
13//!   missing or yields zero `*.json` files, [`for_each_fixture`] panics
14//!   instead of silently iterating zero times — a typo'd path or an
15//!   accidentally-emptied directory must fail loudly, never look like
16//!   "all fixtures passed."
17//! - **Every fixture is provenance-tagged.** Each JSON file must carry a
18//!   `name` and a `source` key (where the expected number came from — a
19//!   hand-worked calculation, an in-game screenshot, another calculator)
20//!   so a reviewer can trace any pinned number back to its origin.
21//! - **Comparisons are relative-tolerance, not exact-float.** [`assert_close`]
22//!   compares `actual` against `expected` within a relative tolerance,
23//!   because floating-point pipelines rarely reproduce bit-for-bit across
24//!   platforms/optimization levels.
25//!
26//! Depend on this crate as a dev-dependency; use [`for_each_fixture`] to
27//! drive your golden-fixture tests and [`assert_close`] to check each
28//! result.
29
30#![warn(missing_docs)]
31
32use std::path::Path;
33
34/// Relative-tolerance assertion with a context message.
35pub fn assert_close(actual: f64, expected: f64, rel_tol: f64, ctx: &str) {
36    let denom = expected.abs().max(1e-12);
37    let rel = (actual - expected).abs() / denom;
38    assert!(
39        rel <= rel_tol,
40        "{ctx}: {actual} != {expected} (rel err {rel:.3e} > {rel_tol:.1e})"
41    );
42}
43
44/// Invoke `f(name, json)` for every `*.json` fixture in `dir`, sorted by
45/// file name. PANICS if the directory holds no fixtures (or is missing) —
46/// the empty-glob rule.
47pub fn for_each_fixture(dir: &Path, mut f: impl FnMut(&str, &serde_json::Value)) {
48    let mut entries: Vec<_> = std::fs::read_dir(dir)
49        .unwrap_or_else(|e| panic!("fixture dir {}: {e}", dir.display()))
50        .filter_map(|e| e.ok())
51        .map(|e| e.path())
52        .filter(|p| p.extension().and_then(|x| x.to_str()) == Some("json"))
53        .collect();
54    entries.sort();
55    assert!(
56        !entries.is_empty(),
57        "no fixtures in {} — an empty suite must not pass",
58        dir.display()
59    );
60    for path in entries {
61        let raw =
62            std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
63        let v: serde_json::Value = serde_json::from_str(&raw)
64            .unwrap_or_else(|e| panic!("{}: invalid JSON: {e}", path.display()));
65        assert!(
66            v.get("name").is_some() && v.get("source").is_some(),
67            "{}: fixtures must carry `name` and `source` provenance",
68            path.display()
69        );
70        f(path.file_stem().unwrap().to_str().unwrap(), &v);
71    }
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use std::fs;
78
79    #[test]
80    fn assert_close_accepts_within_and_rejects_outside_tolerance() {
81        assert_close(100.0005, 100.0, 1e-5, "ok");
82        let r = std::panic::catch_unwind(|| assert_close(101.0, 100.0, 1e-5, "off"));
83        assert!(r.is_err(), "1% off must fail a 1e-5 tolerance");
84    }
85
86    #[test]
87    fn empty_fixture_dir_panics() {
88        let dir = std::env::temp_dir().join(format!("rtce-testkit-empty-{}", std::process::id()));
89        let _ = fs::remove_dir_all(&dir);
90        fs::create_dir_all(&dir).unwrap();
91        let r = std::panic::catch_unwind(|| for_each_fixture(&dir, |_, _| {}));
92        assert!(r.is_err(), "empty dir must panic");
93    }
94
95    #[test]
96    fn fixtures_iterate_sorted_and_demand_provenance() {
97        let dir = std::env::temp_dir().join(format!("rtce-testkit-two-{}", std::process::id()));
98        let _ = fs::remove_dir_all(&dir);
99        fs::create_dir_all(&dir).unwrap();
100        fs::write(dir.join("b.json"), r#"{"name":"b","source":"t","v":2}"#).unwrap();
101        fs::write(dir.join("a.json"), r#"{"name":"a","source":"t","v":1}"#).unwrap();
102        let mut seen = Vec::new();
103        for_each_fixture(&dir, |name, v| {
104            seen.push((name.to_string(), v["v"].as_i64().unwrap()))
105        });
106        assert_eq!(seen, vec![("a".into(), 1), ("b".into(), 2)]);
107
108        fs::write(dir.join("c.json"), r#"{"v":3}"#).unwrap();
109        let r = std::panic::catch_unwind(|| for_each_fixture(&dir, |_, _| {}));
110        assert!(r.is_err(), "missing provenance must panic");
111    }
112}