Files
lucisv/crates/vlog_formatter/tests/cases.rs
T
lucioandClaude Fable 5 6b95d772f1 Add case-tables: Verible-style text-in/text-out test suite
183 {input, expected} cases across 10 construct files under
tests/cases/, driven by a ~180-line std-only harness (==== / ----
format). Each case asserts formatting and idempotency; #SKIP parks
known formatter bugs and fails the suite once they start passing.

Documents four real formatter bugs found while deriving expected
output (block-comment re-indent non-idempotency, comment lifted out
of expression groups, closing block labels dropped, multi-instance
declaration layout) — parked as #SKIP, to be fixed in a follow-up
feature. Also adds rustfmt.toml matching the codebase style.

Dev: Opus agent; QA: Sonnet agent; review in
docs/features/case-tables/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-18 23:38:58 -07:00

193 lines
6.4 KiB
Rust

//! Table tests: every `tests/cases/*.cases` file holds a list of small
//! `{input, expected}` pairs, in the spirit of Verible's `formatter_test.cc`.
//! Cases are separated by a `====` line, input from expected by a `----` line,
//! and `#` lines at the top of a case name it. A case named `#SKIP ...` is
//! parsed but not asserted, so known-bad behavior can be recorded without
//! breaking the suite. Full format spec: `docs/features/case-tables/README.md`.
use std::path::{Path, PathBuf};
use vlog_formatter::{format_source, Config};
/// One `{input, expected}` pair with the source location it came from.
struct Case {
name: String,
line: usize,
input: String,
expected: String,
skip: bool,
}
fn cases_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/cases")
}
/// Splits one `.cases` file into cases; returns an error string on bad syntax.
fn parse_cases(path: &Path, text: &str) -> Result<Vec<Case>, String> {
let file = path.file_name().unwrap_or_default().to_string_lossy();
let mut cases = Vec::new();
let mut start = 1usize;
let mut block: Vec<&str> = Vec::new();
// A synthetic terminator lets the last case close like every other one.
for (idx, line) in text.lines().chain(std::iter::once("====")).enumerate() {
if line.trim_end() != "====" {
if block.is_empty() {
start = idx + 1;
}
block.push(line);
} else {
if block.iter().any(|l| !l.trim().is_empty()) {
cases.push(split_case(&file, start, &block)?);
}
block.clear();
}
}
Ok(cases)
}
/// Splits one case block into header comments, input and expected output.
fn split_case(file: &str, start: usize, block: &[&str]) -> Result<Case, String> {
let mut name = String::new();
let mut skip = false;
let mut body = block;
while let Some(first) = body.first() {
if !first.starts_with('#') && !first.trim().is_empty() {
break;
}
if let Some(rest) = first.strip_prefix('#') {
if rest.trim_start().starts_with("SKIP") {
skip = true;
}
if !name.is_empty() {
name.push(' ');
}
name.push_str(rest.trim());
}
body = &body[1..];
}
let sep = body
.iter()
.position(|l| l.trim_end() == "----")
.ok_or_else(|| format!("{file}:{start}: case has no `----` separator"))?;
if name.is_empty() {
name = format!("<unnamed case at {file}:{start}>");
}
Ok(Case {
name,
line: start,
input: join(&body[..sep]),
expected: join(&body[sep + 1..]),
skip,
})
}
/// Rejoins lines into a source string with a trailing newline (empty stays empty).
fn join(lines: &[&str]) -> String {
let mut out = String::new();
for line in lines {
out.push_str(line);
out.push('\n');
}
out
}
/// True if the case would pass both assertions today.
fn passes(case: &Case, config: &Config) -> bool {
match format_source(&case.input, config) {
Ok(once) if once == case.expected => {
matches!(format_source(&case.expected, config), Ok(twice) if twice == case.expected)
}
_ => false,
}
}
/// Renders expected vs actual as a line-oriented diff.
fn diff(expected: &str, got: &str) -> String {
let (e, g): (Vec<_>, Vec<_>) = (expected.lines().collect(), got.lines().collect());
let mut out = String::new();
for i in 0..e.len().max(g.len()) {
match (e.get(i), g.get(i)) {
(Some(a), Some(b)) if a == b => out.push_str(&format!(" {a}\n")),
(a, b) => {
if let Some(a) = a {
out.push_str(&format!(" - {a}\n"));
}
if let Some(b) = b {
out.push_str(&format!(" + {b}\n"));
}
}
}
}
out
}
#[test]
fn case_tables() {
let config = Config::default();
let mut files: Vec<PathBuf> = std::fs::read_dir(cases_dir())
.expect("cases dir")
.map(|e| e.expect("dir entry").path())
.filter(|p| p.extension().and_then(|e| e.to_str()) == Some("cases"))
.collect();
files.sort();
assert!(!files.is_empty(), "no .cases files found");
let mut failures = Vec::new();
let mut total = 0usize;
for path in &files {
let text = std::fs::read_to_string(path).expect("read cases file");
let file = path.file_name().unwrap().to_string_lossy().to_string();
let cases = match parse_cases(path, &text) {
Ok(c) => c,
Err(e) => {
failures.push(e);
continue;
}
};
for case in cases {
let at = format!("{file}:{} [{}]", case.line, case.name);
if case.skip {
// A #SKIP case documents a known bug: it must still fail.
// The moment it passes, demand the marker's removal so the
// case becomes a live regression test.
if passes(&case, &config) {
failures.push(format!(
"{at}: marked #SKIP but now passes — remove the #SKIP marker"
));
}
continue;
}
total += 1;
let once = match format_source(&case.input, &config) {
Ok(o) => o,
Err(e) => {
failures.push(format!("{at}: format failed: {e}"));
continue;
}
};
if once != case.expected {
failures.push(format!(
"{at}: output differs from expected\n{}",
diff(&case.expected, &once)
));
continue;
}
match format_source(&case.expected, &config) {
Ok(twice) if twice == case.expected => {}
Ok(twice) => failures.push(format!(
"{at}: not idempotent\n{}",
diff(&case.expected, &twice)
)),
Err(e) => failures.push(format!("{at}: reformatting output failed: {e}")),
}
}
}
assert!(total > 0, "no cases found");
assert!(
failures.is_empty(),
"{} of {total} cases failed:\n\n{}",
failures.len(),
failures.join("\n")
);
}