//! Snapshot tests: every file in `tests/fixtures/` is formatted and compared //! against `tests/snapshots/.formatted`; the result must also be //! idempotent (formatting the output again changes nothing). //! //! Regenerate snapshots with: //! UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter --test fixtures use std::path::PathBuf; use vlog_formatter::{format_source, Config}; fn fixture_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") } fn snapshot_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots") } #[test] fn fixtures_match_snapshots_and_are_idempotent() { let update = std::env::var("UPDATE_SNAPSHOTS").is_ok(); let config = Config::default(); let mut entries: Vec<_> = std::fs::read_dir(fixture_dir()) .expect("fixtures dir") .map(|e| e.expect("dir entry").path()) .filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("v") | Some("sv"))) .collect(); entries.sort(); assert!(!entries.is_empty(), "no fixtures found"); let mut failures = Vec::new(); for path in entries { let name = path.file_name().unwrap().to_str().unwrap().to_string(); let src = std::fs::read_to_string(&path).expect("read fixture"); let once = match format_source(&src, &config) { Ok(o) => o, Err(e) => { failures.push(format!("{name}: failed to format: {e}")); continue; } }; // Idempotency. match format_source(&once, &config) { Ok(twice) => { if twice != once { failures.push(format!("{name}: formatting is not idempotent")); } } Err(e) => { failures.push(format!("{name}: reformatting own output failed: {e}")); } } // Snapshot comparison. let snap_path = snapshot_dir().join(format!("{name}.formatted")); if update { std::fs::write(&snap_path, &once).expect("write snapshot"); } else { match std::fs::read_to_string(&snap_path) { Ok(expected) => { if expected != once { failures.push(format!( "{name}: output differs from snapshot \ (run with UPDATE_SNAPSHOTS=1 to update)" )); } } Err(_) => failures.push(format!( "{name}: missing snapshot {} (run with UPDATE_SNAPSHOTS=1)", snap_path.display() )), } } } assert!(failures.is_empty(), "{}", failures.join("\n")); } #[test] fn small_cases() { // (input, expected) pairs for focused behaviors. let cases: &[(&str, &str)] = &[ ("module m;endmodule", "module m;\nendmodule\n"), ( "module m(input a,output b);assign b=~a;endmodule", "module m (input a, output b);\n assign b = ~a;\nendmodule\n", ), ( "module m;wire [7:0] x = {a,b} ;endmodule", "module m;\n wire [7:0] x = {a, b};\nendmodule\n", ), ]; let config = Config::default(); for (input, expected) in cases { let got = format_source(input, &config).expect("format"); assert_eq!(&got, expected, "input: {input}"); } }