Debian Codegraph @

debian/rust-vendor/rstest_reuse/src/lib.rs

raw
1 //! # Reuse `rstest`'s parametrized cases
2 //!
3 //! This crate give a way to define a tests set and apply them to every case you need to
4 //! test.
5 //!
6 //! With `rstest` crate you can define a tests list but if you want to apply the same tests
7 //! to another test function you must rewrite all cases or write some macros that do the job.
8 //! Both solutions have some drawbreak:
9 //!
10 //! - introduce duplication
11 //! - macros makes code harder to read and shift out the focus from tests core
12 //!
13 //! The aim of this crate is solve this problem. `rstest_reuse` expose two attributes:
14 //!
15 //! - `#[template]`: to define a template
16 //! - `#[apply]`: to apply a defined template to create tests
17 //!
18 //! Here is a simple example:
19 //!
20 //! ```
21 //! use rstest::rstest;
22 //! use rstest_reuse::{self, *};
23 //!
24 //! // Here we define the template. This define
25 //! // * The test list name to `two_simple_cases`
26 //! // * cases: here two cases that feed the `a`, `b` values
27 //! #[template]
28 //! #[rstest]
29 //! #[case(2, 2)]
30 //! #[case(4/2, 2)]
31 //! fn two_simple_cases(#[case] a: u32,#[case] b: u32) {}
32 //!
33 //! // Here we apply the `two_simple_cases` template: That is expanded in
34 //! // #[rstest]
35 //! // #[case(2, 2)]
36 //! // #[case(4/2, 2)]
37 //! // fn it_works(#[case] a: u32,#[case] b: u32) {
38 //! // assert!(a == b);
39 //! // }
40 //! #[apply(two_simple_cases)]
41 //! fn it_works(a: u32, b: u32) {
42 //! assert!(a == b);
43 //! }
44 //!
45 //!
46 //! // Here we reuse the `two_simple_cases` template to create two
47 //! // other tests
48 //! #[apply(two_simple_cases)]
49 //! fn it_fail(a: u32, b: u32) {
50 //! assert!(a != b);
51 //! }
52 //! ```
53 //! If we run `cargo test` we have:
54 //!
55 //! ```text
56 //! Finished test [unoptimized + debuginfo] target(s) in 0.05s
57 //! Running target/debug/deps/playground-8a1212f8b5eb00ce
58 //!
59 //! running 4 tests
60 //! test it_fail::case_1 ... FAILED
61 //! test it_works::case_1 ... ok
62 //! test it_works::case_2 ... ok
63 //! test it_fail::case_2 ... FAILED
64 //!
65 //! failures:
66 //!
67 //! ---- it_fail::case_1 stdout ----
68 //! thread 'it_fail::case_1' panicked at 'assertion failed: a != b', src/main.rs:34:5
69 //! note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
70 //!
71 //! ---- it_fail::case_2 stdout ----
72 //! thread 'it_fail::case_2' panicked at 'assertion failed: a != b', src/main.rs:34:5
73 //!
74 //!
75 //! failures:
76 //! it_fail::case_1
77 //! it_fail::case_2
78 //!
79 //! test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out
80 //!
81 //! error: test failed, to rerun pass '--bin playground'
82 //! ```
83 //!
84 //! Simple and neat!
85 //!
86 //! Note that if the test arguments names match the template's ones you can don't
87 //! repeate the arguments attributes.
88 //!
89 //! ## Composition and Values
90 //!
91 //! If you need to add some cases or values when apply a template you can leverage on
92 //! composition. Here a simple example:
93 //!
94 //! ```
95 //! use rstest::rstest;
96 //! use rstest_reuse::{self, *};
97 //!
98 //! #[template]
99 //! #[rstest]
100 //! #[case(2, 2)]
101 //! #[case(4/2, 2)]
102 //! fn base(#[case] a: u32, #[case] b: u32) {}
103 //!
104 //! // Here we add a new case and an argument in a value list:
105 //! #[apply(base)]
106 //! #[case(9/3, 3)]
107 //! fn it_works(a: u32, b: u32, #[values("a", "b")] t: &str) {
108 //! assert!(a == b);
109 //! assert!("abcd".contains(t))
110 //! }
111 //! ```
112 //!
113 //! `cargo test` runs 6 tests:
114 //!
115 //! ```text
116 //! running 6 tests
117 //! test it_works::case_1::t_2 ... ok
118 //! test it_works::case_2::t_2 ... ok
119 //! test it_works::case_2::t_1 ... ok
120 //! test it_works::case_3::t_2 ... ok
121 //! test it_works::case_3::t_1 ... ok
122 //! test it_works::case_1::t_1 ... ok
123 //! ```
124 //!
125 //! Template can also used for `#[values]` and `#[with]` arguments if you need:
126 //!
127 //! ```
128 //! use rstest::*;
129 //! use rstest_reuse::{self, *};
130 //!
131 //! #[template]
132 //! #[rstest]
133 //! fn base(#[with(42)] fix: u32, #[values(1,2,3)] v: u32) {}
134 //!
135 //! #[fixture]
136 //! fn fix(#[default(0)] inner: u32) -> u32 {
137 //! inner
138 //! }
139 //!
140 //! #[apply(base)]
141 //! fn use_it_with_fixture(fix: u32, v: u32) {
142 //! assert!(fix%v == 0);
143 //! }
144 //!
145 //! #[apply(base)]
146 //! fn use_it_without_fixture(v: u32) {
147 //! assert!(24 % v == 0);
148 //! }
149 //! ```
150 //!
151 //! `cargo test` runs 6 tests:
152 //!
153 //! ```text
154 //! running 6 tests
155 //! test use_it_with_fixture::v_1 ... ok
156 //! test use_it_without_fixture::v_1 ... ok
157 //! test use_it_with_fixture::v_3 ... ok
158 //! test use_it_without_fixture::v_2 ... ok
159 //! test use_it_without_fixture::v_3 ... ok
160 //! test use_it_with_fixture::v_2 ... ok
161 //! ```
162 //!
163 //!
164 //! ## Cavelets
165 //!
166 //! ### `use rstest_reuse` at the top of your crate
167 //!
168 //! You **should** add `use rstest_reuse` at the top of your crate:
169 //!
170 //! ```
171 //! #[cfg(test)]
172 //! use rstest_reuse;
173 //! ```
174 //!
175 //! This is due `rstest_reuse::template` define a macro that need to call a `rstest_reuse`'s macro.
176 //! I hope to remove this in the future but for now we should live with it.
177 //!
178 //! Note that
179 //! ```
180 //! use rstest_reuse::*;
181 //! ```
182 //! is not enougth: this statment doesn't include `rstest_reuse` but just its public items.
183 //!
184 //! ## Disclamer
185 //!
186 //! This crate is in developer stage. I don't know if I'll include it in `rstest` or changing some syntax in
187 //! the future.
188 //!
189 //! I did't test it in a lot of cases: if you have some cases where it doesn't works file a ticket on
190 //! [`rstest`](https://github.com/la10736/rstest)
191
192 extern crate proc_macro;
193 use std::collections::HashMap;
194
195 use proc_macro::TokenStream;
196 use quote::{format_ident, quote};
197 use syn::{parse, parse::Parse, parse_macro_input, Attribute, Ident, ItemFn, PatType, Path, Token};
198
199 struct MergeAttrs {
200 template: ItemFn,
201 function: ItemFn,
202 }
203
204 impl Parse for MergeAttrs {
205 fn parse(input: parse::ParseStream) -> syn::Result<Self> {
206 let template = input.parse()?;
207 let _comma: Token![,] = input.parse()?;
208 let function = input.parse()?;
209 Ok(Self { template, function })
210 }
211 }
212
213 fn collect_template_args(template: &ItemFn) -> HashMap<&Ident, &PatType> {
214 template
215 .sig
216 .inputs
217 .iter()
218 .filter_map(|arg| match arg {
219 syn::FnArg::Typed(a) => Some(a),
220 _ => None,
221 })
222 .filter_map(|arg| match *arg.pat {
223 syn::Pat::Ident(ref id) => Some((&id.ident, arg)),
224 _ => None,
225 })
226 .collect()
227 }
228
229 fn merge_arg_attributes(dest: &mut Vec<Attribute>, source: &[Attribute]) {
230 for s in source.iter() {
231 if !dest.contains(s) {
232 dest.push(s.clone())
233 }
234 }
235 }
236
237 fn resolve_template_arg<'a>(
238 template: &HashMap<&'a Ident, &'a PatType>,
239 arg: &Ident,
240 ) -> Option<&'a PatType> {
241 let id_name = arg.to_string();
242 match (template.get(arg), id_name.starts_with('_')) {
243 (Some(&arg), _) => Some(arg),
244 (None, true) => template.get(&format_ident!("{}", id_name[1..])).copied(),
245 _ => None,
246 }
247 }
248
249 fn expand_function_arguments(dest: &mut ItemFn, source: &ItemFn) {
250 let to_merge_args = collect_template_args(source);
251
252 for arg in dest.sig.inputs.iter_mut() {
253 if let syn::FnArg::Typed(a) = arg {
254 if let syn::Pat::Ident(ref id) = *a.pat {
255 if let Some(source_arg) = resolve_template_arg(&to_merge_args, &id.ident) {
256 merge_arg_attributes(&mut a.attrs, &source_arg.attrs);
257 }
258 }
259 }
260 }
261 }
262
263 #[doc(hidden)]
264 #[proc_macro]
265 pub fn merge_attrs(item: TokenStream) -> TokenStream {
266 let MergeAttrs {
267 template,
268 mut function,
269 } = parse_macro_input!(item as MergeAttrs);
270
271 expand_function_arguments(&mut function, &template);
272
273 let mut attrs = template.attrs;
274 attrs.append(&mut function.attrs);
275 function.attrs = attrs;
276
277 let tokens = quote! {
278 #function
279 };
280 tokens.into()
281 }
282
283 fn get_export(attributes: &[Attribute]) -> Option<&Attribute> {
284 attributes
285 .iter()
286 .find(|&attr| attr.path().is_ident(&format_ident!("export")))
287 }
288
289 /// Define a template where the name is given from the function name. This attribute register all
290 /// attributes. The function signature don't really mater but to make it clear is better that you
291 /// use a signature like if you're wrinting a standard `rstest`.
292 ///
293 /// If you need to export the template at the root of your crate or use it from another crate you
294 /// should annotate it with `#[export]` attribute. This attribute add `#[macro_export]` attribute to
295 /// the template macro and make possible to use it from another crate.
296 ///
297 /// When define a template you can also set the arguments attributes like `#[case]`, `#[values]`
298 /// and `#[with]`: when you apply it attributes will be copied to the matched by name arguments.
299 ///
300 #[proc_macro_attribute]
301 pub fn template(_args: proc_macro::TokenStream, input: proc_macro::TokenStream) -> TokenStream {
302 let mut template: ItemFn = parse(input).unwrap();
303
304 let rstest_index = template
305 .attrs
306 .iter()
307 .position(|attr| attr.path().is_ident(&format_ident!("rstest")));
308
309 let mut attributes = template.attrs;
310
311 template.attrs = match rstest_index {
312 Some(idx) => attributes.split_off(idx),
313 None => std::mem::take(&mut attributes),
314 };
315
316 let (macro_attribute, visibility) = match get_export(&attributes) {
317 Some(_) => (
318 quote! {
319 #[macro_export]
320 },
321 quote! {
322 pub
323 },
324 ),
325 None => (
326 quote! {},
327 quote! {
328 pub(crate)
329 },
330 ),
331 };
332
333 let macro_name = template.sig.ident.clone();
334 let macro_name_rand = format_ident!("{}_{}", macro_name, rand::random::<u64>());
335
336 let tokens = quote! {
337 /// Apply #macro_name template to given body
338 #macro_attribute
339 macro_rules! #macro_name_rand {
340 ( $test:item ) => {
341 ::rstest_reuse::merge_attrs! {
342 #template,
343 $test
344 }
345 }
346 }
347 #[allow(unused_imports)]
348 #visibility use #macro_name_rand as #macro_name;
349 };
350 tokens.into()
351 }
352
353 /// Apply a defined template. The function signature should satisfy the template attributes
354 /// but can also add some other fixtures.
355 /// Example:
356 ///
357 /// ```
358 /// use rstest::{rstest, fixture};
359 /// use rstest_reuse::{self, *};
360 ///
361 /// #[fixture]
362 /// fn empty () -> Vec<u32> {
363 /// Vec::new()
364 /// }
365 ///
366 /// #[template]
367 /// #[rstest]
368 /// #[case(2, 2)]
369 /// #[case(4/2, 2)]
370 /// fn two_simple_cases(#[case] a: u32, #[case] b: u32) {}
371 ///
372 /// #[apply(two_simple_cases)]
373 /// fn it_works(mut empty: Vec<u32>, a: u32, b: u32) {
374 /// empty.append(a);
375 /// assert!(empty.last() == b);
376 /// }
377 /// ```
378 /// When use `#[apply]` you can also
379 /// 1. Use a path for template
380 /// 2. Ignore an argument by underscore
381 /// 3. add some cases
382 /// 4. add some values
383 ///
384 ///
385 /// ```
386 /// use rstest::{rstest, fixture};
387 /// use rstest_reuse::{self, *};
388 ///
389 /// #[fixture]
390 /// fn fix (#[default(0)] inner: u32) -> u32 {
391 /// inner
392 /// }
393 ///
394 /// mod outer {
395 /// pub(crate) mod inner {
396 /// use rstest_reuse::template;
397 ///
398 /// #[template]
399 /// #[rstest]
400 /// #[case(2, 2)]
401 /// #[case(4/2, 2)]
402 /// fn two_simple_cases(#[case] a: u32, #[case] b: u32) {}
403 /// }
404 /// }
405 ///
406 ///
407 /// #[apply(outer::inner::two_simple_cases)]
408 /// // Add a case
409 /// #[case(9/3, 3)]
410 /// // Use fixture with 42 as argument
411 /// // Ignore b case values
412 /// // add 2 cases with other in 4, 5 for each case
413 /// fn lot_of_tests(fix: u32, a: u32, _b: u32, #[values(4, 5)] other: u32) {
414 /// assert_eq!(fix, 42);
415 /// assert_eq!(a, 2);
416 /// assert!([4, 5].contains(other));
417 /// }
418 /// ```
419 ///
420
421 #[proc_macro_attribute]
422 pub fn apply(args: proc_macro::TokenStream, input: proc_macro::TokenStream) -> TokenStream {
423 let template: Path = parse(args).unwrap();
424 let test: ItemFn = parse(input).unwrap();
425 let tokens = quote! {
426 #template! {
427 #test
428 }
429 };
430 tokens.into()
431 }