Crate jrest_hooks

source ·
Expand description

This code is currently an (almost) exact copy of https://github.com/TomPridham/test-env-helpers source code.

Getting Started

Using these macros is fairly simple. The four after/before functions all require a function with the same name as the attribute and are only valid when applied to a mod. They are all used like in the below example. Replace before_each with whichever method you want to use. The code in the matching function will be inserted into every fn in the containing mod that has an attribute with the word “test” in it. This is to allow for use with not just normal #[test] attributes, but also other flavors like #[tokio::test] and #[test_case(0)].

#[cfg(test)]
use test_env_helpers::*;

#[before_each]
#[cfg(test)]
mod my_tests{
    fn before_each(){println!("I'm in every test!")}
    #[test]
    fn test_1(){}
    #[test]
    fn test_2(){}
    #[test]
    fn test_3(){}
}

The skip macro is valid on either a mod or an individual test and will remove the mod or test it is applied to. You can use it to skip tests that aren’t working correctly or that you don’t want to run for some reason.

#[cfg(test)]
use test_env_helpers::*;

#[cfg(test)]
mod my_tests{
    #[skip]
    #[test]
    fn broken_test(){panic!("I'm hella broke")}
    #[skip]
    mod broken_mod{
        #[test]
        fn i_will_not_be_run(){panic!("I get skipped too")}
    }
    #[test]
    fn test_2(){}
    #[test]
    fn test_3(){}
}

Attribute Macros

  • Will run the code in the matching after_all function exactly once when all of the tests have run. This works by counting the number of #[test] attributes and decrementing a counter at the beginning of every test. Once the counter reaches 0, it will run the code in after_all. It uses std::sync::Once internally to ensure that the code is run at maximum one time.
  • Will run the code in the matching after_each function at the end of every #[test] function. Useful if you want to cleanup after a test or reset some external state. If the test panics, this code will not be run. If you need something that is infallible, you should use before_each instead.
  • Will run the code in the matching before_all function exactly once at the very beginning of a test run. It uses std::sync::Once internally to ensure that the code is run at maximum one time. Useful for setting up some external state that will be reused in multiple tests.
  • Will run the code in the matching before_each function at the beginning of every test. Useful to reset state to ensure that a test has a clean slate.
  • Will skip running the code it is applied on. You can use it to skip tests that aren’t working correctly or that you don’t want to run for some reason. There are no checks to make sure it’s applied to a #[test] or mod. It will remove whatever it is applied to from the final AST.