1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! # serial_test_derive
//! Helper crate for [serial_test](../serial_test/index.html)

#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::TokenTree;
use proc_macro_error::{abort_call_site, proc_macro_error};
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use std::ops::Deref;

/// Allows for the creation of serialised Rust tests
/// ````
/// #[test]
/// #[serial]
/// fn test_serial_one() {
///   // Do things
/// }
///
/// #[test]
/// #[serial]
/// fn test_serial_another() {
///   // Do things
/// }
/// ````
/// Multiple tests with the [serial](macro@serial) attribute are guaranteed to be executed in serial. Ordering
/// of the tests is not guaranteed however. If you have other tests that can be run in parallel, but would clash
/// if run at the same time as the [serial](macro@serial) tests, you can use the [parallel](macro@parallel) attribute.
///
/// If you want different subsets of tests to be serialised with each
/// other, but not depend on other subsets, you can add an argument to [serial](macro@serial), and all calls
/// with identical arguments will be called in serial. e.g.
/// ````
/// #[test]
/// #[serial(something)]
/// fn test_serial_one() {
///   // Do things
/// }
///
/// #[test]
/// #[serial(something)]
/// fn test_serial_another() {
///   // Do things
/// }
///
/// #[test]
/// #[serial(other)]
/// fn test_serial_third() {
///   // Do things
/// }
///
/// #[test]
/// #[serial(other)]
/// fn test_serial_fourth() {
///   // Do things
/// }
/// ````
/// `test_serial_one` and `test_serial_another` will be executed in serial, as will `test_serial_third` and `test_serial_fourth`
/// but neither sequence will be blocked by the other
///
/// Nested serialised tests (i.e. a [serial](macro@serial) tagged test calling another) are supported
#[proc_macro_attribute]
#[proc_macro_error]
pub fn serial(attr: TokenStream, input: TokenStream) -> TokenStream {
    local_serial_core(attr.into(), input.into()).into()
}

/// Allows for the creation of parallel Rust tests that won't clash with serial tests
/// ````
/// #[test]
/// #[serial]
/// fn test_serial_one() {
///   // Do things
/// }
///
/// #[test]
/// #[parallel]
/// fn test_parallel_one() {
///   // Do things
/// }
///
/// #[test]
/// #[parallel]
/// fn test_parallel_two() {
///   // Do things
/// }
/// ````
/// Multiple tests with the [parallel](macro@parallel) attribute may run in parallel, but not at the
/// same time as [serial](macro@serial) tests. e.g. in the example code above, `test_parallel_one`
/// and `test_parallel_two` may run at the same time, but `test_serial_one` is guaranteed not to run
/// at the same time as either of them. [parallel](macro@parallel) also takes key arguments for groups
/// of tests as per [serial](macro@serial).
///
/// Note that this has zero effect on [file_serial](macro@file_serial) tests, as that uses a different
/// serialisation mechanism.
#[proc_macro_attribute]
#[proc_macro_error]
pub fn parallel(attr: TokenStream, input: TokenStream) -> TokenStream {
    local_parallel_core(attr.into(), input.into()).into()
}

/// Allows for the creation of file-serialised Rust tests
/// ````
/// #[test]
/// #[file_serial]
/// fn test_serial_one() {
///   // Do things
/// }
///
/// #[test]
/// #[file_serial]
/// fn test_serial_another() {
///   // Do things
/// }
/// ````
///
/// Multiple tests with the [file_serial](macro@file_serial) attribute are guaranteed to run in serial, as per the [serial](macro@serial)
/// attribute. Note that there are no guarantees about one test with [serial](macro@serial) and another with [file_serial](macro@file_serial)
/// as they lock using different methods, and [file_serial](macro@file_serial) does not support nested serialised tests, but otherwise acts
/// like [serial](macro@serial).
///
/// It also supports an optional `path` arg e.g
/// ````
/// #[test]
/// #[file_serial(key, "/tmp/foo")]
/// fn test_serial_one() {
///   // Do things
/// }
///
/// #[test]
/// #[file_serial(key, "/tmp/foo")]
/// fn test_serial_another() {
///   // Do things
/// }
/// ````
/// Note that in this case you need to specify the `name` arg as well (as per [serial](macro@serial)). The path defaults to a reasonable temp directory for the OS if not specified.
#[proc_macro_attribute]
#[proc_macro_error]
#[cfg_attr(docsrs, doc(cfg(feature = "file_locks")))]
pub fn file_serial(attr: TokenStream, input: TokenStream) -> TokenStream {
    fs_serial_core(attr.into(), input.into()).into()
}

// Based off of https://github.com/dtolnay/quote/issues/20#issuecomment-437341743
struct QuoteOption<T>(Option<T>);

