Skip to content

Commit

Permalink
refactor: Support generic types in test_context macro (#45)
Browse files Browse the repository at this point in the history
* refactor: Support generic types in test_context macro
  • Loading branch information
JasterV authored Jan 27, 2025
1 parent a58e13e commit 9bfe21f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@ impl TestContext for MyContext {
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);
}
```

with generic types, you can use same type with different values
Expand Down
42 changes: 42 additions & 0 deletions test-context/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,3 +170,45 @@ async fn test_async_skip_teardown(mut _ctx: TeardownPanicContext) {}
#[test_context(TeardownPanicContext, skip_teardown)]
#[test]
fn test_sync_skip_teardown(mut _ctx: TeardownPanicContext) {}

struct GenericContext<T> {
contents: T,
}

impl TestContext for GenericContext<u32> {
fn setup() -> Self {
Self { contents: 1 }
}
}

impl TestContext for GenericContext<String> {
fn setup() -> Self {
Self {
contents: "hello world".to_string(),
}
}
}

impl AsyncTestContext for GenericContext<u64> {
async fn setup() -> Self {
Self { contents: 1 }
}
}

#[test_context(GenericContext<u32>)]
#[test]
fn test_generic_with_u32(ctx: &mut GenericContext<u32>) {
assert_eq!(ctx.contents, 1);
}

#[test_context(GenericContext<String>)]
#[test]
fn test_generic_with_string(ctx: &mut GenericContext<String>) {
assert_eq!(ctx.contents, "hello world");
}

#[test_context(GenericContext<u64>)]
#[tokio::test]
async fn test_async_generic(ctx: &mut GenericContext<u64>) {
assert_eq!(ctx.contents, 1);
}

0 comments on commit 9bfe21f

Please sign in to comment.