Cleanup rustfix parse_and_replace test.

This is just some minor code cleanup for the parse_and_replace test,
there should not be any functional differences.
This commit is contained in:
Eric Huss 2023-12-31 09:56:20 -08:00
parent ef94adb927
commit c54fa88ea4

View file

@ -1,3 +1,22 @@
//! Tests that verify rustfix applies the appropriate changes to a file.
//!
//! This test works by reading a series of `*.rs` files in the
//! `tests/everything` directory. For each `.rs` file, it runs `rustc` to
//! collect JSON diagnostics from the file. It feeds that JSON data into
//! rustfix and applies the recommended suggestions to the `.rs` file. It then
//! compares the result with the corresponding `.fixed.rs` file. If they don't
//! match, then the test fails.
//!
//! There are several debugging environment variables for this test that you can set:
//!
//! - `RUST_LOG=parse_and_replace=debug`: Print debug information.
//! - `RUSTFIX_TEST_RECORD_JSON=1`: Records the JSON output to
//! `*.recorded.json` files. You can then move that to `.json` or whatever
//! you need.
//! - `RUSTFIX_TEST_RECORD_FIXED_RUST=1`: Records the fixed result to
//! `*.recorded.rs` files. You can then move that to `.rs` or whatever you
//! need.
#![allow(clippy::disallowed_methods, clippy::print_stdout, clippy::print_stderr)] #![allow(clippy::disallowed_methods, clippy::print_stdout, clippy::print_stderr)]
use anyhow::{anyhow, ensure, Context, Error}; use anyhow::{anyhow, ensure, Context, Error};
@ -79,15 +98,6 @@ fn compiles_without_errors(file: &Path) -> Result<(), Error> {
} }
} }
fn read_file(path: &Path) -> Result<String, Error> {
use std::io::Read;
let mut buffer = String::new();
let mut file = fs::File::open(path)?;
file.read_to_string(&mut buffer)?;
Ok(buffer)
}
fn diff(expected: &str, actual: &str) -> String { fn diff(expected: &str, actual: &str) -> String {
use similar::{ChangeTag, TextDiff}; use similar::{ChangeTag, TextDiff};
use std::fmt::Write; use std::fmt::Write;
@ -104,11 +114,7 @@ fn diff(expected: &str, actual: &str) -> String {
ChangeTag::Delete => "-", ChangeTag::Delete => "-",
}; };
if !different { if !different {
write!( writeln!(&mut res, "differences found (+ == actual, - == expected):").unwrap();
&mut res,
"differences found (+ == actual, - == expected):\n"
)
.unwrap();
different = true; different = true;
} }
write!(&mut res, "{} {}", prefix, change.value()).unwrap(); write!(&mut res, "{} {}", prefix, change.value()).unwrap();
@ -133,7 +139,7 @@ fn test_rustfix_with_file<P: AsRef<Path>>(file: P, mode: &str) -> Result<(), Err
}; };
debug!("next up: {:?}", file); debug!("next up: {:?}", file);
let code = read_file(file).context(format!("could not read {}", file.display()))?; let code = fs::read_to_string(file)?;
let errors = let errors =
compile_and_get_json_errors(file).context(format!("could compile {}", file.display()))?; compile_and_get_json_errors(file).context(format!("could compile {}", file.display()))?;
let suggestions = let suggestions =
@ -141,15 +147,11 @@ fn test_rustfix_with_file<P: AsRef<Path>>(file: P, mode: &str) -> Result<(), Err
.context("could not load suggestions")?; .context("could not load suggestions")?;
if std::env::var(settings::RECORD_JSON).is_ok() { if std::env::var(settings::RECORD_JSON).is_ok() {
use std::io::Write; fs::write(file.with_extension("recorded.json"), &errors)?;
let mut recorded_json = fs::File::create(&file.with_extension("recorded.json")).context(
format!("could not create recorded.json for {}", file.display()),
)?;
recorded_json.write_all(errors.as_bytes())?;
} }
if std::env::var(settings::CHECK_JSON).is_ok() { if std::env::var(settings::CHECK_JSON).is_ok() {
let expected_json = read_file(&json_file).context(format!( let expected_json = fs::read_to_string(&json_file).context(format!(
"could not load json fixtures for {}", "could not load json fixtures for {}",
file.display() file.display()
))?; ))?;
@ -171,13 +173,11 @@ fn test_rustfix_with_file<P: AsRef<Path>>(file: P, mode: &str) -> Result<(), Err
.context(format!("could not apply suggestions to {}", file.display()))?; .context(format!("could not apply suggestions to {}", file.display()))?;
if std::env::var(settings::RECORD_FIXED_RUST).is_ok() { if std::env::var(settings::RECORD_FIXED_RUST).is_ok() {
use std::io::Write; fs::write(file.with_extension("recorded.rs"), &fixed)?;
let mut recorded_rust = fs::File::create(&file.with_extension("recorded.rs"))?;
recorded_rust.write_all(fixed.as_bytes())?;
} }
let expected_fixed = let expected_fixed = fs::read_to_string(&fixed_file)
read_file(&fixed_file).context(format!("could read fixed file for {}", file.display()))?; .context(format!("could read fixed file for {}", file.display()))?;
ensure!( ensure!(
fixed.trim() == expected_fixed.trim(), fixed.trim() == expected_fixed.trim(),
"file {} doesn't look fixed:\n{}", "file {} doesn't look fixed:\n{}",
@ -191,8 +191,7 @@ fn test_rustfix_with_file<P: AsRef<Path>>(file: P, mode: &str) -> Result<(), Err
} }
fn get_fixture_files(p: &str) -> Result<Vec<PathBuf>, Error> { fn get_fixture_files(p: &str) -> Result<Vec<PathBuf>, Error> {
Ok(fs::read_dir(&p)? Ok(fs::read_dir(p)?
.into_iter()
.map(|e| e.unwrap().path()) .map(|e| e.unwrap().path())
.filter(|p| p.is_file()) .filter(|p| p.is_file())
.filter(|p| { .filter(|p| {
@ -203,7 +202,7 @@ fn get_fixture_files(p: &str) -> Result<Vec<PathBuf>, Error> {
} }
fn assert_fixtures(dir: &str, mode: &str) { fn assert_fixtures(dir: &str, mode: &str) {
let files = get_fixture_files(&dir) let files = get_fixture_files(dir)
.context(format!("couldn't load dir `{}`", dir)) .context(format!("couldn't load dir `{}`", dir))
.unwrap(); .unwrap();
let mut failures = 0; let mut failures = 0;