mod.rs
This file
Path
tests/testenv/mod.rs
270 lines · 8.6 KiB · Rust
Last changed by
Remove code duplication, add feature gatesharkdpbefore adoptioned024ce
History of this fileTake it
The walk stopped after 200 commits: lines older than 047f1be point at it.
Update dependenciessharkdpbefore adoption047f1be
lines 1–2why, one step back1use std::env;2use std::fs;Clean up include ordersharkdpbefore adoption53557ef
line 3why, one step back3use std::io::{self, Write};Update dependenciessharkdpbefore adoption047f1be
lines 4–7why, one step back4#[cfg(unix)]5use std::os::unix;6#[cfg(windows)]7use std::os::windows;Clean up include ordersharkdpbefore adoption53557ef
lines 8–9why, one step back8use std::path::{Path, PathBuf};9use std::process;Update dependenciessharkdpbefore adoption047f1be
line 10why, one step back10[2018 edition] remove all extern crate lines from sourcesAlexandru Macoveibefore adoption051ff59
line 11why, one step back11use tempdir::TempDir;Update dependenciessharkdpbefore adoption047f1be
lines 12–111why, one step back1213/// 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,23}2425/// Create the working directory and the test files.26fn create_working_directory(27 directories: &[&'static str],28 files: &[&'static str],29) -> Result<TempDir, io::Error> {30 let temp_dir = TempDir::new("fd-tests")?;3132 {33 let root = temp_dir.path();3435 // Pretend that this is a Git repository in order for `.gitignore` files to be respected36 fs::create_dir_all(root.join(".git"))?;3738 for directory in directories {39 fs::create_dir_all(root.join(directory))?;40 }4142 for file in files {43 fs::File::create(root.join(file))?;44 }4546 #[cfg(unix)]47 unix::fs::symlink(root.join("one/two"), root.join("symlink"))?;4849 // Note: creating symlinks on Windows requires the `SeCreateSymbolicLinkPrivilege` which50 // is by default only granted for administrators.51 #[cfg(windows)]52 windows::fs::symlink_dir(root.join("one/two"), root.join("symlink"))?;5354 fs::File::create(root.join(".fdignore"))?.write_all(b"fdignored.foo")?;5556 fs::File::create(root.join(".gitignore"))?.write_all(b"gitignored.foo")?;57 }5859 Ok(temp_dir)60}6162/// Find the *fd* executable.63fn find_fd_exe() -> PathBuf {64 // Tests exe is in target/debug/deps, the *fd* exe is in target/debug65 let root = env::current_exe()66 .expect("tests executable")67 .parent()68 .expect("tests executable directory")69 .parent()70 .expect("fd executable directory")71 .to_path_buf();7273 let exe_name = if cfg!(windows) { "fd.exe" } else { "fd" };7475 root.join(exe_name)76}7778/// Format an error message for when *fd* did not exit successfully.79fn format_exit_error(args: &[&str], output: &process::Output) -> String {80 format!(81 "`fd {}` did not exit successfully.\nstdout:\n---\n{}---\nstderr:\n---\n{}---",82 args.join(" "),83 String::from_utf8_lossy(&output.stdout),84 String::from_utf8_lossy(&output.stderr)85 )86}8788/// Format an error message for when the output of *fd* did not match the expected output.89fn format_output_error(args: &[&str], expected: &str, actual: &str) -> String {90 // Generate diff text.91 let diff_text = diff::lines(expected, actual)92 .into_iter()93 .map(|diff| match diff {94 diff::Result::Left(l) => format!("-{}", l),95 diff::Result::Both(l, _) => format!(" {}", l),96 diff::Result::Right(r) => format!("+{}", r),97 })98 .collect::<Vec<_>>()99 .join("\n");100101 format!(102 concat!(103 "`fd {}` did not produce the expected output.\n",104 "Showing diff between expected and actual:\n{}\n"105 ),106 args.join(" "),107 diff_text108 )109}110111/// Normalize the output for comparison.Remove deprecated trim_left(_matches)?Tim Hollandbefore adoption074cfad
line 112why, one step back112fn normalize_output(s: &str, trim_start: bool, normalize_line: bool) -> String {Update dependenciessharkdpbefore adoption047f1be
lines 113–117why, one step back113 // Split into lines and normalize separators.114 let mut lines = s115 .replace('\0', "NULL\n")116 .lines()117 .map(|line| {Remove deprecated trim_left(_matches)?Tim Hollandbefore adoption074cfad
line 118why, one step back118 let line = if trim_start { line.trim_start() } else { line };Update dependenciessharkdpbefore adoption047f1be
lines 119–152why, one step back119 let line = line.replace('/', &std::path::MAIN_SEPARATOR.to_string());120 if normalize_line {121 let mut words: Vec<_> = line.split_whitespace().collect();122 words.sort();123 return words.join(" ");124 }125 line126 })127 .collect::<Vec<_>>();128129 lines.sort();130 lines.join("\n")131}132133impl TestEnv {134 pub fn new(directories: &[&'static str], files: &[&'static str]) -> TestEnv {135 let temp_dir = create_working_directory(directories, files).expect("working directory");136 let fd_exe = find_fd_exe();137138 TestEnv {139 temp_dir,140 fd_exe,141 normalize_line: false,142 }143 }144145 pub fn normalize_line(self, normalize: bool) -> TestEnv {146 TestEnv {147 temp_dir: self.temp_dir,148 fd_exe: self.fd_exe,149 normalize_line: normalize,150 }151 }152test: we should find broken symlink with and without --followTom Milliganbefore adoption06434f2
lines 153–171why, one step back153 /// Create a broken symlink at the given path in the temp_dir.154 pub fn create_broken_symlink<P: AsRef<Path>>(155 &mut self,156 link_path: P,157 ) -> Result<PathBuf, io::Error> {158 let root = self.test_root();159 let broken_symlink_link = root.join(link_path);160 {161 let temp_target_dir = TempDir::new("fd-tests-broken-symlink")?;162 let broken_symlink_target = temp_target_dir.path().join("broken_symlink_target");163 fs::File::create(&broken_symlink_target)?;164 #[cfg(unix)]165 unix::fs::symlink(&broken_symlink_target, &broken_symlink_link)?;166 #[cfg(windows)]167 windows::fs::symlink_file(&broken_symlink_target, &broken_symlink_link)?;168 }169 Ok(broken_symlink_link)170 }171Update dependenciessharkdpbefore adoption047f1be
lines 172–184why, one step back172 /// Get the root directory for the tests.173 pub fn test_root(&self) -> PathBuf {174 self.temp_dir.path().to_path_buf()175 }176177 /// Get the root directory of the file system.178 pub fn system_root(&self) -> PathBuf {179 let mut components = self.temp_dir.path().components();180 PathBuf::from(components.next().expect("root directory").as_os_str())181 }182183 /// Assert that calling *fd* in the specified path under the root working directory,184 /// and with the specified arguments produces the expected output.Add --max-results=<count> optionsharkdpbefore adoptiond43827f
line 185why, one step back185 pub fn assert_success_and_get_output<P: AsRef<Path>>(Update dependenciessharkdpbefore adoption047f1be
lines 186–188why, one step back186 &self,187 path: P,188 args: &[&str],Add --max-results=<count> optionsharkdpbefore adoptiond43827f
line 189why, one step back189 ) -> process::Output {Update dependenciessharkdpbefore adoption047f1be
lines 190–201why, one step back190 // Setup *fd* command.191 let mut cmd = process::Command::new(&self.fd_exe);192 cmd.current_dir(self.temp_dir.path().join(path));193 cmd.args(args);194195 // Run *fd*.196 let output = cmd.output().expect("fd output");197198 // Check for exit status.199 if !output.status.success() {200 panic!(format_exit_error(args, &output));201 }Add --max-results=<count> optionsharkdpbefore adoptiond43827f
lines 202–210why, one step back202203 output204 }205206 /// Assert that calling *fd* with the specified arguments produces the expected output.207 pub fn assert_output(&self, args: &[&str], expected: &str) {208 self.assert_output_subdirectory(".", args, expected)209 }210Add tests originally written by @alexmaco in #309sharkdpbefore adoptionea21df3
line 211why, one step back211 /// Similar to assert_output, but able to handle non-utf8 outputRemove code duplication, add feature gatesharkdpbefore adoptioned024ce
line 212why, one step back212 #[cfg(all(unix, not(target_os = "macos")))]Add tests originally written by @alexmaco in #309sharkdpbefore adoptionea21df3
line 213why, one step back213 pub fn assert_output_raw(&self, args: &[&str], expected: &[u8]) {Remove code duplication, add feature gatesharkdpbefore adoptioned024ce
lines 214–216why, one step back214 let output = self.assert_success_and_get_output(".", args);215216 assert_eq!(expected, &output.stdout[..]);Add tests originally written by @alexmaco in #309sharkdpbefore adoptionea21df3
lines 217–218why, one step back217 }218Add --max-results=<count> optionsharkdpbefore adoptiond43827f
lines 219–227why, one step back219 /// Assert that calling *fd* in the specified path under the root working directory,220 /// and with the specified arguments produces the expected output.221 pub fn assert_output_subdirectory<P: AsRef<Path>>(222 &self,223 path: P,224 args: &[&str],225 expected: &str,226 ) {227 let output = self.assert_success_and_get_output(path, args);Update dependenciessharkdpbefore adoption047f1be
lines 228–270why, one step back228229 // Normalize both expected and actual output.230 let expected = normalize_output(expected, true, self.normalize_line);231 let actual = normalize_output(232 &String::from_utf8_lossy(&output.stdout),233 false,234 self.normalize_line,235 );236237 // Compare actual output to expected output.238 if expected != actual {239 panic!(format_output_error(args, &expected, &actual));240 }241 }242243 /// Assert that calling *fd* with the specified arguments produces the expected error.244 pub fn assert_error(&self, args: &[&str], expected: &str) {245 self.assert_error_subdirectory(".", args, expected)246 }247248 /// Assert that calling *fd* in the specified path under the root working directory,249 /// and with the specified arguments produces an error with the expected message.250 fn assert_error_subdirectory<P: AsRef<Path>>(&self, path: P, args: &[&str], expected: &str) {251 // Setup *fd* command.252 let mut cmd = process::Command::new(&self.fd_exe);253 cmd.current_dir(self.temp_dir.path().join(path));254 cmd.args(args);255256 // Run *fd*.257 let output = cmd.output().expect("fd output");258259 // Check for exit status.260 if output.status.success() {261 panic!("error '{}' did not occur.", expected);262 }263264 // Compare actual output to expected output.265 let actual = String::from_utf8_lossy(&output.stderr);266 if !actual.starts_with(expected) {267 panic!(format_output_error(args, &expected, &actual));268 }269 }270}