Skip to content
Myr

mod.rs

This file

Path

tests/testenv/mod.rs

360 lines · 11.6 KiB · Rust

Last changed by

fix: Better sanitizingThayne McCombsbefore adoption24198d9

History of this file

Take it

1use std::env;2use std::fs;3use std::io::{self, Write};4#[cfg(unix)]5use std::os::unix;6#[cfg(windows)]7use std::os::windows;8use std::path::{Path, PathBuf};9use std::process;1011use tempfile::TempDir;1213/// Environment for the integration tests.14pub struct TestEnv {15    /// Temporary working directory.16    temp_dir: TempDir,1718    /// Path to the *fd* executable.19    fd_exe: PathBuf,2021    /// Normalize each line by sorting the whitespace-separated words22    normalize_line: bool,2324    /// Temporary directory for storing test config (global ignore file)25    config_dir: Option<TempDir>,26}2728/// Create the working directory and the test files.29fn create_working_directory(30    directories: &[&'static str],31    files: &[&'static str],32) -> Result<TempDir, io::Error> {33    let temp_dir = tempfile::Builder::new().prefix("fd-tests").tempdir()?;3435    {36        let root = temp_dir.path();3738        // Pretend that this is a Git repository in order for `.gitignore` files to be respected39        fs::create_dir_all(root.join(".git"))?;4041        for directory in directories {42            fs::create_dir_all(root.join(directory))?;43        }4445        for file in files {46            fs::File::create(root.join(file))?;47        }4849        #[cfg(unix)]50        unix::fs::symlink(root.join("one/two"), root.join("symlink"))?;5152        // Note: creating symlinks on Windows requires the `SeCreateSymbolicLinkPrivilege` which53        // is by default only granted for administrators.54        #[cfg(windows)]55        windows::fs::symlink_dir(root.join("one/two"), root.join("symlink"))?;5657        fs::File::create(root.join(".fdignore"))?.write_all(b"fdignored.foo")?;5859        fs::File::create(root.join(".gitignore"))?.write_all(b"gitignored.foo")?;60    }6162    Ok(temp_dir)63}6465fn create_config_directory_with_global_ignore(ignore_file_content: &str) -> io::Result<TempDir> {66    let config_dir = tempfile::Builder::new().prefix("fd-config").tempdir()?;67    let fd_dir = config_dir.path().join("fd");68    fs::create_dir(&fd_dir)?;69    let mut ignore_file = fs::File::create(fd_dir.join("ignore"))?;70    ignore_file.write_all(ignore_file_content.as_bytes())?;7172    Ok(config_dir)73}7475/// Find the *fd* executable.76fn find_fd_exe() -> PathBuf {77    // Read the location of the fd executable from the environment78    PathBuf::from(env::var("CARGO_BIN_EXE_fd").unwrap_or(env!("CARGO_BIN_EXE_fd").to_string()))79}8081/// Format an error message for when *fd* did not exit successfully.82fn format_exit_error(args: &[&str], output: &process::Output) -> String {83    format!(84        "`fd {}` did not exit successfully.\nstdout:\n---\n{}---\nstderr:\n---\n{}---",85        args.join(" "),86        String::from_utf8_lossy(&output.stdout),87        String::from_utf8_lossy(&output.stderr)88    )89}9091/// Format an error message for when the output of *fd* did not match the expected output.92fn format_output_error(args: &[&str], expected: &str, actual: &str) -> String {93    // Generate diff text.94    let diff_text = diff::lines(expected, actual)95        .into_iter()96        .map(|diff| match diff {97            diff::Result::Left(l) => format!("-{l}"),98            diff::Result::Both(l, _) => format!(" {l}"),99            diff::Result::Right(r) => format!("+{r}"),100        })101        .collect::<Vec<_>>()102        .join("\n");103104    format!(105        concat!(106            "`fd {}` did not produce the expected output.\n",107            "Showing diff between expected and actual:\n{}\n"108        ),109        args.join(" "),110        diff_text111    )112}113114/// Normalize the output for comparison.115fn normalize_output(s: &str, trim_start: bool, normalize_line: bool) -> String {116    // Split into lines and normalize separators.117    let mut lines = s118        .replace('\0', "NULL\n")119        .lines()120        .map(|line| {121            let line = if trim_start { line.trim_start() } else { line };122            let line = line.replace('/', std::path::MAIN_SEPARATOR_STR);123            if normalize_line {124                let mut words: Vec<_> = line.split_whitespace().collect();125                words.sort_unstable();126                return words.join(" ");127            }128            line129        })130        .collect::<Vec<_>>();131132    lines.sort();133    lines.join("\n")134}135136/// Trim whitespace from the beginning of each line.137fn trim_lines(s: &str) -> String {138    s.lines()139        .map(|line| line.trim_start())140        .fold(String::new(), |mut str, line| {141            str.push_str(line);142            str.push('\n');143            str144        })145}146147impl TestEnv {148    pub fn new(directories: &[&'static str], files: &[&'static str]) -> TestEnv {149        let temp_dir = create_working_directory(directories, files).expect("working directory");150        let fd_exe = find_fd_exe();151152        TestEnv {153            temp_dir,154            fd_exe,155            normalize_line: false,156            config_dir: None,157        }158    }159160    pub fn normalize_line(self, normalize: bool) -> TestEnv {161        TestEnv {162            temp_dir: self.temp_dir,163            fd_exe: self.fd_exe,164            normalize_line: normalize,165            config_dir: self.config_dir,166        }167    }168169    pub fn global_ignore_file(self, content: &str) -> TestEnv {170        let config_dir =171            create_config_directory_with_global_ignore(content).expect("config directory");172        TestEnv {173            config_dir: Some(config_dir),174            ..self175        }176    }177178    /// Create a broken symlink at the given path in the temp_dir.179    pub fn create_broken_symlink<P: AsRef<Path>>(180        &mut self,181        link_path: P,182    ) -> Result<PathBuf, io::Error> {183        let root = self.test_root();184        let broken_symlink_link = root.join(link_path);185        {186            let temp_target_dir = tempfile::Builder::new()187                .prefix("fd-tests-broken-symlink")188                .tempdir()?;189            let broken_symlink_target = temp_target_dir.path().join("broken_symlink_target");190            fs::File::create(&broken_symlink_target)?;191            #[cfg(unix)]192            unix::fs::symlink(&broken_symlink_target, &broken_symlink_link)?;193            #[cfg(windows)]194            windows::fs::symlink_file(&broken_symlink_target, &broken_symlink_link)?;195        }196        Ok(broken_symlink_link)197    }198199    pub fn create_symlink<P: AsRef<Path>>(200        &mut self,201        target: P,202        link_path: P,203    ) -> io::Result<PathBuf> {204        let root = self.test_root();205        let target_path = root.join(target);206        let link_path = root.join(link_path);207        #[cfg(unix)]208        unix::fs::symlink(&target_path, &link_path)?;209        #[cfg(windows)]210        windows::fs::symlink_file(&target_path, &link_path)?;211212        Ok(link_path)213    }214215    /// Get the root directory for the tests.216    pub fn test_root(&self) -> PathBuf {217        self.temp_dir.path().to_path_buf()218    }219220    /// Get the path of the fd executable.221    #[cfg_attr(windows, allow(unused))]222    pub fn test_exe(&self) -> &PathBuf {223        &self.fd_exe224    }225226    /// Get the root directory of the file system.227    pub fn system_root(&self) -> PathBuf {228        let mut components = self.temp_dir.path().components();229        PathBuf::from(components.next().expect("root directory").as_os_str())230    }231232    /// Assert that calling *fd* in the specified path under the root working directory,233    /// and with the specified arguments produces the expected output.234    pub fn assert_success_and_get_output<P: AsRef<Path>>(235        &self,236        path: P,237        args: &[&str],238    ) -> process::Output {239        // Run *fd*.240        let output = self.run_command(path.as_ref(), args);241242        // Check for exit status.243        if !output.status.success() {244            panic!("{}", format_exit_error(args, &output));245        }246247        output248    }249250    pub fn assert_success_and_get_normalized_output<P: AsRef<Path>>(251        &self,252        path: P,253        args: &[&str],254    ) -> String {255        let output = self.assert_success_and_get_output(path, args);256        normalize_output(257            &String::from_utf8_lossy(&output.stdout),258            false,259            self.normalize_line,260        )261    }262263    /// Assert that calling *fd* with the specified arguments produces the expected output.264    pub fn assert_output(&self, args: &[&str], expected: &str) {265        self.assert_output_subdirectory(".", args, expected)266    }267268    /// Similar to assert_output, but able to handle non-utf8 output269    #[cfg(all(unix, not(target_os = "macos")))]270    pub fn assert_output_raw(&self, args: &[&str], expected: &[u8]) {271        let output = self.assert_success_and_get_output(".", args);272273        assert_eq!(expected, &output.stdout[..]);274    }275276    /// Assert that calling *fd* in the specified path under the root working directory,277    /// and with the specified arguments produces the expected output.278    pub fn assert_output_subdirectory<P: AsRef<Path>>(279        &self,280        path: P,281        args: &[&str],282        expected: &str,283    ) {284        // Normalize both expected and actual output.285        let expected = normalize_output(expected, true, self.normalize_line);286        let actual = self.assert_success_and_get_normalized_output(path, args);287288        // Compare actual output to expected output.289        if expected != actual {290            panic!("{}", format_output_error(args, &expected, &actual));291        }292    }293294    /// Assert that calling *fd* with the specified arguments produces the expected error,295    /// and does not succeed.296    pub fn assert_failure_with_error(&self, args: &[&str], expected: &str) {297        let status = self.assert_error_subdirectory(".", args, Some(expected));298        if status.success() {299            panic!("error '{expected}' did not occur.");300        }301    }302303    /// Assert that calling *fd* with the specified arguments does not succeed.304    pub fn assert_failure(&self, args: &[&str]) {305        let status = self.assert_error_subdirectory(".", args, None);306        if status.success() {307            panic!("Failure did not occur as expected.");308        }309    }310311    /// Assert that calling *fd* with the specified arguments produces the expected error.312    pub fn assert_error(&self, args: &[&str], expected: &str) -> process::ExitStatus {313        self.assert_error_subdirectory(".", args, Some(expected))314    }315316    fn run_command(&self, path: &Path, args: &[&str]) -> process::Output {317        // Setup *fd* command.318        let mut cmd = process::Command::new(&self.fd_exe);319        cmd.current_dir(self.temp_dir.path().join(path));320        if let Some(config_dir) = &self.config_dir {321            cmd.env("XDG_CONFIG_HOME", config_dir.path());322        } else {323            cmd.arg("--no-global-ignore-file");324        }325        // Make sure LS_COLORS is unset to ensure consistent326        // color output327        cmd.env("LS_COLORS", "");328        cmd.args(args);329330        // Run *fd*.331        cmd.output().expect("fd output")332    }333334    /// Assert that calling *fd* in the specified path under the root working directory,335    /// and with the specified arguments produces an error with the expected message.336    fn assert_error_subdirectory<P: AsRef<Path>>(337        &self,338        path: P,339        args: &[&str],340        expected: Option<&str>,341    ) -> process::ExitStatus {342        let output = self.run_command(path.as_ref(), args);343344        if let Some(expected) = expected {345            // Normalize both expected and actual output.346            let expected_error = trim_lines(expected);347            let actual_err = trim_lines(&String::from_utf8_lossy(&output.stderr));348349            // Compare actual output to expected output.350            if !actual_err.trim_start().starts_with(&expected_error) {351                panic!(352                    "{}",353                    format_output_error(args, &expected_error, &actual_err)354                );355            }356        }357358        output.status359    }360}