impl<T: ToTokens> ToTokens for QuoteOption<T> {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        tokens.append_all(match self.0 {
            Some(ref t) => quote! { ::std::option::Option::Some(#t) },
            None => quote! { ::std::option::Option::None },
        });
    }
}

fn get_raw_args(attr: proc_macro2::TokenStream) -> Vec<String> {
    let mut attrs = attr.into_iter().collect::<Vec<TokenTree>>();
    let mut raw_args: Vec<String> = Vec::new();
    while !attrs.is_empty() {
        match attrs.remove(0) {
            TokenTree::Ident(id) => {
                raw_args.push(id.to_string());
            }
            TokenTree::Literal(literal) => {
                let string_literal = literal.to_string();
                if !string_literal.starts_with('\"') || !string_literal.ends_with('\"') {
                    panic!("Expected a string literal, got '{}'", string_literal);
                }
                // Hacky way of getting a string without the enclosing quotes
                raw_args.push(string_literal[1..string_literal.len() - 1].to_string());
            }
            x => {
                panic!("Expected either strings or literals as args, not {}", x);
            }
        }
        if !attrs.is_empty() {
            match attrs.remove(0) {
                TokenTree::Punct(p) if p.as_char() == ',' => {}
                x => {
                    panic!("Expected , between args, not {}", x);
                }
            }
        }
    }
    raw_args
}

fn get_core_key(attr: proc_macro2::TokenStream) -> String {
    let mut raw_args = get_raw_args(attr);
    match raw_args.len() {
        0 => "".to_string(),
        1 => raw_args.pop().unwrap(),
        n => {
            panic!(
                "Expected either 0 or 1 arguments, got {}: {:?}",
                n, raw_args
            );
        }
    }
}

fn local_serial_core(
    attr: proc_macro2::TokenStream,
    input: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let key = get_core_key(attr);
    serial_setup(input, vec![Box::new(key)], "local")
}

fn local_parallel_core(
    attr: proc_macro2::TokenStream,
    input: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let key = get_core_key(attr);
    parallel_setup(input, vec![Box::new(key)], "local")
}

fn fs_serial_core(
    attr: proc_macro2::TokenStream,
    input: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let none_ident = Box::new(format_ident!("None"));
    let mut args: Vec<Box<dyn quote::ToTokens>> = Vec::new();
    let mut raw_args = get_raw_args(attr);
    match raw_args.len() {
        0 => {
            args.push(Box::new("".to_string()));
            args.push(none_ident);
        }
        1 => {
            args.push(Box::new(raw_args.pop().unwrap()));
            args.push(none_ident);
        }
        2 => {
            let key = raw_args.remove(0);
            let path = raw_args.remove(0);
            args.push(Box::new(key));
            args.push(Box::new(QuoteOption(Some(path))));
        }
        n => {
            panic!("Expected 0-2 arguments, got {}: {:?}", n, raw_args);
        }
    }
    serial_setup(input, args, "fs")
}

fn core_setup<T>(
    input: proc_macro2::TokenStream,
    args: Vec<Box<T>>,
    prefix: &str,
    kind: &str,
) -> proc_macro2::TokenStream
where
    T: quote::ToTokens + ?Sized,
{
    let ast: syn::ItemFn = syn::parse2(input).unwrap();
    let asyncness = ast.sig.asyncness;
    let name = ast.sig.ident;
    let return_type = match ast.sig.output {
        syn::ReturnType::Default => None,
        syn::ReturnType::Type(_rarrow, ref box_type) => Some(box_type.deref()),
    };
    let block = ast.block;
    let attrs: Vec<syn::Attribute> = ast
        .attrs
        .into_iter()
        .filter(|at| {
            if let Ok(m) = at.parse_meta() {
                let path = m.path();
                if asyncness.is_some()
                    && path.segments.len() == 2
                    && path.segments[1].ident == "test"
                {
                    // We assume that any 2-part attribute with the second part as "test" on an async function
                    // is the "do this test with reactor" wrapper. This is true for actix, tokio and async_std.
                    abort_call_site!(
                        "Found async test attribute after serial/parallel, which will break"
                    );
                }

                // we skip ignore/should_panic because the test framework already deals with it
                !(path.is_ident("ignore") || path.is_ident("should_panic"))
            } else {
                true
            }
        })
        .collect();
    if let Some(ret) = return_type {
        match asyncness {
            Some(_) => {
                let fnname = format_ident!("{}_async_{}_core_with_return", prefix, kind);
                quote! {
                    #(#attrs)
                    *
                    async fn #name () -> #ret {
                        serial_test::#fnname(#(#args ),*, || async #block ).await;
                    }
                }
            }
            None => {
                let fnname = format_ident!("{}_{}_core_with_return", prefix, kind);
                quote! {
                    #(#attrs)
                    *
                    fn #name () -> #ret {
                        serial_test::#fnname(#(#args ),*, || #block )
                    }
                }
            }
        }
    } else {
        match asyncness {
            Some(_) => {
                let fnname = format_ident!("{}_async_{}_core", prefix, kind);
                quote! {
                    #(#attrs)
                    *
                    async fn #name () {
                        serial_test::#fnname(#(#args ),*, || async #block ).await;
                    }
                }
            }
            None => {
                let fnname = format_ident!("{}_{}_core", prefix, kind);
                quote! {
                    #(#attrs)
                    *
                    fn #name () {
                        serial_test::#fnname(#(#args ),*, || #block );
                    }
                }
            }
        }
    }
}

