#test #macro #harness #setup #before

macro test-harness

a little test macro to wrap your tests with an arbitrary setup/teardown function

2 releases

0.1.1 Apr 3, 2023
0.1.0 Mar 31, 2023

#515 in Testing

Download history 49/week @ 2023-06-06 67/week @ 2023-06-13 104/week @ 2023-06-20 75/week @ 2023-06-27 141/week @ 2023-07-04 79/week @ 2023-07-11 89/week @ 2023-07-18 1659/week @ 2023-07-25 3743/week @ 2023-08-01 3023/week @ 2023-08-08 2786/week @ 2023-08-15 2962/week @ 2023-08-22 2309/week @ 2023-08-29 2977/week @ 2023-09-05 3497/week @ 2023-09-12 2703/week @ 2023-09-19

11,961 downloads per month
Used in 3 crates

MIT/Apache

12KB
59 lines

test-harness

this proc macro wraps your tests with any function that accepts a function with your test's signature. Your test function can accept any number of arguments and return anything, as long as you call it with the correct arguments in the harness.

Example

use test_harness::test;

fn my_test_harness<F>(test: F)
where F: FnOnce(String) -> Result<(), &'static str> {
    let string = std::iter::repeat_with(fastrand::alphanumeric).take(10).collect();
    test(string).expect("test success");
}

#[test(harness = my_test_harness)]
fn my_test(random_string: String) -> Result<(), &'static str> {
    assert_eq!(string.len(), 10);
    Ok(())
}

This expands to the following, with no further macro magic

fn my_test_harness<F>(test: F)
where F: FnOnce(String) -> Result<(), &'static str> {
    let string = std::iter::repeat_with(fastrand::alphanumeric).take(10).collect();
    test(string).expect("test success");
}

#[test]
fn my_test() {
    fn my_test(random_string: String) -> Result<(), &'static str> {
        assert_eq!(string.len(), 10);
        Ok(())
    }
    my_test_harness(my_test);
}

Async example

You can use this to set up an async runtime and spawn or block on the test.

use test_harness::test;

mod my_mod {
    pub fn set_up<F, Fut>(test: F)
    where
        F: FnOnce(&'static str) -> Fut,
        Fut: std::future::Future<Output = Result<(), Box<dyn std::error::Error>>> + Send + 'static,
    {
        futures_lite::future::block_on(test("hello")).unwrap()
    }
}

#[test(harness = my_mod::set_up)]
async fn my_test(s: &'static str) -> Result<(), Box<dyn std::error::Error>> {
    assert_eq!(s, "hello");
    Ok(())
}

Drop down to standard #[test]

If this macro is used without any additional arguments, it works identically to the built-in #[test] macro.

use test_harness::test;
#[test]
fn normal_test() {
    assert!(true);
}

Dependencies

~365–790KB
~19K SLoC