Skip to content

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.

7.5 KB
Raw Blame
//! `rust-anything selftest` plants wrong ports and tampers with the recording; every planted bug
//! must be refused by the check meant to refuse it. This test is the specification of what is
//! caught and what is a documented gap: when a gap closes (or a catch is lost) it fails and says
//! which row changed. It builds real ports, so it needs cargo and, per language, node or python.

mod common;

use serde_json::Value;

/// Every planted bug, in the order they run.
const BUGS: [&str; 17] = [
    "no-op-port",
    "always-throws",
    "wrong-error-type",
    "hard-coded-table",
    "hard-coded-table-marked",
    "exits-the-process",
    "shells-out-to-original",
    "shells-out-marked-spawns",
    "includes-the-recording",
    "prints-extra-output",
    "differs-outside-recording",
    "delete-recorded-from",
    "delete-cases",
    "marked-legacy-recording",
    "add-known-diffs",
    "raise-tolerance",
    "good-port",
];

/// Not caught by `diff` or `gate`, in both languages, and why (docs/how-it-works.md, "What it
/// can't catch" and "What gate refuses to count").
const GAPS: [&str; 1] = [
    // A unit's `diff` compares what a function returns or throws, not what it prints.
    "prints-extra-output",
];

/// Caught by `gate`'s held-out check in every language whose ports it runs (TS/JS napi and
/// Python PyO3): the recording is the ceiling and `fuzz` is how to look past it, and a recording
/// made before fingerprints is used as it is, which `gate` says.
const OUTSIDE: &str = "differs-outside-recording";
const LEGACY: &str = "marked-legacy-recording";

fn selftest(args: &[&str]) -> std::process::Output {
    common::cli().arg("selftest").args(args).output().unwrap()
}

fn row<'a>(report: &'a Value, language: &str, id: &str) -> &'a Value {
    report["rows"]
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["language"] == language && r["id"] == id)
        .unwrap_or_else(|| panic!("no {language} row for {id}: {report:#}"))
}

#[test]
fn selftest_catches_what_it_claims_and_names_what_it_does_not() {
    let mut langs = Vec::new();
    if common::have("node") {
        langs.push("TypeScript/JavaScript");
    }
    if common::python().is_some() {
        langs.push("Python");
    }
    if langs.is_empty() || !common::have("cargo") {
        return;
    }
    // Every language it can run, as a user runs it: the others are listed as not run.
    let out = selftest(&["--json"]);
    let report: Value = serde_json::from_slice(&out.stdout)
        .unwrap_or_else(|e| panic!("{e}: {}", String::from_utf8_lossy(&out.stderr)));
    assert!(out.status.success(), "{report:#}");
    assert_eq!(report["passed"], true);
    assert_eq!(report["schema"], "rust-anything/selftest@1");

    for language in &langs {
        let rows: Vec<&str> = report["rows"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|r| r["language"] == *language)
            .map(|r| r["id"].as_str().unwrap())
            .collect();
        assert_eq!(rows, BUGS, "{language}");
        for id in BUGS {
            let r = row(&report, language, id);
            let status = r["status"].as_str().unwrap();
            let want = match id {
                "good-port" => "passed",
                id if GAPS.contains(&id) => "known-gap",
                _ => "caught",
            };
            assert_eq!(status, want, "{language}: {id}: {r:#}");
        }
        // Where the refusal happens, not only that there was one.
        let by = |id: &str| {
            row(&report, language, id)["by"]
                .as_str()
                .unwrap()
                .to_string()
        };
        assert_eq!(by("no-op-port"), "diff");
        assert_eq!(by("exits-the-process"), "diff");
        assert_eq!(by("wrong-error-type"), "diff");
        assert_eq!(by("hard-coded-table"), "gate: literals");
        assert_eq!(by("hard-coded-table-marked"), "gate: literals");
        assert_eq!(by("shells-out-to-original"), "gate: runtime, spawns");
        assert_eq!(by("shells-out-marked-spawns"), "gate: runtime, spawns");
        // Python's held-out draw reaches `grade(100)`, which the wrong port gets wrong, after the
        // known-diffs entries excuse its recorded failures; TS/JS stops at the entries.
        assert_eq!(
            by("add-known-diffs"),
            if *language == "Python" {
                "gate: accepted diffs, held-out"
            } else {
                "gate: accepted diffs"
            },
            "{language}"
        );
        assert_eq!(by("includes-the-recording"), "gate: literals, runtime");
        assert_eq!(by("raise-tolerance"), "gate: recording");
        for id in ["delete-recorded-from", "delete-cases"] {
            assert_eq!(by(id), "gate: recording, held-out", "{language}: {id}");
        }
        // The held-out check runs for every language the selftest bridges.
        assert_eq!(by(OUTSIDE), "gate: held-out", "{language}");
        assert_eq!(by(LEGACY), "gate: held-out", "{language}");
    }

    // What did not run is listed with the reason, never skipped silently.
    let not_run: Vec<&str> = report["not_run"]
        .as_array()
        .unwrap()
        .iter()
        .map(|n| n["reason"].as_str().unwrap())
        .collect();
    assert!(not_run.iter().any(|r| r.contains("Go")), "{not_run:?}");
    for (tool, language) in [("node", "TypeScript/JavaScript"), ("python3", "Python")] {
        if !langs.contains(&language) {
            assert!(
                not_run
                    .iter()
                    .any(|r| r.contains("missing") && r.contains(language)),
                "{tool}: {not_run:?}"
            );
        }
    }
    assert!(report["scratch"].is_null(), "the scratch folder is removed");
}

#[test]
fn strict_fails_on_a_known_gap() {
    if !common::have("cargo") || common::python().is_none() {
        return;
    }
    let args = ["--lang", "python", "--only", "prints-extra-output"];
    let lenient = selftest(&args);
    assert!(lenient.status.success(), "{lenient:?}");
    let strict = selftest(&[&args[..], &["--strict"]].concat());
    assert_eq!(strict.status.code(), Some(1), "{strict:?}");
    let text = String::from_utf8_lossy(&strict.stdout);
    assert!(text.contains("not caught"), "{text}");
    assert!(text.trim_end().ends_with("Selftest failed."), "{text}");
}

#[test]
fn an_unknown_bug_or_a_language_without_an_original_is_an_error() {
    let out = selftest(&["--only", "no-such-bug"]);
    assert_eq!(out.status.code(), Some(2));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("no planted bug named `no-such-bug`"), "{err}");
    assert!(err.contains("hard-coded-table"), "{err}");

    // Nothing ran is a failure that says why, not an empty pass.
    let out = selftest(&["--lang", "go"]);
    assert_eq!(out.status.code(), Some(2));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("nothing ran"), "{err}");
    assert!(err.contains("no built-in original for Go"), "{err}");
}

#[cfg(unix)]
#[test]
fn a_missing_toolchain_is_a_visible_line() {
    let empty = std::env::temp_dir().join(format!("ra-selftest-empty-{}", std::process::id()));
    std::fs::create_dir_all(&empty).unwrap();
    let out = common::cli()
        .arg("selftest")
        .env("PATH", &empty)
        .output()
        .unwrap();
    let _ = std::fs::remove_dir_all(&empty);
    assert_eq!(out.status.code(), Some(2));
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("cargo missing (TypeScript/JavaScript)")
            && err.contains("cargo missing (Python)"),
        "{err}"
    );
}