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//! Partial support for async traits was introduced in the Rust language since
1071//! 1.75.0.
1072//! Mockall is compatible with them, as well as both 
1073//! [`async_trait`](https://docs.rs/async-trait/latest/async_trait/) and
1074//! [`trait_variant`](https://docs.rs/trait-variant/latest/trait_variant/)
1075//! crates, with two important limitations:
1076//! 
1077//! * The `#[automock]` attribute must appear _before_ the crate's attribute.
1078//! 
1079//! * The `#[async_trait]` and `#[trait_variant::make]` macros must be 
1080//! imported with their canonical names.
1081//!
1082//! ```
1083//! # use async_trait::async_trait;
1084//! # use mockall::*;
1085//! // async_trait works with both #[automock]
1086//! #[automock]
1087//! #[async_trait]
1088//! pub trait Foo {
1089//!    async fn foo(&self) -> u32;
1090//! }
1091//! // and mock!
1092//! mock! {
1093//!     pub Bar {}
1094//!     #[async_trait]
1095//!     impl Foo for Bar {
1096//!         async fn foo(&self) -> u32;
1097//!     }
1098//! }
1099//! # fn main() {}
1100//! ```
1101//!
1102//! ## Crate features
1103//!
1104//! Mockall has a **nightly** feature.  Currently this feature has two
1105//! effects:
1106//!
1107//! * The compiler will produce better error messages.
1108//!
1109//! * Expectations for methods whose return type implements `Default` needn't
1110//!   have their return values explicitly set.  Instead, they will automatically
1111//!   return the default value.
1112//!
1113//! With **nightly** enabled, you can omit the return value like this:
1114#![cfg_attr(feature = "nightly", doc = "```")]
1115#![cfg_attr(not(feature = "nightly"), doc = "```should_panic")]
1116//! # use mockall::*;
1117//! #[automock]
1118//! trait Foo {
1119//!     fn foo(&self) -> Vec<u32>;
1120//! }
1121//!
1122//! let mut mock = MockFoo::new();
1123//! mock.expect_foo();
1124//! assert!(mock.foo().is_empty());
1125//! ```
1126//!
1127//! ## Examples
1128//!
1129//! For additional examples of Mockall in action, including detailed
1130//! documentation on the autogenerated methods, see
1131//! [`examples`](examples).
1132//!
1133//! [`Predicate`]: trait.Predicate.html
1134//! [`Sequence`]: Sequence
1135//! [`cfg-if`]: https://crates.io/crates/cfg-if
1136//! [`function`]: predicate/fn.function.html
1137//! [`mock!`]: macro.mock.html
1138//! [`predicate`]: predicate/index.html
1139
1140#![cfg_attr(feature = "nightly", feature(specialization))]
1141// Allow the incomplete_feature warning for specialization.  We know it's
1142// incomplete; that's why it's guarded by the "nightly" feature.
1143#![cfg_attr(feature = "nightly", allow(incomplete_features))]
1144
1145#![cfg_attr(feature = "nightly", feature(doc_cfg))]
1146#![cfg_attr(test, deny(warnings))]
1147#![warn(missing_docs)]
1148
1149use downcast::*;
1150use std::{
1151    any,
1152    fmt::Debug,
1153    marker::PhantomData,
1154    ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
1155          RangeToInclusive},
1156    sync::{
1157        Arc,
1158        atomic::{AtomicUsize, Ordering}
1159    },
1160};
1161
1162#[doc(hidden)]
1163pub use downcast::{Any, Downcast};
1164#[doc(hidden)]
1165pub use fragile::Fragile;
1166
1167pub use predicates::{
1168    boolean::PredicateBooleanExt,
1169    prelude::{
1170        Predicate, PredicateBoxExt, PredicateFileContentExt, PredicateStrExt,
1171        predicate
1172    }
1173};
1174#[doc(hidden)]
1175pub use predicates_tree::CaseTreeExt;
1176
1177#[cfg(doc)]
1178extern crate self as mockall;
1179#[cfg(doc)]
1180pub mod examples;
1181
1182/// Automatically generate mock types for structs and traits.
1183///
1184/// This is by far the easiest way to use Mockall.  It works on almost all
1185/// traits, and almost all structs that have a single `impl` block.  In either
1186/// case, it will generate a mock struct whose name is the name of the mocked
1187/// struct/trait prepended with "Mock".  For each method of the original, the
1188/// mock struct will have a method named `expect_whatever` that allows you to
1189/// set expectations.  There will also be one `checkpoint` method that calls
1190/// [`checkpoint`] for every single mocked method.
1191///
1192/// # Examples
1193///
1194/// The simplest use case is mocking a no-frills trait
1195/// ```
1196/// # use mockall_derive::*;
1197/// #[automock]
1198/// pub trait Foo {
1199///     fn foo(&self, key: i16);
1200/// }
1201///
1202/// let mock = MockFoo::new();
1203/// ```
1204///
1205/// Mocking a structure:
1206/// ```
1207/// # use mockall_derive::*;
1208/// struct Foo {}
1209/// #[automock]
1210/// impl Foo {
1211///     fn foo(&self) -> u32 {
1212///         // ...
1213///         # unimplemented!()
1214///     }
1215/// }
1216/// ```
1217///
1218/// You can also mock a trait impl on a struct:
1219/// ```
1220/// # use mockall_derive::*;
1221/// pub trait Foo {
1222///     fn foo(&self, key: i16);
1223/// }
1224/// struct Bar{}
1225/// #[automock]
1226/// impl Foo for Bar {
1227///     fn foo(&self, key: i16){
1228///         // ...
1229///         # unimplemented!()
1230///     }
1231/// }
1232///
1233/// let mock = MockBar::new();
1234/// ```
1235///
1236/// Mocking a trait variant with a different name requires adding a metaitem to the
1237/// attribute in order to mock the variant instead of the original:
1238/// ```
1239/// # use mockall_derive::*;
1240/// #[automock(target = Foo)]
1241/// #[trait_variant::make(Foo: Send)]
1242/// trait LocalFoo {
1243///     fn foo(&self) -> u32;
1244/// }
1245/// ```
1246/// The example above demonstrates using `target = Foo`, which will generate
1247/// a `MockFoo` struct suitable for mocking the `Foo` variant.
1248/// Without `target = Foo`, `#[automock]` would have generated `MockLocalFoo`.
1249///
1250/// Mocking a trait with associated types requires adding a metaitem to the
1251/// attribute:
1252/// ```
1253/// # use mockall_derive::*;
1254/// #[automock(type Item=u32;)]
1255/// trait Foo {
1256///     type Item;
1257///     fn foo(&self) -> Self::Item;
1258/// }
1259/// ```
1260///
1261/// It can mock a module full of functions.  In this case, the mock functions
1262/// will be found in a module whose name is prepended with `mock_`.
1263///
1264/// ```
1265/// # use mockall_derive::*;
1266/// #[automock]
1267/// mod mymod {
1268///     pub fn foo() -> u32 {
1269///        // ...
1270///        # unimplemented!()
1271///     }
1272/// }
1273/// ```
1274/// Finally, `#[automock]` can also mock foreign functions.  This works just
1275/// like mocking a module.
1276///
1277/// ```
1278/// # use mockall_derive::*;
1279/// #[automock]
1280/// mod ffi {
1281///     extern "C" {
1282///         pub fn foo() -> u32;
1283///     }
1284/// }
1285/// ```
1286///
1287/// [`checkpoint`]: ../mockall/index.html#checkpoints
1288///
1289/// # Limitations
1290///
1291/// `#[automock]` can't handle everything.  There are some cases where
1292/// you will need to use [`mock!`] instead:
1293/// * Mocking a struct that has multiple `impl` blocks, including
1294///   structs that implement traits.
1295/// * Mocking a struct or trait defined in another crate.
1296/// * Mocking a trait with trait bounds.
1297/// * If the autogenerated "MockFoo" name isn't acceptable, and you want
1298///   to choose your own name for the mock structure.
1299pub use mockall_derive::automock;
1300
1301/// Decorates a method or function to tell Mockall to treat its generic arguments
1302/// as trait objects when creating expectations.
1303///
1304/// This allows users to use non-`'static` generic parameters, which otherwise
1305/// can't be mocked.  The downsides of using this attribute are:
1306///
1307/// * Mockall can't tell if a parameter isn't `'static`, so you must annotate
1308///   such methods with the `#[mockall::concretize]` attribute.
1309/// * Generic methods will share expectations for all argument types.  That is,
1310///   you won't be able to do `my_mock.expect_foo::<i32>(...)`.
1311/// * It can't be used on methods with a closure argument (though this may be
1312///   fixable).
1313/// * Concretized methods' expectations may only be matched with `.withf` or
1314///   `.withf_st`, not `.with`.
1315/// * It only works for parameters that can be turned into a trait object.
1316///   (may be fixable).
1317/// * Mockall needs to know how to turn the function argument into a trait
1318///   object.  Given a generic parameter `T`, currently supported patterns are:
1319///   - `T`
1320///   - `&T`
1321///   - `&mut T`
1322///   - `&[T]`
1323///
1324/// # Examples
1325/// ```
1326/// # use std::path::Path;
1327/// # use mockall::{automock, concretize};
1328/// #[automock]
1329/// trait Foo {
1330///     #[mockall::concretize]
1331///     fn foo<P: AsRef<Path>>(&self, p: P);
1332/// }
1333///
1334/// # fn main() {
1335/// let mut mock = MockFoo::new();
1336/// mock.expect_foo()
1337///     .withf(|p| p.as_ref() == Path::new("/tmp"))
1338///     .return_const(());
1339/// mock.foo(Path::new("/tmp"));
1340/// # }
1341/// ```
1342///
1343/// NB: This attribute must be imported with its canonical name.  It won't work
1344/// otherwise!
1345/// ```compile_fail
1346/// use mockall::concretize as something_else;
1347/// #[mockall::automock]
1348/// trait Foo {
1349///     #[something_else]
1350///     fn foo<T>(&self, t: T);
1351/// }
1352/// ```
1353pub use mockall_derive::concretize;
1354
1355/// Manually mock a structure.
1356///
1357/// Sometimes [`automock`] can't be used.  In those cases you can use `mock!`,
1358/// which basically involves repeating the struct's or trait's definitions.
1359///
1360/// The format is:
1361///
1362/// * Optional visibility specifier
1363/// * Real structure name and generics fields
1364/// * 0 or more methods of the structure, written without bodies, enclosed in a
1365///   {} block
1366/// * 0 or more impl blocks implementing traits on the structure, also without
1367///   bodies.
1368///
1369/// # Examples
1370///
1371/// Mock a trait.  This is the simplest use case.
1372/// ```
1373/// # use mockall_derive::mock;
1374/// trait Foo {
1375///     fn foo(&self, x: u32);
1376/// }
1377/// mock!{
1378///     pub MyStruct<T: Clone + 'static> {
1379///         fn bar(&self) -> u8;
1380///     }
1381///     impl<T: Clone + 'static> Foo for MyStruct<T> {
1382///         fn foo(&self, x: u32);
1383///     }
1384/// }
1385/// # fn main() {}
1386/// ```
1387/// Mocking an unsupported `#[derive(X)]` attribute, e.g. [`Clone`], is
1388/// similar.
1389/// ```
1390/// # use mockall_derive::mock;
1391/// #[derive(Clone)]
1392/// struct MyStruct;
1393///
1394/// mock!{
1395///     pub MyStruct {
1396///         fn bar(&self);
1397///     }
1398///     impl Clone for MyStruct {
1399///         fn clone(&self) -> Self;
1400///     }
1401/// }
1402/// # fn main() {}
1403/// ```
1404///
1405/// When mocking a generic struct's implementation of a generic trait, use the
1406/// same name for their generic parameters.  For example, if you wanted to mock
1407/// `Rc`, do
1408/// ```
1409/// # use mockall_derive::mock;
1410/// mock!{
1411///     pub Rc<T> {}
1412///     impl<T> AsRef<T> for Rc<T> {
1413///         fn as_ref(&self) -> &T;
1414///     }
1415/// }
1416/// # fn main() {}
1417/// ```
1418/// *not*
1419/// ```compile_fail
1420/// # use mockall_derive::mock;
1421/// mock!{
1422///     pub Rc<Q> {}
1423///     impl<T> AsRef<T> for Rc<T> {
1424///         fn as_ref(&self) -> &T;
1425///     }
1426/// }
1427/// # fn main() {}
1428/// ```
1429/// Associated types can easily be mocked by specifying a concrete type in the
1430/// `mock!{}` invocation.
1431/// ```
1432/// # use mockall_derive::mock;
1433/// mock!{
1434///     MyIter {}
1435///     impl Iterator for MyIter {
1436///         type Item=u32;
1437///
1438///         fn next(&mut self) -> Option<<Self as Iterator>::Item>;
1439///     }
1440/// }
1441/// # fn main() {}
1442/// ```
1443pub use mockall_derive::mock;
1444
1445#[doc(hidden)]
1446pub trait AnyExpectations : Any + Send + Sync {}
1447downcast!(dyn AnyExpectations);
1448
1449#[doc(hidden)]
1450pub trait ReturnDefault<O> {
1451    fn maybe_return_default() -> Option<O>;
1452    fn return_default() -> Result<O, &'static str>;
1453}
1454
1455#[derive(Default)]
1456#[doc(hidden)]
1457pub struct DefaultReturner<O>(PhantomData<O>);
1458
1459::cfg_if::cfg_if! {
1460    if #[cfg(feature = "nightly")] {
1461        impl<O> ReturnDefault<O> for DefaultReturner<O> {
1462            default fn maybe_return_default() -> Option<O> {
1463                None
1464            }
1465
1466            default fn return_default() -> Result<O, &'static str> {
1467                Err("Can only return default values for types that impl std::Default")
1468            }
1469        }
1470
1471        impl<O: Default> ReturnDefault<O> for DefaultReturner<O> {
1472            fn maybe_return_default() -> Option<O> {
1473                Some(O::default())
1474            }
1475
1476            fn return_default() -> Result<O, &'static str> {
1477                Ok(O::default())
1478            }
1479        }
1480    } else {
1481        impl<O> ReturnDefault<O> for DefaultReturner<O> {
1482            fn maybe_return_default() -> Option<O> {
1483                None
1484            }
1485
1486            fn return_default() -> Result<O, &'static str> {
1487                Err("Returning default values requires the \"nightly\" feature")
1488            }
1489        }
1490    }
1491}
1492
1493// Wrapper type to allow for better expectation messages for any type.
1494// Will first try Debug, otherwise will print '?'
1495#[doc(hidden)]
1496pub struct ArgPrinter<'a, T>(pub &'a T);
1497
1498#[doc(hidden)]
1499pub struct DebugPrint<'a, T: Debug>(pub &'a T);
1500impl<T> Debug for DebugPrint<'_, T> where T: Debug {
1501    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1502        Debug::fmt(self.0, f)
1503    }
1504}
1505#[doc(hidden)]
1506pub trait ViaDebug<T> where T: Debug { fn debug_string(&self) -> DebugPrint<'_, T>; }
1507impl<'a, T: Debug> ViaDebug<T> for &ArgPrinter<'a, T> {
1508    fn debug_string(&self) -> DebugPrint<'a, T> {
1509        DebugPrint(self.0)
1510    }
1511}
1512
1513#[doc(hidden)]
1514pub struct NothingPrint;
1515impl Debug for NothingPrint {
1516    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1517        write!(f, "?")
1518    }
1519}
1520#[doc(hidden)]
1521pub trait ViaNothing { fn debug_string(&self) -> NothingPrint; }
1522impl<T> ViaNothing for ArgPrinter<'_, T> {
1523    fn debug_string(&self) -> NothingPrint {
1524        NothingPrint
1525    }
1526}
1527
1528// Though it's not entirely correct, we treat usize::MAX as
1529// approximately infinity.
1530#[derive(Debug)]
1531#[doc(hidden)]
1532pub struct TimesRange(Range<usize>);
1533
1534impl Default for TimesRange {
1535    fn default() -> TimesRange {
1536        // By default, allow any number of calls
1537        TimesRange(0..usize::MAX)
1538    }
1539}
1540
1541impl From<usize> for TimesRange {
1542    fn from(n: usize) -> TimesRange {
1543        TimesRange(n..(n+1))
1544    }
1545}
1546
1547impl From<Range<usize>> for TimesRange {
1548    fn from(r: Range<usize>) -> TimesRange {
1549        assert!(r.end > r.start, "Backwards range");
1550        TimesRange(r)
1551    }
1552}
1553
1554impl From<RangeFrom<usize>> for TimesRange {
1555    fn from(r: RangeFrom<usize>) -> TimesRange {
1556        TimesRange(r.start..usize::MAX)
1557    }
1558}
1559
1560impl From<RangeFull> for TimesRange {
1561    fn from(_: RangeFull) -> TimesRange {
1562        TimesRange(0..usize::MAX)
1563    }
1564}
1565
1566impl From<RangeInclusive<usize>> for TimesRange {
1567    fn from(r: RangeInclusive<usize>) -> TimesRange {
1568        assert!(r.end() >= r.start(), "Backwards range");
1569        TimesRange(*r.start()..*r.end() + 1)
1570    }
1571}
1572
1573impl From<RangeTo<usize>> for TimesRange {
1574    fn from(r: RangeTo<usize>) -> TimesRange {
1575        TimesRange(0..r.end)
1576    }
1577}
1578
1579impl From<RangeToInclusive<usize>> for TimesRange {
1580    fn from(r: RangeToInclusive<usize>) -> TimesRange {
1581        TimesRange(0..r.end + 1)
1582    }
1583}
1584
1585#[derive(PartialEq)]
1586#[doc(hidden)]
1587pub enum ExpectedCalls {
1588    Satisfied,
1589    TooMany,
1590    TooFew,
1591}
1592
1593#[derive(Debug, Default)]
1594#[doc(hidden)]
1595pub struct Times{
1596    /// How many times has the expectation already been called?
1597    count: AtomicUsize,
1598    range: TimesRange
1599}
1600
1601#[doc(hidden)]
1602impl Times {
1603    pub fn call(&self) -> Result<(), String> {
1604        let count = self.count.fetch_add(1, Ordering::Relaxed) + 1;
1605        if count >= self.range.0.end {
1606            if self.range.0.end == 1 {
1607                Err("should not have been called".to_owned())
1608            } else {
1609                Err(format!(
1610                    "called {} times which is more than the expected {}",
1611                    count,
1612                    self.range.0.end - 1
1613                ))
1614            }
1615        } else {
1616            Ok(())
1617        }
1618    }
1619
1620    pub fn any(&mut self) {
1621        self.range.0 = 0..usize::MAX;
1622    }
1623
1624    /// Return how many times this expectation has been called
1625    pub fn count(&self) -> usize {
1626        self.count.load(Ordering::Relaxed)
1627    }
1628
1629    /// Has this expectation already been called the maximum allowed number of
1630    /// times?
1631    pub fn is_done(&self) -> bool {
1632        self.count.load(Ordering::Relaxed) >= self.range.0.end - 1
1633    }
1634
1635    /// Is it required that this expectation be called an exact number of times,
1636    /// or may it be satisfied by a range of call counts?
1637    pub fn is_exact(&self) -> bool {
1638        (self.range.0.end - self.range.0.start) == 1
1639    }
1640
1641    /// Has this expectation already been called the expected number of times?
1642    /// If not, was it too many or too few?
1643    pub fn is_satisfied(&self) -> ExpectedCalls {
1644        let satisfied_lower_bound = self.count.load(Ordering::Relaxed) >= self.range.0.start;
1645        let satisfied_upper_bound = self.count.load(Ordering::Relaxed) < self.range.0.end;
1646        if satisfied_lower_bound && satisfied_upper_bound {
1647            ExpectedCalls::Satisfied
1648        } else if satisfied_lower_bound {
1649            ExpectedCalls::TooMany
1650        } else {
1651            ExpectedCalls::TooFew
1652        }
1653    }
1654
1655    /// The maximum number of times that this expectation must be called
1656    pub fn maximum(&self) -> usize {
1657        self.range.0.end - 1
1658    }
1659
1660    /// The minimum number of times that this expectation must be called
1661    pub fn minimum(&self) -> usize {
1662        self.range.0.start
1663    }
1664
1665    // https://github.com/rust-lang/rust-clippy/issues/3307
1666    #[allow(clippy::range_plus_one)]
1667    pub fn n(&mut self, n: usize) {
1668        self.range.0 = n..(n+1);
1669    }
1670
1671    pub fn never(&mut self) {
1672        self.range.0 = 0..1;
1673    }
1674
1675    pub fn range(&mut self, range: Range<usize>) {
1676        assert!(range.end > range.start, "Backwards range");
1677        self.range.0 = range;
1678    }
1679
1680    pub fn times<T: Into<TimesRange>>(&mut self, t: T) {
1681        self.range = t.into();
1682    }
1683}
1684
1685/// Non-generic keys to `GenericExpectation` internal storage
1686#[doc(hidden)]
1687#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1688pub struct Key(any::TypeId);
1689
1690#[doc(hidden)]
1691impl Key {
1692    pub fn new<T: 'static + ?Sized>() -> Self {
1693        Key(any::TypeId::of::<T>())
1694    }
1695}
1696
1697/// Associates each `Expectation` with its place(s) in a [`Sequence`].
1698/// 
1699/// A SeqHandle is implicitly in one of five states, depending on the
1700/// `satisfaction_level` within SeqInner:
1701/// 
1702/// 1. *Uncallable*
1703/// 
1704///     If a SeqHandle is in this state, other elements earlier in the sequence
1705///     need to be satisfied first - i.e. by being called a minimum amount of
1706///     times.
1707/// 
1708///     A SeqHandle is in this state if `satisfaction_level` is less than
1709///     `min_seq`.
1710///     
1711/// 2. *Callable*
1712/// 
1713///     Preceding expectation(s) are satisified, and we can progress to the
1714///     current expectation, but preceding expectations may still be called
1715///     further.
1716/// 
1717///     A SeqHandle is in this state if `satisfaction_level` is greater than
1718///     or equal to `min_seq`, but less than `seq`.
1719/// 
1720/// 3. *Called*
1721/// 
1722///     The method has been called, and preceding expectations may no longer be
1723///     called. Doing so would constitute an sequence ordering violation.
1724///     However, the current count has not been satisfied yet, and the next
1725///     element in sequence is not allowed to be called.
1726/// 
1727///     A SeqHandle is in this state if `satisfaction_level` is equal to `seq`
1728///     and `has_called_state` is true.
1729/// 
1730///     If this state exists `min_seq` corresponding to the next expectation
1731/// 
1732/// 4. *Satisfied*
1733/// 
1734///     This element in the sequence has had its lower bound satisfied, and the
1735///     next element in sequence is allowed to be called.
1736/// 
1737///     A SeqHandle is in this state if `satisfaction_level` is equal to `seq`
1738///     if `has_called_state` is false, or equal to `seq + 1` if
1739///     `has_called_state` is true.
1740///     If the call count is zero, a SeqHandle is also satisfied once it is
1741///     callable.
1742///
1743///     There is no `is_satisfied` method as the `min_seq` of the next
1744///     expectation(s) are used to check whether this SeqHandle is in the
1745///     satisfied state.
1746/// 
1747/// 5. *History*
1748/// 
1749///     This element can no longer be called, as succeeding elements have been
1750///     performed in the sequence. If a handle is in the history state it can no
1751///     longer be called, and will no longer be called.
1752/// 
1753///     A SeqHandle is in this state if `satisfaction_level` is greater than
1754///     `seq`, or `seq + 1` if `has_called_state` is true.
1755///     
1756#[doc(hidden)]
1757pub struct SeqHandle {
1758    inner: Arc<SeqInner>,
1759    /// An ID counter for every `SeqHandle` associated with the same
1760    /// [`Sequence`].  Starts at 0 and counts upwards.
1761    /// 
1762    /// Identifies the `satisfaction_level` at which the corresponding
1763    /// expectation may still be used, but preceding elements may not.
1764    /// 
1765    /// If `has_called_state` is true, `satisfaction_level = seq` identifies
1766    /// the state in which the expectation has been called, while `seq + 1` 
1767    /// identifies the state in which this expectation is satisfied.
1768    seq: usize,
1769    /// The minimum value the ID must have before the corresponding 
1770    /// `Expectation` may be called.
1771    /// 
1772    /// Within a sequence `min_seq` is used to identify states where preceding
1773    /// expectations are satisfied, and is kept constant if a expectation is
1774    /// always satisfied, i.e., requires zero calls, allowing such expectations
1775    /// to be skipped.
1776    min_seq: usize,
1777    /// Whether this `SeqHandle` differentiates between being called and
1778    /// satisfied. A call count of Zero is already satisfied, and
1779    /// state 3, Called, is always skipped. Similarly, once called, expecations
1780    /// with a minimum call count of one are also satisfied.
1781    /// 
1782    /// This flag is is also used to destinguish between state 2, Callable, and
1783    /// state 4, Satisfied, in the case of the first expectation having a
1784    /// minimum call count of one, as this expectation is not satisfied at
1785    /// initialization.
1786    has_called_state: bool,
1787}
1788
1789impl SeqHandle {
1790    /// Tell the Sequence that this expectation has been used.
1791    pub fn called(&self) {
1792        self.inner.called(self.seq, self.min_seq, self.has_called_state);
1793    }
1794
1795    /// Tell the Sequence that this expectation has been fully satisfied
1796    pub fn satisfy(&self) {
1797        self.inner.satisfy(self.seq, self.min_seq, self.has_called_state);
1798    }
1799
1800    /// Verify that this handle was called in the correct order
1801    pub fn verify<F: Fn() -> String>(&self, desc: F) {
1802        self.inner.verify(self.seq, self.min_seq, self.has_called_state, desc);
1803    }
1804
1805    /// Check whether the current handle is part of history (i.e. has been 
1806    /// skipped or has already taken place)
1807    pub fn is_history(&self) -> bool {
1808        self.inner.is_history(self.seq, self.has_called_state)
1809    }
1810}
1811
1812#[derive(Default)]
1813struct SeqInner {
1814    /// Should match the `seq` field of the next [`SeqHandle`] that has not been
1815    /// fully satisfied.
1816    satisfaction_level: AtomicUsize,
1817}
1818
1819impl SeqInner {
1820    /// Record the call identified by `seq` as being called once.
1821    fn called(&self, seq: usize, min_seq: usize, has_called_state: bool) {
1822        let old_sl = self.satisfaction_level.fetch_max(
1823            seq,
1824            Ordering::Relaxed);
1825        assert!(old_sl >= min_seq,
1826            "Method sequence violation.  Method was called without preceding methods having been satisfied.");
1827        assert!(old_sl <= seq + if has_called_state { 1 } else { 0 } ,
1828            "Method sequence violation.  Method was called while succeeding methods have been called.");
1829    }
1830
1831    /// Record the call identified by `seq` as fully satisfied.
1832    fn satisfy(&self, seq: usize, min_seq: usize, has_called_state: bool) {
1833        // Record that the SeqHandle identified by `seq` has been fully
1834        // satisfied.  It is an error if some previous `SeqHandle` wasn't
1835        // already satisfied.
1836        let old_sl = self.satisfaction_level.fetch_max(
1837            seq + if has_called_state { 1 } else { 0 },
1838            Ordering::Relaxed);
1839        assert!(old_sl >= min_seq,
1840            "Method sequence violation.  Method was called without preceding methods having been satisfied.");
1841        assert!(old_sl <= seq + if has_called_state { 1 } else { 0 } ,
1842            "Method sequence violation.  Method was called while succeeding methods have been called.");
1843    }
1844
1845    /// Verify that the call identified by `seq` was called in the correct order
1846    fn verify<F: Fn() -> String>(
1847        &self,
1848        seq: usize,
1849        min_seq: usize,
1850        has_called_state: bool,
1851        desc: F)
1852    {
1853        let current_level = self.satisfaction_level.load(
1854            Ordering::Relaxed);
1855        let max_seq = seq + if has_called_state { 1 } else { 0 };
1856        
1857        assert!(current_level >= min_seq,
1858            "{}: Method sequence violation", &desc());
1859        assert!(current_level <= max_seq,
1860            "{}: Method sequence violation", &desc());
1861    }
1862
1863    fn is_history(&self, seq: usize, has_called_state: bool) -> bool {
1864        let current_level = self.satisfaction_level.load(
1865            Ordering::Relaxed);
1866        let max_seq = seq + if has_called_state { 1 } else { 0 };
1867
1868        current_level > max_seq
1869    }
1870}
1871
1872/// Used to enforce that mock calls must happen in the sequence specified.
1873/// 
1874/// Sequences are performed greedily, and will try to use the earliest possible
1875/// match.
1876///
1877/// # Examples
1878/// ```
1879/// # use mockall::*;
1880/// #[automock]
1881/// trait Foo {
1882///     fn foo(&self);
1883///     fn bar(&self) -> u32;
1884/// }
1885/// let mut seq = Sequence::new();
1886///
1887/// let mut mock0 = MockFoo::new();
1888/// let mut mock1 = MockFoo::new();
1889///
1890/// mock0.expect_foo()
1891///     .times(1)
1892///     .returning(|| ())
1893///     .in_sequence(&mut seq);
1894///
1895/// mock1.expect_bar()
1896///     .times(1)
1897///     .returning(|| 42)
1898///     .in_sequence(&mut seq);
1899///
1900/// mock0.foo();
1901/// mock1.bar();
1902/// ```
1903/// 
1904/// The count is allowed to vary.
1905/// ```
1906/// # use mockall::*;
1907/// #[automock]
1908/// trait Foo {
1909///     fn foo(&self);
1910///     fn bar(&self) -> u32;
1911/// }
1912/// let mut seq = Sequence::new();
1913///
1914/// let mut mock0 = MockFoo::new();
1915/// let mut mock1 = MockFoo::new();
1916///
1917/// mock0.expect_foo()
1918///     .times(1..4)
1919///     .returning(|| ())
1920///     .in_sequence(&mut seq);
1921///
1922/// mock1.expect_bar()
1923///     .times(1)
1924///     .returning(|| 42)
1925///     .in_sequence(&mut seq);
1926///
1927/// mock0.foo();
1928/// mock0.foo();
1929/// mock1.bar();
1930/// ```
1931/// 
1932/// But, the previous count must be satisfied before a sequence may make
1933/// progress.
1934/// ```should_panic
1935/// # use mockall::*;
1936/// #[automock]
1937/// trait Foo {
1938///     fn foo(&self);
1939///     fn bar(&self) -> u32;
1940/// }
1941/// let mut seq = Sequence::new();
1942///
1943/// let mut mock0 = MockFoo::new();
1944/// let mut mock1 = MockFoo::new();
1945///
1946/// mock0.expect_foo()
1947///     .times(3..5)
1948///     .returning(|| ())
1949///     .in_sequence(&mut seq);
1950///
1951/// mock1.expect_bar()
1952///     .times(1)
1953///     .returning(|| 42)
1954///     .in_sequence(&mut seq);
1955///
1956/// mock0.foo();
1957/// mock0.foo();
1958/// mock1.bar();
1959/// ```
1960/// 
1961/// Furthermore, sequences are greedy, and will only perform the earliest
1962/// element in sequence that is allowed. This results in the following example
1963/// failing the second expectation, as the first expectation is used for both
1964/// calls to `foo`.
1965/// 
1966/// The following example fails as the first expection handles all calls,
1967/// leaving none for the second expectation. As the second expectation goes
1968/// unused, while it is expected to be called at least once, the test panics
1969/// with
1970/// `MockFoo::foo: Expectation(<anything>) called 0 time(s) which is fewer than
1971/// expected 1`.
1972/// 
1973/// ```should_panic
1974/// # use mockall::*;
1975/// #[automock]
1976/// trait Foo {
1977///     fn foo(&self);
1978///     fn bar(&self) -> u32;
1979/// }
1980/// let mut seq = Sequence::new();
1981///
1982/// let mut mock0 = MockFoo::new();
1983///
1984/// mock0.expect_foo()
1985///     .returning(|| ())
1986///     .in_sequence(&mut seq);
1987///
1988/// mock0.expect_foo()
1989///     .times(1..)
1990///     .returning(|| ())
1991///     .in_sequence(&mut seq);
1992///
1993/// mock0.foo();
1994/// mock0.foo();
1995/// ```
1996/// 
1997#[derive(Default)]
1998pub struct Sequence {
1999    inner: Arc<SeqInner>,
2000    /// Counter to use for the next SeqHandle associated with this Sequence
2001    next_seq: usize,
2002    next_min_seq: usize,
2003}
2004
2005/// Indicates whether the minimum call count is zero, one or more.
2006/// 
2007/// Used to ensure the handle count is incremented accordingly.
2008#[doc(hidden)]
2009pub enum MinimumCallCount {
2010    /// Method may never be called
2011    Zero,
2012    /// Method has to be called at least once
2013    One,
2014    /// Method has to be called more than once
2015    More
2016}
2017
2018/// Infer what the minimum call count is
2019#[doc(hidden)]
2020pub fn times_to_minimum_call_count(times: &Times) -> MinimumCallCount {
2021    match times.minimum() {
2022        0 => MinimumCallCount::Zero,
2023        1 => MinimumCallCount::One,
2024        _ => MinimumCallCount::More,
2025    }
2026}
2027
2028impl Sequence {
2029    /// Create a new empty [`Sequence`]
2030    pub fn new() -> Self {
2031        Self::default()
2032    }
2033
2034    /// Not for public consumption, but it must be public so the generated code
2035    /// can call it.
2036    #[doc(hidden)]
2037    pub fn next_handle(
2038        &mut self,
2039        minimum_call_count: MinimumCallCount
2040    ) -> SeqHandle
2041    {
2042        let has_called_state = match minimum_call_count {
2043            // Is satisfied from the get-go, and does not need to differentiate
2044            // between being called and satisfied.
2045            MinimumCallCount::Zero => false,
2046            // Need to differentiate between callable and satisfied if this
2047            // is the first `[Expectation]` in a sequence. As it has to be
2048            // called in order to be satisfied.
2049            // For any later `[Expectation]`s the this initial callable state
2050            // can be reused from the preceding  `[Expectation]`, because as
2051            // soon as it is called, it is also satisfied.
2052            MinimumCallCount::One if self.next_seq != 0 => false,
2053            // If the count is two or more, after a single call the SeqHandle
2054            // is in the called (but not satisfied) state.
2055            _ => true,
2056        };
2057
2058        let handle = SeqHandle {
2059            inner: self.inner.clone(),
2060            seq: self.next_seq,
2061            min_seq: self.next_min_seq,
2062            has_called_state
2063        };
2064
2065        match minimum_call_count {
2066            MinimumCallCount::Zero => {
2067                // We don't update min_seq, as this `[Expectation]` can be
2068                // skipped.
2069                // Furthermore, as the call count can never be too low, only
2070                // a Satisfied state is necessary for this handle.
2071                self.next_seq += 1;
2072            },
2073            MinimumCallCount::One if self.next_seq != 0 => {
2074                // We need to be in at least state next_seq to ensure this
2075                // handle has been performed at least once.
2076                self.next_min_seq = self.next_seq;
2077                // Only need to have a (4) Satisfied state for this handle,
2078                // as (3) Called does not occur.
2079                self.next_seq += 1;
2080            },
2081            // MinimumCallCount::More, or MinimumCallCount::One for the very
2082            // first element in sequence.
2083            _ => {
2084                // We need to be in at least state next_seq to ensure this
2085                // handle has been performed at least once.
2086                self.next_min_seq = self.next_seq + 1;
2087                // next_seq is (3) Called for the current handle, next_seq + 1
2088                // represents (4) Satisified.
2089                self.next_seq += 2;
2090            },
2091        }
2092        handle
2093    }
2094}