mockall/lib.rs
1// vim: tw=80
2//! A powerful mock object library for Rust.
3//!
4//! Mockall provides tools to create mock versions of almost any trait
5//! or struct. They can be used in unit tests as a stand-in for the real
6//! object.
7//!
8//! # Usage
9//!
10//! There are two ways to use Mockall. The easiest is to use
11//! [`#[automock]`](attr.automock.html). It can mock most traits, or structs
12//! that only have a single `impl` block. For things it can't handle, there is
13//! [`mock!`].
14//!
15//! Whichever method is used, the basic idea is the same.
16//! * Create a mock struct. It's name will be the same as the original, with
17//! "Mock" prepended.
18//! * In your test, instantiate the mock struct with its `new` or `default`
19//! method.
20//! * Set expectations on the mock struct. Each expectation can have required
21//! argument matchers, a required call count, and a required position in a
22//! [`Sequence`]. Each expectation must also have a return value.
23//! * Supply the mock object to the code that you're testing. It will return
24//! the preprogrammed return values supplied in the previous step. Any
25//! accesses contrary to your expectations will cause a panic.
26//!
27//! # User Guide
28//!
29//! * [`Getting started`](#getting-started)
30//! * [`Static Return values`](#static-return-values)
31//! * [`Matching arguments`](#matching-arguments)
32//! * [`Call counts`](#call-counts)
33//! * [`Sequences`](#sequences)
34//! * [`Checkpoints`](#checkpoints)
35//! * [`Reference arguments`](#reference-arguments)
36//! * [`Reference return values`](#reference-return-values)
37//! * [`impl Trait`](#impl-trait)
38//! * [`Mocking structs`](#mocking-structs)
39//! * [`Generic methods`](#generic-methods)
40//! * [`Generic traits and structs`](#generic-traits-and-structs)
41//! * [`Associated types`](#associated-types)
42//! * [`Multiple and inherited traits`](#multiple-and-inherited-traits)
43//! * [`External traits`](#external-traits)
44//! * [`Static methods`](#static-methods)
45//! * [`Modules`](#modules)
46//! * [`Foreign functions`](#foreign-functions)
47//! * [`Debug`](#debug)
48//! * [`Async Traits`](#async-traits)
49//! * [`Crate features`](#crate-features)
50//! * [`Examples`](#examples)
51//!
52//! ## Getting Started
53//! ```
54//! use mockall::*;
55//! use mockall::predicate::*;
56//! #[automock]
57//! trait MyTrait {
58//! fn foo(&self, x: u32) -> u32;
59//! }
60//!
61//! fn call_with_four(x: &dyn MyTrait) -> u32 {
62//! x.foo(4)
63//! }
64//!
65//! let mut mock = MockMyTrait::new();
66//! mock.expect_foo()
67//! .with(predicate::eq(4))
68//! .times(1)
69//! .returning(|x| x + 1);
70//! assert_eq!(5, call_with_four(&mock));
71//! ```
72//!
73//! ## Static Return values
74//!
75//! Every expectation must have an associated return value (though when the
76//! **nightly** feature is enabled expectations will automatically return the
77//! default values of their return types, if their return types implement
78//! `Default`.). For methods that return a `static` value, the macros will
79//! generate an `Expectation` struct like
80//! [`this`](examples::__mock_MockFoo_Foo::__foo::Expectation).
81//! There are two ways to set such an expectation's return value: with a
82//! constant
83//! ([`return_const`](examples::__mock_MockFoo_Foo::__foo::Expectation::return_const))
84//! or a closure
85//! ([`returning`](examples::__mock_MockFoo_Foo::__foo::Expectation::returning)).
86//! A closure will take the method's arguments by value.
87//!
88//! ```
89//! # use mockall::*;
90//! #[automock]
91//! trait MyTrait {
92//! fn foo(&self) -> u32;
93//! fn bar(&self, x: u32, y: u32) -> u32;
94//! }
95//!
96//! let mut mock = MockMyTrait::new();
97//! mock.expect_foo()
98//! .return_const(42u32);
99//! mock.expect_bar()
100//! .returning(|x, y| x + y);
101//! ```
102//!
103//! Additionally, constants that aren't `Clone` can be returned with the
104//! [`return_once`](examples::__mock_MockFoo_Foo::__foo::Expectation::return_once)
105//! method.
106//!
107//! ```
108//! # use mockall::*;
109//! struct NonClone();
110//! #[automock]
111//! trait Foo {
112//! fn foo(&self) -> NonClone;
113//! }
114//!
115//! # fn main() {
116//! let mut mock = MockFoo::new();
117//! let r = NonClone{};
118//! mock.expect_foo()
119//! .return_once(move || r);
120//! # }
121//! ```
122//!
123//! `return_once` can also be used for computing the return value with an
124//! `FnOnce` closure. This is useful for returning a non-`Clone` value and also
125//! triggering side effects at the same time.
126//!
127//! ```
128//! # use mockall::*;
129//! fn do_something() {}
130//!
131//! struct NonClone();
132//!
133//! #[automock]
134//! trait Foo {
135//! fn foo(&self) -> NonClone;
136//! }
137//!
138//! # fn main() {
139//! let mut mock = MockFoo::new();
140//! let r = NonClone{};
141//! mock.expect_foo()
142//! .return_once(move || {
143//! do_something();
144//! r
145//! });
146//! # }
147//! ```
148//!
149//! Mock objects are always `Send`. If you need to use a return type that
150//! isn't, you can use the
151//! [`return_const_st`](examples::__mock_MockFoo_Foo::__foo::Expectation::return_const_st),
152//! [`returning_st`](examples::__mock_MockFoo_Foo::__foo::Expectation::returning_st),
153//! or
154//! [`return_once_st`](examples::__mock_MockFoo_Foo::__foo::Expectation::return_once_st),
155//! methods. If you need to match arguments that are not `Send`, you can use the
156//! [`withf_st`](examples::__mock_MockFoo_Foo::__foo::Expectation::withf_st)
157//! These take a non-`Send` object and add runtime access checks. The wrapped
158//! object will be `Send`, but accessing it from multiple threads will cause a
159//! runtime panic.
160//!
161//! ```
162//! # use mockall::*;
163//! # use std::rc::Rc;
164//! #[automock]
165//! trait Foo {
166//! fn foo(&self, x: Rc<u32>) -> Rc<u32>; // Rc<u32> isn't Send
167//! }
168//!
169//! # fn main() {
170//! let mut mock = MockFoo::new();
171//! let x = Rc::new(5);
172//! let argument = x.clone();
173//! mock.expect_foo()
174//! .withf_st(move |x| *x == argument)
175//! .returning_st(move |_| Rc::new(42u32));
176//! assert_eq!(42, *mock.foo(x));
177//! # }
178//! ```
179//!
180//! ## Matching arguments
181//!
182//! Optionally, expectations may have argument matchers set. A matcher will
183//! verify that the expectation was called with the expected arguments, or panic
184//! otherwise. A matcher is anything that implements the [`Predicate`] trait.
185//! For example:
186//!
187//! ```should_panic
188//! # use mockall::*;
189//! # use mockall::predicate::*;
190//! #[automock]
191//! trait Foo {
192//! fn foo(&self, x: u32);
193//! }
194//!
195//! let mut mock = MockFoo::new();
196//! mock.expect_foo()
197//! .with(eq(42))
198//! .return_const(());
199//!
200//! mock.foo(0); // Panics!
201//! ```
202//!
203//! See [`predicate`] for a list of Mockall's builtin predicate functions.
204//! For convenience,
205//! [`withf`](examples::__mock_MockFoo_Foo::__foo::Expectation::withf)
206//! is a shorthand for setting the commonly used
207//! [`function`] predicate. The arguments to the predicate function are the
208//! method's arguments, *by reference*. For example:
209//!
210//! ```should_panic
211//! # use mockall::*;
212//! #[automock]
213//! trait Foo {
214//! fn foo(&self, x: u32, y: u32);
215//! }
216//!
217//! # fn main() {
218//! let mut mock = MockFoo::new();
219//! mock.expect_foo()
220//! .withf(|x: &u32, y: &u32| x == y)
221//! .return_const(());
222//!
223//! mock.foo(2 + 2, 5); // Panics!
224//! # }
225//! ```
226//!
227//! ### Matching multiple calls
228//!
229//! Matchers can also be used to discriminate between different invocations of
230//! the same function. Used that way, they can provide different return values
231//! for different arguments. The way this works is that on a method call, all
232//! expectations set on a given method are evaluated in FIFO order. The first
233//! matching expectation is used. Only if none of the expectations match does
234//! Mockall panic. For example:
235//!
236//! ```
237//! # use mockall::*;
238//! # use mockall::predicate::*;
239//! #[automock]
240//! trait Foo {
241//! fn foo(&self, x: u32) -> u32;
242//! }
243//!
244//! # fn main() {
245//! let mut mock = MockFoo::new();
246//! mock.expect_foo()
247//! .with(eq(5))
248//! .return_const(50u32);
249//! mock.expect_foo()
250//! .with(eq(6))
251//! .return_const(60u32);
252//! # }
253//! ```
254//!
255//! One common pattern is to use multiple expectations in order of decreasing
256//! specificity. The last expectation can provide a default or fallback value,
257//! and earlier ones can be more specific. For example:
258//!
259//! ```
260//! # use mockall::*;
261//! # use mockall::predicate::*;
262//! #[automock]
263//! trait Foo {
264//! fn open(&self, path: String) -> Option<u32>;
265//! }
266//!
267//! let mut mock = MockFoo::new();
268//! mock.expect_open()
269//! .with(eq(String::from("something.txt")))
270//! .returning(|_| Some(5));
271//! mock.expect_open()
272//! .return_const(None);
273//! ```
274//!
275//! ## Call counts
276//!
277//! By default, every expectation is allowed to be called an unlimited number of
278//! times. But Mockall can optionally verify that an expectation was called a
279//! fixed number of times, or any number of times within a given range.
280//!
281//! ```should_panic
282//! # use mockall::*;
283//! # use mockall::predicate::*;
284//! #[automock]
285//! trait Foo {
286//! fn foo(&self, x: u32);
287//! }
288//!
289//! let mut mock = MockFoo::new();
290//! mock.expect_foo()
291//! .times(1)
292//! .return_const(());
293//!
294//! mock.foo(0); // Ok
295//! mock.foo(1); // Panics!
296//! ```
297//!
298//! See also
299//! [`never`](examples::__mock_MockFoo_Foo::__foo::Expectation::never) and
300//! [`times`](examples::__mock_MockFoo_Foo::__foo::Expectation::times).
301//!
302//! ## Sequences
303//!
304//! By default expectations may be matched in any order. But it's possible to
305//! specify the order by using a [`Sequence`]. Any expectations may be added to
306//! the same sequence. They don't even need to come from the same object.
307//!
308//! ```should_panic
309//! # use mockall::*;
310//! #[automock]
311//! trait Foo {
312//! fn foo(&self);
313//! }
314//!
315//! # fn main() {
316//! let mut seq = Sequence::new();
317//!
318//! let mut mock1 = MockFoo::new();
319//! mock1.expect_foo()
320//! .times(1)
321//! .in_sequence(&mut seq)
322//! .returning(|| ());
323//!
324//! let mut mock2 = MockFoo::new();
325//! mock2.expect_foo()
326//! .times(1)
327//! .in_sequence(&mut seq)
328//! .returning(|| ());
329//!
330//! mock2.foo(); // Panics! mock1.foo should've been called first.
331//! # }
332//! ```
333//!
334//! ## Checkpoints
335//!
336//! Sometimes its useful to validate all expectations mid-test, throw them away,
337//! and add new ones. That's what checkpoints do. Every mock object has a
338//! `checkpoint` method. When called, it will immediately validate all methods'
339//! expectations. So any expectations that haven't satisfied their call count
340//! will panic. Afterwards, those expectations will be cleared so you can add
341//! new expectations and keep testing.
342//!
343//! ```should_panic
344//! # use mockall::*;
345//! #[automock]
346//! trait Foo {
347//! fn foo(&self);
348//! }
349//!
350//! let mut mock = MockFoo::new();
351//! mock.expect_foo()
352//! .times(2)
353//! .returning(|| ());
354//!
355//! mock.foo();
356//! mock.checkpoint(); // Panics! foo hasn't yet been called twice.
357//! ```
358//!
359//! ```should_panic
360//! # use mockall::*;
361//! #[automock]
362//! trait Foo {
363//! fn foo(&self);
364//! }
365//!
366//! # fn main() {
367//! let mut mock = MockFoo::new();
368//! mock.expect_foo()
369//! .times(1)
370//! .returning(|| ());
371//!
372//! mock.foo();
373//! mock.checkpoint();
374//! mock.foo(); // Panics! The expectation has been cleared.
375//! # }
376//! ```
377//!
378//! ## Reference arguments
379//!
380//! Mockall can mock methods with reference arguments, too. There's one catch:
381//! the matcher [`Predicate`] will take reference arguments by value, not by
382//! reference.
383//!
384//! ```
385//! # use mockall::*;
386//! #[automock]
387//! trait Foo {
388//! fn foo(&self, x: &u32) -> u32;
389//! }
390//!
391//! let mut mock = MockFoo::new();
392//! let e = mock.expect_foo()
393//! // Note that x is a &u32, not a &&u32
394//! .withf(|x: &u32| *x == 5)
395//! .returning(|x: &u32| *x + 1);
396//!
397//! assert_eq!(6, mock.foo(&5));
398//! ```
399//!
400//! ## Reference return values
401//!
402//! Mockall can also use reference return values. There is one restriction: the
403//! lifetime of the returned reference must be either the same as the lifetime
404//! of the mock object, or `'static`.
405//!
406//! Mockall creates different expectation types for methods that return
407//! references. Their API is the same as the basic `Expectation`, except for
408//! setting return values.
409//!
410//! Methods that return `'static` references work just like methods that return
411//! any other `'static` value.
412//! ```
413//! # use mockall::*;
414//! struct Thing(u32);
415//!
416//! #[automock]
417//! trait Container {
418//! fn get(&self, i: u32) -> &'static Thing;
419//! }
420//!
421//! # fn main() {
422//! const THING: Thing = Thing(42);
423//! let mut mock = MockContainer::new();
424//! mock.expect_get()
425//! .return_const(&THING);
426//!
427//! assert_eq!(42, mock.get(0).0);
428//! # }
429//! ```
430//!
431//! Methods that take a `&self` argument use an `Expectation` class like
432//! [this](examples::__mock_MockFoo_Foo::__bar::Expectation),
433//! which
434//! gets its return value from the
435//! [`return_const`](examples::__mock_MockFoo_Foo::__bar::Expectation::return_const) method.
436//!
437//! ```
438//! # use mockall::*;
439//! struct Thing(u32);
440//!
441//! #[automock]
442//! trait Container {
443//! fn get(&self, i: u32) -> &Thing;
444//! }
445//!
446//! # fn main() {
447//! let thing = Thing(42);
448//! let mut mock = MockContainer::new();
449//! mock.expect_get()
450//! .return_const(thing);
451//!
452//! assert_eq!(42, mock.get(0).0);
453//! # }
454//! ```
455//!
456//! Methods that take a `&mut self` argument use an `Expectation` class like
457//! [this](examples::__mock_MockFoo_Foo::__baz::Expectation),
458//! class, regardless of whether the return value is actually mutable. They can
459//! take their return value either from the
460//! [`return_var`](examples::__mock_MockFoo_Foo::__baz::Expectation::return_var)
461//! or
462//! [`returning`](examples::__mock_MockFoo_Foo::__baz::Expectation::returning)
463//! methods.
464//!
465//! ```
466//! # use mockall::*;
467//! struct Thing(u32);
468//!
469//! #[automock]
470//! trait Container {
471//! fn get_mut(&mut self, i: u32) -> &mut Thing;
472//! }
473//!
474//! # fn main() {
475//! let thing = Thing(42);
476//! let mut mock = MockContainer::new();
477//! mock.expect_get_mut()
478//! .return_var(thing);
479//!
480//! mock.get_mut(0).0 = 43;
481//! assert_eq!(43, mock.get_mut(0).0);
482//! # }
483//! ```
484//!
485//! Unsized types that are common targets for
486//! [`Deref`](core::ops::Deref)
487//! are special. Mockall
488//! will automatically use the type's owned form for the Expectation.
489//! Currently, the
490//! [`CStr`](std::ffi::CStr),
491//! [`OsStr`](std::ffi::OsStr),
492//! [`Path`](std::path::Path),
493//! [`Slice`][std::slice],
494//! and
495//! [`str`](std::str)
496//! types are supported. Using this feature is automatic:
497//!
498//! ```
499//! # use mockall::*;
500//! #[automock]
501//! trait Foo {
502//! fn name(&self) -> &str;
503//! }
504//!
505//! let mut mock = MockFoo::new();
506//! mock.expect_name().return_const("abcd".to_owned());
507//! assert_eq!("abcd", mock.name());
508//! ```
509//!
510//! Similarly, Mockall will use a Boxed trait object for the Expectation of
511//! methods that return references to trait objects.
512//!
513//! ```
514//! # use mockall::*;
515//! # use std::fmt::Display;
516//! #[automock]
517//! trait Foo {
518//! fn name(&self) -> &dyn Display;
519//! }
520//!
521//! # fn main() {
522//! let mut mock = MockFoo::new();
523//! mock.expect_name().return_const(Box::new("abcd"));
524//! assert_eq!("abcd", format!("{}", mock.name()));
525//! # }
526//! ```
527//!
528//!
529//! ## Impl Trait
530//!
531//! Rust 1.26.0 introduced the `impl Trait` feature. It allows functions to
532//! return concrete but unnamed types (and, less usefully, to take them as
533//! arguments). It's *almost* the same as `Box<dyn Trait>` but without the
534//! extra allocation. Mockall supports deriving mocks for methods that return
535//! `impl Trait`, with limitations. When you derive the mock for such a method,
536//! Mockall internally transforms the Expectation's return type to `Box<dyn
537//! Trait>`, without changing the mock method's signature. So you can use it
538//! like this:
539//!
540//! ```
541//! # use mockall::*;
542//! # use std::fmt::Debug;
543//! struct Foo {}
544//! #[automock]
545//! impl Foo {
546//! fn foo(&self) -> impl Debug {
547//! // ...
548//! # 4
549//! }
550//! }
551//!
552//! # fn main() {
553//! let mut mock = MockFoo::new();
554//! mock.expect_foo()
555//! .returning(|| Box::new(String::from("Hello, World!")));
556//! println!("{:?}", mock.foo());
557//! # }
558//! ```
559//!
560//! However, `impl Trait` isn't *exactly* equivalent to `Box<dyn Trait>` but
561//! with fewer allocations. There are some things the former can do but the
562//! latter can't. For one thing, you can't build a trait object out of a
563//! `Sized` trait. So this won't work:
564//!
565//! ```compile_fail
566//! # use mockall::*;
567//! struct Foo {}
568//! #[automock]
569//! impl Foo {
570//! fn foo(&self) -> impl Clone {
571//! // ...
572//! # 4
573//! }
574//! }
575//! ```
576//!
577//! Nor can you create a trait object that implements two or more non-auto
578//! types. So this won't work either:
579//!
580//! ```compile_fail
581//! # use mockall::*;
582//! struct Foo {}
583//! #[automock]
584//! impl Foo {
585//! fn foo(&self) -> impl Debug + Display {
586//! // ...
587//! # 4
588//! }
589//! }
590//! ```
591//!
592//! For such cases, there is no magic bullet. The best way to mock methods like
593//! those would be to refactor them to return named (but possibly opaque) types
594//! instead.
595//!
596//! 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)
597//!
598//! ### impl Future
599//!
600//! Rust 1.36.0 added the `Future` trait. Unlike virtually every trait that
601//! preceeded it, `Box<dyn Future>` is mostly useless. Instead, you usually
602//! need a `Pin<Box<dyn Future>>`. So that's what Mockall will do when you mock
603//! a method returning `impl Future` or the related `impl Stream`. Just
604//! remember to use `pin` in your expectations, like this:
605//!
606//! ```
607//! # use mockall::*;
608//! # use std::fmt::Debug;
609//! # use futures::{Future, future};
610//! struct Foo {}
611//! #[automock]
612//! impl Foo {
613//! fn foo(&self) -> impl Future<Output=i32> {
614//! // ...
615//! # future::ready(42)
616//! }
617//! }
618//!
619//! # fn main() {
620//! let mut mock = MockFoo::new();
621//! mock.expect_foo()
622//! .returning(|| Box::pin(future::ready(42)));
623//! # }
624//! ```
625//!
626//! ## Mocking structs
627//!
628//! Mockall mocks structs as well as traits. The problem here is a namespace
629//! problem: it's hard to supply the mock object to your code under test,
630//! because it has a different name. The solution is to alter import paths
631//! during test. The easiest way to do that is with the
632//! [`mockall_double`](https://docs.rs/mockall_double/latest) crate.
633//!
634//! [`#[automock]`](attr.automock.html)
635//! works for structs that have a single `impl` block:
636//! ```no_run
637//! use mockall_double::double;
638//! mod thing {
639//! use mockall::automock;
640//! pub struct Thing{}
641//! #[automock]
642//! impl Thing {
643//! pub fn foo(&self) -> u32 {
644//! // ...
645//! # unimplemented!()
646//! }
647//! }
648//! }
649//!
650//! #[double]
651//! use thing::Thing;
652//!
653//! fn do_stuff(thing: &Thing) -> u32 {
654//! thing.foo()
655//! }
656//!
657//! #[cfg(test)]
658//! mod t {
659//! use super::*;
660//!
661//! #[test]
662//! fn test_foo() {
663//! let mut mock = Thing::default();
664//! mock.expect_foo().returning(|| 42);
665//! do_stuff(&mock);
666//! }
667//! }
668//! # fn main() {}
669//! ```
670//! For structs with more than one `impl` block or that have unsupported
671//! `#[derive(X)]` attributes, e.g. `Clone`, see [`mock!`] instead.
672//!
673//! ## Generic methods
674//!
675//! Mocking generic methods is possible, but the exact process depends on
676//! whether the parameters are `'static`, non-`'static`, or lifetimes.
677//!
678//! ### With static parameters
679//!
680//! With fully `'static` parameters, the mock method is generic and so is its
681//! expect_* method. The expect_* method usually must be called with a
682//! turbofish. Expectations set with different generic parameters operate
683//! completely independently of one another.
684//!
685//! ```
686//! # use mockall::*;
687//! #[automock]
688//! trait Foo {
689//! fn foo<T: 'static>(&self, t: T) -> i32;
690//! }
691//!
692//! let mut mock = MockFoo::new();
693//! mock.expect_foo::<i16>()
694//! .returning(|t| i32::from(t));
695//! mock.expect_foo::<i8>()
696//! .returning(|t| -i32::from(t));
697//!
698//! assert_eq!(5, mock.foo(5i16));
699//! assert_eq!(-5, mock.foo(5i8));
700//! ```
701//!
702//! ### With non-`static` type parameters
703//!
704//! Mocking methods with non-`'static` type parameters is harder. The way
705//! Mockall does it is by turning the generic parameters into trait objects
706//! before evaluating expectations. This makes the expect_* method concrete,
707//! rather than generic. It also comes with many restrictions. See
708//! [`#[concretize]`](attr.concretize.html) for more details.
709//!
710//! ### With generic lifetimes
711//!
712//! A method with a lifetime parameter is technically a generic method, but
713//! Mockall treats it like a non-generic method that must work for all possible
714//! lifetimes. Mocking such a method is similar to mocking a non-generic
715//! method, with a few additional restrictions. One restriction is that you
716//! can't match calls with `with`, you must use `withf` instead. Another is
717//! that the generic lifetime may not appear as part of the return type.
718//! Finally, no method may have both generic lifetime parameters *and* generic
719//! type parameters.
720//!
721//! ```
722//! # use mockall::*;
723//! struct X<'a>(&'a i32);
724//!
725//! #[automock]
726//! trait Foo {
727//! fn foo<'a>(&self, x: X<'a>) -> i32;
728//! }
729//!
730//! # fn main() {
731//! let mut mock = MockFoo::new();
732//! mock.expect_foo()
733//! .withf(|f| *f.0 == 5)
734//! .return_const(42);
735//! let x = X(&5);
736//! assert_eq!(42, mock.foo(x));
737//! # }
738//! ```
739//!
740//! ## Generic traits and structs
741//!
742//! Mocking generic structs and generic traits is not a problem. The mock
743//! struct will be generic, too. As with generic methods, lifetime parameters
744//! are not allowed. However, as long as the generic parameters are not used by
745//! any static methods, then the parameters need not be `'static'`.
746//!
747//! ```
748//! # use mockall::*;
749//! #[automock]
750//! trait Foo<T> {
751//! fn foo(&self, t: T) -> i32;
752//! }
753//!
754//! # fn main() {
755//! let mut mock = MockFoo::<i16>::new();
756//! mock.expect_foo()
757//! .returning(|t| i32::from(t));
758//! assert_eq!(5, mock.foo(5i16));
759//! # }
760//! ```
761//!
762//! ## Associated types
763//!
764//! Traits with associated types can be mocked too. Unlike generic traits, the
765//! mock struct will not be generic. Instead, you must specify the associated
766//! types when defining the mock struct. They're specified as metaitems to the
767//! [`#[automock]`](attr.automock.html) attribute.
768//!
769//! ```
770//! # use mockall::*;
771//! #[automock(type Key=u16; type Value=i32;)]
772//! pub trait A {
773//! type Key;
774//! type Value;
775//! fn foo(&self, k: Self::Key) -> Self::Value;
776//! }
777//!
778//! let mut mock = MockA::new();
779//! mock.expect_foo()
780//! .returning(|x: u16| i32::from(x));
781//! assert_eq!(4, mock.foo(4));
782//! ```
783//!
784//! ## Multiple and inherited traits
785//!
786//! Creating a mock struct that implements multiple traits, whether inherited or
787//! not, requires using the [`mock!`] macro. But once created,
788//! using it is just the same as using any other mock object:
789//!
790//! ```
791//! # use mockall::*;
792//! pub trait A {
793//! fn foo(&self);
794//! }
795//!
796//! pub trait B: A {
797//! fn bar(&self);
798//! }
799//!
800//! mock! {
801//! // Structure to mock
802//! C {}
803//! // First trait to implement on C
804//! impl A for C {
805//! fn foo(&self);
806//! }
807//! // Second trait to implement on C
808//! impl B for C {
809//! fn bar(&self);
810//! }
811//! }
812//! # fn main() {
813//! let mut mock = MockC::new();
814//! mock.expect_foo().returning(|| ());
815//! mock.expect_bar().returning(|| ());
816//! mock.foo();
817//! mock.bar();
818//! # }
819//! ```
820//!
821//! ## External traits
822//!
823//! Mockall can mock traits and structs defined in external crates that are
824//! beyond your control, but you must use [`mock!`] instead of
825//! [`#[automock]`](attr.automock.html). Mock an external trait like this:
826//!
827//! ```
828//! # use mockall::*;
829//! mock! {
830//! MyStruct {} // Name of the mock struct, less the "Mock" prefix
831//! impl Clone for MyStruct { // specification of the trait to mock
832//! fn clone(&self) -> Self;
833//! }
834//! }
835//!
836//! # fn main() {
837//! let mut mock1 = MockMyStruct::new();
838//! let mock2 = MockMyStruct::new();
839//! mock1.expect_clone()
840//! .return_once(move || mock2);
841//! let cloned = mock1.clone();
842//! # }
843//! ```
844//!
845//! ## Static methods
846//!
847//! Mockall can also mock static methods. But be careful! The expectations are
848//! global. If you want to use a static method in multiple tests, you must
849//! provide your own synchronization. See the [`synchronization
850//! example`](https://github.com/asomers/mockall/blob/master/mockall/examples/synchronization.rs)
851//! for a basic implementation. For ordinary methods, expectations are
852//! set on the mock object. But static methods don't have any mock object.
853//! Instead, you must create a `Context` object just to set their expectations.
854//!
855//! ```
856//! # use mockall::*;
857//! #[automock]
858//! pub trait A {
859//! fn foo() -> u32;
860//! }
861//!
862//! let ctx = MockA::foo_context();
863//! ctx.expect().returning(|| 99);
864//! assert_eq!(99, MockA::foo());
865//! ```
866//!
867//! A common pattern is mocking a trait with a constructor method. In this case,
868//! you can easily set the mock constructor method to return a mock object.
869//!
870//! ```
871//! # use mockall::*;
872//! struct Foo{}
873//! #[automock]
874//! impl Foo {
875//! fn from_i32(x: i32) -> Self {
876//! // ...
877//! # unimplemented!()
878//! }
879//! fn foo(&self) -> i32 {
880//! // ...
881//! # unimplemented!()
882//! }
883//! }
884//!
885//! # fn main() {
886//! let ctx = MockFoo::from_i32_context();
887//! ctx.expect()
888//! .returning(|x| {
889//! let mut mock = MockFoo::default();
890//! mock.expect_foo()
891//! .return_const(x);
892//! mock
893//! });
894//! let foo = MockFoo::from_i32(42);
895//! assert_eq!(42, foo.foo());
896//! # }
897//! ```
898//!
899//! ### Generic static methods
900//!
901//! Mocking static methods of generic structs or traits, whether or not the
902//! methods themselves are generic, should work seamlessly as long as the
903//! generic parameter is `'static`
904//!
905//! ```
906//! # use mockall::*;
907//! #[automock]
908//! trait Foo<T: 'static> {
909//! fn new(t: T) -> MockFoo<T>;
910//! }
911//!
912//! # fn main() {
913//! let ctx = MockFoo::<u32>::new_context();
914//! ctx.expect()
915//! .returning(|_| MockFoo::default());
916//! let mock = MockFoo::<u32>::new(42u32);
917//! # }
918//! ```
919//!
920//! ### Context checkpoints
921//!
922//! The context object cleans up all expectations when it leaves scope. It also
923//! has a `checkpoint` method that functions just like a mock object's
924//! `checkpoint` method.
925//!
926//! ```should_panic
927//! # use mockall::*;
928//! #[automock]
929//! pub trait A {
930//! fn foo() -> u32;
931//! }
932//!
933//! let ctx = MockA::foo_context();
934//! ctx.expect()
935//! .times(1)
936//! .returning(|| 99);
937//! ctx.checkpoint(); // Panics!
938//! ```
939//!
940//! A mock object's checkpoint method does *not* checkpoint static methods.
941//! This behavior is useful when using multiple mock objects at once. For
942//! example:
943//!
944//! ```
945//! # use mockall::*;
946//! #[automock]
947//! pub trait A {
948//! fn build() -> Self;
949//! fn bar(&self) -> i32;
950//! }
951//!
952//! # fn main() {
953//! let ctx = MockA::build_context();
954//! ctx.expect()
955//! .times(2)
956//! .returning(|| MockA::default());
957//! let mut mock0 = MockA::build();
958//! mock0.expect_bar().return_const(4);
959//! mock0.bar();
960//! mock0.checkpoint(); // Does not checkpoint the build method
961//! let mock1 = MockA::build();
962//! # }
963//! ```
964//!
965//! One more thing: Mockall normally creates a zero-argument `new` method for
966//! every mock struct. But it *won't* do that when mocking a struct that
967//! already has a method named `new`. The `default` method will still be
968//! present.
969//!
970//! ## Modules
971//!
972//! In addition to mocking types, Mockall can also derive mocks for
973//! entire modules of Rust functions. Mockall will generate a new module named
974//! "mock_xxx", if "xxx" is the original module's name. You can also use
975//! `#[double]` to selectively import the mock module.
976//!
977//! Be careful! Module functions are static and so have the same caveats as
978//! [static methods](#static-methods) described above.
979//!
980//! ```
981//! # use mockall::*;
982//! # use mockall_double::*;
983//! mod outer {
984//! use mockall::automock;
985//! #[automock()]
986//! pub(super) mod inner {
987//! pub fn bar(x: u32) -> i64 {
988//! // ...
989//! # 4
990//! }
991//! }
992//! }
993//!
994//! #[double]
995//! use outer::inner;
996//!
997//! #[cfg(test)]
998//! mod t {
999//! use super::*;
1000//!
1001//! #[test]
1002//! fn test_foo_bar() {
1003//! let ctx = inner::bar_context();
1004//! ctx.expect()
1005//! .returning(|x| i64::from(x + 1));
1006//! assert_eq!(5, inner::bar(4));
1007//! }
1008//! }
1009//! # fn main() {}
1010//! ```
1011//!
1012//! ### Foreign functions
1013//!
1014//! One reason to mock modules is when working with foreign functions. Modules
1015//! may contain foreign functions, even though structs and traits may not. Like
1016//! static methods, the expectations are global.
1017//!
1018//! ```
1019//! # use mockall_double::*;
1020//! mod outer {
1021//! # use mockall::*;
1022//! #[automock]
1023//! pub mod ffi {
1024//! extern "C" {
1025//! pub fn foo(x: u32) -> i64;
1026//! }
1027//! }
1028//! }
1029//!
1030//! #[double]
1031//! use outer::ffi;
1032//!
1033//! fn do_stuff() -> i64 {
1034//! unsafe{ ffi::foo(42) }
1035//! }
1036//!
1037//! #[cfg(test)]
1038//! mod t {
1039//! use super::*;
1040//!
1041//! #[test]
1042//! fn test_foo() {
1043//! let ctx = ffi::foo_context();
1044//! ctx.expect()
1045//! .returning(|x| i64::from(x + 1));
1046//! assert_eq!(43, do_stuff());
1047//! }
1048//! }
1049//! # fn main() {}
1050//! ```
1051//!
1052//! ## Debug
1053//!
1054//! `#[automock]` will automatically generate `Debug` impls when mocking traits
1055//! and struct impls. `mock!` will too, if you add a `#[derive(Debug)]`, like
1056//! this:
1057//! ```no_run
1058//! # use mockall::*;
1059//! mock! {
1060//! #[derive(Debug)]
1061//! pub Foo {}
1062//! }
1063//! # fn main() {
1064//! # format!("{:?}", &MockFoo::default());
1065//! # }
1066//! ```
1067//!
1068//! ## Async Traits
1069//!
1070//! Async traits aren't yet (as of 1.47.0) a part of the Rust language. But
1071//! they're available from the
1072//! [`async_trait`](https://docs.rs/async-trait/0.1.38/async_trait/) crate.
1073//! Mockall is compatible with this crate, with two important limitations:
1074//!
1075//! * The `#[automock]` attribute must appear _before_ the `#[async_trait]`
1076//! attribute.
1077//!
1078//! * The `#[async_trait]` macro must be imported with its canonical name.
1079//!
1080//! ```
1081//! # use async_trait::async_trait;
1082//! # use mockall::*;
1083//! // async_trait works with both #[automock]
1084//! #[automock]
1085//! #[async_trait]
1086//! pub trait Foo {
1087//! async fn foo(&self) -> u32;
1088//! }
1089//! // and mock!
1090//! mock! {
1091//! pub Bar {}
1092//! #[async_trait]
1093//! impl Foo for Bar {
1094//! async fn foo(&self) -> u32;
1095//! }
1096//! }
1097//! # fn main() {}
1098//! ```
1099//!
1100//! ## Crate features
1101//!
1102//! Mockall has a **nightly** feature. Currently this feature has two
1103//! effects:
1104//!
1105//! * The compiler will produce better error messages.
1106//!
1107//! * Expectations for methods whose return type implements `Default` needn't
1108//! have their return values explicitly set. Instead, they will automatically
1109//! return the default value.
1110//!
1111//! With **nightly** enabled, you can omit the return value like this:
1112#![cfg_attr(feature = "nightly", doc = "```")]
1113#![cfg_attr(not(feature = "nightly"), doc = "```should_panic")]
1114//! # use mockall::*;
1115//! #[automock]
1116//! trait Foo {
1117//! fn foo(&self) -> Vec<u32>;
1118//! }
1119//!
1120//! let mut mock = MockFoo::new();
1121//! mock.expect_foo();
1122//! assert!(mock.foo().is_empty());
1123//! ```
1124//!
1125//! ## Examples
1126//!
1127//! For additional examples of Mockall in action, including detailed
1128//! documentation on the autogenerated methods, see
1129//! [`examples`](examples).
1130//!
1131//! [`Predicate`]: trait.Predicate.html
1132//! [`Sequence`]: Sequence
1133//! [`cfg-if`]: https://crates.io/crates/cfg-if
1134//! [`function`]: predicate/fn.function.html
1135//! [`mock!`]: macro.mock.html
1136//! [`predicate`]: predicate/index.html
1137
1138#![cfg_attr(feature = "nightly", feature(specialization))]
1139// Allow the incomplete_feature warning for specialization. We know it's
1140// incomplete; that's why it's guarded by the "nightly" feature.
1141#![cfg_attr(feature = "nightly", allow(incomplete_features))]
1142
1143#![cfg_attr(feature = "nightly", feature(doc_cfg))]
1144#![cfg_attr(test, deny(warnings))]
1145#![warn(missing_docs)]
1146
1147use downcast::*;
1148use std::{
1149 any,
1150 fmt::Debug,
1151 marker::PhantomData,
1152 ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
1153 RangeToInclusive},
1154 sync::{
1155 Arc,
1156 atomic::{AtomicUsize, Ordering}
1157 },
1158};
1159
1160#[doc(hidden)]
1161pub use downcast::{Any, Downcast};
1162#[doc(hidden)]
1163pub use fragile::Fragile;
1164
1165pub use predicates::{
1166 boolean::PredicateBooleanExt,
1167 prelude::{
1168 Predicate, PredicateBoxExt, PredicateFileContentExt, PredicateStrExt,
1169 predicate
1170 }
1171};
1172#[doc(hidden)]
1173pub use predicates_tree::CaseTreeExt;
1174
1175#[cfg(doc)]
1176extern crate self as mockall;
1177#[cfg(doc)]
1178pub mod examples;
1179
1180/// Automatically generate mock types for structs and traits.
1181///
1182/// This is by far the easiest way to use Mockall. It works on almost all
1183/// traits, and almost all structs that have a single `impl` block. In either
1184/// case, it will generate a mock struct whose name is the name of the mocked
1185/// struct/trait prepended with "Mock". For each method of the original, the
1186/// mock struct will have a method named `expect_whatever` that allows you to
1187/// set expectations. There will also be one `checkpoint` method that calls
1188/// [`checkpoint`] for every single mocked method.
1189///
1190/// # Examples
1191///
1192/// The simplest use case is mocking a no-frills trait
1193/// ```
1194/// # use mockall_derive::*;
1195/// #[automock]
1196/// pub trait Foo {
1197/// fn foo(&self, key: i16);
1198/// }
1199///
1200/// let mock = MockFoo::new();
1201/// ```
1202///
1203/// Mocking a structure:
1204/// ```
1205/// # use mockall_derive::*;
1206/// struct Foo {}
1207/// #[automock]
1208/// impl Foo {
1209/// fn foo(&self) -> u32 {
1210/// // ...
1211/// # unimplemented!()
1212/// }
1213/// }
1214/// ```
1215///
1216/// You can also mock a trait impl on a struct:
1217/// ```
1218/// # use mockall_derive::*;
1219/// pub trait Foo {
1220/// fn foo(&self, key: i16);
1221/// }
1222/// struct Bar{}
1223/// #[automock]
1224/// impl Foo for Bar {
1225/// fn foo(&self, key: i16){
1226/// // ...
1227/// # unimplemented!()
1228/// }
1229/// }
1230///
1231/// let mock = MockBar::new();
1232/// ```
1233///
1234/// Mocking a trait with associated types requires adding a metaitem to the
1235/// attribute:
1236/// ```
1237/// # use mockall_derive::*;
1238/// #[automock(type Item=u32;)]
1239/// trait Foo {
1240/// type Item;
1241/// fn foo(&self) -> Self::Item;
1242/// }
1243/// ```
1244///
1245/// It can mock a module full of functions. In this case, the mock functions
1246/// will be found in a module whose name is prepended with `mock_`.
1247///
1248/// ```
1249/// # use mockall_derive::*;
1250/// #[automock]
1251/// mod mymod {
1252/// pub fn foo() -> u32 {
1253/// // ...
1254/// # unimplemented!()
1255/// }
1256/// }
1257/// ```
1258/// Finally, `#[automock]` can also mock foreign functions. This works just
1259/// like mocking a module.
1260///
1261/// ```
1262/// # use mockall_derive::*;
1263/// #[automock]
1264/// mod ffi {
1265/// extern "C" {
1266/// pub fn foo() -> u32;
1267/// }
1268/// }
1269/// ```
1270///
1271/// [`checkpoint`]: ../mockall/index.html#checkpoints
1272///
1273/// # Limitations
1274///
1275/// `#[automock]` can't handle everything. There are some cases where
1276/// you will need to use [`mock!`] instead:
1277/// * Mocking a struct that has multiple `impl` blocks, including
1278/// structs that implement traits.
1279/// * Mocking a struct or trait defined in another crate.
1280/// * Mocking a trait with trait bounds.
1281/// * If the autogenerated "MockFoo" name isn't acceptable, and you want
1282/// to choose your own name for the mock structure.
1283pub use mockall_derive::automock;
1284
1285/// Decorates a method or function to tell Mockall to treat its generic arguments
1286/// as trait objects when creating expectations.
1287///
1288/// This allows users to use non-`'static` generic parameters, which otherwise
1289/// can't be mocked. The downsides of using this attribute are:
1290///
1291/// * Mockall can't tell if a parameter isn't `'static`, so you must annotate
1292/// such methods with the `#[mockall::concretize]` attribute.
1293/// * Generic methods will share expectations for all argument types. That is,
1294/// you won't be able to do `my_mock.expect_foo::<i32>(...)`.
1295/// * It can't be used on methods with a closure argument (though this may be
1296/// fixable).
1297/// * Concretized methods' expectations may only be matched with `.withf` or
1298/// `.withf_st`, not `.with`.
1299/// * It only works for parameters that can be turned into a trait object.
1300/// (may be fixable).
1301/// * Mockall needs to know how to turn the function argument into a trait
1302/// object. Given a generic parameter `T`, currently supported patterns are:
1303/// - `T`
1304/// - `&T`
1305/// - `&mut T`
1306/// - `&[T]`
1307///
1308/// # Examples
1309/// ```
1310/// # use std::path::Path;
1311/// # use mockall::{automock, concretize};
1312/// #[automock]
1313/// trait Foo {
1314/// #[mockall::concretize]
1315/// fn foo<P: AsRef<Path>>(&self, p: P);
1316/// }
1317///
1318/// # fn main() {
1319/// let mut mock = MockFoo::new();
1320/// mock.expect_foo()
1321/// .withf(|p| p.as_ref() == Path::new("/tmp"))
1322/// .return_const(());
1323/// mock.foo(Path::new("/tmp"));
1324/// # }
1325/// ```
1326///
1327/// NB: This attribute must be imported with its canonical name. It won't work
1328/// otherwise!
1329/// ```compile_fail
1330/// use mockall::concretize as something_else;
1331/// #[mockall::automock]
1332/// trait Foo {
1333/// #[something_else]
1334/// fn foo<T>(&self, t: T);
1335/// }
1336/// ```
1337pub use mockall_derive::concretize;
1338
1339/// Manually mock a structure.
1340///
1341/// Sometimes [`automock`] can't be used. In those cases you can use `mock!`,
1342/// which basically involves repeating the struct's or trait's definitions.
1343///
1344/// The format is:
1345///
1346/// * Optional visibility specifier
1347/// * Real structure name and generics fields
1348/// * 0 or more methods of the structure, written without bodies, enclosed in a
1349/// {} block
1350/// * 0 or more impl blocks implementing traits on the structure, also without
1351/// bodies.
1352///
1353/// # Examples
1354///
1355/// Mock a trait. This is the simplest use case.
1356/// ```
1357/// # use mockall_derive::mock;
1358/// trait Foo {
1359/// fn foo(&self, x: u32);
1360/// }
1361/// mock!{
1362/// pub MyStruct<T: Clone + 'static> {
1363/// fn bar(&self) -> u8;
1364/// }
1365/// impl<T: Clone + 'static> Foo for MyStruct<T> {
1366/// fn foo(&self, x: u32);
1367/// }
1368/// }
1369/// # fn main() {}
1370/// ```
1371/// Mocking an unsupported `#[derive(X)]` attribute, e.g. [`Clone`], is
1372/// similar.
1373/// ```
1374/// # use mockall_derive::mock;
1375/// #[derive(Clone)]
1376/// struct MyStruct;
1377///
1378/// mock!{
1379/// pub MyStruct {
1380/// fn bar(&self);
1381/// }
1382/// impl Clone for MyStruct {
1383/// fn clone(&self) -> Self;
1384/// }
1385/// }
1386/// # fn main() {}
1387/// ```
1388///
1389/// When mocking a generic struct's implementation of a generic trait, use the
1390/// same name for their generic parameters. For example, if you wanted to mock
1391/// `Rc`, do
1392/// ```
1393/// # use mockall_derive::mock;
1394/// mock!{
1395/// pub Rc<T> {}
1396/// impl<T> AsRef<T> for Rc<T> {
1397/// fn as_ref(&self) -> &T;
1398/// }
1399/// }
1400/// # fn main() {}
1401/// ```
1402/// *not*
1403/// ```compile_fail
1404/// # use mockall_derive::mock;
1405/// mock!{
1406/// pub Rc<Q> {}
1407/// impl<T> AsRef<T> for Rc<T> {
1408/// fn as_ref(&self) -> &T;
1409/// }
1410/// }
1411/// # fn main() {}
1412/// ```
1413/// Associated types can easily be mocked by specifying a concrete type in the
1414/// `mock!{}` invocation.
1415/// ```
1416/// # use mockall_derive::mock;
1417/// mock!{
1418/// MyIter {}
1419/// impl Iterator for MyIter {
1420/// type Item=u32;
1421///
1422/// fn next(&mut self) -> Option<<Self as Iterator>::Item>;
1423/// }
1424/// }
1425/// # fn main() {}
1426/// ```
1427pub use mockall_derive::mock;
1428
1429#[doc(hidden)]
1430pub trait AnyExpectations : Any + Send + Sync {}
1431downcast!(dyn AnyExpectations);
1432
1433#[doc(hidden)]
1434pub trait ReturnDefault<O> {
1435 fn maybe_return_default() -> Option<O>;
1436 fn return_default() -> Result<O, &'static str>;
1437}
1438
1439#[derive(Default)]
1440#[doc(hidden)]
1441pub struct DefaultReturner<O>(PhantomData<O>);
1442
1443::cfg_if::cfg_if! {
1444 if #[cfg(feature = "nightly")] {
1445 impl<O> ReturnDefault<O> for DefaultReturner<O> {
1446 default fn maybe_return_default() -> Option<O> {
1447 None
1448 }
1449
1450 default fn return_default() -> Result<O, &'static str> {
1451 Err("Can only return default values for types that impl std::Default")
1452 }
1453 }
1454
1455 impl<O: Default> ReturnDefault<O> for DefaultReturner<O> {
1456 fn maybe_return_default() -> Option<O> {
1457 Some(O::default())
1458 }
1459
1460 fn return_default() -> Result<O, &'static str> {
1461 Ok(O::default())
1462 }
1463 }
1464 } else {
1465 impl<O> ReturnDefault<O> for DefaultReturner<O> {
1466 fn maybe_return_default() -> Option<O> {
1467 None
1468 }
1469
1470 fn return_default() -> Result<O, &'static str> {
1471 Err("Returning default values requires the \"nightly\" feature")
1472 }
1473 }
1474 }
1475}
1476
1477// Wrapper type to allow for better expectation messages for any type.
1478// Will first try Debug, otherwise will print '?'
1479#[doc(hidden)]
1480pub struct ArgPrinter<'a, T>(pub &'a T);
1481
1482#[doc(hidden)]
1483pub struct DebugPrint<'a, T: Debug>(pub &'a T);
1484impl<T> Debug for DebugPrint<'_, T> where T: Debug {
1485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1486 Debug::fmt(self.0, f)
1487 }
1488}
1489#[doc(hidden)]
1490pub trait ViaDebug<T> where T: Debug { fn debug_string(&self) -> DebugPrint<'_, T>; }
1491impl<'a, T: Debug> ViaDebug<T> for &ArgPrinter<'a, T> {
1492 fn debug_string(&self) -> DebugPrint<'a, T> {
1493 DebugPrint(self.0)
1494 }
1495}
1496
1497#[doc(hidden)]
1498pub struct NothingPrint;
1499impl Debug for NothingPrint {
1500 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1501 write!(f, "?")
1502 }
1503}
1504#[doc(hidden)]
1505pub trait ViaNothing { fn debug_string(&self) -> NothingPrint; }
1506impl<T> ViaNothing for ArgPrinter<'_, T> {
1507 fn debug_string(&self) -> NothingPrint {
1508 NothingPrint
1509 }
1510}
1511
1512// Though it's not entirely correct, we treat usize::MAX as
1513// approximately infinity.
1514#[derive(Debug)]
1515#[doc(hidden)]
1516pub struct TimesRange(Range<usize>);
1517
1518impl Default for TimesRange {
1519 fn default() -> TimesRange {
1520 // By default, allow any number of calls
1521 TimesRange(0..usize::MAX)
1522 }
1523}
1524
1525impl From<usize> for TimesRange {
1526 fn from(n: usize) -> TimesRange {
1527 TimesRange(n..(n+1))
1528 }
1529}
1530
1531impl From<Range<usize>> for TimesRange {
1532 fn from(r: Range<usize>) -> TimesRange {
1533 assert!(r.end > r.start, "Backwards range");
1534 TimesRange(r)
1535 }
1536}
1537
1538impl From<RangeFrom<usize>> for TimesRange {
1539 fn from(r: RangeFrom<usize>) -> TimesRange {
1540 TimesRange(r.start..usize::MAX)
1541 }
1542}
1543
1544impl From<RangeFull> for TimesRange {
1545 fn from(_: RangeFull) -> TimesRange {
1546 TimesRange(0..usize::MAX)
1547 }
1548}
1549
1550impl From<RangeInclusive<usize>> for TimesRange {
1551 fn from(r: RangeInclusive<usize>) -> TimesRange {
1552 assert!(r.end() >= r.start(), "Backwards range");
1553 TimesRange(*r.start()..*r.end() + 1)
1554 }
1555}
1556
1557impl From<RangeTo<usize>> for TimesRange {
1558 fn from(r: RangeTo<usize>) -> TimesRange {
1559 TimesRange(0..r.end)
1560 }
1561}
1562
1563impl From<RangeToInclusive<usize>> for TimesRange {
1564 fn from(r: RangeToInclusive<usize>) -> TimesRange {
1565 TimesRange(0..r.end + 1)
1566 }
1567}
1568
1569#[derive(PartialEq)]
1570#[doc(hidden)]
1571pub enum ExpectedCalls {
1572 Satisfied,
1573 TooMany,
1574 TooFew,
1575}
1576
1577#[derive(Debug, Default)]
1578#[doc(hidden)]
1579pub struct Times{
1580 /// How many times has the expectation already been called?
1581 count: AtomicUsize,
1582 range: TimesRange
1583}
1584
1585#[doc(hidden)]
1586impl Times {
1587 pub fn call(&self) -> Result<(), String> {
1588 let count = self.count.fetch_add(1, Ordering::Relaxed) + 1;
1589 if count >= self.range.0.end {
1590 if self.range.0.end == 1 {
1591 Err("should not have been called".to_owned())
1592 } else {
1593 Err(format!(
1594 "called {} times which is more than the expected {}",
1595 count,
1596 self.range.0.end - 1
1597 ))
1598 }
1599 } else {
1600 Ok(())
1601 }
1602 }
1603
1604 pub fn any(&mut self) {
1605 self.range.0 = 0..usize::MAX;
1606 }
1607
1608 /// Return how many times this expectation has been called
1609 pub fn count(&self) -> usize {
1610 self.count.load(Ordering::Relaxed)
1611 }
1612
1613 /// Has this expectation already been called the maximum allowed number of
1614 /// times?
1615 pub fn is_done(&self) -> bool {
1616 self.count.load(Ordering::Relaxed) >= self.range.0.end - 1
1617 }
1618
1619 /// Is it required that this expectation be called an exact number of times,
1620 /// or may it be satisfied by a range of call counts?
1621 pub fn is_exact(&self) -> bool {
1622 (self.range.0.end - self.range.0.start) == 1
1623 }
1624
1625 /// Has this expectation already been called the expected number of times?
1626 /// If not, was it too many or too few?
1627 pub fn is_satisfied(&self) -> ExpectedCalls {
1628 let satisfied_lower_bound = self.count.load(Ordering::Relaxed) >= self.range.0.start;
1629 let satisfied_upper_bound = self.count.load(Ordering::Relaxed) < self.range.0.end;
1630 if satisfied_lower_bound && satisfied_upper_bound {
1631 ExpectedCalls::Satisfied
1632 } else if satisfied_lower_bound {
1633 ExpectedCalls::TooMany
1634 } else {
1635 ExpectedCalls::TooFew
1636 }
1637 }
1638
1639 /// The maximum number of times that this expectation must be called
1640 pub fn maximum(&self) -> usize {
1641 self.range.0.end - 1
1642 }
1643
1644 /// The minimum number of times that this expectation must be called
1645 pub fn minimum(&self) -> usize {
1646 self.range.0.start
1647 }
1648
1649 // https://github.com/rust-lang/rust-clippy/issues/3307
1650 #[allow(clippy::range_plus_one)]
1651 pub fn n(&mut self, n: usize) {
1652 self.range.0 = n..(n+1);
1653 }
1654
1655 pub fn never(&mut self) {
1656 self.range.0 = 0..1;
1657 }
1658
1659 pub fn range(&mut self, range: Range<usize>) {
1660 assert!(range.end > range.start, "Backwards range");
1661 self.range.0 = range;
1662 }
1663
1664 pub fn times<T: Into<TimesRange>>(&mut self, t: T) {
1665 self.range = t.into();
1666 }
1667}
1668
1669/// Non-generic keys to `GenericExpectation` internal storage
1670#[doc(hidden)]
1671#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1672pub struct Key(any::TypeId);
1673
1674#[doc(hidden)]
1675impl Key {
1676 pub fn new<T: 'static + ?Sized>() -> Self {
1677 Key(any::TypeId::of::<T>())
1678 }
1679}
1680
1681#[doc(hidden)]
1682pub struct SeqHandle {
1683 inner: Arc<SeqInner>,
1684 seq: usize
1685}
1686
1687impl SeqHandle {
1688 /// Tell the Sequence that this expectation has been fully satisfied
1689 pub fn satisfy(&self) {
1690 self.inner.satisfy(self.seq);
1691 }
1692
1693 /// Verify that this handle was called in the correct order
1694 pub fn verify(&self, desc: &str) {
1695 self.inner.verify(self.seq, desc);
1696 }
1697}
1698
1699#[derive(Default)]
1700struct SeqInner {
1701 satisfaction_level: AtomicUsize,
1702}
1703
1704impl SeqInner {
1705 /// Record the call identified by `seq` as fully satisfied.
1706 fn satisfy(&self, seq: usize) {
1707 let old_sl = self.satisfaction_level.fetch_add(1, Ordering::Relaxed);
1708 assert_eq!(old_sl, seq, "Method sequence violation. Was an already-satisfied method called another time?");
1709 }
1710
1711 /// Verify that the call identified by `seq` was called in the correct order
1712 fn verify(&self, seq: usize, desc: &str) {
1713 assert_eq!(seq, self.satisfaction_level.load(Ordering::Relaxed),
1714 "{desc}: Method sequence violation")
1715 }
1716}
1717
1718/// Used to enforce that mock calls must happen in the sequence specified.
1719///
1720/// Each expectation must expect to be called a fixed number of times. Once
1721/// satisfied, the next expectation in the sequence will expect to be called.
1722///
1723/// # Examples
1724/// ```
1725/// # use mockall::*;
1726/// #[automock]
1727/// trait Foo {
1728/// fn foo(&self);
1729/// fn bar(&self) -> u32;
1730/// }
1731/// let mut seq = Sequence::new();
1732///
1733/// let mut mock0 = MockFoo::new();
1734/// let mut mock1 = MockFoo::new();
1735///
1736/// mock0.expect_foo()
1737/// .times(1)
1738/// .returning(|| ())
1739/// .in_sequence(&mut seq);
1740///
1741/// mock1.expect_bar()
1742/// .times(1)
1743/// .returning(|| 42)
1744/// .in_sequence(&mut seq);
1745///
1746/// mock0.foo();
1747/// mock1.bar();
1748/// ```
1749///
1750/// It is an error to add an expectation to a `Sequence` if its call count is
1751/// unspecified.
1752/// ```should_panic(expected = "with an exact call count")
1753/// # use mockall::*;
1754/// #[automock]
1755/// trait Foo {
1756/// fn foo(&self);
1757/// }
1758/// let mut seq = Sequence::new();
1759///
1760/// let mut mock = MockFoo::new();
1761/// mock.expect_foo()
1762/// .returning(|| ())
1763/// .in_sequence(&mut seq); // panics!
1764/// ```
1765#[derive(Default)]
1766pub struct Sequence {
1767 inner: Arc<SeqInner>,
1768 next_seq: usize,
1769}
1770
1771impl Sequence {
1772 /// Create a new empty [`Sequence`]
1773 pub fn new() -> Self {
1774 Self::default()
1775 }
1776
1777 /// Not for public consumption, but it must be public so the generated code
1778 /// can call it.
1779 #[doc(hidden)]
1780 pub fn next_handle(&mut self) -> SeqHandle {
1781 let handle = SeqHandle{inner: self.inner.clone(), seq: self.next_seq};
1782 self.next_seq += 1;
1783 handle
1784 }
1785}