Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 //! # serial_test_derive
2 //! Helper crate for [serial_test](../serial_test/index.html)
3
4 #![cfg_attr(docsrs, feature(doc_cfg))]
5 #![deny(missing_docs)]
6
7 extern crate proc_macro;
8
9 use proc_macro::TokenStream;
10 use proc_macro2::{Literal, TokenTree};
11 use quote::{format_ident, quote, ToTokens, TokenStreamExt};
12 use std::{iter::FromIterator, ops::Deref};
13 use syn::Result as SynResult;
14
15 /// Allows for the creation of serialised Rust tests
16 /// ````no_run
17 /// #[test]
18 /// #[serial]
19 /// fn test_serial_one() {
20 /// // Do things
21 /// }
22 ///
23 /// #[test]
24 /// #[serial]
25 /// fn test_serial_another() {
26 /// // Do things
27 /// }
28 /// ````
29 /// Multiple tests with the [serial](macro@serial) attribute are guaranteed to be executed in serial. Ordering
30 /// of the tests is not guaranteed however. If you have other tests that can be run in parallel, but would clash
31 /// if run at the same time as the [serial](macro@serial) tests, you can use the [parallel](macro@parallel) attribute.
32 ///
33 /// ## Serial Keys
34 ///
35 /// If you want different subsets of tests to be serialised with each
36 /// other, but not depend on other subsets, you can add a key argument to [serial](macro@serial), and all calls
37 /// with identical arguments will be called in serial. Multiple comma-separated keys will make a test run in serial with all of the sets with any of those keys.
38 ///
39 /// ````no_run
40 /// #[test]
41 /// #[serial(something)]
42 /// fn test_serial_one() {
43 /// // Do things
44 /// }
45 ///
46 /// #[test]
47 /// #[serial(something)]
48 /// fn test_serial_another() {
49 /// // Do things
50 /// }
51 ///
52 /// #[test]
53 /// #[serial(other)]
54 /// fn test_serial_third() {
55 /// // Do things
56 /// }
57 ///
58 /// #[test]
59 /// #[serial(other)]
60 /// fn test_serial_fourth() {
61 /// // Do things
62 /// }
63 ///
64 /// #[test]
65 /// #[serial(something, other)]
66 /// fn test_serial_fifth() {
67 /// // Do things, eventually
68 /// }
69 /// ````
70 /// `test_serial_one` and `test_serial_another` will be executed in serial, as will `test_serial_third` and `test_serial_fourth`
71 /// but neither sequence will be blocked by the other. `test_serial_fifth` is blocked by tests in either sequence.
72 ///
73 /// Nested serialised tests (i.e. a [serial](macro@serial) tagged test calling another) are supported.
74 ///
75 /// ## Inner Attributes
76 ///
77 /// You can apply attributes to an inner test function using `inner_attrs`. This is useful for
78 /// applying attributes like `ntest::timeout` that should only affect the test body, not the
79 /// mutex acquisition:
80 ///
81 /// ````no_run
82 /// #[test]
83 /// #[serial(inner_attrs = [ntest::timeout(1000)])]
84 /// fn test_with_timeout() {
85 /// // The timeout only applies to this body, not the serial lock acquisition
86 /// }
87 /// ````
88 ///
89 /// Multiple inner attributes can be specified:
90 /// ````no_run
91 /// #[test]
92 /// #[serial(inner_attrs = [ntest::timeout(1000), other_attr])]
93 /// fn test_with_multiple_attrs() {
94 /// // Both attributes apply to the inner function
95 /// }
96 /// ````
97 ///
98 /// Inner attributes can be combined with keys:
99 /// ````no_run
100 /// #[test]
101 /// #[serial(my_key, inner_attrs = [ntest::timeout(1000)])]
102 /// fn test_with_key_and_timeout() {
103 /// // Serialized with 'my_key' group, with timeout on the body
104 /// }
105 /// ````
106 #[proc_macro_attribute]
107 pub fn serial(attr: TokenStream, input: TokenStream) -> TokenStream {
108 local_serial_core(attr.into(), input.into()).into()
109 }
110
111 /// Allows for the creation of parallel Rust tests that won't clash with serial tests
112 /// ````no_run
113 /// #[test]
114 /// #[serial]
115 /// fn test_serial_one() {
116 /// // Do things
117 /// }
118 ///
119 /// #[test]
120 /// #[parallel]
121 /// fn test_parallel_one() {
122 /// // Do things
123 /// }
124 ///
125 /// #[test]
126 /// #[parallel]
127 /// fn test_parallel_two() {
128 /// // Do things
129 /// }
130 /// ````
131 /// Multiple tests with the [parallel](macro@parallel) attribute may run in parallel, but not at the
132 /// same time as [serial](macro@serial) tests. e.g. in the example code above, `test_parallel_one`
133 /// and `test_parallel_two` may run at the same time, but `test_serial_one` is guaranteed not to run
134 /// at the same time as either of them. [parallel](macro@parallel) also takes key arguments for groups
135 /// of tests as per [serial](macro@serial).
136 ///
137 /// Note that this has zero effect on [file_serial](macro@file_serial) tests, as that uses a different
138 /// serialisation mechanism. For that, you want [file_parallel](macro@file_parallel).
139 ///
140 /// Inner attributes are also supported via `inner_attrs`, see [serial](macro@serial) for details.
141 #[proc_macro_attribute]
142 pub fn parallel(attr: TokenStream, input: TokenStream) -> TokenStream {
143 local_parallel_core(attr.into(), input.into()).into()
144 }
145
146 /// Allows for the creation of file-serialised Rust tests
147 /// ````no_run
148 /// #[test]
149 /// #[file_serial]
150 /// fn test_serial_one() {
151 /// // Do things
152 /// }
153 ///
154 /// #[test]
155 /// #[file_serial]
156 /// fn test_serial_another() {
157 /// // Do things
158 /// }
159 /// ````
160 ///
161 /// Multiple tests with the [file_serial](macro@file_serial) attribute are guaranteed to run in serial, as per the [serial](macro@serial)
162 /// attribute. Note that there are no guarantees about one test with [serial](macro@serial) and another with [file_serial](macro@file_serial)
163 /// as they lock using different methods, and [file_serial](macro@file_serial) does not support nested serialised tests, but otherwise acts
164 /// like [serial](macro@serial). If you have other tests that can be run in parallel, but would clash
165 /// if run at the same time as the [file_serial](macro@file_serial) tests, you can use the [file_parallel](macro@file_parallel) attribute.
166 ///
167 /// It also supports an optional `path` arg as well as key(s) as per [serial](macro@serial), which is the path to the file used for
168 /// locking purposes. This file is managed by `serial_test` and no assumptions about it's format should be made. The `path` defaults to
169 /// a file under a reasonable temp directory for the OS if not specified. If the `path` is specified, you can only use one key, as we
170 /// can't generate per-key paths if you've done that.
171 /// ````no_run
172 /// #[test]
173 /// #[file_serial(key)]
174 /// fn test_serial_one() {
175 /// // Do things
176 /// }
177 ///
178 /// #[test]
179 /// #[file_serial(key, path => "/tmp/foo")]
180 /// fn test_serial_another() {
181 /// // Do things
182 /// }
183 /// ````
184 ///
185 /// Inner attributes are also supported via `inner_attrs`, see [serial](macro@serial) for details.
186 #[proc_macro_attribute]
187 #[cfg_attr(docsrs, doc(cfg(feature = "file_locks")))]
188 pub fn file_serial(attr: TokenStream, input: TokenStream) -> TokenStream {
189 fs_serial_core(attr.into(), input.into()).into()
190 }
191
192 /// Allows for the creation of file-serialised parallel Rust tests that won't clash with file-serialised serial tests
193 /// ````no_run
194 /// #[test]
195 /// #[file_serial]
196 /// fn test_serial_one() {
197 /// // Do things
198 /// }
199 ///
200 /// #[test]
201 /// #[file_parallel]
202 /// fn test_parallel_one() {
203 /// // Do things
204 /// }
205 ///
206 /// #[test]
207 /// #[file_parallel]
208 /// fn test_parallel_two() {
209 /// // Do things
210 /// }
211 /// ````
212 /// Effectively, this should behave like [parallel](macro@parallel) but for [file_serial](macro@file_serial).
213 /// Note that as per [file_serial](macro@file_serial) this doesn't do anything for [serial](macro@serial)/[parallel](macro@parallel) tests.
214 ///
215 /// It also supports an optional `path` arg as well as key(s) as per [serial](macro@serial), which is the path to the file used for
216 /// locking purposes. This file is managed by `serial_test` and no assumptions about it's format should be made. The `path` defaults to
217 /// a file under a reasonable temp directory for the OS if not specified. If the `path` is specified, you can only use one key, as we
218 /// can't generate per-key paths if you've done that.
219 /// ````no_run
220 /// #[test]
221 /// #[file_parallel(key, path => "/tmp/foo")]
222 /// fn test_parallel_one() {
223 /// // Do things
224 /// }
225 ///
226 /// #[test]
227 /// #[file_parallel(key, path => "/tmp/foo")]
228 /// fn test_parallel_another() {
229 /// // Do things
230 /// }
231 /// ````
232 ///
233 /// Inner attributes are also supported via `inner_attrs`, see [serial](macro@serial) for details.
234 #[proc_macro_attribute]
235 #[cfg_attr(docsrs, doc(cfg(feature = "file_locks")))]
236 pub fn file_parallel(attr: TokenStream, input: TokenStream) -> TokenStream {
237 fs_parallel_core(attr.into(), input.into()).into()
238 }
239
240 // Based off of https://github.com/dtolnay/quote/issues/20#issuecomment-437341743
241 #[derive(Default, Debug, Clone)]
242 struct QuoteOption<T>(Option<T>);
243
244 impl<T: ToTokens> ToTokens for QuoteOption<T> {
245 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
246 tokens.append_all(match self.0 {
247 Some(ref t) => quote! { ::std::option::Option::Some(#t) },
248 None => quote! { ::std::option::Option::None },
249 });
250 }
251 }
252
253 #[derive(Default, Debug)]
254 struct Config {
255 names: Vec<String>,
256 path: QuoteOption<String>,
257 crate_ident: Vec<TokenTree>,
258 inner_attrs: Vec<proc_macro2::TokenStream>,
259 }
260
261 fn string_from_literal(literal: Literal) -> String {
262 let string_literal = literal.to_string();
263 if !string_literal.starts_with('\"') || !string_literal.ends_with('\"') {
264 panic!("Expected a string literal, got '{}'", string_literal);
265 }
266 // Hacky way of getting a string without the enclosing quotes
267 string_literal[1..string_literal.len() - 1].to_string()
268 }
269
270 /// Parse the contents of a bracket group `[attr1(args), attr2]` into a vector of token streams
271 /// where each element represents a single attribute.
272 fn parse_inner_attrs_from_group(group: proc_macro2::Group) -> Vec<proc_macro2::TokenStream> {
273 let mut inner_attrs = Vec::new();
274 let mut current_attr: Vec<TokenTree> = Vec::new();
275
276 for token in group.stream() {
277 let is_comma = matches!(&token, TokenTree::Punct(p) if p.as_char() == ',');
278
279 if is_comma {
280 // End of current attribute
281 if !current_attr.is_empty() {
282 inner_attrs.push(proc_macro2::TokenStream::from_iter(current_attr.drain(..)));
283 }
284 } else {
285 current_attr.push(token);
286 }
287 }
288
289 // Don't forget the last attribute
290 if !current_attr.is_empty() {
291 inner_attrs.push(proc_macro2::TokenStream::from_iter(current_attr));
292 }
293
294 inner_attrs
295 }
296
297 fn get_config(attr: proc_macro2::TokenStream) -> Config {
298 let mut attrs = attr.into_iter().collect::<Vec<TokenTree>>();
299 let mut raw_args: Vec<String> = Vec::new();
300 let mut in_path: bool = false;
301 let mut path: Option<String> = None;
302 let mut in_crate: bool = false;
303 let mut crate_ident: Option<Vec<TokenTree>> = None;
304 let mut in_inner_attrs: bool = false;
305 let mut inner_attrs: Vec<proc_macro2::TokenStream> = Vec::new();
306 while !attrs.is_empty() {
307 match attrs.remove(0) {
308 TokenTree::Ident(id) if id.to_string().eq_ignore_ascii_case("path") => {
309 in_path = true;
310 }
311 TokenTree::Ident(id) if id.to_string().eq_ignore_ascii_case("crate") => {
312 in_crate = true;
313 }
314 TokenTree::Ident(id) if id.to_string().eq_ignore_ascii_case("inner_attrs") => {
315 in_inner_attrs = true;
316 }
317 TokenTree::Ident(id) => {
318 let name = id.to_string();
319 raw_args.push(name);
320 }
321 x => {
322 panic!(
323 "Expected literal as key args (or a 'path => '\"foo\"'), not {}",
324 x
325 );
326 }
327 }
328 if in_path {
329 if attrs.len() < 3 {
330 panic!("Expected a '=> <path>' after 'path'");
331 }
332 match attrs.remove(0) {
333 TokenTree::Punct(p) if p.as_char() == '=' => {}
334 x => {
335 panic!("Expected = after path, not {}", x);
336 }
337 }
338 match attrs.remove(0) {
339 TokenTree::Punct(p) if p.as_char() == '>' => {}
340 x => {
341 panic!("Expected > after path, not {}", x);
342 }
343 }
344 match attrs.remove(0) {
345 TokenTree::Literal(literal) => {
346 path = Some(string_from_literal(literal));
347 }
348 x => {
349 panic!("Expected literals as path arg, not {}", x);
350 }
351 }
352 in_path = false;
353 }
354 if in_crate {
355 if attrs.len() < 2 {
356 panic!("Expected a '= <import-path>' after 'crate'");
357 }
358 match attrs.remove(0) {
359 TokenTree::Punct(p) if p.as_char() == '=' => {}
360 x => {
361 panic!("Expected = after crate, not {}", x);
362 }
363 }
364 let ident_items: Vec<_> = attrs
365 .iter()
366 .map_while(|t| {
367 match t {
368 TokenTree::Ident(_) => {}
369 TokenTree::Punct(p) if p.as_char() != ',' => {}
370 _ => {
371 return None;
372 }
373 };
374 Some(t.clone())
375 })
376 .collect();
377 for _ in 0..ident_items.len() {
378 attrs.remove(0);
379 }
380 crate_ident = Some(ident_items);
381 in_crate = false;
382 }
383 if in_inner_attrs {
384 if attrs.len() < 2 {
385 panic!("Expected a '= [attr1, attr2, ...]' after 'inner_attrs'");
386 }
387 match attrs.remove(0) {
388 TokenTree::Punct(p) if p.as_char() == '=' => {}
389 x => {
390 panic!("Expected '=' after 'inner_attrs' not {}", x);
391 }
392 }
393 match attrs.remove(0) {
394 TokenTree::Group(group) if group.delimiter() == proc_macro2::Delimiter::Bracket => {
395 inner_attrs = parse_inner_attrs_from_group(group);
396 }
397 x => {
398 panic!("Expected [...] after 'inner_attrs =' not {}", x);
399 }
400 }
401 in_inner_attrs = false;
402 }
403 if !attrs.is_empty() {
404 match attrs.remove(0) {
405 TokenTree::Punct(p) if p.as_char() == ',' => {}
406 x => {
407 panic!("Expected ',' between args not {}", x);
408 }
409 }
410 }
411 }
412 if raw_args.is_empty() {
413 raw_args.push(String::new());
414 }
415 raw_args.sort(); // So the keys are always requested in the same order. Avoids dining philosopher issues.
416 Config {
417 names: raw_args,
418 path: QuoteOption(path),
419 crate_ident: crate_ident.unwrap_or(vec![TokenTree::Ident(format_ident!("serial_test"))]),
420 inner_attrs,
421 }
422 }
423
424 fn local_serial_core(
425 attr: proc_macro2::TokenStream,
426 input: proc_macro2::TokenStream,
427 ) -> proc_macro2::TokenStream {
428 let config = get_config(attr);
429 serial_setup(input, config, "local")
430 }
431
432 fn local_parallel_core(
433 attr: proc_macro2::TokenStream,
434 input: proc_macro2::TokenStream,
435 ) -> proc_macro2::TokenStream {
436 let config = get_config(attr);
437 parallel_setup(input, config, "local")
438 }
439
440 fn fs_serial_core(
441 attr: proc_macro2::TokenStream,
442 input: proc_macro2::TokenStream,
443 ) -> proc_macro2::TokenStream {
444 let config = get_config(attr);
445 serial_setup(input, config, "fs")
446 }
447
448 fn fs_parallel_core(
449 attr: proc_macro2::TokenStream,
450 input: proc_macro2::TokenStream,
451 ) -> proc_macro2::TokenStream {
452 let config = get_config(attr);
453 parallel_setup(input, config, "fs")
454 }
455
456 #[allow(clippy::cmp_owned)]
457 fn core_setup(
458 input: proc_macro2::TokenStream,
459 config: &Config,
460 prefix: &str,
461 kind: &str,
462 ) -> proc_macro2::TokenStream {
463 let fn_ast: SynResult<syn::ItemFn> = syn::parse2(input.clone());
464 if let Ok(ast) = fn_ast {
465 return fn_setup(ast, config, prefix, kind);
466 };
467 let mod_ast: SynResult<syn::ItemMod> = syn::parse2(input);
468 match mod_ast {
469 Ok(mut ast) => {
470 let new_content = ast.content.clone().map(|(brace, items)| {
471 let new_items = items
472 .into_iter()
473 .map(|item| match item {
474 syn::Item::Fn(item_fn)
475 if item_fn.attrs.iter().any(|attr| {
476 attr.meta
477 .path()
478 .segments
479 .iter()
480 .map(|s| s.ident.to_string())
481 .collect::<Vec<String>>()
482 .join("::")
483 .contains("test")
484 }) =>
485 {
486 let tokens = fn_setup(item_fn, config, prefix, kind);
487 let token_display = format!("tokens: {tokens}");
488 syn::parse2(tokens).expect(&token_display)
489 }
490 other => other,
491 })
492 .collect();
493 (brace, new_items)
494 });
495 if let Some(nc) = new_content {
496 ast.content.replace(nc);
497 }
498 ast.attrs.retain(|attr| {
499 attr.meta.path().segments.first().unwrap().ident.to_string() != "serial"
500 });
501 ast.into_token_stream()
502 }
503 Err(_) => {
504 panic!("Attribute applied to something other than mod or fn!");
505 }
506 }
507 }
508
509 fn fn_setup(
510 ast: syn::ItemFn,
511 config: &Config,
512 prefix: &str,
513 kind: &str,
514 ) -> proc_macro2::TokenStream {
515 let asyncness = ast.sig.asyncness;
516 if asyncness.is_some() && cfg!(not(feature = "async")) {
517 panic!("async testing attempted with async feature disabled in serial_test!");
518 }
519 let vis = ast.vis;
520 let name = ast.sig.ident;
521 #[cfg(all(feature = "test_logging", not(test)))]
522 let print_name = {
523 let print_str = format!("Starting {name}");
524 quote! {
525 println!(#print_str);
526 }
527 };
528 #[cfg(any(not(feature = "test_logging"), test))]
529 let print_name = quote! {};
530 let return_type = match ast.sig.output {
531 syn::ReturnType::Default => None,
532 syn::ReturnType::Type(_rarrow, ref box_type) => Some(box_type.deref()),
533 };
534 let block = ast.block;
535 let attrs: Vec<syn::Attribute> = ast.attrs.into_iter().collect();
536 let names = config.names.clone();
537 let path = config.path.clone();
538 let crate_ident = config.crate_ident.clone();
539 let inner_attrs = &config.inner_attrs;
540 let has_inner_attrs = !inner_attrs.is_empty();
541 if let Some(ret) = return_type {
542 match asyncness {
543 Some(_) => {
544 let fnname = format_ident!("{}_async_{}_core_with_return", prefix, kind);
545 let temp_fn = format_ident!("_{}_internal", name);
546 quote! {
547 #(#attrs)
548 *
549 #vis async fn #name () -> #ret {
550 #(#[#inner_attrs])*
551 async fn #temp_fn () -> #ret
552 #block
553
554 #print_name
555 #(#crate_ident)*::#fnname(vec![#(#names ),*], #path, #temp_fn()).await
556 }
557 }
558 }
559 None => {
560 let fnname = format_ident!("{}_{}_core_with_return", prefix, kind);
561 if has_inner_attrs {
562 let temp_fn = format_ident!("_{}_inner", name);
563 quote! {
564 #(#attrs)
565 *
566 #vis fn #name () -> #ret {
567 #(#[#inner_attrs])*
568 fn #temp_fn () -> #ret
569 #block
570
571 #print_name
572 #(#crate_ident)*::#fnname(vec![#(#names ),*], #path, || #temp_fn() )
573 }
574 }
575 } else {
576 quote! {
577 #(#attrs)
578 *
579 #vis fn #name () -> #ret {
580 #print_name
581 #(#crate_ident)*::#fnname(vec![#(#names ),*], #path, || #block )
582 }
583 }
584 }
585 }
586 }
587 } else {
588 match asyncness {
589 Some(_) => {
590 let fnname = format_ident!("{}_async_{}_core", prefix, kind);
591 let temp_fn = format_ident!("_{}_internal", name);
592 quote! {
593 #(#attrs)
594 *
595 #vis async fn #name () {
596 #(#[#inner_attrs])*
597 async fn #temp_fn ()
598 #block
599
600 #print_name
601 #(#crate_ident)*::#fnname(vec![#(#names ),*], #path, #temp_fn()).await;
602 }
603 }
604 }
605 None => {
606 let fnname = format_ident!("{}_{}_core", prefix, kind);
607 if has_inner_attrs {
608 let temp_fn = format_ident!("_{}_inner", name);
609 quote! {
610 #(#attrs)
611 *
612 #vis fn #name () {
613 #(#[#inner_attrs])*
614 fn #temp_fn ()
615 #block
616
617 #print_name
618 #(#crate_ident)*::#fnname(vec![#(#names ),*], #path, || #temp_fn() );
619 }
620 }
621 } else {
622 quote! {
623 #(#attrs)
624 *
625 #vis fn #name () {
626 #print_name
627 #(#crate_ident)*::#fnname(vec![#(#names ),*], #path, || #block );
628 }
629 }
630 }
631 }
632 }
633 }
634 }
635
636 fn serial_setup(
637 input: proc_macro2::TokenStream,
638 config: Config,
639 prefix: &str,
640 ) -> proc_macro2::TokenStream {
641 core_setup(input, &config, prefix, "serial")
642 }
643
644 fn parallel_setup(
645 input: proc_macro2::TokenStream,
646 config: Config,
647 prefix: &str,
648 ) -> proc_macro2::TokenStream {
649 core_setup(input, &config, prefix, "parallel")
650 }
651
652 #[cfg(test)]
653 mod tests {
654 use super::{fs_serial_core, local_parallel_core, local_serial_core};
655 use proc_macro2::{TokenStream, TokenTree};
656 use quote::quote;
657 use std::iter::FromIterator;
658
659 fn init() {
660 let _ = env_logger::builder().is_test(false).try_init();
661 }
662
663 fn unparse(input: TokenStream) -> String {
664 let item = syn::parse2(input).unwrap();
665 let file = syn::File {
666 attrs: vec![],
667 items: vec![item],
668 shebang: None,
669 };
670
671 prettyplease::unparse(&file)
672 }
673
674 fn compare_streams(first: TokenStream, second: TokenStream) {
675 let f = unparse(first);
676 assert_eq!(f, unparse(second));
677 }
678
679 #[test]
680 fn test_serial() {
681 init();
682 let attrs = proc_macro2::TokenStream::new();
683 let input = quote! {
684 #[test]
685 fn foo() {}
686 };
687 let stream = local_serial_core(attrs.into(), input);
688 let compare = quote! {
689 #[test]
690 fn foo () {
691 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || {} );
692 }
693 };
694 compare_streams(compare, stream);
695 }
696
697 #[test]
698 fn test_serial_with_pub() {
699 init();
700 let attrs = proc_macro2::TokenStream::new();
701 let input = quote! {
702 #[test]
703 pub fn foo() {}
704 };
705 let stream = local_serial_core(attrs.into(), input);
706 let compare = quote! {
707 #[test]
708 pub fn foo () {
709 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || {} );
710 }
711 };
712 compare_streams(compare, stream);
713 }
714
715 #[test]
716 fn test_other_attributes() {
717 init();
718 let attrs = proc_macro2::TokenStream::new();
719 let input = quote! {
720 #[test]
721 #[ignore]
722 #[should_panic(expected = "Testing panic")]
723 #[something_else]
724 fn foo() {}
725 };
726 let stream = local_serial_core(attrs.into(), input);
727 let compare = quote! {
728 #[test]
729 #[ignore]
730 #[should_panic(expected = "Testing panic")]
731 #[something_else]
732 fn foo () {
733 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || {} );
734 }
735 };
736 compare_streams(compare, stream);
737 }
738
739 #[test]
740 #[cfg(feature = "async")]
741 fn test_serial_async() {
742 init();
743 let attrs = proc_macro2::TokenStream::new();
744 let input = quote! {
745 async fn foo() {}
746 };
747 let stream = local_serial_core(attrs.into(), input);
748 let compare = quote! {
749 async fn foo () {
750 async fn _foo_internal () { }
751 serial_test::local_async_serial_core(vec![""], ::std::option::Option::None, _foo_internal() ).await;
752 }
753 };
754 assert_eq!(format!("{}", compare), format!("{}", stream));
755 }
756
757 #[test]
758 #[cfg(feature = "async")]
759 fn test_serial_async_return() {
760 init();
761 let attrs = proc_macro2::TokenStream::new();
762 let input = quote! {
763 async fn foo() -> Result<(), ()> { Ok(()) }
764 };
765 let stream = local_serial_core(attrs.into(), input);
766 let compare = quote! {
767 async fn foo () -> Result<(), ()> {
768 async fn _foo_internal () -> Result<(), ()> { Ok(()) }
769 serial_test::local_async_serial_core_with_return(vec![""], ::std::option::Option::None, _foo_internal() ).await
770 }
771 };
772 assert_eq!(format!("{}", compare), format!("{}", stream));
773 }
774
775 #[test]
776 fn test_file_serial() {
777 init();
778 let attrs: Vec<_> = quote! { foo }.into_iter().collect();
779 let input = quote! {
780 #[test]
781 fn foo() {}
782 };
783 let stream = fs_serial_core(
784 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
785 input,
786 );
787 let compare = quote! {
788 #[test]
789 fn foo () {
790 serial_test::fs_serial_core(vec!["foo"], ::std::option::Option::None, || {} );
791 }
792 };
793 compare_streams(compare, stream);
794 }
795
796 #[test]
797 fn test_file_serial_no_args() {
798 init();
799 let attrs = proc_macro2::TokenStream::new();
800 let input = quote! {
801 #[test]
802 fn foo() {}
803 };
804 let stream = fs_serial_core(
805 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
806 input,
807 );
808 let compare = quote! {
809 #[test]
810 fn foo () {
811 serial_test::fs_serial_core(vec![""], ::std::option::Option::None, || {} );
812 }
813 };
814 compare_streams(compare, stream);
815 }
816
817 #[test]
818 fn test_file_serial_with_path() {
819 init();
820 let attrs: Vec<_> = quote! { foo, path => "bar_path" }.into_iter().collect();
821 let input = quote! {
822 #[test]
823 fn foo() {}
824 };
825 let stream = fs_serial_core(
826 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
827 input,
828 );
829 let compare = quote! {
830 #[test]
831 fn foo () {
832 serial_test::fs_serial_core(vec!["foo"], ::std::option::Option::Some("bar_path"), || {} );
833 }
834 };
835 compare_streams(compare, stream);
836 }
837
838 #[test]
839 fn test_single_attr() {
840 init();
841 let attrs: Vec<_> = quote! { one}.into_iter().collect();
842 let input = quote! {
843 #[test]
844 fn single() {}
845 };
846 let stream = local_serial_core(
847 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
848 input,
849 );
850 let compare = quote! {
851 #[test]
852 fn single () {
853 serial_test::local_serial_core(vec!["one"], ::std::option::Option::None, || {} );
854 }
855 };
856 compare_streams(compare, stream);
857 }
858
859 #[test]
860 fn test_multiple_attr() {
861 init();
862 let attrs: Vec<_> = quote! { two, one }.into_iter().collect();
863 let input = quote! {
864 #[test]
865 fn multiple() {}
866 };
867 let stream = local_serial_core(
868 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
869 input,
870 );
871 let compare = quote! {
872 #[test]
873 fn multiple () {
874 serial_test::local_serial_core(vec!["one", "two"], ::std::option::Option::None, || {} );
875 }
876 };
877 compare_streams(compare, stream);
878 }
879
880 #[test]
881 fn test_mod() {
882 init();
883 let attrs = proc_macro2::TokenStream::new();
884 let input = quote! {
885 #[cfg(test)]
886 #[serial]
887 mod serial_attr_tests {
888 pub fn foo() {
889 println!("Nothing");
890 }
891
892 #[test]
893 fn bar() {}
894 }
895 };
896 let stream = local_serial_core(
897 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
898 input,
899 );
900 let compare = quote! {
901 #[cfg(test)]
902 mod serial_attr_tests {
903 pub fn foo() {
904 println!("Nothing");
905 }
906
907 #[test]
908 fn bar() {
909 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || {} );
910 }
911 }
912 };
913 compare_streams(compare, stream);
914 }
915
916 #[test]
917 fn test_later_test_mod() {
918 init();
919 let attrs = proc_macro2::TokenStream::new();
920 let input = quote! {
921 #[cfg(test)]
922 #[serial]
923 mod serial_attr_tests {
924 pub fn foo() {
925 println!("Nothing");
926 }
927
928 #[demo_library::test]
929 fn bar() {}
930 }
931 };
932 let stream = local_serial_core(
933 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
934 input,
935 );
936 let compare = quote! {
937 #[cfg(test)]
938 mod serial_attr_tests {
939 pub fn foo() {
940 println!("Nothing");
941 }
942
943 #[demo_library::test]
944 fn bar() {
945 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || {} );
946 }
947 }
948 };
949 compare_streams(compare, stream);
950 }
951
952 #[test]
953 #[cfg(feature = "async")]
954 fn test_mod_with_async() {
955 init();
956 let attrs = proc_macro2::TokenStream::new();
957 let input = quote! {
958 #[cfg(test)]
959 #[serial]
960 mod serial_attr_tests {
961 #[demo_library::test]
962 async fn foo() -> Result<(), ()> {
963 Ok(())
964 }
965
966 #[demo_library::test]
967 #[ignore = "bla"]
968 async fn bar() -> Result<(), ()> {
969 Ok(())
970 }
971 }
972 };
973 let stream = local_serial_core(
974 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
975 input,
976 );
977 let compare = quote! {
978 #[cfg(test)]
979 mod serial_attr_tests {
980 #[demo_library::test]
981 async fn foo() -> Result<(), ()> {
982 async fn _foo_internal() -> Result<(), ()> { Ok(())}
983 serial_test::local_async_serial_core_with_return(vec![""], ::std::option::Option::None, _foo_internal() ).await
984 }
985
986 #[demo_library::test]
987 #[ignore = "bla"]
988 async fn bar() -> Result<(), ()> {
989 async fn _bar_internal() -> Result<(), ()> { Ok(())}
990 serial_test::local_async_serial_core_with_return(vec![""], ::std::option::Option::None, _bar_internal() ).await
991 }
992 }
993 };
994 compare_streams(compare, stream);
995 }
996
997 #[test]
998 fn test_nested_return() {
999 init();
1000 let attrs = proc_macro2::TokenStream::new();
1001 let input = quote! {
1002 #[test]
1003 fn test() -> Result<Result<(), ()>, ()> {
1004 Ok(Ok(()))
1005 }
1006 };
1007 let stream = local_serial_core(
1008 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1009 input,
1010 );
1011 let compare = quote! {
1012 #[test]
1013 fn test() -> Result<Result<(), ()>, ()> {
1014 serial_test::local_serial_core_with_return(vec![""], ::std::option::Option::None, || {Ok(Ok(()))} )
1015 }
1016 };
1017 compare_streams(compare, stream);
1018 }
1019
1020 #[test]
1021 fn test_crate_wrapper() {
1022 init();
1023 let attrs: Vec<_> = quote! { crate = wrapper::__derive_refs::serial }
1024 .into_iter()
1025 .collect();
1026 let input = quote! {
1027 #[test]
1028 fn foo() {}
1029 };
1030 let stream = fs_serial_core(
1031 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1032 input,
1033 );
1034 let compare = quote! {
1035 #[test]
1036 fn foo () {
1037 wrapper::__derive_refs::serial::fs_serial_core(vec![""], ::std::option::Option::None, || {} );
1038 }
1039 };
1040 compare_streams(compare, stream);
1041 }
1042
1043 #[test]
1044 fn test_crate_wrapper_with_path() {
1045 init();
1046 let attrs: Vec<_> = quote! {crate = wrapper::__derive_refs::serial, path => "/tmp/bar" }
1047 .into_iter()
1048 .collect();
1049 let input = quote! {
1050 #[test]
1051 fn foo() {}
1052 };
1053 let stream = fs_serial_core(
1054 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1055 input,
1056 );
1057 let compare = quote! {
1058 #[test]
1059 fn foo () {
1060 wrapper::__derive_refs::serial::fs_serial_core(vec![""], ::std::option::Option::Some("/tmp/bar"), || {} );
1061 }
1062 };
1063 compare_streams(compare, stream);
1064 }
1065
1066 #[test]
1067 fn test_crate_wrapper_with_path_and_key() {
1068 init();
1069 let attrs: Vec<_> =
1070 quote! { key1, key2, path => "/tmp/bar", crate = wrapper::__derive_refs::serial }
1071 .into_iter()
1072 .collect();
1073 let input = quote! {
1074 #[test]
1075 fn foo() {}
1076 };
1077 let stream = fs_serial_core(
1078 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1079 input,
1080 );
1081 let compare = quote! {
1082 #[test]
1083 fn foo () {
1084 wrapper::__derive_refs::serial::fs_serial_core(vec!["key1", "key2"], ::std::option::Option::Some("/tmp/bar"), || {} );
1085 }
1086 };
1087 compare_streams(compare, stream);
1088 }
1089
1090 #[test]
1091 fn test_inner_attrs_single() {
1092 init();
1093 let attrs: Vec<_> = quote! { inner_attrs = [timeout(100)] }
1094 .into_iter()
1095 .collect();
1096 let input = quote! {
1097 #[test]
1098 fn foo() {}
1099 };
1100 let stream = local_serial_core(
1101 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1102 input,
1103 );
1104 let compare = quote! {
1105 #[test]
1106 fn foo () {
1107 #[timeout(100)]
1108 fn _foo_inner() {}
1109 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || _foo_inner() );
1110 }
1111 };
1112 compare_streams(compare, stream);
1113 }
1114
1115 #[test]
1116 fn test_inner_attrs_multiple() {
1117 init();
1118 let attrs: Vec<_> = quote! { inner_attrs = [timeout(100), other_attr] }
1119 .into_iter()
1120 .collect();
1121 let input = quote! {
1122 #[test]
1123 fn foo() {}
1124 };
1125 let stream = local_serial_core(
1126 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1127 input,
1128 );
1129 let compare = quote! {
1130 #[test]
1131 fn foo () {
1132 #[timeout(100)]
1133 #[other_attr]
1134 fn _foo_inner() {}
1135 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || _foo_inner() );
1136 }
1137 };
1138 compare_streams(compare, stream);
1139 }
1140
1141 #[test]
1142 fn test_inner_attrs_with_key() {
1143 init();
1144 let attrs: Vec<_> = quote! { my_key, inner_attrs = [timeout(100)] }
1145 .into_iter()
1146 .collect();
1147 let input = quote! {
1148 #[test]
1149 fn foo() {}
1150 };
1151 let stream = local_serial_core(
1152 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1153 input,
1154 );
1155 let compare = quote! {
1156 #[test]
1157 fn foo () {
1158 #[timeout(100)]
1159 fn _foo_inner() {}
1160 serial_test::local_serial_core(vec!["my_key"], ::std::option::Option::None, || _foo_inner() );
1161 }
1162 };
1163 compare_streams(compare, stream);
1164 }
1165
1166 #[test]
1167 fn test_inner_attrs_with_return() {
1168 init();
1169 let attrs: Vec<_> = quote! { inner_attrs = [timeout(100)] }
1170 .into_iter()
1171 .collect();
1172 let input = quote! {
1173 #[test]
1174 fn foo() -> Result<(), ()> { Ok(()) }
1175 };
1176 let stream = local_serial_core(
1177 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1178 input,
1179 );
1180 let compare = quote! {
1181 #[test]
1182 fn foo () -> Result<(), ()> {
1183 #[timeout(100)]
1184 fn _foo_inner() -> Result<(), ()> { Ok(()) }
1185 serial_test::local_serial_core_with_return(vec![""], ::std::option::Option::None, || _foo_inner() )
1186 }
1187 };
1188 compare_streams(compare, stream);
1189 }
1190
1191 #[test]
1192 #[cfg(feature = "async")]
1193 fn test_inner_attrs_async() {
1194 init();
1195 let attrs: Vec<_> = quote! { inner_attrs = [timeout(100)] }
1196 .into_iter()
1197 .collect();
1198 let input = quote! {
1199 async fn foo() {}
1200 };
1201 let stream = local_serial_core(
1202 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1203 input,
1204 );
1205 let compare = quote! {
1206 async fn foo () {
1207 #[timeout(100)]
1208 async fn _foo_internal () { }
1209 serial_test::local_async_serial_core(vec![""], ::std::option::Option::None, _foo_internal() ).await;
1210 }
1211 };
1212 assert_eq!(format!("{}", compare), format!("{}", stream));
1213 }
1214
1215 #[test]
1216 #[cfg(feature = "async")]
1217 fn test_inner_attrs_async_with_return() {
1218 init();
1219 let attrs: Vec<_> = quote! { inner_attrs = [timeout(100)] }
1220 .into_iter()
1221 .collect();
1222 let input = quote! {
1223 async fn foo() -> Result<(), ()> { Ok(()) }
1224 };
1225 let stream = local_serial_core(
1226 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1227 input,
1228 );
1229 let compare = quote! {
1230 async fn foo () -> Result<(), ()> {
1231 #[timeout(100)]
1232 async fn _foo_internal () -> Result<(), ()> { Ok(()) }
1233 serial_test::local_async_serial_core_with_return(vec![""], ::std::option::Option::None, _foo_internal() ).await
1234 }
1235 };
1236 assert_eq!(format!("{}", compare), format!("{}", stream));
1237 }
1238
1239 #[test]
1240 fn test_inner_attrs_with_namespaced_attr() {
1241 init();
1242 let attrs: Vec<_> = quote! { inner_attrs = [ntest::timeout(100)] }
1243 .into_iter()
1244 .collect();
1245 let input = quote! {
1246 #[test]
1247 fn foo() {}
1248 };
1249 let stream = local_serial_core(
1250 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1251 input,
1252 );
1253 let compare = quote! {
1254 #[test]
1255 fn foo () {
1256 #[ntest::timeout(100)]
1257 fn _foo_inner() {}
1258 serial_test::local_serial_core(vec![""], ::std::option::Option::None, || _foo_inner() );
1259 }
1260 };
1261 compare_streams(compare, stream);
1262 }
1263
1264 #[test]
1265 fn test_inner_attrs_parallel() {
1266 init();
1267 let attrs: Vec<_> = quote! { inner_attrs = [timeout(100)] }
1268 .into_iter()
1269 .collect();
1270 let input = quote! {
1271 #[test]
1272 fn foo() {}
1273 };
1274 let stream = local_parallel_core(
1275 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1276 input,
1277 );
1278 let compare = quote! {
1279 #[test]
1280 fn foo () {
1281 #[timeout(100)]
1282 fn _foo_inner() {}
1283 serial_test::local_parallel_core(vec![""], ::std::option::Option::None, || _foo_inner() );
1284 }
1285 };
1286 compare_streams(compare, stream);
1287 }
1288
1289 #[test]
1290 #[should_panic(expected = "Expected '=' after 'inner_attrs'")]
1291 fn test_inner_attrs_missing_equals() {
1292 // Use a comma after the bracket to ensure we get past the length check
1293 let attrs: Vec<TokenTree> = quote! { inner_attrs [timeout(100)], foo }
1294 .into_iter()
1295 .collect();
1296 let input = quote! {
1297 #[test]
1298 fn foo() {}
1299 };
1300 local_serial_core(
1301 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1302 input,
1303 );
1304 }
1305
1306 #[test]
1307 #[should_panic(expected = "Expected [...] after 'inner_attrs ='")]
1308 fn test_inner_attrs_missing_brackets() {
1309 let attrs: Vec<TokenTree> = quote! { inner_attrs = timeout(100) }.into_iter().collect();
1310 let input = quote! {
1311 #[test]
1312 fn foo() {}
1313 };
1314 local_serial_core(
1315 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1316 input,
1317 );
1318 }
1319
1320 #[test]
1321 #[should_panic(expected = "Expected a '= [attr1, attr2, ...]' after 'inner_attrs'")]
1322 fn test_inner_attrs_nothing_after() {
1323 let attrs: Vec<TokenTree> = quote! { inner_attrs }.into_iter().collect();
1324 let input = quote! {
1325 #[test]
1326 fn foo() {}
1327 };
1328 local_serial_core(
1329 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1330 input,
1331 );
1332 }
1333
1334 #[test]
1335 #[should_panic(expected = "Expected [...] after 'inner_attrs ='")]
1336 fn test_inner_attrs_wrong_delimiter() {
1337 // Using parentheses instead of brackets
1338 let attrs: Vec<TokenTree> = quote! { inner_attrs = (timeout(100)) }
1339 .into_iter()
1340 .collect();
1341 let input = quote! {
1342 #[test]
1343 fn foo() {}
1344 };
1345 local_serial_core(
1346 proc_macro2::TokenStream::from_iter(attrs.into_iter()),
1347 input,
1348 );
1349 }
1350 }