fn serial_setup<T>(
    input: proc_macro2::TokenStream,
    args: Vec<Box<T>>,
    prefix: &str,
) -> proc_macro2::TokenStream
where
    T: quote::ToTokens + ?Sized,
{
    core_setup(input, args, prefix, "serial")
}

fn parallel_setup<T>(
    input: proc_macro2::TokenStream,
    args: Vec<Box<T>>,
    prefix: &str,
) -> proc_macro2::TokenStream
where
    T: quote::ToTokens + ?Sized,
{
    core_setup(input, args, prefix, "parallel")
}

#[cfg(test)]
mod tests {
    use super::{fs_serial_core, local_serial_core};
    use proc_macro2::{Literal, Punct, Spacing, TokenTree};
    use quote::{format_ident, quote};
    use std::iter::FromIterator;

    #[test]
    fn test_serial() {
        let attrs = proc_macro2::TokenStream::new();
        let input = quote! {
            #[test]
            fn foo() {}
        };
        let stream = local_serial_core(attrs.into(), input);
        let compare = quote! {
            #[test]
            fn foo () {
                serial_test::local_serial_core("", || {} );
            }
        };
        assert_eq!(format!("{}", compare), format!("{}", stream));
    }

    #[test]
    fn test_stripped_attributes() {
        let _ = env_logger::builder().is_test(true).try_init();
        let attrs = proc_macro2::TokenStream::new();
        let input = quote! {
            #[test]
            #[ignore]
            #[should_panic(expected = "Testing panic")]
            #[something_else]
            fn foo() {}
        };
        let stream = local_serial_core(attrs.into(), input);
        let compare = quote! {
            #[test]
            #[something_else]
            fn foo () {
                serial_test::local_serial_core("", || {} );
            }
        };
        assert_eq!(format!("{}", compare), format!("{}", stream));
    }

    #[test]
    fn test_serial_async() {
        let attrs = proc_macro2::TokenStream::new();
        let input = quote! {
            async fn foo() {}
        };
        let stream = local_serial_core(attrs.into(), input);
        let compare = quote! {
            async fn foo () {
                serial_test::local_async_serial_core("", || async {} ).await;
            }
        };
        assert_eq!(format!("{}", compare), format!("{}", stream));
    }

    #[test]
    fn test_serial_async_return() {
        let attrs = proc_macro2::TokenStream::new();
        let input = quote! {
            async fn foo() -> Result<(), ()> { Ok(()) }
        };
        let stream = local_serial_core(attrs.into(), input);
        let compare = quote! {
            async fn foo () -> Result<(), ()> {
                serial_test::local_async_serial_core_with_return("", || async { Ok(()) } ).await;
            }
        };
        assert_eq!(format!("{}", compare), format!("{}", stream));
    }

    // 1.54 needed for https://github.com/rust-lang/rust/commit/9daf546b77dbeab7754a80d7336cd8d00c6746e4 change in note message
    #[rustversion::since(1.54)]
    #[test]
    fn test_serial_async_before_wrapper() {
        let t = trybuild::TestCases::new();
        t.compile_fail("tests/broken/test_serial_async_before_wrapper.rs");
    }

    #[test]
    fn test_file_serial() {
        let attrs = vec![TokenTree::Ident(format_ident!("foo"))];
        let input = quote! {
            #[test]
            fn foo() {}
        };
        let stream = fs_serial_core(
            proc_macro2::TokenStream::from_iter(attrs.into_iter()),
            input,
        );
        let compare = quote! {
            #[test]
            fn foo () {
                serial_test::fs_serial_core("foo", None, || {} );
            }
        };
        assert_eq!(format!("{}", compare), format!("{}", stream));
    }

    #[test]
    fn test_file_serial_with_path() {
        let attrs = vec![
            TokenTree::Ident(format_ident!("foo")),
            TokenTree::Punct(Punct::new(',', Spacing::Alone)),
            TokenTree::Literal(Literal::string("bar_path")),
        ];
        let input = quote! {
            #[test]
            fn foo() {}
        };
        let stream = fs_serial_core(
            proc_macro2::TokenStream::from_iter(attrs.into_iter()),
            input,
        );
        let compare = quote! {
            #[test]
            fn foo () {
                serial_test::fs_serial_core("foo", ::std::option::Option::Some("bar_path"), || {} );
            }
        };
        assert_eq!(format!("{}", compare), format!("{}", stream));
    }
}