Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Injecting static types #232

Open
antimora opened this issue Mar 12, 2024 · 2 comments
Open

Injecting static types #232

antimora opened this issue Mar 12, 2024 · 2 comments

Comments

@antimora
Copy link

I have a burn-tensor crate that defines tensor operations and traits, and I have separate backend crates (burn-ndarray and burn-tch) that implement these traits for specific tensor backends.

How can I use rstest to write tests for the tensor operations in the burn-tensor crate and inject static backend types into the tests?

A couple of constraints that I wish to keep: 1) I do not want to define macro in burn-tensor crate that will be re-imported into the backend crates (this is how it's currently done 2) I do not want burn-tensor to depend on the backend crates.

@la10736
Copy link
Owner

la10736 commented Apr 9, 2024

Sorry, but I'm not sure to have understood your question. Do you want to write some tests and apply them on the 2 backends?

Something like the follow code?

trait MyTrait {
    fn get() -> u32;
}

struct A;
struct B;

impl MyTrait for A {
    fn get() -> u32 {
        42
    }
}

impl MyTrait for B {
    fn get() -> u32 {
        84
    }
}

use rstest::rstest;
use std::marker::PhantomData;

#[rstest]
#[case(PhantomData::<A>)]
#[case(PhantomData::<B>)]
fn test_get<T: MyTrait>(#[case] _a: PhantomData<T>) {
    assert_eq!(T::get() % 2, 0);
}

You can also use rstest_reuse to spread these cases to some tests.

@antimora
Copy link
Author

antimora commented Apr 9, 2024

@a10736, thank you so much for you suggestion and great examples. rstest_reuse is a great pointer. I didn't know about it.

Continuing with your example, let me clarify.

Basically, I need to have MyTrait and the unit tests defined in crate "MyTraitAndTests". And the trait implementations in "ImplA" and "ImplB" crates, which will consume the unit tests defined in "MyTraitAndTests". It would very convenient when I import the unit tests, I can pass type A (that implements MyTrait) to a whole suit without referencing individual methods. It seems rstest_reuse supports such use case, correct?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants