fixtures_example/
fixtures_example.rs

1use rest::prelude::*;
2use std::cell::RefCell;
3
4// A shared counter for demonstration
5thread_local! {
6    static TEST_COUNTER: RefCell<u32> = RefCell::new(0);
7}
8
9// Define a module for the first test example with the run_test method
10mod test1 {
11    use super::*;
12
13    // Setup function with attribute style
14    #[setup]
15    fn setup() {
16        println!("Setting up test environment for test1...");
17        TEST_COUNTER.with(|counter| {
18            *counter.borrow_mut() = 0;
19        });
20    }
21
22    // Teardown function with attribute style
23    #[tear_down]
24    fn tear_down() {
25        println!("Cleaning up test environment for test1...");
26        TEST_COUNTER.with(|counter| {
27            println!("Final counter value: {}", *counter.borrow());
28        });
29    }
30
31    // Add the run_test function to the test1 module with attribute style
32    #[with_fixtures]
33    pub fn run_test() {
34        // Initial value should be 0
35        expect!(get_counter()).to_equal(0);
36
37        // Increment and check
38        increment_counter();
39        expect!(get_counter()).to_equal(1);
40
41        // Increment again and check
42        increment_counter();
43        expect!(get_counter()).to_equal(2);
44    }
45}
46
47// Define a module for the second test example with the run_test method
48mod test2 {
49    use super::*;
50
51    // Setup function with attribute style
52    #[setup]
53    fn setup() {
54        println!("Setting up test environment for test2...");
55        TEST_COUNTER.with(|counter| {
56            *counter.borrow_mut() = 0;
57        });
58    }
59
60    // Teardown function with attribute style
61    #[tear_down]
62    fn tear_down() {
63        println!("Cleaning up test environment for test2...");
64        TEST_COUNTER.with(|counter| {
65            println!("Final counter value: {}", *counter.borrow());
66        });
67    }
68
69    // Add the run_test function to the test2 module with attribute style
70    #[with_fixtures]
71    pub fn run_test() {
72        // Each test gets a fresh environment
73        expect!(get_counter()).to_equal(0);
74    }
75}
76
77// Helper to increment the counter - used by both modules
78fn increment_counter() {
79    TEST_COUNTER.with(|counter| {
80        *counter.borrow_mut() += 1;
81    });
82}
83
84// Helper to get the counter value - used by both modules
85fn get_counter() -> u32 {
86    // Reset counter after getting the value outside of test scope
87    let value = TEST_COUNTER.with(|counter| *counter.borrow());
88    return value;
89}
90
91fn main() {
92    // Enable enhanced output for better test reporting
93    config().enhanced_output(true).apply();
94
95    println!("Running first test with fixtures:");
96    test1::run_test();
97
98    println!("\nRunning second test with fixtures:");
99    test2::run_test();
100
101    println!("\nBoth tests passed!");
102}