Crate testdir

source ·
Expand description

Semi-persistent, scoped test directories

This module provides a convenient way to have an empty directory for tests which can be inspected after the test run in a predicatable location. On subsequent test runs the directory trees of previous runs will be cleaned up to keep the total number of directories limited.


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

    fn test_write() {
        let dir: PathBuf = testdir!();
        let path = dir.join("hello.txt");
        std::fs::write(&path, "hi there").ok();

    fn test_nonexisting() {
        let dir: PathBuf = testdir!();
        let path = dir.join("hello.txt");

For each cargo test invocation this will create a directory named testdir-$N in the cargo target directory. The number suffix will increase each time you run the tests and a testdir-current symlink is created to the most recent suffix created. Only the 8 most recent directories are kept so that this does not keep growing forever.

Inside the numbered directory you will find a directory structure resembling your crate’s modules structure. For example if the above tests are in of a crate called mycrate, than on my UNIX system it looks like this:

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