Skip to main content

Module resource

Module resource 

Source
Expand description

Test resource lifecycle management (setup/teardown). Test resource management with automatic setup and teardown

This module provides traits and helpers for managing test resources with automatic cleanup, similar to pytest fixtures or JUnit’s BeforeEach/AfterEach.

§Overview

  • TestResource: Per-test setup/teardown (BeforeEach/AfterEach pattern)
  • TeardownGuard: RAII guard for automatic resource cleanup
  • SuiteResource: Suite-wide shared resources (BeforeAll/AfterAll pattern)
  • SuiteGuard: Reference-counted guard with automatic cleanup when last user drops

§Examples

§Per-test resource (BeforeEach/AfterEach)

use reinhardt_testkit::resource::{TestResource, TeardownGuard};
use rstest::*;

struct TestEnv {
    temp_dir: std::path::PathBuf,
}

impl TestResource for TestEnv {
    fn setup() -> Self {
        let temp = tempfile::tempdir().unwrap();
        Self { temp_dir: temp.path().to_path_buf() }
    }

    fn teardown(&mut self) {
        // Cleanup code here
        let _ = std::fs::remove_dir_all(&self.temp_dir);
    }
}

#[fixture]
fn ctx() -> TeardownGuard<TestEnv> {
    TeardownGuard::new()
}

#[rstest]
fn test_something(ctx: TeardownGuard<TestEnv>) {
    // ctx.temp_dir is available
    // teardown() is automatically called when ctx goes out of scope
}

§Suite-wide resource (BeforeAll/AfterAll)

use reinhardt_testkit::resource::{SuiteResource, SuiteGuard, acquire_suite};
use rstest::*;
use std::sync::{OnceLock, Mutex, Weak};

struct DatabaseSuite {
    connection_string: String,
}

impl SuiteResource for DatabaseSuite {
    fn init() -> Self {
        // Expensive setup (e.g., start test database)
        Self { connection_string: "test_db".to_string() }
    }
}

impl Drop for DatabaseSuite {
    fn drop(&mut self) {
        // Cleanup when last test completes
        println!("Dropping suite resource");
    }
}

static SUITE: OnceLock<Mutex<Weak<DatabaseSuite>>> = OnceLock::new();

#[fixture]
fn suite() -> SuiteGuard<DatabaseSuite> {
    acquire_suite(&SUITE)
}

#[rstest]
fn test_with_database(suite: SuiteGuard<DatabaseSuite>) {
    // suite.connection_string is available
    // Drop is called automatically when last test finishes
}

Structs§

AsyncTeardownGuard
RAII guard for async test resource cleanup using async-dropper
SuiteGuard
Guard for suite-wide shared resource
TeardownGuard
RAII guard for automatic test resource cleanup

Traits§

AsyncTestResource
Async version of TestResource for async setup/teardown
SuiteResource
Suite-wide shared resource (BeforeAll/AfterAll pattern)
TestResource
Per-test resource with setup and teardown hooks

Functions§

acquire_suite
Acquire suite-wide shared resource