Skip to main content

fnmock_derive/
lib.rs

1//! Proc-macro implementation behind [`fnmock`](https://docs.rs/fnmock).
2//!
3//! Everything here except the [`macro@mockable`] attribute and its two single-half variants,
4//! [`macro@fakeable`] and [`macro@spyable`], is a fnmock internal. Depend on the `fnmock` crate
5//! rather than on this one. It re-exports the attributes as `fnmock::mockable`, `fnmock::fakeable`
6//! and `fnmock::spyable`.
7//!
8//! See the [README](https://github.com/jakob-rzeppa/fnmock/blob/master/README.md) for installation,
9//! a walkthrough and the current limitations.
10
11use crate::{fakeable::handle_fakeable, mockable::handle_mockable, spyable::handle_spyable};
12
13mod entry;
14mod expandable;
15mod expanded;
16mod fakeable;
17mod item_info;
18mod mockable;
19mod scheme;
20mod spyable;
21mod strategy;
22
23/// Mock a free function or the methods of an inherent impl block in tests.
24///
25/// The attribute leaves the original body in place and injects a `#[cfg(test)]`-gated block at the
26/// top of it. The block records the call. Then, if the test has installed a replacement closure on
27/// the current thread, the closure's result is returned instead of running the body. The attribute
28/// also generates an accessor named after the function (`get_user` gets `get_user_mock()`), which
29/// tests use to control the mock:
30///
31/// | Method | Behaviour |
32/// | --- | --- |
33/// | `setup(closure)` | Replace the body with a closure of the same signature. Calling it again replaces the previous one. |
34/// | `is_set()` | Whether a replacement closure is installed. |
35/// | `expect(pred, ..)` | Expect calls whose arguments satisfy one predicate per parameter. |
36/// | `expectf(closure)` | Expect calls whose arguments satisfy one closure over all of them. |
37/// | `expect_times(n)` / `expect_once()` / `expect_never()` | Expect this many calls, whatever their arguments. |
38/// | `assert()` | Assert every expectation set on this mock is fulfilled. |
39/// | `clear()` | Reset the whole mock: remove the closure, and drop every expectation and recorded call. |
40///
41/// ```ignore
42/// #[fnmock::mockable]
43/// fn fetch_user_name(id: u32) -> String {
44///     // real database call
45/// }
46///
47/// #[test]
48/// fn test_greeting() {
49///     let mock = fetch_user_name_mock();
50///     mock.setup(|_| "Test".into());
51///     mock.expect(fnmock::predicate::eq(1)).once();
52///
53///     assert_eq!(greet(1), "Hello, Test");
54///
55///     mock.assert();
56/// }
57/// ```
58///
59/// Every call is recorded, including calls the closure answers, so a canned return value and an
60/// assertion on the call work together. A call the closure answers never runs the real body, so the
61/// real body's side effects don't happen. Arguments are matched by shared reference: a `String`
62/// parameter is matched by a `Predicate<String>` and a `&str` one by a `Predicate<str>`.
63///
64/// `expect` and `expectf` return a handle that refines the expectation by chaining: `times(2)`,
65/// `once()`, `never()`, `describe(..)`, `in_sequence(&seq)`. See
66/// [FEATURES.md](https://github.com/jakob-rzeppa/fnmock/blob/master/docs/FEATURES.md).
67///
68/// Applied to an inherent impl block, every method in it gets its own mock, and the accessors are
69/// generated as associated functions on the same type (`Type::method_mock()`). The `setup` closure
70/// receives the receiver as its first argument. Expectations never match on the receiver.
71///
72/// Mocks are stored per thread, and the test harness gives each `#[test]` its own thread, so tests
73/// can't leak into one another and no reset step is needed. The flip side is that a mock is only
74/// visible on the thread that set it up. Because the injected block is `#[cfg(test)]`-gated,
75/// release builds keep the original body and compile no mock code at all.
76#[proc_macro_attribute]
77pub fn mockable(
78    attr: proc_macro::TokenStream,
79    item: proc_macro::TokenStream,
80) -> proc_macro::TokenStream {
81    // These attribute functions are the only place proc_macro::TokenStream should appear: the
82    // actual proc-macro ABI boundary requires it, but proc_macro::TokenStream cannot be constructed
83    // or parsed outside a live macro expansion (it panics), which makes anything using it
84    // untestable. Converting to proc_macro2::TokenStream here lets the rest of the crate be tested
85    // with ordinary unit tests.
86    let res = handle_mockable(attr.into(), item.into());
87
88    match res {
89        Ok(expanded) => expanded.into(),
90        Err(e) => e.to_compile_error().into(),
91    }
92}
93
94/// Replace a free function's or impl method's body in tests, without recording calls.
95///
96/// This is the replacing half of [`macro@mockable`] on its own. It generates `<fn_name>_fake()`:
97///
98/// | Method | Behaviour |
99/// | --- | --- |
100/// | `setup(closure)` | Install a fake, replacing any previous one. |
101/// | `clear()` | Remove the fake; calls run the real body again. |
102/// | `is_set()` | Whether a fake is currently installed. |
103///
104/// ```ignore
105/// #[fnmock::fakeable]
106/// fn fetch_user(id: u32) -> User {
107///     // real database call
108/// }
109///
110/// #[test]
111/// fn returns_the_faked_user() {
112///     fetch_user_fake().setup(|id| User { id, name: "Test".into() });
113///
114///     assert_eq!(fetch_user(1).name, "Test");
115/// }
116/// ```
117#[proc_macro_attribute]
118pub fn fakeable(
119    attr: proc_macro::TokenStream,
120    item: proc_macro::TokenStream,
121) -> proc_macro::TokenStream {
122    let res = handle_fakeable(attr.into(), item.into());
123
124    match res {
125        Ok(expanded) => expanded.into(),
126        Err(e) => e.to_compile_error().into(),
127    }
128}
129
130/// Record a free function's or impl method's calls in tests and assert on them. The real body
131/// always runs.
132///
133/// This is the recording half of [`macro@mockable`] on its own. It generates `<fn_name>_spy()`
134/// with the mock's expectation methods, `expect`, `expectf`, `expect_times`, `expect_once`,
135/// `expect_never` and `assert`, plus a `clear()` that drops the expectations and call history. It
136/// has no `setup` or `is_set`.
137///
138/// ```ignore
139/// #[fnmock::spyable]
140/// fn get_user(id: String, uuid: &str) -> String {
141///     // real database call
142/// }
143///
144/// #[test]
145/// fn asks_for_the_user_once() {
146///     let spy = get_user_spy();
147///     spy.expect(predicate::eq("a".to_string()), predicate::always()).once();
148///
149///     get_user("a".to_string(), "uuid");
150///
151///     spy.assert();
152/// }
153/// ```
154#[proc_macro_attribute]
155pub fn spyable(
156    attr: proc_macro::TokenStream,
157    item: proc_macro::TokenStream,
158) -> proc_macro::TokenStream {
159    let res = handle_spyable(attr.into(), item.into());
160
161    match res {
162        Ok(expanded) => expanded.into(),
163        Err(e) => e.to_compile_error().into(),
164    }
165}