//! End-to-end tests that drive the real `vfmt` binary. //! //! Fixtures use the most trivial Verilog possible so these tests stay //! stable while the formatter's layout rules evolve. use std::io::Write; use std::path::PathBuf; use std::process::{Command, Output, Stdio}; use std::sync::atomic::{AtomicUsize, Ordering}; const VFMT: &str = env!("CARGO_BIN_EXE_vfmt"); /// Formats to `FORMATTED`: the only change is the newline before `endmodule`. const UNFORMATTED: &str = "module m;endmodule\n"; const FORMATTED: &str = "module m;\nendmodule\n"; /// Truncated header — the parser cannot recover from this. const UNPARSEABLE: &str = "module\n"; /// Formats to `INDENT_2` or `INDENT_4` depending on the `indent` setting. const UNINDENTED: &str = "module m;\nwire x;\nendmodule\n"; const INDENT_2: &str = "module m;\n wire x;\nendmodule\n"; const INDENT_4: &str = "module m;\n wire x;\nendmodule\n"; /// 44 columns: one line under the default 100, split under `line-length = 40`. const WIDE: &str = "module m (input wire aaaa, input wire bbbb);\nendmodule\n"; const WIDE_SPLIT: &str = "module m (\n input wire aaaa,\n input wire bbbb\n);\nendmodule\n"; /// A throwaway directory under the system temp dir, removed on drop. struct TempDir { path: PathBuf, } impl TempDir { fn new(tag: &str) -> TempDir { static COUNTER: AtomicUsize = AtomicUsize::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); let path = std::env::temp_dir().join(format!("vfmt-cli-{}-{tag}-{n}", std::process::id())); let _ = std::fs::remove_dir_all(&path); std::fs::create_dir_all(&path).expect("create temp dir"); TempDir { path } } fn write(&self, rel: &str, contents: &str) -> String { let path = self.path.join(rel); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).expect("create parent dir"); } std::fs::write(&path, contents).expect("write fixture"); path.to_string_lossy().into_owned() } fn read(&self, rel: &str) -> String { std::fs::read_to_string(self.path.join(rel)).expect("read fixture") } fn root(&self) -> String { self.path.to_string_lossy().into_owned() } } impl Drop for TempDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.path); } } fn run(args: &[&str]) -> Output { Command::new(VFMT).args(args).output().expect("run vfmt") } fn run_with_stdin(args: &[&str], input: &str) -> Output { let mut child = Command::new(VFMT) .args(args) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("spawn vfmt"); child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin"); child.wait_with_output().expect("run vfmt") } fn code(out: &Output) -> i32 { out.status.code().expect("exit code") } fn stdout(out: &Output) -> String { String::from_utf8_lossy(&out.stdout).into_owned() } fn stderr(out: &Output) -> String { String::from_utf8_lossy(&out.stderr).into_owned() } #[test] fn formats_files_in_place() { let dir = TempDir::new("inplace"); dir.write("a.sv", UNFORMATTED); dir.write("nested/b.v", UNFORMATTED); dir.write("notes.txt", "not verilog\n"); let out = run(&[&dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("a.sv"), FORMATTED); assert_eq!(dir.read("nested/b.v"), FORMATTED); assert_eq!(dir.read("notes.txt"), "not verilog\n", "non-Verilog files are not touched"); assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out)); // Second run is a no-op: nothing left to change. let out = run(&[&dir.root()]); assert_eq!(code(&out), 0); assert!(stderr(&out).contains("2 files left unchanged"), "{}", stderr(&out)); } #[test] fn check_reports_without_writing() { let dir = TempDir::new("check"); let path = dir.write("a.sv", UNFORMATTED); let out = run(&["--check", &path]); assert_eq!(code(&out), 1, "would-change must exit 1"); assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out)); assert_eq!(dir.read("a.sv"), UNFORMATTED, "--check must not write"); dir.write("a.sv", FORMATTED); let out = run(&["--check", &path]); assert_eq!(code(&out), 0, "nothing to change must exit 0"); assert_eq!(stdout(&out), ""); } #[test] fn diff_prints_a_unified_diff_without_writing() { let dir = TempDir::new("diff"); let path = dir.write("a.sv", UNFORMATTED); let out = run(&["--diff", &path]); assert_eq!(code(&out), 1, "would-change must exit 1"); assert_eq!(dir.read("a.sv"), UNFORMATTED, "--diff must not write"); let text = stdout(&out); let lines: Vec<&str> = text.lines().collect(); assert_eq!(lines[0], format!("--- {path}"), "{text}"); assert_eq!(lines[1], format!("+++ {path}"), "{text}"); assert!(lines[2].starts_with("@@ ") && lines[2].ends_with(" @@"), "{text}"); assert!(lines.contains(&"-module m;endmodule"), "{text}"); assert!(lines.contains(&"+module m;"), "{text}"); assert!(lines.contains(&"+endmodule"), "{text}"); // The summary goes to stderr so stdout is a clean patch. assert!(stderr(&out).contains("would be reformatted"), "{}", stderr(&out)); dir.write("a.sv", FORMATTED); let out = run(&["--diff", &path]); assert_eq!(code(&out), 0); assert_eq!(stdout(&out), "", "an unchanged file prints no diff"); } #[test] fn diff_conflicts_with_stdout() { let dir = TempDir::new("diffconflict"); let path = dir.write("a.sv", UNFORMATTED); let out = run(&["--diff", "--stdout", &path]); assert_eq!(code(&out), 2); assert!(stderr(&out).contains("--diff cannot be combined with --stdout"), "{}", stderr(&out)); } #[test] fn stdin_mode_uses_stdin_filename_in_errors() { let out = run_with_stdin(&["-"], UNPARSEABLE); assert_eq!(code(&out), 2); assert!(stderr(&out).starts_with("error: : "), "{}", stderr(&out)); let out = run_with_stdin(&["--stdin-filename", "rtl/top.sv", "-"], UNPARSEABLE); assert_eq!(code(&out), 2); assert!(stderr(&out).starts_with("error: rtl/top.sv: "), "{}", stderr(&out)); assert!(!stderr(&out).contains(""), "{}", stderr(&out)); assert!(!std::path::Path::new("rtl/top.sv").exists(), "--stdin-filename must not touch disk"); // It also names the buffer in --diff and --check output. let out = run_with_stdin(&["--diff", "--stdin-filename", "rtl/top.sv", "-"], UNFORMATTED); assert_eq!(code(&out), 1); assert!(stdout(&out).starts_with("--- rtl/top.sv\n+++ rtl/top.sv\n"), "{}", stdout(&out)); let out = run_with_stdin(&["--check", "--stdin-filename", "rtl/top.sv", "-"], UNFORMATTED); assert_eq!(code(&out), 1); assert_eq!(stdout(&out), "would reformat: rtl/top.sv\n"); } #[test] fn stdin_mode_formats_to_stdout() { let out = run_with_stdin(&["-"], UNFORMATTED); assert_eq!(code(&out), 0); assert_eq!(stdout(&out), FORMATTED); } #[test] fn exclude_skips_files_and_directories() { let dir = TempDir::new("exclude"); dir.write("keep.sv", UNFORMATTED); dir.write("skip_gen.sv", UNFORMATTED); dir.write("build/inner.sv", UNFORMATTED); dir.write("sub/keep.sv", UNFORMATTED); let out = run(&["--exclude", "*_gen.sv", "--exclude", "build", &dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("keep.sv"), FORMATTED); assert_eq!(dir.read("sub/keep.sv"), FORMATTED); assert_eq!(dir.read("skip_gen.sv"), UNFORMATTED, "name glob must be excluded"); assert_eq!(dir.read("build/inner.sv"), UNFORMATTED, "excluded dir is not descended into"); assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out)); } #[test] fn exclude_matches_a_path_suffix_when_it_contains_a_slash() { let dir = TempDir::new("excludepath"); dir.write("gen/rtl/a.sv", UNFORMATTED); dir.write("gen/hand/b.sv", UNFORMATTED); let out = run(&["--exclude", "gen/rtl", &dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("gen/rtl/a.sv"), UNFORMATTED); assert_eq!(dir.read("gen/hand/b.sv"), FORMATTED); } #[test] fn exclude_does_not_apply_to_explicitly_named_files() { let dir = TempDir::new("excludeexplicit"); let path = dir.write("skip_gen.sv", UNFORMATTED); let out = run(&["--exclude", "*_gen.sv", &path]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("skip_gen.sv"), FORMATTED); } #[test] fn unformattable_file_exits_2_and_is_left_untouched() { let dir = TempDir::new("badparse"); dir.write("bad.sv", UNPARSEABLE); dir.write("good.sv", UNFORMATTED); let out = run(&[&dir.root()]); assert_eq!(code(&out), 2, "an error must exit 2"); assert_eq!(dir.read("bad.sv"), UNPARSEABLE, "a file that fails to format is not rewritten"); assert_eq!(dir.read("good.sv"), FORMATTED, "other files are still formatted"); let err = stderr(&out); assert!(err.contains("bad.sv: parse error"), "{err}"); assert!(err.contains("1 file failed to format"), "{err}"); // An error outranks "would reformat" in --check and --diff too. dir.write("good.sv", UNFORMATTED); assert_eq!(code(&run(&["--check", &dir.root()])), 2); assert_eq!(code(&run(&["--diff", &dir.root()])), 2); } #[test] fn deeply_nested_file_does_not_kill_the_batch() { // Before `vlog_parser`'s depth limit this input overflowed the stack and // aborted the process, so files sorted after it were never processed — // and a stack overflow is not a panic, so `catch_unwind` cannot help. let deep = format!( "module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n", "if (clk) begin\n".repeat(150), "end\n".repeat(150) ); // A postfix chain is built by a loop, not by recursion: it costs the // parser no depth but hands the formatter an equally deep AST, which // crashed it the same way until chains got a budget of their own. let chain = format!("module m;\nassign x = a{};\nendmodule\n", ".b".repeat(1500)); let dir = TempDir::new("deep"); dir.write("a_before.sv", UNFORMATTED); dir.write("b_deep.sv", &deep); dir.write("c_chain.sv", &chain); dir.write("d_after.sv", UNFORMATTED); let out = run(&[&dir.root()]); assert_eq!(code(&out), 2, "a file that cannot be parsed exits 2"); assert_eq!(dir.read("b_deep.sv"), deep, "the offending file is left untouched"); assert_eq!(dir.read("c_chain.sv"), chain, "the offending file is left untouched"); assert_eq!(dir.read("a_before.sv"), FORMATTED); assert_eq!(dir.read("d_after.sv"), FORMATTED, "files after the bad ones are still processed"); let err = stderr(&out); assert!(err.contains("b_deep.sv: parse error"), "{err}"); assert!(err.contains("nesting too deep"), "{err}"); assert!(err.contains("c_chain.sv: parse error"), "{err}"); assert!(err.contains("expression chain too long"), "{err}"); assert!(err.contains("2 files reformatted"), "{err}"); assert!(err.contains("2 files failed to format"), "{err}"); } #[test] fn usage_errors_exit_2() { assert_eq!(code(&run(&[])), 2, "no inputs"); assert_eq!(code(&run(&["--nope", "x.sv"])), 2, "unknown option"); assert_eq!(code(&run(&["--exclude"])), 2, "missing option value"); assert_eq!(code(&run(&["/definitely/not/here.sv"])), 2, "missing input file"); } #[test] fn help_documents_the_exit_codes() { let out = run(&["--help"]); assert_eq!(code(&out), 0); let text = stdout(&out); assert!(text.contains("EXIT CODES:"), "{text}"); assert!(text.contains("CONFIGURATION:"), "{text}"); for flag in ["--check", "--diff", "--exclude", "--stdin-filename", "--no-config"] { assert!(text.contains(flag), "help is missing {flag}"); } } #[test] fn a_config_file_is_found_by_searching_upward() { let dir = TempDir::new("configup"); dir.write("vfmt.toml", "indent = 4\nline-length = 40\n"); dir.write("a/b/x.sv", UNINDENTED); dir.write("a/b/wide.sv", WIDE); let out = run(&[&dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("a/b/x.sv"), INDENT_4); // Both keys took effect: split by `line-length`, indented by `indent`. assert_eq!( dir.read("a/b/wide.sv"), "module m (\n input wire aaaa,\n input wire bbbb\n);\nendmodule\n" ); // Both names work; `.vfmt.toml` is the fallback within one directory. dir.write("a/b/x.sv", UNINDENTED); std::fs::rename(dir.path.join("vfmt.toml"), dir.path.join(".vfmt.toml")).expect("rename"); assert_eq!(code(&run(&[&dir.root()])), 0); assert_eq!(dir.read("a/b/x.sv"), INDENT_4); } #[test] fn each_file_gets_the_config_of_its_own_directory() { let dir = TempDir::new("configper"); dir.write("vfmt.toml", "indent = 4\n"); dir.write("root.sv", UNINDENTED); dir.write("sub/vfmt.toml", "indent = 8\n"); dir.write("sub/deep/inner.sv", UNINDENTED); dir.write("other/plain.sv", UNINDENTED); let out = run(&[&dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("root.sv"), INDENT_4); assert_eq!(dir.read("sub/deep/inner.sv"), "module m;\n wire x;\nendmodule\n"); assert_eq!(dir.read("other/plain.sv"), INDENT_4, "the nearest config is the root's"); // --check uses the same per-file settings and its summary is unchanged: // everything is now formatted to its own directory's config. let out = run(&["--check", &dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert!(stderr(&out).contains("3 files left unchanged"), "{}", stderr(&out)); } #[test] fn a_cli_flag_overrides_the_config_file() { let dir = TempDir::new("configcli"); dir.write("vfmt.toml", "indent = 4\nline-length = 40\n"); dir.write("x.sv", UNINDENTED); dir.write("wide.sv", WIDE); let out = run(&["--indent", "2", &dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("x.sv"), INDENT_2, "--indent wins over the file"); assert_eq!(dir.read("wide.sv"), WIDE_SPLIT, "line-length is still the file's"); } #[test] fn no_config_ignores_config_files_entirely() { let dir = TempDir::new("noconfig"); // Not even parsed: --no-config reads nothing from disk. dir.write("vfmt.toml", "this file is not valid at all\n"); dir.write("x.sv", UNINDENTED); let out = run(&["--no-config", &dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("x.sv"), INDENT_2, "defaults apply"); } #[test] fn a_broken_config_exits_2_before_writing_anything() { let dir = TempDir::new("configbad"); dir.write("vfmt.toml", "indent = 4\nline_length = 80\n"); dir.write("x.sv", UNINDENTED); let out = run(&[&dir.root()]); assert_eq!(code(&out), 2, "a config error is an error, not a warning"); assert_eq!(dir.read("x.sv"), UNINDENTED, "nothing is written when the config is broken"); let err = stderr(&out); assert!(err.contains("vfmt.toml:2:"), "the error names the file and line: {err}"); assert!(err.contains("unknown key `line_length`"), "{err}"); for (contents, expected) in [ ("indent = 99\n", "between 1 and 8"), ("line-length = wide\n", "expects an integer"), ("[tool.vfmt]\nindent = 2\n", "tables"), ("exclude = [\n \"a\",\n]\n", "multi-line arrays are unsupported"), ] { dir.write("vfmt.toml", contents); let out = run(&[&dir.root()]); assert_eq!(code(&out), 2, "{contents}"); assert!(stderr(&out).contains(expected), "{contents}: {}", stderr(&out)); assert_eq!(dir.read("x.sv"), UNINDENTED); } } #[test] fn config_excludes_are_added_to_cli_excludes() { let dir = TempDir::new("configexclude"); dir.write("vfmt.toml", "exclude = [ \"*_gen.sv\", \"build\" ] # generated\n"); dir.write("keep.sv", UNINDENTED); dir.write("skip_gen.sv", UNINDENTED); dir.write("build/inner.sv", UNINDENTED); dir.write("vendor/v.sv", UNINDENTED); let out = run(&["--exclude", "vendor", &dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("keep.sv"), INDENT_2); assert_eq!(dir.read("skip_gen.sv"), UNINDENTED, "config exclude applies"); assert_eq!(dir.read("build/inner.sv"), UNINDENTED, "config exclude applies to dirs"); assert_eq!(dir.read("vendor/v.sv"), UNINDENTED, "--exclude still applies"); } #[test] fn stdin_discovers_config_from_stdin_filename() { let dir = TempDir::new("configstdin"); dir.write("vfmt.toml", "indent = 4\n"); let buffer = format!("{}/rtl/buffer.sv", dir.root()); let out = run_with_stdin(&["--stdin-filename", &buffer, "-"], UNINDENTED); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(stdout(&out), INDENT_4); assert!(!std::path::Path::new(&buffer).exists(), "--stdin-filename must not touch disk"); // Without the flag the anchor is the cwd, which has no config here. let out = run_with_stdin(&["-"], UNINDENTED); assert_eq!(code(&out), 0); assert_eq!(stdout(&out), INDENT_2); let out = run_with_stdin(&["--no-config", "--stdin-filename", &buffer, "-"], UNINDENTED); assert_eq!(code(&out), 0); assert_eq!(stdout(&out), INDENT_2, "--no-config applies to stdin too"); // A broken config is an error in stdin mode too, and nothing is echoed. dir.write("vfmt.toml", "indent = 4\nbogus = 1\n"); let out = run_with_stdin(&["--stdin-filename", &buffer, "-"], UNINDENTED); assert_eq!(code(&out), 2); assert_eq!(stdout(&out), "", "no output when the config is broken"); assert!(stderr(&out).contains("unknown key `bogus`"), "{}", stderr(&out)); } #[test] fn the_search_stops_at_a_git_directory_after_checking_it() { let dir = TempDir::new("configgit"); dir.write("vfmt.toml", "indent = 4\n"); std::fs::create_dir_all(dir.path.join("repo/.git")).expect("create .git"); dir.write("repo/rtl/x.sv", UNINDENTED); let out = run(&[&dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("repo/rtl/x.sv"), INDENT_2, "the walk stops at the repo root"); // A config file *in* the repo root is still found: `.git` only stops // the walk after its own directory has been checked. dir.write("repo/rtl/x.sv", UNINDENTED); dir.write("repo/vfmt.toml", "indent = 8\n"); let out = run(&[&dir.root()]); assert_eq!(code(&out), 0, "{}", stderr(&out)); assert_eq!(dir.read("repo/rtl/x.sv"), "module m;\n wire x;\nendmodule\n"); }