Skip to content
Myr

util.rs

This file

Path

tests/util.rs

528 lines · 17.6 KiB · Rust

Last changed by

ci: fix binary discoveryAndrew Gallantbefore adoption7525479

History of this file

Take it

1use std::env;2use std::error;3use std::ffi::OsStr;4use std::fs::{self, File};5use std::io::{self, Write};6use std::path::{Path, PathBuf};7use std::process::{self, Command};8use std::sync::atomic::{AtomicUsize, Ordering};9use std::thread;10use std::time::Duration;1112use bstr::ByteSlice;1314static TEST_DIR: &'static str = "ripgrep-tests";15static NEXT_ID: AtomicUsize = AtomicUsize::new(0);1617/// Setup an empty work directory and return a command pointing to the ripgrep18/// executable whose CWD is set to the work directory.19///20/// The name given will be used to create the directory. Generally, it should21/// correspond to the test name.22pub fn setup(test_name: &str) -> (Dir, TestCommand) {23    let dir = Dir::new(test_name);24    let cmd = dir.command();25    (dir, cmd)26}2728/// Like `setup`, but uses PCRE2 as the underlying regex engine.29pub fn setup_pcre2(test_name: &str) -> (Dir, TestCommand) {30    let mut dir = Dir::new(test_name);31    dir.pcre2(true);32    let cmd = dir.command();33    (dir, cmd)34}3536/// Break the given string into lines, sort them and then join them back37/// together. This is useful for testing output from ripgrep that may not38/// always be in the same order.39pub fn sort_lines(lines: &str) -> String {40    let mut lines: Vec<&str> = lines.trim().lines().collect();41    lines.sort();42    format!("{}\n", lines.join("\n"))43}4445/// Returns true if and only if the given program can be successfully executed46/// with a `--help` flag.47pub fn cmd_exists(program: &str) -> bool {48    match Command::new(program).arg("--help").output() {49        Ok(output) => output.status.success(),50        Err(_) => false,51    }52}5354/// Dir represents a directory in which tests should be run.55///56/// Directories are created from a global atomic counter to avoid duplicates.57#[derive(Clone, Debug)]58pub struct Dir {59    /// The directory in which this test executable is running.60    root: PathBuf,61    /// The directory in which the test should run. If a test needs to create62    /// files, they should go in here. This directory is also used as the CWD63    /// for any processes created by the test.64    dir: PathBuf,65    /// Set to true when the test should use PCRE2 as the regex engine.66    pcre2: bool,67}6869impl Dir {70    /// Create a new test working directory with the given name. The name71    /// does not need to be distinct for each invocation, but should correspond72    /// to a logical grouping of tests.73    pub fn new(name: &str) -> Dir {74        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);75        let root = env::current_exe()76            .unwrap()77            .parent()78            .expect("executable's directory")79            .to_path_buf();80        let dir =81            env::temp_dir().join(TEST_DIR).join(name).join(&format!("{id}"));82        if dir.exists() {83            nice_err(&dir, fs::remove_dir_all(&dir));84        }85        nice_err(&dir, repeat(|| fs::create_dir_all(&dir)));86        Dir { root, dir, pcre2: false }87    }8889    /// Use PCRE2 for this test.90    pub fn pcre2(&mut self, yes: bool) {91        self.pcre2 = yes;92    }9394    /// Returns true if and only if this test is configured to use PCRE2 as95    /// the regex engine.96    pub fn is_pcre2(&self) -> bool {97        self.pcre298    }99100    /// Create a new file with the given name and contents in this directory,101    /// or panic on error.102    pub fn create<P: AsRef<Path>>(&self, name: P, contents: &str) {103        self.create_bytes(name, contents.as_bytes());104    }105106    /// Try to create a new file with the given name and contents in this107    /// directory.108    #[allow(dead_code)] // unused on Windows109    pub fn try_create<P: AsRef<Path>>(110        &self,111        name: P,112        contents: &str,113    ) -> io::Result<()> {114        let path = self.dir.join(name);115        self.try_create_bytes(path, contents.as_bytes())116    }117118    /// Create a new file with the given name and size.119    pub fn create_size<P: AsRef<Path>>(&self, name: P, filesize: u64) {120        let path = self.dir.join(name);121        let file = nice_err(&path, File::create(&path));122        nice_err(&path, file.set_len(filesize));123    }124125    /// Create a new file with the given name and contents in this directory,126    /// or panic on error.127    pub fn create_bytes<P: AsRef<Path>>(&self, name: P, contents: &[u8]) {128        let path = self.dir.join(&name);129        nice_err(&path, self.try_create_bytes(name, contents));130    }131132    /// Try to create a new file with the given name and contents in this133    /// directory.134    pub fn try_create_bytes<P: AsRef<Path>>(135        &self,136        name: P,137        contents: &[u8],138    ) -> io::Result<()> {139        let path = self.dir.join(name);140        let mut file = File::create(path)?;141        file.write_all(contents)?;142        file.flush()143    }144145    /// Remove a file with the given name from this directory.146    pub fn remove<P: AsRef<Path>>(&self, name: P) {147        let path = self.dir.join(name);148        nice_err(&path, fs::remove_file(&path));149    }150151    /// Create a new directory with the given path (and any directories above152    /// it) inside this directory.153    pub fn create_dir<P: AsRef<Path>>(&self, path: P) {154        let path = self.dir.join(path);155        nice_err(&path, repeat(|| fs::create_dir_all(&path)));156    }157158    /// Creates a new command that is set to use the ripgrep executable in159    /// this working directory.160    ///161    /// This also:162    ///163    /// * Unsets the `RIPGREP_CONFIG_PATH` environment variable.164    /// * Sets the `--path-separator` to `/` so that paths have the same output165    ///   on all systems. Tests that need to check `--path-separator` itself166    ///   can simply pass it again to override it.167    pub fn command(&self) -> TestCommand {168        let mut cmd = self.bin();169        cmd.env_remove("RIPGREP_CONFIG_PATH");170        cmd.current_dir(&self.dir);171        cmd.arg("--path-separator").arg("/");172        if self.is_pcre2() {173            cmd.arg("--pcre2");174        }175        TestCommand { dir: self.clone(), cmd }176    }177178    /// Returns the path to the ripgrep executable.179    pub fn bin(&self) -> process::Command {180        let rg = std::env::var_os("CARGO_BIN_EXE_rg")181            .map(PathBuf::from)182            .unwrap_or_else(|| {183                self.root.join(format!("../rg{}", env::consts::EXE_SUFFIX))184            });185        match cross_runner() {186            None => process::Command::new(rg),187            Some(runner) => {188                let mut cmd = process::Command::new(runner);189                cmd.arg(rg);190                cmd191            }192        }193    }194195    /// Returns the path to this directory.196    pub fn path(&self) -> &Path {197        &self.dir198    }199200    /// Creates a directory symlink to the src with the given target name201    /// in this directory.202    #[cfg(not(windows))]203    pub fn link_dir<S: AsRef<Path>, T: AsRef<Path>>(&self, src: S, target: T) {204        use std::os::unix::fs::symlink;205        let src = self.dir.join(src);206        let target = self.dir.join(target);207        let _ = fs::remove_file(&target);208        nice_err(&target, symlink(&src, &target));209    }210211    /// Creates a directory symlink to the src with the given target name212    /// in this directory.213    #[cfg(windows)]214    pub fn link_dir<S: AsRef<Path>, T: AsRef<Path>>(&self, src: S, target: T) {215        use std::os::windows::fs::symlink_dir;216        let src = self.dir.join(src);217        let target = self.dir.join(target);218        let _ = fs::remove_dir(&target);219        nice_err(&target, symlink_dir(&src, &target));220    }221222    /// Creates a file symlink to the src with the given target name223    /// in this directory.224    #[cfg(not(windows))]225    pub fn link_file<S: AsRef<Path>, T: AsRef<Path>>(226        &self,227        src: S,228        target: T,229    ) {230        self.link_dir(src, target);231    }232233    /// Creates a file symlink to the src with the given target name234    /// in this directory.235    #[cfg(windows)]236    #[allow(dead_code)] // unused on Windows237    pub fn link_file<S: AsRef<Path>, T: AsRef<Path>>(238        &self,239        src: S,240        target: T,241    ) {242        use std::os::windows::fs::symlink_file;243        let src = self.dir.join(src);244        let target = self.dir.join(target);245        let _ = fs::remove_file(&target);246        nice_err(&target, symlink_file(&src, &target));247    }248}249250/// A simple wrapper around a process::Command with some conveniences.251#[derive(Debug)]252pub struct TestCommand {253    /// The dir used to launched this command.254    dir: Dir,255    /// The actual command we use to control the process.256    cmd: Command,257}258259impl TestCommand {260    /// Returns a mutable reference to the underlying command.261    pub fn cmd(&mut self) -> &mut Command {262        &mut self.cmd263    }264265    /// Add an argument to pass to the command.266    pub fn arg<A: AsRef<OsStr>>(&mut self, arg: A) -> &mut TestCommand {267        self.cmd.arg(arg);268        self269    }270271    /// Add any number of arguments to the command.272    pub fn args<I, A>(&mut self, args: I) -> &mut TestCommand273    where274        I: IntoIterator<Item = A>,275        A: AsRef<OsStr>,276    {277        self.cmd.args(args);278        self279    }280281    /// Set an environment variable for this command.282    pub fn env(283        &mut self,284        key: impl AsRef<OsStr>,285        val: impl AsRef<OsStr>,286    ) -> &mut TestCommand {287        self.cmd.env(key, val);288        self289    }290291    /// Set the working directory for this command.292    ///293    /// The path given is interpreted relative to the directory that this294    /// command was created for.295    ///296    /// Note that this does not need to be called normally, since the creation297    /// of this TestCommand causes its working directory to be set to the298    /// test's directory automatically.299    pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut TestCommand {300        self.cmd.current_dir(self.dir.path().join(dir));301        self302    }303304    /// Runs and captures the stdout of the given command.305    pub fn stdout(&mut self) -> String {306        let o = self.output();307        String::from_utf8_lossy(&o.stdout).into_owned()308    }309310    /// Pipe `input` to a command, and collect the output.311    pub fn pipe(&mut self, input: &[u8]) -> String {312        self.cmd.stdin(process::Stdio::piped());313        self.cmd.stdout(process::Stdio::piped());314        self.cmd.stderr(process::Stdio::piped());315316        let mut child = self.cmd.spawn().unwrap();317318        // Pipe input to child process using a separate thread to avoid319        // risk of deadlock between parent and child process.320        let mut stdin = child.stdin.take().expect("expected standard input");321        let input = input.to_owned();322        let worker = thread::spawn(move || stdin.write_all(&input));323324        let output = self.expect_success(child.wait_with_output().unwrap());325        worker.join().unwrap().unwrap();326327        String::from_utf8_lossy(&output.stdout).into_owned()328    }329330    /// Gets the output of a command. If the command failed, then this panics.331    pub fn output(&mut self) -> process::Output {332        let output = self.raw_output();333        self.expect_success(output)334    }335336    /// Gets the raw output of a command after filtering nonsense like jemalloc337    /// error messages from stderr.338    pub fn raw_output(&mut self) -> process::Output {339        let mut output = self.cmd.output().unwrap();340        output.stderr = strip_jemalloc_nonsense(&output.stderr);341        output342    }343344    /// Runs the command and asserts that it resulted in an error exit code.345    pub fn assert_err(&mut self) {346        let o = self.raw_output();347        if o.status.success() {348            panic!(349                "\n\n===== {:?} =====\n\350                 command succeeded but expected failure!\351                 \n\ncwd: {}\352                 \n\ndir list: {:?}\353                 \n\nstatus: {}\354                 \n\nstdout: {}\n\nstderr: {}\355                 \n\n=====\n",356                self.cmd,357                self.dir.dir.display(),358                dir_list(&self.dir.dir),359                o.status,360                String::from_utf8_lossy(&o.stdout),361                String::from_utf8_lossy(&o.stderr)362            );363        }364    }365366    /// Runs the command and asserts that its exit code matches expected exit367    /// code.368    pub fn assert_exit_code(&mut self, expected_code: i32) {369        let code = self.cmd.output().unwrap().status.code().unwrap();370        assert_eq!(371            expected_code,372            code,373            "\n\n===== {:?} =====\n\374             expected exit code did not match\375             \n\ncwd: {}\376             \n\ndir list: {:?}\377             \n\nexpected: {}\378             \n\nfound: {}\379             \n\n=====\n",380            self.cmd,381            self.dir.dir.display(),382            dir_list(&self.dir.dir),383            expected_code,384            code385        );386    }387388    /// Runs the command and asserts that something was printed to stderr.389    pub fn assert_non_empty_stderr(&mut self) {390        let o = self.cmd.output().unwrap();391        if o.status.success() || o.stderr.is_empty() {392            panic!(393                "\n\n===== {:?} =====\n\394                 command succeeded but expected failure!\395                 \n\ncwd: {}\396                 \n\ndir list: {:?}\397                 \n\nstatus: {}\398                 \n\nstdout: {}\n\nstderr: {}\399                 \n\n=====\n",400                self.cmd,401                self.dir.dir.display(),402                dir_list(&self.dir.dir),403                o.status,404                String::from_utf8_lossy(&o.stdout),405                String::from_utf8_lossy(&o.stderr)406            );407        }408    }409410    fn expect_success(&self, o: process::Output) -> process::Output {411        if !o.status.success() {412            let suggest = if o.stderr.is_empty() {413                "\n\nDid your search end up with no results?".to_string()414            } else {415                "".to_string()416            };417418            panic!(419                "\n\n==========\n\420                    command failed but expected success!\421                    {}\422                    \n\ncommand: {:?}\423                    \n\ncwd: {}\424                    \n\ndir list: {:?}\425                    \n\nstatus: {}\426                    \n\nstdout: {}\427                    \n\nstderr: {}\428                    \n\n==========\n",429                suggest,430                self.cmd,431                self.dir.dir.display(),432                dir_list(&self.dir.dir),433                o.status,434                String::from_utf8_lossy(&o.stdout),435                String::from_utf8_lossy(&o.stderr)436            );437        }438        o439    }440}441442fn nice_err<T, E: error::Error>(path: &Path, res: Result<T, E>) -> T {443    match res {444        Ok(t) => t,445        Err(err) => panic!("{}: {:?}", path.display(), err),446    }447}448449fn repeat<F: FnMut() -> io::Result<()>>(mut f: F) -> io::Result<()> {450    let mut last_err = None;451    for _ in 0..10 {452        if let Err(err) = f() {453            last_err = Some(err);454            thread::sleep(Duration::from_millis(500));455        } else {456            return Ok(());457        }458    }459    Err(last_err.unwrap())460}461462/// Return a recursive listing of all files and directories in the given463/// directory. This is useful for debugging transient and odd failures in464/// integration tests.465fn dir_list<P: AsRef<Path>>(dir: P) -> Vec<String> {466    walkdir::WalkDir::new(dir)467        .follow_links(true)468        .into_iter()469        .map(|result| result.unwrap().path().to_string_lossy().into_owned())470        .collect()471}472473/// When running tests with cross, we need to be a bit smarter about how we474/// run our `rg` binary. We can't just run it directly since it might be475/// compiled for a totally different target. Instead, it's likely that `cross`476/// will have setup qemu to run it. While this is integrated into the Rust477/// testing by default, we need to handle it ourselves for integration tests.478///479/// Now thankfully, cross sets `CROSS_RUNNER` to point to the right qemu480/// executable. Or so one thinks. But it seems to always be set to `qemu-user`481/// and I cannot find `qemu-user` anywhere in the Docker image. Awesome.482///483/// Thers is `/linux-runner` which seems to work sometimes? But not always.484///485/// Instead, it looks like we have to use `qemu-aarch64` in the `aarch64`486/// case. Perfect, so just get the current target architecture and append it487/// to `qemu-`. Wrong. Cross (or qemu or whoever) uses `qemu-ppc64` for488/// `powerpc64`, so we can't just use the target architecture as Rust knows489/// it verbatim.490///491/// So... we just manually handle these cases. So fucking fun.492fn cross_runner() -> Option<String> {493    let runner = std::env::var("CROSS_RUNNER").ok()?;494    if runner.is_empty() || runner == "empty" {495        return None;496    }497    if cfg!(target_arch = "powerpc64") {498        Some("qemu-ppc64".to_string())499    } else if cfg!(target_arch = "x86") {500        Some("i386".to_string())501    } else {502        // Make a guess... Sigh.503        Some(format!("qemu-{}", std::env::consts::ARCH))504    }505}506507/// Returns true if the test setup believes Cross is running and `qemu` is508/// needed to run ripgrep.509///510/// This is useful because it has been difficult to get some tests to pass511/// under Cross.512pub fn is_cross() -> bool {513    std::env::var("CROSS_RUNNER").ok().map_or(false, |v| !v.is_empty())514}515516/// Strips absolutely fucked `<jemalloc>:` lines from the output.517///518/// In theory this only happens under qemu, which is where our tests run under519/// `cross`. But is messes with our tests, because... they don't expect the520/// allocator to fucking write to stderr. I mean, what the fuck? Who prints a521/// warning message with absolutely no instruction for what to do with it or522/// how to disable it. Absolutely fucking bonkers.523fn strip_jemalloc_nonsense(data: &[u8]) -> Vec<u8> {524    let lines = data525        .lines_with_terminator()526        .filter(|line| !line.starts_with_str("<jemalloc>:"));527    bstr::concat(lines)528}