audunhalland / unimock

A versatile and developer-friendly trait mocking library
MIT License
71 stars 3 forks source link

Support generic input parameters that are not 'static #52

Open audunhalland opened 5 months ago

audunhalland commented 5 months ago

(from https://stackoverflow.com/questions/76818001/use-mockall-crate-for-a-trait-with-trait-bounds)

trait MyTrait {
    fn process<T: Read>(&self, data: T) -> i32;
}

This currently yields a compile error due to missing T: 'static. But it's still possible to mock it, in a more limited sense. If the T is replaced with unimock::Impossible it's doable. What will be missing then is argument matching and access to the parameter in AnswerFn.

Consider using a different Impossible-like variant like MissingStaticBound, to serve as a diagnostic hint.

A problem is that it's impossible to statically detect whether a trait already has an implicit 'static bound. I think a solution to that could be something like:

#[unimock(api=MyTraitMock, skip_generic=Read)]
trait MyTrait {
    fn process<T: Read>(&self, data: T) -> i32;
}

if that's not too big of a hammer. I'd like to avoid sub-attributes for unimock, since those are difficult to combine with cfg_attr.

audunhalland commented 2 months ago

Of course, the macro should just require a syntactic + 'static even if implicit from the trait definition. With a MissingStaticBound error type, it should be clear why that parameter is left out.