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//! * [`Methods with generic lifetimes`](#methods-with-generic-lifetimes)
41//! * [`Generic traits and structs`](#generic-traits-and-structs)
42//! * [`Associated types`](#associated-types-1)
43//! * [`Multiple and inherited traits`](#multiple-and-inherited-traits)
44//! * [`External traits`](#external-traits)
45//! * [`Static methods`](#static-methods)
46//! * [`Modules`](#modules)
47//! * [`Foreign functions`](#foreign-functions)
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: &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(expected = "Method sequence violation")
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/latest/mockall_double) 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, see [`mock!`]
671//! instead.
672//!
673//! ## Generic methods
674//!
675//! Generic methods can be mocked, too. Effectively each generic method is an
676//! infinite set of regular methods, and each of those works just like any other
677//! regular method. The expect_* method is generic, too, and usually must be
678//! called with a turbofish. The only restrictions on mocking generic methods
679//! are that all generic parameters must be `'static`, and generic lifetime
680//! parameters are not allowed.
681//!
682//! ```
683//! # use mockall::*;
684//! #[automock]
685//! trait Foo {
686//! fn foo<T: 'static>(&self, t: T) -> i32;
687//! }
688//!
689//! let mut mock = MockFoo::new();
690//! mock.expect_foo::<i16>()
691//! .returning(|t| i32::from(t));
692//! mock.expect_foo::<i8>()
693//! .returning(|t| -i32::from(t));
694//!
695//! assert_eq!(5, mock.foo(5i16));
696//! assert_eq!(-5, mock.foo(5i8));
697//! ```
698//!
699//! ## Methods with generic lifetimes
700//!
701//! A method with a lifetime parameter is technically a generic method, but
702//! Mockall treats it like a non-generic method that must work for all possible
703//! lifetimes. Mocking such a method is similar to mocking a non-generic
704//! method, with a few additional restrictions. One restriction is that you
705//! can't match calls with `with`, you must use `withf` instead. Another is
706//! that the generic lifetime may not appear as part of the return type.
707//! Finally, no method may have both generic lifetime parameters *and* generic
708//! type parameters.
709//!
710//! ```
711//! # use mockall::*;
712//! struct X<'a>(&'a i32);
713//!
714//! #[automock]
715//! trait Foo {
716//! fn foo<'a>(&self, x: X<'a>) -> i32;
717//! }
718//!
719//! # fn main() {
720//! let mut mock = MockFoo::new();
721//! mock.expect_foo()
722//! .withf(|f| *f.0 == 5)
723//! .return_const(42);
724//! let x = X(&5);
725//! assert_eq!(42, mock.foo(x));
726//! # }
727//! ```
728//!
729//! ## Generic traits and structs
730//!
731//! Mocking generic structs and generic traits is not a problem. The mock
732//! struct will be generic, too. The same restrictions apply as with mocking
733//! generic methods: each generic parameter must be `'static`, and generic
734//! lifetime parameters are not allowed.
735//!
736//! ```
737//! # use mockall::*;
738//! #[automock]
739//! trait Foo<T: 'static> {
740//! fn foo(&self, t: T) -> i32;
741//! }
742//!
743//! # fn main() {
744//! let mut mock = MockFoo::<i16>::new();
745//! mock.expect_foo()
746//! .returning(|t| i32::from(t));
747//! assert_eq!(5, mock.foo(5i16));
748//! # }
749//! ```
750//!
751//! ## Associated types
752//!
753//! Traits with associated types can be mocked too. Unlike generic traits, the
754//! mock struct will not be generic. Instead, you must specify the associated
755//! types when defining the mock struct. They're specified as metaitems to the
756//! [`#[automock]`](attr.automock.html) attribute.
757//!
758//! ```
759//! # use mockall::*;
760//! #[automock(type Key=u16; type Value=i32;)]
761//! pub trait A {
762//! type Key;
763//! type Value;
764//! fn foo(&self, k: Self::Key) -> Self::Value;
765//! }
766//!
767//! let mut mock = MockA::new();
768//! mock.expect_foo()
769//! .returning(|x: u16| i32::from(x));
770//! assert_eq!(4, mock.foo(4));
771//! ```
772//!
773//! ## Multiple and inherited traits
774//!
775//! Creating a mock struct that implements multiple traits, whether inherited or
776//! not, requires using the [`mock!`] macro. But once created,
777//! using it is just the same as using any other mock object:
778//!
779//! ```
780//! # use mockall::*;
781//! pub trait A {
782//! fn foo(&self);
783//! }
784//!
785//! pub trait B: A {
786//! fn bar(&self);
787//! }
788//!
789//! mock! {
790//! // Structure to mock
791//! C {}
792//! // First trait to implement on C
793//! impl A for C {
794//! fn foo(&self);
795//! }
796//! // Second trait to implement on C
797//! impl B for C {
798//! fn bar(&self);
799//! }
800//! }
801//! # fn main() {
802//! let mut mock = MockC::new();
803//! mock.expect_foo().returning(|| ());
804//! mock.expect_bar().returning(|| ());
805//! mock.foo();
806//! mock.bar();
807//! # }
808//! ```
809//!
810//! ## External traits
811//!
812//! Mockall can mock traits and structs defined in external crates that are
813//! beyond your control, but you must use [`mock!`] instead of
814//! [`#[automock]`](attr.automock.html). Mock an external trait like this:
815//!
816//! ```
817//! # use mockall::*;
818//! mock! {
819//! MyStruct {} // Name of the mock struct, less the "Mock" prefix
820//! impl Clone for MyStruct { // specification of the trait to mock
821//! fn clone(&self) -> Self;
822//! }
823//! }
824//!
825//! # fn main() {
826//! let mut mock1 = MockMyStruct::new();
827//! let mock2 = MockMyStruct::new();
828//! mock1.expect_clone()
829//! .return_once(move || mock2);
830//! let cloned = mock1.clone();
831//! # }
832//! ```
833//!
834//! ## Static methods
835//!
836//! Mockall can also mock static methods. But be careful! The expectations are
837//! global. If you want to use a static method in multiple tests, you must
838//! provide your own synchronization. For ordinary methods, expectations are
839//! set on the mock object. But static methods don't have any mock object.
840//! Instead, you must create a `Context` object just to set their expectations.
841//!
842//! ```
843//! # use mockall::*;
844//! #[automock]
845//! pub trait A {
846//! fn foo() -> u32;
847//! }
848//!
849//! let ctx = MockA::foo_context();
850//! ctx.expect().returning(|| 99);
851//! assert_eq!(99, MockA::foo());
852//! ```
853//!
854//! A common pattern is mocking a trait with a constructor method. In this case,
855//! you can easily set the mock constructor method to return a mock object.
856//!
857//! ```
858//! # use mockall::*;
859//! struct Foo{}
860//! #[automock]
861//! impl Foo {
862//! fn from_i32(x: i32) -> Self {
863//! // ...
864//! # unimplemented!()
865//! }
866//! fn foo(&self) -> i32 {
867//! // ...
868//! # unimplemented!()
869//! }
870//! }
871//!
872//! # fn main() {
873//! let ctx = MockFoo::from_i32_context();
874//! ctx.expect()
875//! .returning(|x| {
876//! let mut mock = MockFoo::default();
877//! mock.expect_foo()
878//! .return_const(x);
879//! mock
880//! });
881//! let foo = MockFoo::from_i32(42);
882//! assert_eq!(42, foo.foo());
883//! # }
884//! ```
885//!
886//! ### Generic static methods
887//!
888//! Mocking static methods of generic structs or traits, whether or not the
889//! methods themselves are generic, should work seamlessly.
890//!
891//! ```
892//! # use mockall::*;
893//! #[automock]
894//! trait Foo<T: 'static> {
895//! fn new(t: T) -> MockFoo<T>;
896//! }
897//!
898//! # fn main() {
899//! let ctx = MockFoo::<u32>::new_context();
900//! ctx.expect()
901//! .returning(|_| MockFoo::default());
902//! let mock = MockFoo::<u32>::new(42u32);
903//! # }
904//! ```
905//!
906//! ### Context checkpoints
907//!
908//! The context object cleans up all expectations when it leaves scope. It also
909//! has a `checkpoint` method that functions just like a mock object's
910//! `checkpoint` method.
911//!
912//! ```should_panic
913//! # use mockall::*;
914//! #[automock]
915//! pub trait A {
916//! fn foo() -> u32;
917//! }
918//!
919//! let ctx = MockA::foo_context();
920//! ctx.expect()
921//! .times(1)
922//! .returning(|| 99);
923//! ctx.checkpoint(); // Panics!
924//! ```
925//!
926//! A mock object's checkpoint method does *not* checkpoint static methods.
927//! This behavior is useful when using multiple mock objects at once. For
928//! example:
929//!
930//! ```
931//! # use mockall::*;
932//! #[automock]
933//! pub trait A {
934//! fn build() -> Self;
935//! fn bar(&self) -> i32;
936//! }
937//!
938//! # fn main() {
939//! let ctx = MockA::build_context();
940//! ctx.expect()
941//! .times(2)
942//! .returning(|| MockA::default());
943//! let mut mock0 = MockA::build();
944//! mock0.expect_bar().return_const(4);
945//! mock0.bar();
946//! mock0.checkpoint(); // Does not checkpoint the build method
947//! let mock1 = MockA::build();
948//! # }
949//! ```
950//!
951//! One more thing: Mockall normally creates a zero-argument `new` method for
952//! every mock struct. But it *won't* do that when mocking a struct that
953//! already has a method named `new`.
954//!
955//! ## Modules
956//!
957//! In addition to mocking types, Mockall can also derive mocks for
958//! entire modules of Rust functions. Mockall will generate a new module named
959//! "mock_xxx", if "xxx" is the original module's name. You can also use
960//! `#[double]` to selectively import the mock module.
961//!
962//! ```
963//! # use mockall::*;
964//! # use mockall_double::*;
965//! mod outer {
966//! use mockall::automock;
967//! #[automock()]
968//! pub(super) mod inner {
969//! pub fn bar(x: u32) -> i64 {
970//! // ...
971//! # 4
972//! }
973//! }
974//! }
975//!
976//! #[double]
977//! use outer::inner;
978//!
979//! #[cfg(test)]
980//! mod t {
981//! use super::*;
982//!
983//! #[test]
984//! fn test_foo_bar() {
985//! let ctx = inner::bar_context();
986//! ctx.expect()
987//! .returning(|x| i64::from(x + 1));
988//! assert_eq!(5, inner::bar(4));
989//! }
990//! }
991//! # fn main() {}
992//! ```
993//!
994//! ### Foreign functions
995//!
996//! One reason to mock modules is when working with foreign functions. Modules
997//! may contain foreign functions, even though structs and traits may not. Like
998//! static methods, the expectations are global.
999//!
1000//! ```
1001//! # use mockall_double::*;
1002//! mod outer {
1003//! # use mockall::*;
1004//! #[automock]
1005//! pub mod ffi {
1006//! extern "C" {
1007//! pub fn foo(x: u32) -> i64;
1008//! }
1009//! }
1010//! }
1011//!
1012//! #[double]
1013//! use outer::ffi;
1014//!
1015//! fn do_stuff() -> i64 {
1016//! unsafe{ ffi::foo(42) }
1017//! }
1018//!
1019//! #[cfg(test)]
1020//! mod t {
1021//! use super::*;
1022//!
1023//! #[test]
1024//! fn test_foo() {
1025//! let ctx = ffi::foo_context();
1026//! ctx.expect()
1027//! .returning(|x| i64::from(x + 1));
1028//! assert_eq!(43, do_stuff());
1029//! }
1030//! }
1031//! # fn main() {}
1032//! ```
1033//!
1034//! ## Async Traits
1035//!
1036//! Async traits aren't yet (as of 1.47.0) a part of the Rust language. But
1037//! they're available from the
1038//! [`async_trait`](https://docs.rs/async-trait/0.1.38/async_trait/) crate.
1039//! Mockall is compatible with this crate, with two important limitations:
1040//!
1041//! * The `#[automock]` attribute must appear _before_ the `#[async_trait]`
1042//! attribute.
1043//!
1044//! * The `#[async_trait]` macro must be imported with its canonical name.
1045//!
1046//! ```
1047//! # use async_trait::async_trait;
1048//! # use mockall::*;
1049//! // async_trait works with both #[automock]
1050//! #[automock]
1051//! #[async_trait]
1052//! pub trait Foo {
1053//! async fn foo(&self) -> u32;
1054//! }
1055//! // and mock!
1056//! mock! {
1057//! pub Bar {}
1058//! #[async_trait]
1059//! impl Foo for Bar {
1060//! async fn foo(&self) -> u32;
1061//! }
1062//! }
1063//! # fn main() {}
1064//! ```
1065//!
1066//! ## Crate features
1067//!
1068//! Mockall has a **nightly** feature. Currently this feature has three
1069//! effects:
1070//!
1071//! * The compiler will produce better error messages.
1072//!
1073//! * Mocking modules will be enabled.
1074//!
1075//! * Expectations for methods whose return type implements `Default` needn't
1076//! have their return values explicitly set. Instead, they will automatically
1077//! return the default value.
1078//!
1079//! With **nightly** enabled, you can omit the return value like this:
1080#![cfg_attr(feature = "nightly", doc = "```")]
1081#![cfg_attr(not(feature = "nightly"), doc = "```should_panic")]
1082//! # use mockall::*;
1083//! #[automock]
1084//! trait Foo {
1085//! fn foo(&self) -> Vec<u32>;
1086//! }
1087//!
1088//! let mut mock = MockFoo::new();
1089//! mock.expect_foo();
1090//! assert!(mock.foo().is_empty());
1091//! ```
1092//!
1093//! ## Examples
1094//!
1095//! For additional examples of Mockall in action, including detailed
1096//! documentation on the autogenerated methods, see
1097//! [`examples`](examples).
1098//!
1099//! [`Predicate`]: trait.Predicate.html
1100//! [`Sequence`]: Sequence
1101//! [`cfg-if`]: https://crates.io/crates/cfg-if
1102//! [`function`]: predicate/fn.function.html
1103//! [`mock!`]: macro.mock.html
1104//! [`predicate`]: predicate/index.html
1105
1106#![cfg_attr(feature = "nightly", feature(specialization))]
1107// Allow the incomplete_feature warning for specialization. We know it's
1108// incomplete; that's why it's guarded by the "nightly" feature.
1109#![cfg_attr(feature = "nightly", allow(incomplete_features))]
1110
1111#![cfg_attr(feature = "nightly", feature(doc_cfg))]
1112#![cfg_attr(test, deny(warnings))]
1113
1114use downcast::*;
1115use std::{
1116 any,
1117 marker::PhantomData,
1118 ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
1119 RangeToInclusive},
1120 sync::{
1121 Arc,
1122 atomic::{AtomicUsize, Ordering}
1123 },
1124};
1125
1126#[doc(hidden)]
1127pub use downcast::{Any, Downcast};
1128#[doc(hidden)]
1129pub use fragile::Fragile;
1130
1131/// For mocking static methods
1132#[doc(hidden)]
1133pub use lazy_static::lazy_static;
1134
1135pub use predicates::{
1136 boolean::PredicateBooleanExt,
1137 prelude::{
1138 Predicate, PredicateBoxExt, PredicateFileContentExt, PredicateStrExt,
1139 predicate
1140 }
1141};
1142#[doc(hidden)]
1143pub use predicates_tree::CaseTreeExt;
1144
1145#[cfg(doc)]
1146extern crate self as mockall;
1147#[cfg(doc)]
1148pub mod examples;
1149
1150/// Automatically generate mock types for structs and traits.
1151///
1152/// This is by far the easiest way to use Mockall. It works on almost all
1153/// traits, and almost all structs that have a single `impl` block. In either
1154/// case, it will generate a mock struct whose name is the name of the mocked
1155/// struct/trait prepended with "Mock". For each method of the original, the
1156/// mock struct will have a method named `expect_whatever` that allows you to
1157/// set expectations. There will also be one `checkpoint` method that calls
1158/// [`checkpoint`] for every single mocked method.
1159///
1160/// # Examples
1161///
1162/// The simplest use case is mocking a no-frills trait
1163/// ```
1164/// # use mockall_derive::*;
1165/// #[automock]
1166/// pub trait Foo {
1167/// fn foo(&self, key: i16);
1168/// }
1169///
1170/// let mock = MockFoo::new();
1171/// ```
1172///
1173/// Mocking a structure:
1174/// ```
1175/// # use mockall_derive::*;
1176/// struct Foo {}
1177/// #[automock]
1178/// impl Foo {
1179/// fn foo(&self) -> u32 {
1180/// // ...
1181/// # unimplemented!()
1182/// }
1183/// }
1184/// ```
1185///
1186/// You can also mock a trait impl on a struct:
1187/// ```
1188/// # use mockall_derive::*;
1189/// pub trait Foo {
1190/// fn foo(&self, key: i16);
1191/// }
1192/// struct Bar{}
1193/// #[automock]
1194/// impl Foo for Bar {
1195/// fn foo(&self, key: i16){
1196/// // ...
1197/// # unimplemented!()
1198/// }
1199/// }
1200///
1201/// let mock = MockBar::new();
1202/// ```
1203///
1204/// Mocking a trait with associated types requires adding a metaitem to the
1205/// attribute:
1206/// ```
1207/// # use mockall_derive::*;
1208/// #[automock(type Item=u32;)]
1209/// trait Foo {
1210/// type Item;
1211/// fn foo(&self) -> Self::Item;
1212/// }
1213/// ```
1214///
1215/// Finally, `#[automock]` can also mock foreign functions. This requires
1216/// another metaitem to specify the mock module name.
1217///
1218/// ```
1219/// # use mockall_derive::*;
1220/// #[automock(mod mock_ffi;)]
1221/// extern "C" {
1222/// pub fn foo() -> u32;
1223/// }
1224/// ```
1225///
1226/// [`checkpoint`]: ../mockall/index.html#checkpoints
1227///
1228/// # Limitations
1229///
1230/// `#[automock]` can't handle everything. There are some cases where
1231/// you will need to use [`mock`] instead:
1232/// * Mocking a struct that has multiple `impl` blocks, including
1233/// structs that implement traits.
1234/// * Mocking a struct or trait defined in another crate.
1235/// * Mocking a trait with trait bounds.
1236/// * If the autogenerated "MockFoo" name isn't acceptable, and you want
1237/// to choose your own name for the mock structure.
1238pub use mockall_derive::automock;
1239
1240/// Manually mock a structure.
1241///
1242/// Sometimes `automock` can't be used. In those cases you can use `mock!`,
1243/// which basically involves repeating the struct's or trait's definitions.
1244///
1245/// The format is:
1246///
1247/// * Optional visibility specifier
1248/// * Real structure name and generics fields
1249/// * 0 or more methods of the structure, written without bodies, enclosed in a
1250/// {} block
1251/// * 0 or more impl blocks implementing traits on the structure, also without
1252/// bodies.
1253///
1254/// # Examples
1255///
1256/// Mock a trait. This is the simplest use case.
1257/// ```
1258/// # use mockall_derive::mock;
1259/// trait Foo {
1260/// fn foo(&self, x: u32);
1261/// }
1262/// mock!{
1263/// pub MyStruct<T: Clone + 'static> {
1264/// fn bar(&self) -> u8;
1265/// }
1266/// impl Foo for MyStruct {
1267/// fn foo(&self, x: u32);
1268/// }
1269/// }
1270/// # fn main() {}
1271/// ```
1272///
1273/// When mocking a generic struct's implementation of a generic trait, use the
1274/// same namespace for their generic parameters. For example, if you wanted to
1275/// mock `Rc`, do
1276/// ```
1277/// # use mockall_derive::mock;
1278/// mock!{
1279/// pub Rc<T: 'static> {}
1280/// impl<T: 'static> AsRef<T> for Rc<T> {
1281/// fn as_ref(&self) -> &T;
1282/// }
1283/// }
1284/// # fn main() {}
1285/// ```
1286/// *not*
1287/// ```compile_fail
1288/// # use mockall_derive::mock;
1289/// mock!{
1290/// pub Rc<Q: 'static> {}
1291/// impl<T: 'static> AsRef<T> for Rc<T> {
1292/// fn as_ref(&self) -> &T;
1293/// }
1294/// }
1295/// # fn main() {}
1296/// ```
1297/// Associated types can easily be mocked by specifying a concrete type in the
1298/// `mock!{}` invocation.
1299/// ```
1300/// # use mockall_derive::mock;
1301/// mock!{
1302/// MyIter {}
1303/// impl Iterator for MyIter {
1304/// type Item=u32;
1305///
1306/// fn next(&mut self) -> Option<<Self as Iterator>::Item>;
1307/// }
1308/// }
1309/// # fn main() {}
1310/// ```
1311pub use mockall_derive::mock;
1312
1313#[doc(hidden)]
1314pub trait AnyExpectations : Any + Send + Sync {}
1315downcast!(dyn AnyExpectations);
1316
1317#[doc(hidden)]
1318pub trait ReturnDefault<O> {
1319 fn maybe_return_default() -> Option<O>;
1320 fn return_default() -> Result<O, &'static str>;
1321}
1322
1323#[derive(Default)]
1324#[doc(hidden)]
1325pub struct DefaultReturner<O>(PhantomData<O>);
1326
1327::cfg_if::cfg_if! {
1328 if #[cfg(feature = "nightly")] {
1329 impl<O> ReturnDefault<O> for DefaultReturner<O> {
1330 default fn maybe_return_default() -> Option<O> {
1331 None
1332 }
1333
1334 default fn return_default() -> Result<O, &'static str> {
1335 Err("Can only return default values for types that impl std::Default")
1336 }
1337 }
1338
1339 impl<O: Default> ReturnDefault<O> for DefaultReturner<O> {
1340 fn maybe_return_default() -> Option<O> {
1341 Some(O::default())
1342 }
1343
1344 fn return_default() -> Result<O, &'static str> {
1345 Ok(O::default())
1346 }
1347 }
1348 } else {
1349 impl<O> ReturnDefault<O> for DefaultReturner<O> {
1350 fn maybe_return_default() -> Option<O> {
1351 None
1352 }
1353
1354 fn return_default() -> Result<O, &'static str> {
1355 Err("Returning default values requires the \"nightly\" feature")
1356 }
1357 }
1358 }
1359}
1360
1361// Though it's not entirely correct, we treat usize::max_value() as
1362// approximately infinity.
1363#[derive(Debug)]
1364#[doc(hidden)]
1365pub struct TimesRange(Range<usize>);
1366
1367impl Default for TimesRange {
1368 fn default() -> TimesRange {
1369 // By default, allow any number of calls
1370 TimesRange(0..usize::max_value())
1371 }
1372}
1373
1374impl From<usize> for TimesRange {
1375 fn from(n: usize) -> TimesRange {
1376 TimesRange(n..(n+1))
1377 }
1378}
1379
1380impl From<Range<usize>> for TimesRange {
1381 fn from(r: Range<usize>) -> TimesRange {
1382 assert!(r.end > r.start, "Backwards range");
1383 TimesRange(r)
1384 }
1385}
1386
1387impl From<RangeFrom<usize>> for TimesRange {
1388 fn from(r: RangeFrom<usize>) -> TimesRange {
1389 TimesRange(r.start..usize::max_value())
1390 }
1391}
1392
1393impl From<RangeFull> for TimesRange {
1394 fn from(_: RangeFull) -> TimesRange {
1395 TimesRange(0..usize::max_value())
1396 }
1397}
1398
1399impl From<RangeInclusive<usize>> for TimesRange {
1400 fn from(r: RangeInclusive<usize>) -> TimesRange {
1401 assert!(r.end() >= r.start(), "Backwards range");
1402 TimesRange(*r.start()..*r.end() + 1)
1403 }
1404}
1405
1406impl From<RangeTo<usize>> for TimesRange {
1407 fn from(r: RangeTo<usize>) -> TimesRange {
1408 TimesRange(0..r.end)
1409 }
1410}
1411
1412impl From<RangeToInclusive<usize>> for TimesRange {
1413 fn from(r: RangeToInclusive<usize>) -> TimesRange {
1414 TimesRange(0..r.end + 1)
1415 }
1416}
1417
1418#[derive(Debug, Default)]
1419#[doc(hidden)]
1420pub struct Times{
1421 /// How many times has the expectation already been called?
1422 count: AtomicUsize,
1423 range: TimesRange
1424}
1425
1426impl Times {
1427 pub fn call(&self) -> Result<(), String> {
1428 let count = self.count.fetch_add(1, Ordering::Relaxed) + 1;
1429 if count >= self.range.0.end {
1430 if self.range.0.end == 1 {
1431 Err("should not have been called".to_owned())
1432 } else {
1433 Err(format!("called more than {} times", self.range.0.end - 1))
1434 }
1435 } else {
1436 Ok(())
1437 }
1438 }
1439
1440 pub fn any(&mut self) {
1441 self.range.0 = 0..usize::max_value();
1442 }
1443
1444 /// Has this expectation already been called the maximum allowed number of
1445 /// times?
1446 pub fn is_done(&self) -> bool {
1447 self.count.load(Ordering::Relaxed) >= self.range.0.end - 1
1448 }
1449
1450 /// Is it required that this expectation be called an exact number of times,
1451 /// or may it be satisfied by a range of call counts?
1452 pub fn is_exact(&self) -> bool {
1453 (self.range.0.end - self.range.0.start) == 1
1454 }
1455
1456 /// Has this expectation already been called the minimum required number of
1457 /// times?
1458 pub fn is_satisfied(&self) -> bool {
1459 self.count.load(Ordering::Relaxed) >= self.range.0.start
1460 }
1461
1462 /// The minimum number of times that this expectation must be called
1463 pub fn minimum(&self) -> usize {
1464 self.range.0.start
1465 }
1466
1467 // https://github.com/rust-lang/rust-clippy/issues/3307
1468 #[allow(clippy::range_plus_one)]
1469 pub fn n(&mut self, n: usize) {
1470 self.range.0 = n..(n+1);
1471 }
1472
1473 pub fn never(&mut self) {
1474 self.range.0 = 0..1;
1475 }
1476
1477 pub fn range(&mut self, range: Range<usize>) {
1478 assert!(range.end > range.start, "Backwards range");
1479 self.range.0 = range;
1480 }
1481
1482 pub fn times<T: Into<TimesRange>>(&mut self, t: T) {
1483 self.range = t.into();
1484 }
1485}
1486
1487/// Non-generic keys to `GenericExpectation` internal storage
1488#[doc(hidden)]
1489#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1490pub struct Key(any::TypeId);
1491
1492impl Key {
1493 pub fn new<T: 'static>() -> Self {
1494 Key(any::TypeId::of::<T>())
1495 }
1496}
1497
1498#[doc(hidden)]
1499pub struct SeqHandle {
1500 inner: Arc<SeqInner>,
1501 seq: usize
1502}
1503
1504impl SeqHandle {
1505 /// Tell the Sequence that this expectation has been fully satisfied
1506 pub fn satisfy(&self) {
1507 self.inner.satisfy(self.seq);
1508 }
1509
1510 /// Verify that this handle was called in the correct order
1511 pub fn verify(&self) {
1512 self.inner.verify(self.seq);
1513 }
1514}
1515
1516#[derive(Default)]
1517struct SeqInner {
1518 satisfaction_level: AtomicUsize,
1519}
1520
1521impl SeqInner {
1522 /// Record the call identified by `seq` as fully satisfied.
1523 fn satisfy(&self, seq: usize) {
1524 let old_sl = self.satisfaction_level.fetch_add(1, Ordering::Relaxed);
1525 assert_eq!(old_sl, seq, "Method sequence violation. Was an already-satisfied method called another time?");
1526 }
1527
1528 /// Verify that the call identified by `seq` was called in the correct order
1529 fn verify(&self, seq: usize) {
1530 assert_eq!(seq, self.satisfaction_level.load(Ordering::Relaxed),
1531 "Method sequence violation")
1532 }
1533}
1534
1535/// Used to enforce that mock calls must happen in the sequence specified.
1536///
1537/// Each expectation must expect to be called a fixed number of times. Once
1538/// satisfied, the next expectation in the sequence will expect to be called.
1539///
1540/// # Examples
1541/// ```
1542/// # use mockall::*;
1543/// #[automock]
1544/// trait Foo {
1545/// fn foo(&self);
1546/// fn bar(&self) -> u32;
1547/// }
1548/// let mut seq = Sequence::new();
1549///
1550/// let mut mock0 = MockFoo::new();
1551/// let mut mock1 = MockFoo::new();
1552///
1553/// mock0.expect_foo()
1554/// .times(1)
1555/// .returning(|| ())
1556/// .in_sequence(&mut seq);
1557///
1558/// mock1.expect_bar()
1559/// .times(1)
1560/// .returning(|| 42)
1561/// .in_sequence(&mut seq);
1562///
1563/// mock0.foo();
1564/// mock1.bar();
1565/// ```
1566///
1567/// It is an error to add an expectation to a `Sequence` if its call count is
1568/// unspecified.
1569/// ```should_panic(expected = "with an exact call count")
1570/// # use mockall::*;
1571/// #[automock]
1572/// trait Foo {
1573/// fn foo(&self);
1574/// }
1575/// let mut seq = Sequence::new();
1576///
1577/// let mut mock = MockFoo::new();
1578/// mock.expect_foo()
1579/// .returning(|| ())
1580/// .in_sequence(&mut seq); // panics!
1581/// ```
1582#[derive(Default)]
1583pub struct Sequence {
1584 inner: Arc<SeqInner>,
1585 next_seq: usize,
1586}
1587
1588impl Sequence {
1589 pub fn new() -> Self {
1590 Self::default()
1591 }
1592
1593 /// Not for public consumption, but it must be public so the generated code
1594 /// can call it.
1595 #[doc(hidden)]
1596 pub fn next_handle(&mut self) -> SeqHandle {
1597 let handle = SeqHandle{inner: self.inner.clone(), seq: self.next_seq};
1598 self.next_seq += 1;
1599 handle
1600 }
1601}