#test-harness #teardown #async-context #setup #async-test #test

test-context

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

8 releases

0.3.0 Feb 27, 2024
0.2.0 Feb 26, 2024
0.1.6 Feb 26, 2024
0.1.4 Jul 19, 2022
0.1.1 Jan 18, 2021

#37 in Testing

Download history 3543/week @ 2023-12-23 6339/week @ 2023-12-30 10333/week @ 2024-01-06 8743/week @ 2024-01-13 9790/week @ 2024-01-20 11011/week @ 2024-01-27 12355/week @ 2024-02-03 11858/week @ 2024-02-10 7042/week @ 2024-02-17 9313/week @ 2024-02-24 11403/week @ 2024-03-02 13017/week @ 2024-03-09 13375/week @ 2024-03-16 13841/week @ 2024-03-23 14036/week @ 2024-03-30 13064/week @ 2024-04-06

56,295 downloads per month
Used in 268 crates (15 directly)

MIT license

10KB

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!");
}

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

~1–1.6MB
~33K SLoC