8 releases

0.4.1 Jan 27, 2025
0.4.0 Jan 27, 2025
0.3.0 Feb 27, 2024
0.2.0 Feb 26, 2024
0.1.1 Jan 18, 2021

#1603 in Procedural macros

Download history 27511/week @ 2024-12-16 8716/week @ 2024-12-23 10123/week @ 2024-12-30 26045/week @ 2025-01-06 27773/week @ 2025-01-13 25613/week @ 2025-01-20 28875/week @ 2025-01-27 33193/week @ 2025-02-03 34240/week @ 2025-02-10 27717/week @ 2025-02-17 31358/week @ 2025-02-24 34017/week @ 2025-03-03 39187/week @ 2025-03-10 31874/week @ 2025-03-17 22395/week @ 2025-03-24 23010/week @ 2025-03-31

117,463 downloads per month
Used in 278 crates (via test-context)

MIT license

7KB
135 lines

crates.io Documentation License Github

test-context

A library for providing custom setup/teardown for Rust tests without needing a test harness.

use test_context::{test_context, TestContext};

struct MyContext {
    value: String
}

impl TestContext for MyContext {
    fn setup() -> MyContext {
        MyContext {  value: "Hello, World!".to_string() }
    }

    fn teardown(self) {
        // Perform any teardown you wish.
    }
}

#[test_context(MyContext)]
#[test]
fn test_works(ctx: &mut MyContext) {
    assert_eq!(ctx.value, "Hello, World!");
}

struct MyGenericContext<T> {
    value: T
}

impl TestContext for MyGenericContext<u32> {
    fn setup() -> MyGenericContext<u32> {
        MyGenericContext { value: 1 }
    }
}

#[test_context(MyGenericContext<u32>)]
#[test]
fn test_generic_type(ctx: &mut MyGenericContext<u32>) {
    assert_eq!(ctx.value, 1);
}

Alternatively, you can use async functions in your test context by using the AsyncTestContext.

use test_context::{test_context, AsyncTestContext};

struct MyAsyncContext {
    value: String
}

impl AsyncTestContext for MyAsyncContext {
    async fn setup() -> MyAsyncContext {
        MyAsyncContext { value: "Hello, World!".to_string() }
    }

    async fn teardown(self) {
        // Perform any teardown you wish.
    }
}

#[test_context(MyAsyncContext)]
fn test_works(ctx: &mut MyAsyncContext) {
    assert_eq!(ctx.value, "Hello, World!");
}

The AsyncTestContext works well with async test wrappers like actix_rt::test or tokio::test.

#[test_context(MyAsyncContext)]
#[tokio::test]
async fn test_works(ctx: &mut MyAsyncContext) {
    assert_eq!(ctx.value, "Hello, World!");
}

Skipping the teardown execution

If what you need is to take full ownership of the context and don't care about the teardown execution for a specific test, you can use the skip_teardown keyword on the macro like this:

 use test_context::{test_context, TestContext};

 struct MyContext {}

 impl TestContext for MyContext {
     fn setup() -> MyContext {
         MyContext {}
     }
 }

#[test_context(MyContext, skip_teardown)]
#[test]
fn test_without_teardown(ctx: MyContext) {
  // Perform any operations that require full ownership of your context
}

License: MIT

Dependencies

~205–640KB
~15K SLoC