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

Automock methods returning "impl Future" #229

Merged
merged 1 commit into from
Nov 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ This project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased] - ReleaseDate
### Added

- Added the ability to mock methods returning `impl Future` or `impl Stream`.
Unlike other traits, these two aren't very useful in a `Box`. Instead,
Mockall will now change the Expectation's return type to `Pin<Box<_>>`.
([#229](https://github.com/asomers/mockall/pull/229))

- Added the ability to mock methods returning references to trait objects.
([#213](https://github.com/asomers/mockall/pull/213))

Expand Down
28 changes: 28 additions & 0 deletions mockall/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,34 @@
//!
//! See Also [`impl-trait-for-returning-complex-types-with-ease.html`](https://rust-lang-nursery.github.io/edition-guide/rust-2018/trait-system/impl-trait-for-returning-complex-types-with-ease)
//!
//! ### impl Future
//!
//! Rust 1.36.0 added the `Future` trait. Unlike virtually every trait that
//! preceeded it, `Box<dyn Future>` is mostly useless. Instead, you usually
//! need a `Pin<Box<dyn Future>>`. So that's what Mockall will do when you mock
//! a method returning `impl Future` or the related `impl Stream`. Just
//! remember to use `pin` in your expectations, like this:
//!
//! ```
//! # use mockall::*;
//! # use std::fmt::Debug;
//! # use futures::{Future, future};
//! struct Foo {}
//! #[automock]
//! impl Foo {
//! fn foo(&self) -> impl Future<Output=i32> {
//! // ...
//! # future::ready(42)
//! }
//! }
//!
//! # fn main() {
//! let mut mock = MockFoo::new();
//! mock.expect_foo()
//! .returning(|| Box::pin(future::ready(42)));
//! # }
//! ```
//!
//! ## Mocking structs
//!
//! Mockall mocks structs as well as traits. The problem here is a namespace
Expand Down
13 changes: 5 additions & 8 deletions mockall/tests/automock_associated_type_constructor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,19 @@

use mockall::*;

pub trait Future {
pub trait MyIterator {
type Item;
type Error;
}

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

#[automock]
impl Foo {
pub fn open() -> impl Future<Item=Self, Error=i32> {
pub fn open() -> impl MyIterator<Item=Self> {
struct Bar {}
impl Future for Bar {
impl MyIterator for Bar {
type Item=Foo;
type Error=i32;
}
Bar{}
}
Expand All @@ -30,9 +28,8 @@ fn returning() {
let ctx = MockFoo::open_context();
ctx.expect().returning(|| {
struct Baz {}
impl Future for Baz {
type Item=MockFoo;
type Error=i32;
impl MyIterator for Baz {
type Item = MockFoo;
}
Box::new(Baz{})
});
Expand Down
50 changes: 50 additions & 0 deletions mockall/tests/automock_impl_future.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// vim: tw=80
//! A trait with a constructor method that returns impl Future<...>.
//!
//! This needs special handling, because Box<dyn Future<...>> is pretty useless.
//! You need Pin<Box<dyn Future<...>>> instead.
#![deny(warnings)]

use futures::{Future, FutureExt, Stream, StreamExt, future, stream};
use mockall::*;

pub struct Foo{}

#[automock]
impl Foo {
pub fn foo(&self) -> impl Future<Output=u32>
{
future::ready(42)
}

pub fn bar(&self) -> impl Stream<Item=u32>
{
stream::empty()
}
}

#[test]
fn returning_future() {
let mut mock = MockFoo::new();
mock.expect_foo()
.returning(|| {
Box::pin(future::ready(42))
});
mock.foo()
.now_or_never()
.unwrap();
}

#[test]
fn returning_stream() {
let mut mock = MockFoo::new();
mock.expect_bar()
.returning(|| {
Box::pin(stream::iter(vec![42].into_iter()))
});
let all = mock.bar()
.collect::<Vec<u32>>()
.now_or_never()
.unwrap();
assert_eq!(&all[..], &[42][..]);
}
78 changes: 76 additions & 2 deletions mockall_derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,12 +246,31 @@ fn declosurefy(gen: &Generics, args: &Punctuated<FnArg, Token![,]>) ->
(outg, outargs, callargs)
}

/// Replace any "impl trait" types with "Box<dyn trait>" equivalents
/// Replace any "impl trait" types with "Box<dyn trait>" or equivalent.
fn deimplify(rt: &mut ReturnType) {
if let ReturnType::Type(_, ty) = rt {
if let Type::ImplTrait(ref tit) = &**ty {
let needs_pin = tit.bounds
.iter()
.any(|tpb| {
if let TypeParamBound::Trait(tb) = tpb {
if let Some(seg) = tb.path.segments.last() {
seg.ident == "Future" || seg.ident == "Stream"
} else {
// It might still be a Future, but we can't guess
// what names it might be imported under. Too bad.
false
}
} else {
false
}
});
let bounds = &tit.bounds;
*ty = parse2(quote!(Box<dyn #bounds>)).unwrap();
if needs_pin {
*ty = parse2(quote!(::std::pin::Pin<Box<dyn #bounds>>)).unwrap();
} else {
*ty = parse2(quote!(Box<dyn #bounds>)).unwrap();
}
}
}
}
Expand Down Expand Up @@ -1133,6 +1152,61 @@ mod automock {
}
}

mod deimplify {
use super::*;

fn check_deimplify(orig_ts: TokenStream, expected_ts: TokenStream) {
let mut orig: ReturnType = parse2(orig_ts).unwrap();
let expected: ReturnType = parse2(expected_ts).unwrap();
deimplify(&mut orig);
assert_eq!(quote!(#orig).to_string(), quote!(#expected).to_string());
}

// Future is a special case
#[test]
fn impl_future() {
check_deimplify(
quote!(-> impl Future<Output=i32>),
quote!(-> ::std::pin::Pin<Box<dyn Future<Output=i32>>>)
);
}

// Future is a special case, wherever it appears
#[test]
fn impl_future_reverse() {
check_deimplify(
quote!(-> impl Send + Future<Output=i32>),
quote!(-> ::std::pin::Pin<Box<dyn Send + Future<Output=i32>>>)
);
}

// Stream is a special case
#[test]
fn impl_stream() {
check_deimplify(
quote!(-> impl Stream<Item=i32>),
quote!(-> ::std::pin::Pin<Box<dyn Stream<Item=i32>>>)
);
}

#[test]
fn impl_trait() {
check_deimplify(
quote!(-> impl Foo),
quote!(-> Box<dyn Foo>)
);
}

// With extra bounds
#[test]
fn impl_trait2() {
check_deimplify(
quote!(-> impl Foo + Send),
quote!(-> Box<dyn Foo + Send>)
);
}
}

mod deselfify {
use super::*;

Expand Down