glob_test 0.2.0

Generate tests from a glob pattern
Documentation

Read files based on a glob pattern, and generate a separate test for each matching file:

#[glob_test::glob("./usage/inputs/**/*.txt")]
fn test(path: &std::path::Path) {
    std::fs::read_to_string(path).unwrap();
}
mod usage {
    use super::*;
    mod inputs {
        use super::*;

        #[test]
        fn a() {
            (|path: &std::path::Path| {
                std::fs::read_to_string(path).unwrap();
            })(
                ::std::path::Path::new(
                    "CARGO_MANIFEST_DIR/tests/usage/inputs/a.txt"
                )
            )
        }

        #[test]
        fn b() {
            (|path: &std::path::Path| {
                std::fs::read_to_string(path).unwrap();
            })(
                ::std::path::Path::new(
                    "CARGO_MANIFEST_DIR/tests/usage/inputs/b.txt"
                )
            )
        }
    }
}

Details

  • One module is emitted for each nested directory, and each file in that directory becomes a test function:
    • inputs/a.txt -> mod inputs { #[test] fn a() {} }
    • inputs/nested/a.txt -> mod inputs { mod nested { #[test] fn a() {} } }
  • The proc macro doesn't use syn or quote, instead parsing from proc_macro2 tokens.
  • Globbing is powered by glob.

This library was specifically developed with insta in mind:

#[glob_test::glob("./**/*.txt")]
fn snapshots(path: &Path) {
    insta::assert_snapshot!(std::fs::read_to_string(path).unwrap());
}

Each file will produce one snapshot, just like insta::glob!. The primary difference is that now each snapshot also gets its own unique test function, which means:

  • All snapshot tests can run in parallel.
  • Tests continue on error: A panic in one snapshot test doesn't cause all other tests in the same glob! to stop.

It is recommended that you put a build.rs file in any crate which uses this library:

// build.rs
fn main() {
    println!("cargo:rerun-if-changed=tests/usage/inputs")
}

That ensures changes to test files are always reflected in the test binary.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.