libtest_mimic_collect/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use libtest_mimic::{Arguments, Failed, Trial};
4use std::sync::Mutex;
5
6static TESTS: Mutex<Vec<Trial>> = Mutex::new(Vec::new());
7
8/// This macro automatically adds tests marked with #[test] to the test collection.
9/// Tests then can be run with libtest_mimic_collect::TestCollection::run().
10pub use libtest_mimic_collect_macro::test;
11/// This macro is used by #[test] to add tests to the test collection.
12pub use ctor::ctor;
13/// Re-export libtest_mimic to be used in macros.
14pub use libtest_mimic;
15
16/// A global collection of tests.
17/// Tests can be added to the collection from different modules and then run.
18pub struct TestCollection {}
19
20impl TestCollection {
21    /// Adds a test trial to the test collection.
22    pub fn add_test(trial: Trial) {
23        TESTS.lock().unwrap().push(trial);
24    }
25
26    /// Returns the collected tests and clears the storage.
27    pub fn collect_tests() -> Vec<Trial> {
28        std::mem::take(TESTS.lock().unwrap().as_mut())
29    }
30
31    /// Runs all the collected tests.
32    pub fn run() {
33        let args = Arguments::from_args();
34        libtest_mimic::run(&args, TestCollection::collect_tests()).exit();
35    }
36
37    /// Runs all the collected tests with the provided arguments.
38    pub fn run_with_args(args: Arguments) {
39        libtest_mimic::run(&args, TestCollection::collect_tests()).exit();
40    }
41}
42
43/// Converts typical test function results to the Result type used by libtest_mimic.
44pub trait ConvertResult<T> {
45    fn convert_result(result: T) -> Result<(), Failed>;
46}
47
48impl ConvertResult<()> for TestCollection {
49    fn convert_result(_: ()) -> Result<(), Failed> {
50        Ok(())
51    }
52}
53
54impl ConvertResult<Result<(), Failed>> for TestCollection {
55    fn convert_result(result: Result<(), Failed>) -> Result<(), Failed> {
56        result
57    }
58}
59
60impl ConvertResult<Result<(), &str>> for TestCollection {
61    fn convert_result(result: Result<(), &str>) -> Result<(), Failed> {
62        result.map_err(|e| e.into())
63    }
64}
65
66impl ConvertResult<Result<(), String>> for TestCollection {
67    fn convert_result(result: Result<(), String>) -> Result<(), Failed> {
68        result.map_err(|e| e.into())
69    }
70}