Skip to content

Commit

Permalink
Fix deselfify for trait objects with associated types
Browse files Browse the repository at this point in the history
This is especially important for constructors that return impl
Future<Type=Self,...>
  • Loading branch information
asomers committed Aug 10, 2019
1 parent 8804975 commit a68d724
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ This project adheres to [Semantic Versioning](http://semver.org/).

### Fixed

- Fixed mocking methods with arguments or return values that use `Self` as an
associated type of some other trait.
([#28](https://github.com/asomers/mockall/pull/28))

- Fixed mocking structs and traits with more than one static method.
([#22](https://github.com/asomers/mockall/pull/22))

Expand Down
38 changes: 38 additions & 0 deletions mockall/tests/automock_associated_type_constructor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// vim: tw=80
/// A constructor that returns Self as an associated type of some other trait.
/// This is very useful when working with Futures.
use mockall::*;

pub trait Future {
type Item;
type Error;
}

#[allow(unused)]
pub struct Foo{}

#[automock]
impl Foo {
pub fn open() -> impl Future<Item=Self, Error=i32> {
struct Bar {}
impl Future for Bar {
type Item=Foo;
type Error=i32;
}
Bar{}
}
}

#[test]
fn returning() {
MockFoo::expect_open().returning(|| {
struct Baz {}
impl Future for Baz {
type Item=MockFoo;
type Error=i32;
}
Box::new(Baz{})
});
let _a = MockFoo::open();
}
10 changes: 9 additions & 1 deletion mockall_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,14 +303,22 @@ fn deselfify(literal_type: &mut Type, actual: &Ident, generics: &Generics) {
panic!("deimplify should've already been run on this output type");
},
Type::TraitObject(tto) => {
//dbg!(&tto);
// Change types like `dyn Self` into `MockXXX`. For now,
// don't worry about multiple trait bounds, because they aren't very
// useful in combination with Self.
if tto.bounds.len() == 1 {
if let TypeParamBound::Trait(t)
= tto.bounds.first().unwrap().value()
{
let path = &t.path;
// No need to substitute Self for the full path, because
// traits can't return "impl Trait", and structs can't
// return "impl Self" (because Self, in that case, isn't a
// trait). However, we do need to recurse to deselfify any
// generics and associated types.
let tp = TypePath{qself: None, path: t.path.clone()};
let mut path = Type::Path(tp);
deselfify(&mut path, actual, generics);
let new_type: Type = parse2(quote!(dyn #path)).unwrap();
*literal_type = new_type;
}
Expand Down

0 comments on commit a68d724

Please sign in to comment.