Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 // vim: tw=80
2 //! Test double adapter for use with Mockall
3 //!
4 //! This crate provides [`#[double]`](macro@double), which can swap in Mock
5 //! objects for real objects while in test mode. It's intended to be used in
6 //! tandem with the [`mockall`](https://docs.rs/mockall/latest/mockall) crate.
7 //! However, it is defined in its own crate so that the bulk of Mockall can
8 //! remain a dev-dependency, instead of a regular dependency.
9
10 #![cfg_attr(feature = "nightly", feature(proc_macro_diagnostic))]
11 #![cfg_attr(test, deny(warnings))]
12 extern crate proc_macro;
13
14 use cfg_if::cfg_if;
15 use proc_macro2::{Span, TokenStream};
16 use quote::{format_ident, quote};
17 use syn::{
18 *,
19 spanned::Spanned
20 };
21
22 cfg_if! {
23 // proc-macro2's Span::unstable method requires the nightly feature, and it
24 // doesn't work in test mode.
25 // https://github.com/alexcrichton/proc-macro2/issues/159
26 if #[cfg(all(feature = "nightly", not(test)))] {
27 fn compile_error(span: Span, msg: &'static str) {
28 span.unstable()
29 .error(msg)
30 .emit();
31 }
32 } else {
33 fn compile_error(_span: Span, msg: &str) {
34 panic!("{msg}. More information may be available when mockall_double is built with the \"nightly\" feature.");
35 }
36 }
37 }
38
39 fn do_double(_attrs: TokenStream, input: TokenStream) -> TokenStream {
40 let mut item: Item = match parse2(input.clone()) {
41 Ok(u) => u,
42 Err(e) => return e.to_compile_error()
43 };
44 match &mut item {
45 Item::Use(use_stmt) => mock_itemuse(use_stmt),
46 Item::Type(item_type) => mock_itemtype(item_type),
47 _ => {
48 compile_error(item.span(),
49 "Only use statements and type aliases may be doubled");
50 }
51 };
52 quote!(
53 #[cfg(not(test))]
54 #input
55 #[cfg(test)]
56 #item
57 )
58 }
59
60 /// Import a mock type in test mode, or a real type otherwise.
61 ///
62 /// In a regular build, this macro is a no-op. But when `#[cfg(test)]`, it
63 /// substitutes "MockXXX" for any imported "XXX". This makes it easy to to use
64 /// mock objects, especially structs, in your unit tests.
65 ///
66 /// This macro uses the same naming convention as
67 /// [`mockall`](https://docs.rs/mockall/latest/mockall), but doesn't strictly
68 /// require it. It can work with hand-built Mock objects, or any other crate
69 /// using the same naming convention.
70 ///
71 /// This is the most common way to use `#[double]`. In order to replace a type,
72 /// it must come from a separate module. So to mock type `Foo`, place it into a
73 /// submodule, along with its mock counterpart. Then simply import `Foo` with
74 /// `#[double]` like this:
75 /// ```no_run
76 /// # use mockall_double::double;
77 /// mod foo {
78 /// pub(super) struct Foo {
79 /// // ...
80 /// }
81 /// #[cfg(test)]
82 /// pub(super) struct MockFoo {
83 /// // ...
84 /// }
85 /// }
86 /// #[double]
87 /// use foo::Foo;
88 /// ```
89 /// That will expand to the following:
90 /// ```no_run
91 /// # use mockall_double::double;
92 /// # mod foo { pub struct Foo {} }
93 /// #[cfg(not(test))]
94 /// use foo::Foo;
95 /// #[cfg(test)]
96 /// use foo::MockFoo as Foo;
97 /// ```
98 /// `#[double]` can handle deeply nested paths,
99 /// ```no_run
100 /// # use mockall_double::double;
101 /// # mod foo { pub mod bar { pub struct Baz{} } }
102 /// #[double]
103 /// use foo::bar::Baz;
104 /// ```
105 /// grouped imports,
106 /// ```no_run
107 /// # mod foo { pub mod bar { pub struct Baz{} pub struct Bean {} } }
108 /// # use mockall_double::double;
109 /// #[double]
110 /// use foo::bar::{
111 /// Baz,
112 /// Bean
113 /// };
114 /// ```
115 /// type aliases,
116 /// ```no_run
117 /// # mod bar { pub struct Baz {} }
118 /// # use mockall_double::double;
119 /// #[double]
120 /// type Foo = bar::Baz;
121 /// ```
122 /// and renamed imports, too. With renamed imports, it isn't even necessary to
123 /// declare a submodule.
124 /// ```no_run
125 /// # use mockall_double::double;
126 /// # struct Foo {}
127 /// #[double]
128 /// use Foo as Bar;
129 /// ```
130 /// Finally, `#[double]` can also import entire mocked modules, not just
131 /// structures. In this case the naming convention is different. It will
132 /// replace "xxx" with "mock_xxx". For example:
133 /// ```no_run
134 /// # use mockall_double::double;
135 /// mod foo {
136 /// pub mod inner {
137 /// // ...
138 /// }
139 /// pub mod mock_inner {
140 /// // ...
141 /// }
142 /// }
143 /// #[double]
144 /// use foo::inner;
145 /// ```
146 /// will expand to:
147 /// ```no_run
148 /// # use mockall_double::double;
149 /// # mod foo { pub mod inner { } pub mod mock_inner { } }
150 /// #[cfg(not(test))]
151 /// use foo::inner;
152 /// #[cfg(test)]
153 /// use foo::mock_inner as inner;
154 /// ```
155 ///
156 #[proc_macro_attribute]
157 pub fn double(attrs: proc_macro::TokenStream, input: proc_macro::TokenStream)
158 -> proc_macro::TokenStream
159 {
160 do_double(attrs.into(), input.into()).into()
161 }
162
163 fn mock_itemtype(orig: &mut ItemType) {
164 match &mut *orig.ty {
165 Type::Path(tp) => {
166 let ident = &tp.path.segments.last_mut().unwrap().ident;
167 tp.path.segments.last_mut().unwrap().ident = mock_ident(ident);
168 }
169 x => compile_error(x.span(), "Only path types may be doubled")
170 }
171 }
172
173 fn mock_itemuse(orig: &mut ItemUse) {
174 if let UseTree::Name(un) = &orig.tree {
175 compile_error(un.span(),
176 "Cannot double types in the current module. Use a submodule (use foo::Foo) or a rename (use Foo as Bar)");
177 } else {
178 mock_usetree(&mut orig.tree)
179 }
180 }
181
182 fn mock_ident(i: &Ident) -> Ident {
183 let is_type = format!("{i}")
184 .chars()
185 .next()
186 .expect("zero-length ident?")
187 .is_uppercase();
188 if is_type {
189 // probably a Type
190 format_ident!("Mock{}", i)
191 } else {
192 // probably a module
193 format_ident!("mock_{}", i)
194 }
195 }
196
197 fn mock_usetree(mut orig: &mut UseTree) {
198 match &mut orig {
199 UseTree::Glob(star) => {
200 compile_error(star.span(),
201 "Cannot double glob imports. Import by fully qualified name instead.");
202 },
203 UseTree::Group(ug) => {
204 for ut in ug.items.iter_mut() {
205 mock_usetree(ut);
206 }
207 },
208 UseTree::Name(un) => {
209 *orig = UseTree::Rename(UseRename {
210 ident: mock_ident(&un.ident),
211 as_token: <Token![as]>::default(),
212 rename: un.ident.clone()
213 });
214 },
215 UseTree::Path(up) => {
216 mock_usetree(up.tree.as_mut());
217 },
218 UseTree::Rename(ur) => {
219 ur.ident = mock_ident(&ur.ident)
220 },
221 }
222 }
223
224 #[cfg(test)]
225 mod t {
226 use super::*;
227
228 mod double {
229 use super::*;
230 use std::str::FromStr;
231
232 fn cmp(attrs: &str, code: &str, expected: &str) {
233 let attrs_ts = TokenStream::from_str(attrs).unwrap();
234 let code_ts = TokenStream::from_str(code).unwrap();
235 let output = do_double(attrs_ts, code_ts);
236 let output = output.to_string();
237 // Round-trip expected through proc_macro2 so whitespace will be
238 // identically formatted
239 let expected = TokenStream::from_str(expected)
240 .unwrap()
241 .to_string();
242 assert_eq!(output, expected);
243 }
244
245 #[test]
246 #[should_panic(expected = "Cannot double glob")]
247 fn glob() {
248 let code = "use foo::*;";
249 cmp("", code, "");
250 }
251
252 #[test]
253 fn group() {
254 let code = "
255 use foo::bar::{
256 Baz,
257 Bean
258 };
259 ";
260 let expected = "
261 #[cfg(not(test))]
262 use foo::bar::{
263 Baz,
264 Bean
265 };
266 #[cfg(test)]
267 use foo::bar::{
268 MockBaz as Baz,
269 MockBean as Bean
270 };
271 ";
272 cmp("", code, expected);
273 }
274
275 #[test]
276 fn module() {
277 let code = "use foo::bar;";
278 let expected = "
279 #[cfg(not(test))]
280 use foo::bar;
281 #[cfg(test)]
282 use foo::mock_bar as bar;
283 ";
284 cmp("", code, expected);
285 }
286
287 #[test]
288 #[should_panic(expected = "Cannot double types in the current module")]
289 fn name() {
290 let code = "use Foo;";
291 cmp("", code, "");
292 }
293
294 #[test]
295 fn path() {
296 let code = "use foo::bar::Baz;";
297 let expected = "
298 #[cfg(not(test))]
299 use foo::bar::Baz;
300 #[cfg(test)]
301 use foo::bar::MockBaz as Baz;
302 ";
303 cmp("", code, expected);
304 }
305
306 #[test]
307 fn pub_use() {
308 let code = "pub use foo::bar;";
309 let expected = "
310 #[cfg(not(test))]
311 pub use foo::bar;
312 #[cfg(test)]
313 pub use foo::mock_bar as bar;
314 ";
315 cmp("", code, expected);
316 }
317
318 #[test]
319 fn rename() {
320 let code = "use Foo as Bar;";
321 let expected = "
322 #[cfg(not(test))]
323 use Foo as Bar;
324 #[cfg(test)]
325 use MockFoo as Bar;
326 ";
327 cmp("", code, expected);
328 }
329
330 #[test]
331 fn type_() {
332 let code = "type Foo = bar::Baz;";
333 let expected = "
334 #[cfg(not(test))]
335 type Foo = bar::Baz;
336 #[cfg(test)]
337 type Foo = bar::MockBaz;
338 ";
339 cmp("", code, expected);
340 }
341
342 #[test]
343 #[should_panic(expected = "Only use statements and type aliases")]
344 fn undoubleable() {
345 let code = "struct Foo{}";
346 cmp("", code, "");
347 }
348 }
349 }