refactor: Support generic types in test_context macro (#45)

* refactor: Support generic types in test_context macro
This commit is contained in:
Víctor Martínez 2025-01-27 12:49:28 +01:00 committed by GitHub
parent a58e13ecf5
commit 9bfe21fa4c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 58 additions and 0 deletions

View file

@ -29,6 +29,22 @@ impl TestContext for MyContext {
fn test_works(ctx: &mut MyContext) { fn test_works(ctx: &mut MyContext) {
assert_eq!(ctx.value, "Hello, World!"); 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 with generic types, you can use same type with different values

View file

@ -170,3 +170,45 @@ async fn test_async_skip_teardown(mut _ctx: TeardownPanicContext) {}
#[test_context(TeardownPanicContext, skip_teardown)] #[test_context(TeardownPanicContext, skip_teardown)]
#[test] #[test]
fn test_sync_skip_teardown(mut _ctx: TeardownPanicContext) {} 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);
}