18 releases

new 0.9.3 Dec 4, 2024
0.9.1 Dec 14, 2023
0.9.0 Nov 27, 2023
0.8.0 Jun 27, 2023
0.4.0 Dec 29, 2020

#193 in Filesystem

Download history 1829/week @ 2024-08-19 2096/week @ 2024-08-26 1962/week @ 2024-09-02 1574/week @ 2024-09-09 1181/week @ 2024-09-16 1300/week @ 2024-09-23 1822/week @ 2024-09-30 1190/week @ 2024-10-07 1549/week @ 2024-10-14 1684/week @ 2024-10-21 1854/week @ 2024-10-28 1907/week @ 2024-11-04 2118/week @ 2024-11-11 2623/week @ 2024-11-18 2282/week @ 2024-11-25 3116/week @ 2024-12-02

10,216 downloads per month
Used in 23 crates

MIT/Apache

44KB
609 lines

Semi-persistent, scoped test directories

This crate aims to make it easier to use temporary directories in tests, primarily by calling the testdir!() macro somewhere in a test function. The directories are structured per-scope and per-test and will be available for inspection after the test has finished. On subsequent test runs older generations of test directories will be cleaned up.

If you've ever used pytest's tmp_path or tmpdir fixtures this pattern should be similar.

By default test directories are created in cargo's target directory:

target/testdir-$N/module/path/test_name

Here $N is an integer generation number increasing with each cargo test invocation. Generations older than the 8 most recent ones are removed on the next cargo test run.

There is also a symlink pointing to the most recent generation:

target/testdir-current -> testdir-$N`

Note however that on windows sometimes this can not be updated due to permissions, this symlink is a best-effort on windows.

Example

Even when executing this with cargo test --jobs=1 these tests will pass as each gets their own unique directory:

// E.g. in lib.rs

mod tests {
    use std::path::PathBuf;
    use testdir::testdir;

    #[test]
    fn test_write() {
        let dir: PathBuf = testdir!();
        let path = dir.join("hello.txt");
        std::fs::write(&path, "hi there").ok();
        assert!(path.exists());
    }
    
    #[test]
    fn test_read() {
        let dir: PathBuf = testdir!();
        let path = dir.join("hello.txt");
        assert!(!path.exists());
    }
}

Afterwards you can inspect the directories and they should look something like this:

$ tree target/
target/
+- testdir-0
|    +- cratename
|         +- tests
|              +- test_read
|              +- test_write
|                   +- hello.txt
+- testdir-current -> testdir-0

Feedback and contributing

The code lives in a git repository at https://github.com/flub/testdir from which you can create issues, clone the repository and create pull requests.

Dependencies

~4–11MB
~129K SLoC