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(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_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. The same restrictions apply as with mocking
744 //! generic methods: each generic parameter must be `'static`, and generic
745 //! lifetime parameters are not allowed.
746 //!
747 //! ```
748 //! # use mockall::*;
749 //! #[automock]
750 //! trait Foo<T: 'static> {
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.
903 //!
904 //! ```
905 //! # use mockall::*;
906 //! #[automock]
907 //! trait Foo<T: 'static> {
908 //! fn new(t: T) -> MockFoo<T>;
909 //! }
910 //!
911 //! # fn main() {
912 //! let ctx = MockFoo::<u32>::new_context();
913 //! ctx.expect()
914 //! .returning(|_| MockFoo::default());
915 //! let mock = MockFoo::<u32>::new(42u32);
916 //! # }
917 //! ```
918 //!
919 //! ### Context checkpoints
920 //!
921 //! The context object cleans up all expectations when it leaves scope. It also
922 //! has a `checkpoint` method that functions just like a mock object's
923 //! `checkpoint` method.
924 //!
925 //! ```should_panic
926 //! # use mockall::*;
927 //! #[automock]
928 //! pub trait A {
929 //! fn foo() -> u32;
930 //! }
931 //!
932 //! let ctx = MockA::foo_context();
933 //! ctx.expect()
934 //! .times(1)
935 //! .returning(|| 99);
936 //! ctx.checkpoint(); // Panics!
937 //! ```
938 //!
939 //! A mock object's checkpoint method does *not* checkpoint static methods.
940 //! This behavior is useful when using multiple mock objects at once. For
941 //! example:
942 //!
943 //! ```
944 //! # use mockall::*;
945 //! #[automock]
946 //! pub trait A {
947 //! fn build() -> Self;
948 //! fn bar(&self) -> i32;
949 //! }
950 //!
951 //! # fn main() {
952 //! let ctx = MockA::build_context();
953 //! ctx.expect()
954 //! .times(2)
955 //! .returning(|| MockA::default());
956 //! let mut mock0 = MockA::build();
957 //! mock0.expect_bar().return_const(4);
958 //! mock0.bar();
959 //! mock0.checkpoint(); // Does not checkpoint the build method
960 //! let mock1 = MockA::build();
961 //! # }
962 //! ```
963 //!
964 //! One more thing: Mockall normally creates a zero-argument `new` method for
965 //! every mock struct. But it *won't* do that when mocking a struct that
966 //! already has a method named `new`. The `default` method will still be
967 //! present.
968 //!
969 //! ## Modules
970 //!
971 //! In addition to mocking types, Mockall can also derive mocks for
972 //! entire modules of Rust functions. Mockall will generate a new module named
973 //! "mock_xxx", if "xxx" is the original module's name. You can also use
974 //! `#[double]` to selectively import the mock module.
975 //!
976 //! Be careful! Module functions are static and so have the same caveats as
977 //! [static methods](#static-methods) described above.
978 //!
979 //! ```
980 //! # use mockall::*;
981 //! # use mockall_double::*;
982 //! mod outer {
983 //! use mockall::automock;
984 //! #[automock()]
985 //! pub(super) mod inner {
986 //! pub fn bar(x: u32) -> i64 {
987 //! // ...
988 //! # 4
989 //! }
990 //! }
991 //! }
992 //!
993 //! #[double]
994 //! use outer::inner;
995 //!
996 //! #[cfg(test)]
997 //! mod t {
998 //! use super::*;
999 //!
1000 //! #[test]
1001 //! fn test_foo_bar() {
1002 //! let ctx = inner::bar_context();
1003 //! ctx.expect()
1004 //! .returning(|x| i64::from(x + 1));
1005 //! assert_eq!(5, inner::bar(4));
1006 //! }
1007 //! }
1008 //! # fn main() {}
1009 //! ```
1010 //!
1011 //! ### Foreign functions
1012 //!
1013 //! One reason to mock modules is when working with foreign functions. Modules
1014 //! may contain foreign functions, even though structs and traits may not. Like
1015 //! static methods, the expectations are global.
1016 //!
1017 //! ```
1018 //! # use mockall_double::*;
1019 //! mod outer {
1020 //! # use mockall::*;
1021 //! #[automock]
1022 //! pub mod ffi {
1023 //! extern "C" {
1024 //! pub fn foo(x: u32) -> i64;
1025 //! }
1026 //! }
1027 //! }
1028 //!
1029 //! #[double]
1030 //! use outer::ffi;
1031 //!
1032 //! fn do_stuff() -> i64 {
1033 //! unsafe{ ffi::foo(42) }
1034 //! }
1035 //!
1036 //! #[cfg(test)]
1037 //! mod t {
1038 //! use super::*;
1039 //!
1040 //! #[test]
1041 //! fn test_foo() {
1042 //! let ctx = ffi::foo_context();
1043 //! ctx.expect()
1044 //! .returning(|x| i64::from(x + 1));
1045 //! assert_eq!(43, do_stuff());
1046 //! }
1047 //! }
1048 //! # fn main() {}
1049 //! ```
1050 //!
1051 //! ## Debug
1052 //!
1053 //! `#[automock]` will automatically generate `Debug` impls when mocking traits
1054 //! and struct impls. `mock!` will too, if you add a `#[derive(Debug)]`, like
1055 //! this:
1056 //! ```no_run
1057 //! # use mockall::*;
1058 //! mock! {
1059 //! #[derive(Debug)]
1060 //! pub Foo {}
1061 //! }
1062 //! # fn main() {
1063 //! # format!("{:?}", &MockFoo::default());
1064 //! # }
1065 //! ```
1066 //!
1067 //! ## Async Traits
1068 //!
1069 //! Async traits aren't yet (as of 1.47.0) a part of the Rust language. But
1070 //! they're available from the
1071 //! [`async_trait`](https://docs.rs/async-trait/0.1.38/async_trait/) crate.
1072 //! Mockall is compatible with this crate, with two important limitations:
1073 //!
1074 //! * The `#[automock]` attribute must appear _before_ the `#[async_trait]`
1075 //! attribute.
1076 //!
1077 //! * The `#[async_trait]` macro must be imported with its canonical name.
1078 //!
1079 //! ```
1080 //! # use async_trait::async_trait;
1081 //! # use mockall::*;
1082 //! // async_trait works with both #[automock]
1083 //! #[automock]
1084 //! #[async_trait]
1085 //! pub trait Foo {
1086 //! async fn foo(&self) -> u32;
1087 //! }
1088 //! // and mock!
1089 //! mock! {
1090 //! pub Bar {}
1091 //! #[async_trait]
1092 //! impl Foo for Bar {
1093 //! async fn foo(&self) -> u32;
1094 //! }
1095 //! }
1096 //! # fn main() {}
1097 //! ```
1098 //!
1099 //! ## Crate features
1100 //!
1101 //! Mockall has a **nightly** feature. Currently this feature has two
1102 //! effects:
1103 //!
1104 //! * The compiler will produce better error messages.
1105 //!
1106 //! * Expectations for methods whose return type implements `Default` needn't
1107 //! have their return values explicitly set. Instead, they will automatically
1108 //! return the default value.
1109 //!
1110 //! With **nightly** enabled, you can omit the return value like this:
1111 #![cfg_attr(feature = "nightly", doc = "```")]
1112 #![cfg_attr(not(feature = "nightly"), doc = "```should_panic")]
1113 //! # use mockall::*;
1114 //! #[automock]
1115 //! trait Foo {
1116 //! fn foo(&self) -> Vec<u32>;
1117 //! }
1118 //!
1119 //! let mut mock = MockFoo::new();
1120 //! mock.expect_foo();
1121 //! assert!(mock.foo().is_empty());
1122 //! ```
1123 //!
1124 //! ## Examples
1125 //!
1126 //! For additional examples of Mockall in action, including detailed
1127 //! documentation on the autogenerated methods, see
1128 //! [`examples`](examples).
1129 //!
1130 //! [`Predicate`]: trait.Predicate.html
1131 //! [`Sequence`]: Sequence
1132 //! [`cfg-if`]: https://crates.io/crates/cfg-if
1133 //! [`function`]: predicate/fn.function.html
1134 //! [`mock!`]: macro.mock.html
1135 //! [`predicate`]: predicate/index.html
1136
1137 #![cfg_attr(feature = "nightly", feature(specialization))]
1138 // Allow the incomplete_feature warning for specialization. We know it's
1139 // incomplete; that's why it's guarded by the "nightly" feature.
1140 #![cfg_attr(feature = "nightly", allow(incomplete_features))]
1141
1142 #![cfg_attr(feature = "nightly", feature(doc_cfg))]
1143 #![cfg_attr(test, deny(warnings))]
1144 #![warn(missing_docs)]
1145
1146 use downcast::*;
1147 use std::{
1148 any,
1149 fmt::Debug,
1150 marker::PhantomData,
1151 ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo,
1152 RangeToInclusive},
1153 sync::{
1154 Arc,
1155 atomic::{AtomicUsize, Ordering}
1156 },
1157 };
1158
1159 #[doc(hidden)]
1160 pub use downcast::{Any, Downcast};
1161 #[doc(hidden)]
1162 pub use fragile::Fragile;
1163
1164 /// For mocking static methods
1165 #[doc(hidden)]
1166 pub use lazy_static::lazy_static;
1167
1168 pub use predicates::{
1169 boolean::PredicateBooleanExt,
1170 prelude::{
1171 Predicate, PredicateBoxExt, PredicateFileContentExt, PredicateStrExt,
1172 predicate
1173 }
1174 };
1175 #[doc(hidden)]
1176 pub use predicates_tree::CaseTreeExt;
1177
1178 #[cfg(doc)]
1179 extern crate self as mockall;
1180 #[cfg(doc)]
1181 pub mod examples;
1182
1183 /// Automatically generate mock types for structs and traits.
1184 ///
1185 /// This is by far the easiest way to use Mockall. It works on almost all
1186 /// traits, and almost all structs that have a single `impl` block. In either
1187 /// case, it will generate a mock struct whose name is the name of the mocked
1188 /// struct/trait prepended with "Mock". For each method of the original, the
1189 /// mock struct will have a method named `expect_whatever` that allows you to
1190 /// set expectations. There will also be one `checkpoint` method that calls
1191 /// [`checkpoint`] for every single mocked method.
1192 ///
1193 /// # Examples
1194 ///
1195 /// The simplest use case is mocking a no-frills trait
1196 /// ```
1197 /// # use mockall_derive::*;
1198 /// #[automock]
1199 /// pub trait Foo {
1200 /// fn foo(&self, key: i16);
1201 /// }
1202 ///
1203 /// let mock = MockFoo::new();
1204 /// ```
1205 ///
1206 /// Mocking a structure:
1207 /// ```
1208 /// # use mockall_derive::*;
1209 /// struct Foo {}
1210 /// #[automock]
1211 /// impl Foo {
1212 /// fn foo(&self) -> u32 {
1213 /// // ...
1214 /// # unimplemented!()
1215 /// }
1216 /// }
1217 /// ```
1218 ///
1219 /// You can also mock a trait impl on a struct:
1220 /// ```
1221 /// # use mockall_derive::*;
1222 /// pub trait Foo {
1223 /// fn foo(&self, key: i16);
1224 /// }
1225 /// struct Bar{}
1226 /// #[automock]
1227 /// impl Foo for Bar {
1228 /// fn foo(&self, key: i16){
1229 /// // ...
1230 /// # unimplemented!()
1231 /// }
1232 /// }
1233 ///
1234 /// let mock = MockBar::new();
1235 /// ```
1236 ///
1237 /// Mocking a trait with associated types requires adding a metaitem to the
1238 /// attribute:
1239 /// ```
1240 /// # use mockall_derive::*;
1241 /// #[automock(type Item=u32;)]
1242 /// trait Foo {
1243 /// type Item;
1244 /// fn foo(&self) -> Self::Item;
1245 /// }
1246 /// ```
1247 ///
1248 /// It can mock a module full of functions. In this case, the mock functions
1249 /// will be found in a module whose name is prepended with `mock_`.
1250 ///
1251 /// ```
1252 /// # use mockall_derive::*;
1253 /// #[automock]
1254 /// mod mymod {
1255 /// pub fn foo() -> u32 {
1256 /// // ...
1257 /// # unimplemented!()
1258 /// }
1259 /// }
1260 /// ```
1261 /// Finally, `#[automock]` can also mock foreign functions. This works just
1262 /// like mocking a module.
1263 ///
1264 /// ```
1265 /// # use mockall_derive::*;
1266 /// #[automock]
1267 /// mod ffi {
1268 /// extern "C" {
1269 /// pub fn foo() -> u32;
1270 /// }
1271 /// }
1272 /// ```
1273 ///
1274 /// [`checkpoint`]: ../mockall/index.html#checkpoints
1275 ///
1276 /// # Limitations
1277 ///
1278 /// `#[automock]` can't handle everything. There are some cases where
1279 /// you will need to use [`mock`] instead:
1280 /// * Mocking a struct that has multiple `impl` blocks, including
1281 /// structs that implement traits.
1282 /// * Mocking a struct or trait defined in another crate.
1283 /// * Mocking a trait with trait bounds.
1284 /// * If the autogenerated "MockFoo" name isn't acceptable, and you want
1285 /// to choose your own name for the mock structure.
1286 pub use mockall_derive::automock;
1287
1288 /// Decorates a method or function to tell Mockall to treat its generic arguments
1289 /// as trait objects when creating expectations.
1290 ///
1291 /// This allows users to use non-`'static` generic parameters, which otherwise
1292 /// can't be mocked. The downsides of using this attribute are:
1293 ///
1294 /// * Mockall can't tell if a parameter isn't `'static`, so you must annotate
1295 /// such methods with the `#[mockall::concretize]` attribute.
1296 /// * Generic methods will share expectations for all argument types. That is,
1297 /// you won't be able to do `my_mock.expect_foo::<i32>(...)`.
1298 /// * It can't be used on methods with a closure argument (though this may be
1299 /// fixable).
1300 /// * Concretized methods' expectations may only be matched with `.withf` or
1301 /// `.withf_st`, not `.with`.
1302 /// * It only works for parameters that can be turned into a trait object.
1303 /// (may be fixable).
1304 /// * Mockall needs to know how to turn the function argument into a trait
1305 /// object. Given a generic parameter `T`, currently supported patterns are:
1306 /// - `T`
1307 /// - `&T`
1308 /// - `&mut T`
1309 /// - `&[T]`
1310 ///
1311 /// # Examples
1312 /// ```
1313 /// # use std::path::Path;
1314 /// # use mockall::{automock, concretize};
1315 /// #[automock]
1316 /// trait Foo {
1317 /// #[mockall::concretize]
1318 /// fn foo<P: AsRef<Path>>(&self, p: P);
1319 /// }
1320 ///
1321 /// # fn main() {
1322 /// let mut mock = MockFoo::new();
1323 /// mock.expect_foo()
1324 /// .withf(|p| p.as_ref() == Path::new("/tmp"))
1325 /// .return_const(());
1326 /// mock.foo(Path::new("/tmp"));
1327 /// # }
1328 /// ```
1329 ///
1330 /// NB: This attribute must be imported with its canonical name. It won't work
1331 /// otherwise!
1332 /// ```compile_fail
1333 /// use mockall::concretize as something_else;
1334 /// #[mockall::automock]
1335 /// trait Foo {
1336 /// #[something_else]
1337 /// fn foo<T>(&self, t: T);
1338 /// }
1339 /// ```
1340 pub use mockall_derive::concretize;
1341
1342 /// Manually mock a structure.
1343 ///
1344 /// Sometimes `automock` can't be used. In those cases you can use `mock!`,
1345 /// which basically involves repeating the struct's or trait's definitions.
1346 ///
1347 /// The format is:
1348 ///
1349 /// * Optional visibility specifier
1350 /// * Real structure name and generics fields
1351 /// * 0 or more methods of the structure, written without bodies, enclosed in a
1352 /// {} block
1353 /// * 0 or more impl blocks implementing traits on the structure, also without
1354 /// bodies.
1355 ///
1356 /// # Examples
1357 ///
1358 /// Mock a trait. This is the simplest use case.
1359 /// ```
1360 /// # use mockall_derive::mock;
1361 /// trait Foo {
1362 /// fn foo(&self, x: u32);
1363 /// }
1364 /// mock!{
1365 /// pub MyStruct<T: Clone + 'static> {
1366 /// fn bar(&self) -> u8;
1367 /// }
1368 /// impl<T: Clone + 'static> Foo for MyStruct<T> {
1369 /// fn foo(&self, x: u32);
1370 /// }
1371 /// }
1372 /// # fn main() {}
1373 /// ```
1374 /// Mocking an unsupported `#[derive(X)]` attribute, e.g. `Clone`, is
1375 /// similar.
1376 /// ```
1377 /// # use mockall_derive::mock;
1378 /// #[derive(Clone)]
1379 /// struct MyStruct;
1380 ///
1381 /// mock!{
1382 /// pub MyStruct {
1383 /// fn bar(&self);
1384 /// }
1385 /// impl Clone for MyStruct {
1386 /// fn clone(&self) -> Self;
1387 /// }
1388 /// }
1389 /// # fn main() {}
1390 /// ```
1391 ///
1392 /// When mocking a generic struct's implementation of a generic trait, use the
1393 /// same name for their generic parameters. For example, if you wanted to mock
1394 /// `Rc`, do
1395 /// ```
1396 /// # use mockall_derive::mock;
1397 /// mock!{
1398 /// pub Rc<T: 'static> {}
1399 /// impl<T: 'static> AsRef<T> for Rc<T> {
1400 /// fn as_ref(&self) -> &T;
1401 /// }
1402 /// }
1403 /// # fn main() {}
1404 /// ```
1405 /// *not*
1406 /// ```compile_fail
1407 /// # use mockall_derive::mock;
1408 /// mock!{
1409 /// pub Rc<Q: 'static> {}
1410 /// impl<T: 'static> AsRef<T> for Rc<T> {
1411 /// fn as_ref(&self) -> &T;
1412 /// }
1413 /// }
1414 /// # fn main() {}
1415 /// ```
1416 /// Associated types can easily be mocked by specifying a concrete type in the
1417 /// `mock!{}` invocation.
1418 /// ```
1419 /// # use mockall_derive::mock;
1420 /// mock!{
1421 /// MyIter {}
1422 /// impl Iterator for MyIter {
1423 /// type Item=u32;
1424 ///
1425 /// fn next(&mut self) -> Option<<Self as Iterator>::Item>;
1426 /// }
1427 /// }
1428 /// # fn main() {}
1429 /// ```
1430 pub use mockall_derive::mock;
1431
1432 #[doc(hidden)]
1433 pub trait AnyExpectations : Any + Send + Sync {}
1434 downcast!(dyn AnyExpectations);
1435
1436 #[doc(hidden)]
1437 pub trait ReturnDefault<O> {
maybe_return_default() -> Option<O>1438 fn maybe_return_default() -> Option<O>;
return_default() -> Result<O, &'static str>1439 fn return_default() -> Result<O, &'static str>;
1440 }
1441
1442 #[derive(Default)]
1443 #[doc(hidden)]
1444 pub struct DefaultReturner<O>(PhantomData<O>);
1445
1446 ::cfg_if::cfg_if! {
1447 if #[cfg(feature = "nightly")] {
1448 impl<O> ReturnDefault<O> for DefaultReturner<O> {
1449 default fn maybe_return_default() -> Option<O> {
1450 None
1451 }
1452
1453 default fn return_default() -> Result<O, &'static str> {
1454 Err("Can only return default values for types that impl std::Default")
1455 }
1456 }
1457
1458 impl<O: Default> ReturnDefault<O> for DefaultReturner<O> {
1459 fn maybe_return_default() -> Option<O> {
1460 Some(O::default())
1461 }
1462
1463 fn return_default() -> Result<O, &'static str> {
1464 Ok(O::default())
1465 }
1466 }
1467 } else {
1468 impl<O> ReturnDefault<O> for DefaultReturner<O> {
1469 fn maybe_return_default() -> Option<O> {
1470 None
1471 }
1472
1473 fn return_default() -> Result<O, &'static str> {
1474 Err("Returning default values requires the \"nightly\" feature")
1475 }
1476 }
1477 }
1478 }
1479
1480 // Wrapper type to allow for better expectation messages for any type.
1481 // Will first try Debug, otherwise will print '?'
1482 #[doc(hidden)]
1483 pub struct ArgPrinter<'a, T>(pub &'a T);
1484
1485 #[doc(hidden)]
1486 pub struct DebugPrint<'a, T: Debug>(pub &'a T);
1487 impl<'a, T> Debug for DebugPrint<'a, T> where T: Debug {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result1488 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1489 Debug::fmt(self.0, f)
1490 }
1491 }
1492 #[doc(hidden)]
debug_string(&self) -> DebugPrint<'_, T>1493 pub trait ViaDebug<T> where T: Debug { fn debug_string(&self) -> DebugPrint<'_, T>; }
1494 impl<'a, T: Debug> ViaDebug<T> for &ArgPrinter<'a, T> {
debug_string(&self) -> DebugPrint<'a, T>1495 fn debug_string(&self) -> DebugPrint<'a, T> {
1496 DebugPrint(self.0)
1497 }
1498 }
1499
1500 #[doc(hidden)]
1501 pub struct NothingPrint;
1502 impl Debug for NothingPrint {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result1503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1504 write!(f, "?")
1505 }
1506 }
1507 #[doc(hidden)]
debug_string(&self) -> NothingPrint1508 pub trait ViaNothing { fn debug_string(&self) -> NothingPrint; }
1509 impl<'a, T> ViaNothing for ArgPrinter<'a, T> {
debug_string(&self) -> NothingPrint1510 fn debug_string(&self) -> NothingPrint {
1511 NothingPrint
1512 }
1513 }
1514
1515 // Though it's not entirely correct, we treat usize::max_value() as
1516 // approximately infinity.
1517 #[derive(Debug)]
1518 #[doc(hidden)]
1519 pub struct TimesRange(Range<usize>);
1520
1521 impl Default for TimesRange {
default() -> TimesRange1522 fn default() -> TimesRange {
1523 // By default, allow any number of calls
1524 TimesRange(0..usize::max_value())
1525 }
1526 }
1527
1528 impl From<usize> for TimesRange {
from(n: usize) -> TimesRange1529 fn from(n: usize) -> TimesRange {
1530 TimesRange(n..(n+1))
1531 }
1532 }
1533
1534 impl From<Range<usize>> for TimesRange {
from(r: Range<usize>) -> TimesRange1535 fn from(r: Range<usize>) -> TimesRange {
1536 assert!(r.end > r.start, "Backwards range");
1537 TimesRange(r)
1538 }
1539 }
1540
1541 impl From<RangeFrom<usize>> for TimesRange {
from(r: RangeFrom<usize>) -> TimesRange1542 fn from(r: RangeFrom<usize>) -> TimesRange {
1543 TimesRange(r.start..usize::max_value())
1544 }
1545 }
1546
1547 impl From<RangeFull> for TimesRange {
from(_: RangeFull) -> TimesRange1548 fn from(_: RangeFull) -> TimesRange {
1549 TimesRange(0..usize::max_value())
1550 }
1551 }
1552
1553 impl From<RangeInclusive<usize>> for TimesRange {
from(r: RangeInclusive<usize>) -> TimesRange1554 fn from(r: RangeInclusive<usize>) -> TimesRange {
1555 assert!(r.end() >= r.start(), "Backwards range");
1556 TimesRange(*r.start()..*r.end() + 1)
1557 }
1558 }
1559
1560 impl From<RangeTo<usize>> for TimesRange {
from(r: RangeTo<usize>) -> TimesRange1561 fn from(r: RangeTo<usize>) -> TimesRange {
1562 TimesRange(0..r.end)
1563 }
1564 }
1565
1566 impl From<RangeToInclusive<usize>> for TimesRange {
from(r: RangeToInclusive<usize>) -> TimesRange1567 fn from(r: RangeToInclusive<usize>) -> TimesRange {
1568 TimesRange(0..r.end + 1)
1569 }
1570 }
1571
1572 #[derive(PartialEq)]
1573 #[doc(hidden)]
1574 pub enum ExpectedCalls {
1575 Satisfied,
1576 TooMany,
1577 TooFew,
1578 }
1579
1580 #[derive(Debug, Default)]
1581 #[doc(hidden)]
1582 pub struct Times{
1583 /// How many times has the expectation already been called?
1584 count: AtomicUsize,
1585 range: TimesRange
1586 }
1587
1588 #[doc(hidden)]
1589 impl Times {
call(&self) -> Result<(), String>1590 pub fn call(&self) -> Result<(), String> {
1591 let count = self.count.fetch_add(1, Ordering::Relaxed) + 1;
1592 if count >= self.range.0.end {
1593 if self.range.0.end == 1 {
1594 Err("should not have been called".to_owned())
1595 } else {
1596 Err(format!(
1597 "called {} times which is more than the expected {}",
1598 count,
1599 self.range.0.end - 1
1600 ))
1601 }
1602 } else {
1603 Ok(())
1604 }
1605 }
1606
any(&mut self)1607 pub fn any(&mut self) {
1608 self.range.0 = 0..usize::max_value();
1609 }
1610
1611 /// Return how many times this expectation has been called
count(&self) -> usize1612 pub fn count(&self) -> usize {
1613 self.count.load(Ordering::Relaxed)
1614 }
1615
1616 /// Has this expectation already been called the maximum allowed number of
1617 /// times?
is_done(&self) -> bool1618 pub fn is_done(&self) -> bool {
1619 self.count.load(Ordering::Relaxed) >= self.range.0.end - 1
1620 }
1621
1622 /// Is it required that this expectation be called an exact number of times,
1623 /// or may it be satisfied by a range of call counts?
is_exact(&self) -> bool1624 pub fn is_exact(&self) -> bool {
1625 (self.range.0.end - self.range.0.start) == 1
1626 }
1627
1628 /// Has this expectation already been called the expected number of times?
1629 /// If not, was it too many or too few?
is_satisfied(&self) -> ExpectedCalls1630 pub fn is_satisfied(&self) -> ExpectedCalls {
1631 let satisfied_lower_bound = self.count.load(Ordering::Relaxed) >= self.range.0.start;
1632 let satisfied_upper_bound = self.count.load(Ordering::Relaxed) < self.range.0.end;
1633 if satisfied_lower_bound && satisfied_upper_bound {
1634 ExpectedCalls::Satisfied
1635 } else if satisfied_lower_bound {
1636 ExpectedCalls::TooMany
1637 } else {
1638 ExpectedCalls::TooFew
1639 }
1640 }
1641
1642 /// The maximum number of times that this expectation must be called
maximum(&self) -> usize1643 pub fn maximum(&self) -> usize {
1644 self.range.0.end - 1
1645 }
1646
1647 /// The minimum number of times that this expectation must be called
minimum(&self) -> usize1648 pub fn minimum(&self) -> usize {
1649 self.range.0.start
1650 }
1651
1652 // https://github.com/rust-lang/rust-clippy/issues/3307
1653 #[allow(clippy::range_plus_one)]
n(&mut self, n: usize)1654 pub fn n(&mut self, n: usize) {
1655 self.range.0 = n..(n+1);
1656 }
1657
never(&mut self)1658 pub fn never(&mut self) {
1659 self.range.0 = 0..1;
1660 }
1661
range(&mut self, range: Range<usize>)1662 pub fn range(&mut self, range: Range<usize>) {
1663 assert!(range.end > range.start, "Backwards range");
1664 self.range.0 = range;
1665 }
1666
times<T: Into<TimesRange>>(&mut self, t: T)1667 pub fn times<T: Into<TimesRange>>(&mut self, t: T) {
1668 self.range = t.into();
1669 }
1670 }
1671
1672 /// Non-generic keys to `GenericExpectation` internal storage
1673 #[doc(hidden)]
1674 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
1675 pub struct Key(any::TypeId);
1676
1677 #[doc(hidden)]
1678 impl Key {
new<T: 'static + ?Sized>() -> Self1679 pub fn new<T: 'static + ?Sized>() -> Self {
1680 Key(any::TypeId::of::<T>())
1681 }
1682 }
1683
1684 #[doc(hidden)]
1685 pub struct SeqHandle {
1686 inner: Arc<SeqInner>,
1687 seq: usize
1688 }
1689
1690 impl SeqHandle {
1691 /// Tell the Sequence that this expectation has been fully satisfied
satisfy(&self)1692 pub fn satisfy(&self) {
1693 self.inner.satisfy(self.seq);
1694 }
1695
1696 /// Verify that this handle was called in the correct order
verify(&self, desc: &str)1697 pub fn verify(&self, desc: &str) {
1698 self.inner.verify(self.seq, desc);
1699 }
1700 }
1701
1702 #[derive(Default)]
1703 struct SeqInner {
1704 satisfaction_level: AtomicUsize,
1705 }
1706
1707 impl SeqInner {
1708 /// Record the call identified by `seq` as fully satisfied.
satisfy(&self, seq: usize)1709 fn satisfy(&self, seq: usize) {
1710 let old_sl = self.satisfaction_level.fetch_add(1, Ordering::Relaxed);
1711 assert_eq!(old_sl, seq, "Method sequence violation. Was an already-satisfied method called another time?");
1712 }
1713
1714 /// Verify that the call identified by `seq` was called in the correct order
verify(&self, seq: usize, desc: &str)1715 fn verify(&self, seq: usize, desc: &str) {
1716 assert_eq!(seq, self.satisfaction_level.load(Ordering::Relaxed),
1717 "{desc}: Method sequence violation")
1718 }
1719 }
1720
1721 /// Used to enforce that mock calls must happen in the sequence specified.
1722 ///
1723 /// Each expectation must expect to be called a fixed number of times. Once
1724 /// satisfied, the next expectation in the sequence will expect to be called.
1725 ///
1726 /// # Examples
1727 /// ```
1728 /// # use mockall::*;
1729 /// #[automock]
1730 /// trait Foo {
1731 /// fn foo(&self);
1732 /// fn bar(&self) -> u32;
1733 /// }
1734 /// let mut seq = Sequence::new();
1735 ///
1736 /// let mut mock0 = MockFoo::new();
1737 /// let mut mock1 = MockFoo::new();
1738 ///
1739 /// mock0.expect_foo()
1740 /// .times(1)
1741 /// .returning(|| ())
1742 /// .in_sequence(&mut seq);
1743 ///
1744 /// mock1.expect_bar()
1745 /// .times(1)
1746 /// .returning(|| 42)
1747 /// .in_sequence(&mut seq);
1748 ///
1749 /// mock0.foo();
1750 /// mock1.bar();
1751 /// ```
1752 ///
1753 /// It is an error to add an expectation to a `Sequence` if its call count is
1754 /// unspecified.
1755 /// ```should_panic(expected = "with an exact call count")
1756 /// # use mockall::*;
1757 /// #[automock]
1758 /// trait Foo {
1759 /// fn foo(&self);
1760 /// }
1761 /// let mut seq = Sequence::new();
1762 ///
1763 /// let mut mock = MockFoo::new();
1764 /// mock.expect_foo()
1765 /// .returning(|| ())
1766 /// .in_sequence(&mut seq); // panics!
1767 /// ```
1768 #[derive(Default)]
1769 pub struct Sequence {
1770 inner: Arc<SeqInner>,
1771 next_seq: usize,
1772 }
1773
1774 impl Sequence {
1775 /// Create a new empty [`Sequence`]
new() -> Self1776 pub fn new() -> Self {
1777 Self::default()
1778 }
1779
1780 /// Not for public consumption, but it must be public so the generated code
1781 /// can call it.
1782 #[doc(hidden)]
next_handle(&mut self) -> SeqHandle1783 pub fn next_handle(&mut self) -> SeqHandle {
1784 let handle = SeqHandle{inner: self.inner.clone(), seq: self.next_seq};
1785 self.next_seq += 1;
1786 handle
1787 }
1788 }
1789