From 9bfe21fa4c98ad38f3fbc8110d7206353b956370 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Mart=C3=ADnez?= <49537445+JasterV@users.noreply.github.com> Date: Mon, 27 Jan 2025 12:49:28 +0100 Subject: [PATCH] refactor: Support generic types in test_context macro (#45) * refactor: Support generic types in test_context macro --- README.md | 16 +++++++++++++++ test-context/tests/test.rs | 42 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/README.md b/README.md index e8bf947..f65ca15 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,22 @@ impl TestContext for MyContext { fn test_works(ctx: &mut MyContext) { assert_eq!(ctx.value, "Hello, World!"); } + +struct MyGenericContext { + value: T +} + +impl TestContext for MyGenericContext { + fn setup() -> MyGenericContext { + MyGenericContext { value: 1 } + } +} + +#[test_context(MyGenericContext)] +#[test] +fn test_generic_type(ctx: &mut MyGenericContext) { + assert_eq!(ctx.value, 1); +} ``` with generic types, you can use same type with different values diff --git a/test-context/tests/test.rs b/test-context/tests/test.rs index 4cdcd88..1055077 100644 --- a/test-context/tests/test.rs +++ b/test-context/tests/test.rs @@ -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 { + contents: T, +} + +impl TestContext for GenericContext { + fn setup() -> Self { + Self { contents: 1 } + } +} + +impl TestContext for GenericContext { + fn setup() -> Self { + Self { + contents: "hello world".to_string(), + } + } +} + +impl AsyncTestContext for GenericContext { + async fn setup() -> Self { + Self { contents: 1 } + } +} + +#[test_context(GenericContext)] +#[test] +fn test_generic_with_u32(ctx: &mut GenericContext) { + assert_eq!(ctx.contents, 1); +} + +#[test_context(GenericContext)] +#[test] +fn test_generic_with_string(ctx: &mut GenericContext) { + assert_eq!(ctx.contents, "hello world"); +} + +#[test_context(GenericContext)] +#[tokio::test] +async fn test_async_generic(ctx: &mut GenericContext) { + assert_eq!(ctx.contents, 1); +}