Debian Codegraph @

debian/rust-vendor/rstest_macros/src/parse/rstest.rs

raw
1 use syn::{parse::{Parse, ParseStream}, Ident, ItemFn, Pat, Token};
2
3 use self::files::{extract_files, ValueListFromFiles};
4
5 use super::{
6 arguments::ArgumentsInfo,
7 by_ref::extract_by_ref,
8 check_timeout_attrs,
9 context::extract_context,
10 extract_case_args, extract_cases, extract_excluded_trace, extract_fixtures, extract_value_list,
11 future::{extract_futures, extract_global_awt},
12 ignore::extract_ignores,
13 parse_vector_trailing_till_double_comma,
14 testcase::TestCase,
15 Attribute, Attributes, ExtendWithFunctionAttrs, Fixture,
16 };
17 use crate::{error::ErrorsVec, refident::IntoPat};
18 use crate::{parse::vlist::ValueList, refident::MaybePat};
19 use proc_macro2::{Span, TokenStream};
20 use quote::{format_ident, ToTokens};
21 use crate::parse::rstest::test_attr::extract_test_attr;
22
23 pub(crate) mod files;
24 mod test_attr;
25
26 #[derive(PartialEq, Debug, Default)]
27 pub(crate) struct RsTestInfo {
28 pub(crate) data: RsTestData,
29 pub(crate) attributes: RsTestAttributes,
30 pub(crate) arguments: ArgumentsInfo,
31 }
32
33 impl Parse for RsTestInfo {
34 fn parse(input: ParseStream) -> syn::Result<Self> {
35 Ok(if input.is_empty() {
36 Default::default()
37 } else {
38 Self {
39 data: input.parse()?,
40 attributes: input
41 .parse::<Token![::]>()
42 .or_else(|_| Ok(Default::default()))
43 .and_then(|_| input.parse())?,
44 arguments: Default::default(),
45 }
46 })
47 }
48 }
49
50 impl ExtendWithFunctionAttrs for RsTestInfo {
51 fn extend_with_function_attrs(&mut self, item_fn: &mut ItemFn) -> Result<(), ErrorsVec> {
52 let (composed_tuple!(
53 excluded, _timeout, futures, global_awt, by_refs, ignores, contexts, test_attr
54 // Append here new extraction
55 ), _inner) = merge_errors!(
56 merge_errors!(
57 extract_excluded_trace(item_fn),
58 check_timeout_attrs(item_fn),
59 extract_futures(item_fn),
60 extract_global_awt(item_fn),
61 extract_by_ref(item_fn),
62 extract_ignores(item_fn),
63 extract_context(item_fn),
64 extract_test_attr(item_fn),
65 // Append here new extraction
66 ),
67 // This one should be always the last one!
68 self.data.extend_with_function_attrs(item_fn)
69 )?;
70
71 self.attributes.add_notraces(excluded);
72 self.arguments.set_global_await(global_awt);
73 self.arguments.set_futures(futures.into_iter());
74 self.arguments.set_by_refs(by_refs.into_iter());
75 self.arguments.set_ignores(ignores.into_iter());
76 self.arguments.set_contexts(contexts.into_iter());
77 self.arguments.set_test_attr(test_attr);
78 self.arguments
79 .register_inner_destructored_idents_names(item_fn);
80 Ok(())
81 }
82 }
83
84 #[derive(PartialEq, Debug, Default)]
85 pub(crate) struct RsTestData {
86 pub(crate) items: Vec<RsTestItem>,
87 }
88
89 impl RsTestData {
90 pub(crate) fn case_args(&self) -> impl Iterator<Item = &Pat> {
91 self.items.iter().filter_map(|it| match it {
92 RsTestItem::CaseArgName(ref arg) => Some(arg),
93 _ => None,
94 })
95 }
96
97 #[allow(dead_code)]
98 pub(crate) fn has_case_args(&self) -> bool {
99 self.case_args().next().is_some()
100 }
101
102 pub(crate) fn cases(&self) -> impl Iterator<Item = &TestCase> {
103 self.items.iter().filter_map(|it| match it {
104 RsTestItem::TestCase(ref case) => Some(case),
105 _ => None,
106 })
107 }
108
109 pub(crate) fn has_cases(&self) -> bool {
110 self.cases().next().is_some()
111 }
112
113 pub(crate) fn fixtures(&self) -> impl Iterator<Item = &Fixture> {
114 self.items.iter().filter_map(|it| match it {
115 RsTestItem::Fixture(ref fixture) => Some(fixture),
116 _ => None,
117 })
118 }
119
120 #[allow(dead_code)]
121 pub(crate) fn has_fixtures(&self) -> bool {
122 self.fixtures().next().is_some()
123 }
124
125 pub(crate) fn list_values(&self) -> impl Iterator<Item = &ValueList> {
126 self.items.iter().filter_map(|mv| match mv {
127 RsTestItem::ValueList(ref value_list) => Some(value_list),
128 _ => None,
129 })
130 }
131
132 pub(crate) fn has_list_values(&self) -> bool {
133 self.list_values().next().is_some()
134 }
135 }
136
137 impl Parse for RsTestData {
138 fn parse(input: ParseStream) -> syn::Result<Self> {
139 if input.peek(Token![::]) {
140 Ok(Default::default())
141 } else {
142 Ok(Self {
143 items: parse_vector_trailing_till_double_comma::<_, Token![,]>(input)?,
144 })
145 }
146 }
147 }
148
149 impl ExtendWithFunctionAttrs for RsTestData {
150 fn extend_with_function_attrs(&mut self, item_fn: &mut ItemFn) -> Result<(), ErrorsVec> {
151 let composed_tuple!(fixtures, case_args, cases, value_list, files) = merge_errors!(
152 extract_fixtures(item_fn),
153 extract_case_args(item_fn),
154 extract_cases(item_fn),
155 extract_value_list(item_fn),
156 extract_files(item_fn)
157 )?;
158
159 self.items.extend(fixtures.into_iter().map(|f| f.into()));
160 self.items.extend(case_args.into_iter().map(|f| f.into()));
161 self.items.extend(cases.into_iter().map(|f| f.into()));
162 self.items.extend(value_list.into_iter().map(|f| f.into()));
163 self.items.extend(
164 ValueListFromFiles::default()
165 .to_value_list(files)?
166 .into_iter()
167 .map(|f| f.into()),
168 );
169 Ok(())
170 }
171 }
172
173 #[derive(PartialEq, Debug)]
174 pub(crate) enum RsTestItem {
175 Fixture(Fixture),
176 CaseArgName(Pat),
177 TestCase(TestCase),
178 ValueList(ValueList),
179 }
180
181 impl MaybePat for Fixture {
182 fn maybe_pat(&self) -> Option<&syn::Pat> {
183 Some(&self.arg)
184 }
185 }
186
187 impl MaybePat for RsTestItem {
188 fn maybe_pat(&self) -> Option<&syn::Pat> {
189 match self {
190 RsTestItem::Fixture(f) => f.maybe_pat(),
191 RsTestItem::CaseArgName(c) => Some(c),
192 RsTestItem::TestCase(_) => None,
193 RsTestItem::ValueList(vl) => Some(&vl.arg),
194 }
195 }
196 }
197
198 impl From<Fixture> for RsTestItem {
199 fn from(f: Fixture) -> Self {
200 RsTestItem::Fixture(f)
201 }
202 }
203
204 impl From<Pat> for RsTestItem {
205 fn from(pat: Pat) -> Self {
206 RsTestItem::CaseArgName(pat)
207 }
208 }
209
210 impl From<Ident> for RsTestItem {
211 fn from(ident: Ident) -> Self {
212 RsTestItem::CaseArgName(ident.into_pat())
213 }
214 }
215
216 impl From<TestCase> for RsTestItem {
217 fn from(case: TestCase) -> Self {
218 RsTestItem::TestCase(case)
219 }
220 }
221
222 impl From<ValueList> for RsTestItem {
223 fn from(value_list: ValueList) -> Self {
224 RsTestItem::ValueList(value_list)
225 }
226 }
227
228 impl Parse for RsTestItem {
229 fn parse(input: ParseStream) -> syn::Result<Self> {
230 if input.fork().parse::<TestCase>().is_ok() {
231 input.parse::<TestCase>().map(RsTestItem::TestCase)
232 } else if input.peek2(Token![=>]) {
233 input.parse::<ValueList>().map(RsTestItem::ValueList)
234 } else if input.fork().parse::<Fixture>().is_ok() {
235 input.parse::<Fixture>().map(RsTestItem::Fixture)
236 } else if input.fork().parse::<Ident>().is_ok() {
237 input
238 .parse::<Ident>()
239 .map(IntoPat::into_pat)
240 .map(RsTestItem::CaseArgName)
241 } else {
242 Err(syn::Error::new(Span::call_site(), "Cannot parse it"))
243 }
244 }
245 }
246
247 impl ToTokens for RsTestItem {
248 fn to_tokens(&self, tokens: &mut TokenStream) {
249 use RsTestItem::*;
250 match self {
251 Fixture(ref fixture) => fixture.to_tokens(tokens),
252 CaseArgName(ref case_arg) => case_arg.to_tokens(tokens),
253 TestCase(ref case) => case.to_tokens(tokens),
254 ValueList(ref list) => list.to_tokens(tokens),
255 }
256 }
257 }
258
259 wrap_attributes!(RsTestAttributes);
260
261 impl RsTestAttributes {
262 const TRACE_VARIABLE_ATTR: &'static str = "trace";
263 const NOTRACE_VARIABLE_ATTR: &'static str = "notrace";
264
265 pub(crate) fn trace_me(&self, pat: &Pat) -> bool {
266 if self.should_trace() {
267 !self.iter().any(|m| Self::is_notrace(pat, m))
268 } else {
269 false
270 }
271 }
272
273 fn is_notrace(pat: &Pat, m: &Attribute) -> bool {
274 match m {
275 Attribute::Tagged(i, args) if i == Self::NOTRACE_VARIABLE_ATTR => {
276 args.iter().any(|a| a == pat)
277 }
278 _ => false,
279 }
280 }
281
282 pub(crate) fn should_trace(&self) -> bool {
283 self.iter().any(Self::is_trace)
284 }
285
286 pub(crate) fn add_trace(&mut self, trace: Ident) {
287 self.inner.attributes.push(Attribute::Attr(trace));
288 }
289
290 pub(crate) fn add_notraces(&mut self, notraces: Vec<Pat>) {
291 if notraces.is_empty() {
292 return;
293 }
294 self.inner.attributes.push(Attribute::Tagged(
295 format_ident!("{}", Self::NOTRACE_VARIABLE_ATTR),
296 notraces,
297 ));
298 }
299
300 fn is_trace(m: &Attribute) -> bool {
301 matches!(m, Attribute::Attr(i) if i == Self::TRACE_VARIABLE_ATTR)
302 }
303 }
304
305 impl Parse for RsTestAttributes {
306 fn parse(input: ParseStream) -> syn::Result<Self> {
307 Ok(input.parse::<Attributes>()?.into())
308 }
309 }
310
311 #[cfg(test)]
312 mod test {
313 use super::*;
314 use crate::test::{assert_eq, *};
315 use rstest_test::assert_in;
316
317 mod parse_rstest_data {
318 use super::assert_eq;
319 use super::*;
320
321 fn parse_rstest_data<S: AsRef<str>>(fixtures: S) -> RsTestData {
322 parse_meta(fixtures)
323 }
324
325 #[test]
326 fn one_arg() {
327 let fixtures = parse_rstest_data("my_fixture(42)");
328
329 let expected = RsTestData {
330 items: vec![fixture("my_fixture", &["42"]).into()],
331 };
332
333 assert_eq!(expected, fixtures);
334 }
335 }
336
337 #[test]
338 fn should_check_all_timeout_to_catch_the_right_errors() {
339 let mut item_fn = r#"
340 #[timeout(<some>)]
341 #[timeout(42)]
342 #[timeout]
343 #[timeout(Duration::from_millis(20))]
344 fn test_fn(#[case] arg: u32) {
345 }
346 "#
347 .ast();
348
349 let mut info = RsTestInfo::default();
350
351 let errors = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
352
353 assert_eq!(2, errors.len());
354 }
355
356 #[cfg(feature = "async-timeout")]
357 #[test]
358 fn should_parse_async_timeout() {
359 let mut item_fn = r#"
360 #[timeout(Duration::from_millis(20))]
361 async fn test_fn(#[case] arg: u32) {
362 }
363 "#
364 .ast();
365
366 let mut info = RsTestInfo::default();
367
368 info.extend_with_function_attrs(&mut item_fn).unwrap();
369 }
370
371 #[cfg(not(feature = "async-timeout"))]
372 #[test]
373 fn should_return_error_for_async_timeout() {
374 let mut item_fn = r#"
375 #[timeout(Duration::from_millis(20))]
376 async fn test_fn(#[case] arg: u32) {
377 }
378 "#
379 .ast();
380
381 let mut info = RsTestInfo::default();
382
383 let errors = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
384
385 assert_eq!(1, errors.len());
386 assert!(format!("{:?}", errors).contains("async-timeout feature"))
387 }
388
389 fn parse_rstest<S: AsRef<str>>(rstest_data: S) -> RsTestInfo {
390 parse_meta(rstest_data)
391 }
392
393 mod no_cases {
394 use std::collections::HashSet;
395 use super::{assert_eq, *};
396
397 #[test]
398 fn happy_path() {
399 let data = parse_rstest(
400 r#"my_fixture(42, "other"), other(vec![42])
401 :: trace :: no_trace(some)"#,
402 );
403
404 let expected = RsTestInfo {
405 data: vec![
406 fixture("my_fixture", &["42", r#""other""#]).into(),
407 fixture("other", &["vec![42]"]).into(),
408 ]
409 .into(),
410 attributes: Attributes {
411 attributes: vec![
412 Attribute::attr("trace"),
413 Attribute::tagged("no_trace", vec!["some"]),
414 ],
415 }
416 .into(),
417 ..Default::default()
418 };
419
420 assert_eq!(expected, data);
421 }
422
423 mod fixture_extraction {
424 use super::{assert_eq, *};
425
426 #[test]
427 fn rename() {
428 let data = parse_rstest(
429 r#"long_fixture_name(42, "other") as short, sub_module::fix as f, simple as s, no_change()"#,
430 );
431
432 let expected = RsTestInfo {
433 data: vec![
434 fixture("short", &["42", r#""other""#])
435 .with_resolve("long_fixture_name")
436 .into(),
437 fixture("f", &[]).with_resolve("sub_module::fix").into(),
438 fixture("s", &[]).with_resolve("simple").into(),
439 fixture("no_change", &[]).into(),
440 ]
441 .into(),
442 ..Default::default()
443 };
444
445 assert_eq!(expected, data);
446 }
447
448 #[test]
449 fn rename_with_attributes() {
450 let mut item_fn = r#"
451 fn test_fn(
452 #[from(long_fixture_name)]
453 #[with(42, "other")] short: u32,
454 #[from(simple)]
455 s: &str,
456 #[from(sub_module::fix)]
457 f: u32,
458 no_change: i32) {
459 }
460 "#
461 .ast();
462
463 let expected = RsTestInfo {
464 data: vec![
465 fixture("short", &["42", r#""other""#])
466 .with_resolve("long_fixture_name")
467 .into(),
468 fixture("s", &[]).with_resolve("simple").into(),
469 fixture("f", &[]).with_resolve("sub_module::fix").into(),
470 ]
471 .into(),
472 ..Default::default()
473 };
474
475 let mut data = RsTestInfo::default();
476
477 data.extend_with_function_attrs(&mut item_fn).unwrap();
478
479 assert_eq!(expected, data);
480 }
481
482 #[test]
483 fn defined_via_with_attributes() {
484 let mut item_fn = r#"
485 fn test_fn(#[with(42, "other")] my_fixture: u32, #[with(vec![42])] other: &str) {
486 }
487 "#
488 .ast();
489
490 let expected = RsTestInfo {
491 data: vec![
492 fixture("my_fixture", &["42", r#""other""#]).into(),
493 fixture("other", &["vec![42]"]).into(),
494 ]
495 .into(),
496 ..Default::default()
497 };
498
499 let mut data = RsTestInfo::default();
500
501 data.extend_with_function_attrs(&mut item_fn).unwrap();
502
503 assert_eq!(expected, data);
504 }
505 }
506
507 #[test]
508 fn empty_fixtures() {
509 let data = parse_rstest(r#"::trace::no_trace(some)"#);
510
511 let expected = RsTestInfo {
512 attributes: Attributes {
513 attributes: vec![
514 Attribute::attr("trace"),
515 Attribute::tagged("no_trace", vec!["some"]),
516 ],
517 }
518 .into(),
519 ..Default::default()
520 };
521
522 assert_eq!(expected, data);
523 }
524
525 #[test]
526 fn empty_attributes() {
527 let data = parse_rstest(r#"my_fixture(42, "other")"#);
528
529 let expected = RsTestInfo {
530 data: vec![fixture("my_fixture", &["42", r#""other""#]).into()].into(),
531 ..Default::default()
532 };
533
534 assert_eq!(expected, data);
535 }
536
537 #[test]
538 fn extract_notrace_args_attribute() {
539 let mut item_fn = r#"
540 fn test_fn(#[notrace] a: u32, #[something_else] b: &str, #[notrace] c: i32) {
541 }
542 "#
543 .ast();
544
545 let mut info = RsTestInfo::default();
546
547 info.extend_with_function_attrs(&mut item_fn).unwrap();
548 info.attributes.add_trace(ident("trace"));
549
550 assert!(!info.attributes.trace_me(&pat("a")));
551 assert!(info.attributes.trace_me(&pat("b")));
552 assert!(!info.attributes.trace_me(&pat("c")));
553 let b_args = item_fn
554 .sig
555 .inputs
556 .into_iter()
557 .nth(1)
558 .and_then(|id| match id {
559 syn::FnArg::Typed(arg) => Some(arg.attrs),
560 _ => None,
561 })
562 .unwrap();
563 assert_eq!(attrs("#[something_else]"), b_args);
564 }
565
566 #[rstest]
567 fn extract_future() {
568 let mut item_fn = "fn f(#[future] a: u32, b: u32) {}".ast();
569 let expected = "fn f(a: u32, b: u32) {}".ast();
570
571 let mut info = RsTestInfo::default();
572
573 info.extend_with_function_attrs(&mut item_fn).unwrap();
574
575 assert_eq!(item_fn, expected);
576 assert!(info.arguments.is_future(&pat("a")));
577 assert!(!info.arguments.is_future(&pat("b")));
578 }
579
580 #[rstest]
581 fn extract_context() {
582 let mut item_fn =
583 "fn f(#[context] c: Context, #[context] other: Context, more: u32) {}".ast();
584 let expected = "fn f(c: Context, other: Context, more: u32) {}".ast();
585
586 let mut info = RsTestInfo::default();
587
588 info.extend_with_function_attrs(&mut item_fn).unwrap();
589
590 assert_eq!(item_fn, expected);
591 assert_eq!(
592 info.arguments.contexts().cloned().collect::<HashSet<_>>(),
593 vec![pat("c"), pat("other")]
594 .into_iter()
595 .collect::<HashSet<_>>()
596 );
597 }
598
599 #[test]
600 fn extract_test_attr() {
601 let mut item_fn =
602 "#[test_attr(some_valid_data)] fn f() {}".ast();
603 let expected = "fn f() {}".ast();
604
605 let mut info = RsTestInfo::default();
606
607 info.extend_with_function_attrs(&mut item_fn).unwrap();
608
609 assert_eq!(item_fn, expected);
610 assert_eq!(
611 info.arguments.test_attr().cloned(),
612 Some(attr("#[some_valid_data]").into()),
613 );
614 }
615 }
616
617 mod parametrize_cases {
618 use super::{assert_eq, *};
619
620 #[test]
621 fn one_simple_case_one_arg() {
622 let data = parse_rstest(r#"arg, case(42)"#).data;
623
624 let args = data.case_args().collect::<Vec<_>>();
625 let cases = data.cases().collect::<Vec<_>>();
626
627 assert_eq!(1, args.len());
628 assert_eq!(1, cases.len());
629 assert_eq!("arg", &args[0].display_code());
630 assert_eq!(to_args!(["42"]), cases[0].args())
631 }
632
633 #[test]
634 fn happy_path() {
635 let info = parse_rstest(
636 r#"
637 my_fixture(42,"foo"),
638 arg1, arg2, arg3,
639 case(1,2,3),
640 case(11,12,13),
641 case(21,22,23)
642 "#,
643 );
644
645 let data = info.data;
646 let fixtures = data.fixtures().cloned().collect::<Vec<_>>();
647
648 assert_eq!(vec![fixture("my_fixture", &["42", r#""foo""#])], fixtures);
649 assert_eq!(
650 to_strs!(vec!["arg1", "arg2", "arg3"]),
651 data.case_args()
652 .map(DisplayCode::display_code)
653 .collect::<Vec<_>>()
654 );
655
656 let cases = data.cases().collect::<Vec<_>>();
657
658 assert_eq!(3, cases.len());
659 assert_eq!(to_args!(["1", "2", "3"]), cases[0].args());
660 assert_eq!(to_args!(["11", "12", "13"]), cases[1].args());
661 assert_eq!(to_args!(["21", "22", "23"]), cases[2].args());
662 }
663
664 mod defined_via_with_attributes {
665 use super::{assert_eq, *};
666
667 #[test]
668 fn one_case() {
669 let mut item_fn = r#"
670 #[case::first(42, "first")]
671 fn test_fn(#[case] arg1: u32, #[case] arg2: &str) {
672 }
673 "#
674 .ast();
675
676 let mut info = RsTestInfo::default();
677
678 info.extend_with_function_attrs(&mut item_fn).unwrap();
679
680 let case_args = info.data.case_args().cloned().collect::<Vec<_>>();
681 let cases = info.data.cases().cloned().collect::<Vec<_>>();
682
683 assert_eq!(to_pats!(["arg1", "arg2"]), case_args);
684 assert_eq!(
685 vec![
686 TestCase::from_iter(["42", r#""first""#].iter()).with_description("first"),
687 ],
688 cases
689 );
690 }
691
692 #[test]
693 fn destruct_case() {
694 let mut item_fn: ItemFn = r#"
695 #[case::destruct(T::new(2, 21))]
696 fn test_fn(#[case] T{a, b}: T) {
697 }
698 "#
699 .ast();
700
701 let mut info = RsTestInfo::default();
702
703 info.extend_with_function_attrs(&mut item_fn).unwrap();
704
705 let case_args = info.data.case_args().cloned().collect::<Vec<_>>();
706 let cases = info.data.cases().cloned().collect::<Vec<_>>();
707
708 // Should just remove attributes
709 assert_eq!(
710 to_fnargs!(["T{a, b}: T"]),
711 item_fn.sig.inputs.into_iter().collect::<Vec<_>>()
712 );
713 assert_eq!(to_pats!(["T{a, b}"]), case_args);
714 assert_eq!(
715 vec![
716 TestCase::from_iter(["T::new(2, 21)"].iter()).with_description("destruct"),
717 ],
718 cases
719 );
720 assert_eq!(
721 info.arguments.inner_pat(&pat("T{a, b}")),
722 &pat("__destruct_1")
723 );
724 }
725
726 #[test]
727 fn parse_tuple_value() {
728 let mut item_fn = r#"
729 #[case(42, (24, "first"))]
730 fn test_fn(#[case] arg1: u32, #[case] tupled: (u32, &str)) {
731 }
732 "#
733 .ast();
734
735 let mut info = RsTestInfo::default();
736
737 info.extend_with_function_attrs(&mut item_fn).unwrap();
738
739 let cases = info.data.cases().cloned().collect::<Vec<_>>();
740
741 assert_eq!(
742 vec![TestCase::from_iter(["42", r#"(24, "first")"#].iter()),],
743 cases
744 );
745 }
746
747 #[test]
748 fn more_cases() {
749 let mut item_fn = r#"
750 #[case::first(42, "first")]
751 #[case(24, "second")]
752 #[case::third(0, "third")]
753 fn test_fn(#[case] arg1: u32, #[case] arg2: &str) {
754 }
755 "#
756 .ast();
757
758 let mut info = RsTestInfo::default();
759
760 info.extend_with_function_attrs(&mut item_fn).unwrap();
761
762 let case_args = info.data.case_args().cloned().collect::<Vec<_>>();
763 let cases = info.data.cases().cloned().collect::<Vec<_>>();
764
765 assert_eq!(to_pats!(["arg1", "arg2"]), case_args);
766 assert_eq!(
767 vec![
768 TestCase::from_iter(["42", r#""first""#].iter()).with_description("first"),
769 TestCase::from_iter(["24", r#""second""#].iter()),
770 TestCase::from_iter(["0", r#""third""#].iter()).with_description("third"),
771 ],
772 cases
773 );
774 }
775
776 #[test]
777 fn should_collect_attributes() {
778 let mut item_fn = r#"
779 #[first]
780 #[first2(42)]
781 #[case(42)]
782 #[second]
783 #[case(24)]
784 #[global]
785 fn test_fn(#[case] arg: u32) {
786 }
787 "#
788 .ast();
789
790 let mut info = RsTestInfo::default();
791
792 info.extend_with_function_attrs(&mut item_fn).unwrap();
793
794 let cases = info.data.cases().cloned().collect::<Vec<_>>();
795
796 assert_eq!(
797 vec![
798 TestCase::from_iter(["42"].iter()).with_attrs(attrs(
799 "
800 #[first]
801 #[first2(42)]
802 "
803 )),
804 TestCase::from_iter(["24"].iter()).with_attrs(attrs(
805 "
806 #[second]
807 "
808 )),
809 ],
810 cases
811 );
812 }
813
814 #[test]
815 fn should_consume_all_used_attributes() {
816 let mut item_fn = r#"
817 #[first]
818 #[first2(42)]
819 #[case(42)]
820 #[second]
821 #[case(24)]
822 #[global]
823 fn test_fn(#[case] arg: u32) {
824 }
825 "#
826 .ast();
827
828 let mut info = RsTestInfo::default();
829
830 info.extend_with_function_attrs(&mut item_fn).unwrap();
831
832 assert_eq!(
833 item_fn.attrs,
834 attrs(
835 "
836 #[global]
837 "
838 )
839 );
840 assert!(!format!("{:?}", item_fn).contains("case"));
841 }
842
843 #[test]
844 fn should_report_all_errors() {
845 let mut item_fn = r#"
846 #[case(#case_error#)]
847 fn test_fn(#[case] arg: u32, #[with(#fixture_error#)] err_fixture: u32) {
848 }
849 "#
850 .ast();
851
852 let mut info = RsTestInfo::default();
853
854 let errors = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
855
856 assert_eq!(2, errors.len());
857 }
858 }
859
860 #[test]
861 fn should_accept_comma_at_the_end_of_cases() {
862 let data = parse_rstest(
863 r#"
864 arg,
865 case(42),
866 "#,
867 )
868 .data;
869
870 let args = data.case_args().collect::<Vec<_>>();
871 let cases = data.cases().collect::<Vec<_>>();
872
873 assert_eq!(1, args.len());
874 assert_eq!(1, cases.len());
875 assert_eq!("arg", &args[0].display_code());
876 assert_eq!(to_args!(["42"]), cases[0].args())
877 }
878
879 #[test]
880 #[should_panic]
881 fn should_not_accept_invalid_separator_from_args_and_cases() {
882 parse_rstest(
883 r#"
884 ret
885 case::should_success(Ok(())),
886 case::should_fail(Err("Return Error"))
887 "#,
888 );
889 }
890
891 #[test]
892 fn case_could_be_arg_name() {
893 let data = parse_rstest(
894 r#"
895 case,
896 case(42)
897 "#,
898 )
899 .data;
900
901 assert_eq!("case", &data.case_args().next().unwrap().display_code());
902
903 let cases = data.cases().collect::<Vec<_>>();
904
905 assert_eq!(1, cases.len());
906 assert_eq!(to_args!(["42"]), cases[0].args());
907 }
908
909 #[test]
910 fn should_reject_case_args_marked_more_than_once() {
911 let mut item_fn = r#"
912 #[case(42)]
913 fn test_fn(#[case] #[case] arg: u32) {
914 }
915 "#
916 .ast();
917
918 let mut info = RsTestInfo::default();
919
920 let errors = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
921
922 assert_eq!(1, errors.len());
923 assert_in!(errors[0].to_string(), "more than once");
924 }
925 }
926
927 mod matrix_cases {
928
929 use super::{assert_eq, *};
930
931 #[test]
932 fn happy_path() {
933 let info = parse_rstest(
934 r#"
935 expected => [12, 34 * 2],
936 input => [format!("aa_{}", 2), "other"],
937 "#,
938 );
939
940 let value_ranges = info.data.list_values().collect::<Vec<_>>();
941 assert_eq!(2, value_ranges.len());
942 assert_eq!(to_args!(["12", "34 * 2"]), value_ranges[0].args());
943 assert_eq!(
944 to_args!([r#"format!("aa_{}", 2)"#, r#""other""#]),
945 value_ranges[1].args()
946 );
947 assert_eq!(info.attributes, Default::default());
948 }
949
950 #[test]
951 fn should_parse_attributes_too() {
952 let info = parse_rstest(
953 r#"
954 a => [12, 24, 42]
955 ::trace
956 "#,
957 );
958
959 assert_eq!(
960 info.attributes,
961 Attributes {
962 attributes: vec![Attribute::attr("trace")]
963 }
964 .into()
965 );
966 }
967
968 #[test]
969 fn should_parse_injected_fixtures_too() {
970 let info = parse_rstest(
971 r#"
972 a => [12, 24, 42],
973 fixture_1(42, "foo"),
974 fixture_2("bar")
975 "#,
976 );
977
978 let fixtures = info.data.fixtures().cloned().collect::<Vec<_>>();
979
980 assert_eq!(
981 vec![
982 fixture("fixture_1", &["42", r#""foo""#]),
983 fixture("fixture_2", &[r#""bar""#])
984 ],
985 fixtures
986 );
987 }
988
989 #[test]
990 #[should_panic(expected = "should not be empty")]
991 fn should_not_compile_if_empty_expression_slice() {
992 parse_rstest(
993 r#"
994 invalid => []
995 "#,
996 );
997 }
998
999 mod defined_via_with_attributes {
1000 use super::{assert_eq, *};
1001
1002 #[test]
1003 fn one_arg() {
1004 let mut item_fn = r#"
1005 fn test_fn(#[values(1, 2, 1+2)] arg1: u32, #[values(format!("a"), "b b".to_owned(), String::new())] arg2: String) {
1006 }
1007 "#
1008 .ast();
1009
1010 let mut info = RsTestInfo::default();
1011
1012 info.extend_with_function_attrs(&mut item_fn).unwrap();
1013
1014 let list_values = info.data.list_values().cloned().collect::<Vec<_>>();
1015
1016 assert_eq!(2, list_values.len());
1017 assert_eq!(to_args!(["1", "2", "1+2"]), list_values[0].args());
1018 assert_eq!(
1019 to_args!([r#"format!("a")"#, r#""b b".to_owned()"#, "String::new()"]),
1020 list_values[1].args()
1021 );
1022 }
1023
1024 #[test]
1025 fn destruct() {
1026 let mut item_fn = r#"
1027 fn test_fn(#[values(S(1,2), S(3,4))] S(a,b): S, #[values(T::new("a", "b"), T{s: "a" ,t: "c" })] T{s, t}: T) {
1028 }
1029 "#
1030 .ast();
1031
1032 let mut info = RsTestInfo::default();
1033
1034 info.extend_with_function_attrs(&mut item_fn).unwrap();
1035
1036 let list_values = info.data.list_values().cloned().collect::<Vec<_>>();
1037
1038 // Should just remove attributes
1039 assert_eq!(
1040 to_fnargs!(["S(a, b): S", "T{s, t}: T"]),
1041 item_fn.sig.inputs.into_iter().collect::<Vec<_>>()
1042 );
1043 assert_eq!(2, list_values.len());
1044 assert_eq!(list_values[0].arg, pat("S(a, b)"));
1045 assert_eq!(to_args!(["S(1,2)", "S(3,4)"]), list_values[0].args());
1046 assert_eq!(list_values[1].arg, pat("T{s, t}"));
1047 assert_eq!(
1048 to_args!([r#"T::new("a", "b")"#, r#"T{s: "a" ,t: "c" }"#]),
1049 list_values[1].args()
1050 );
1051 assert_eq!(
1052 info.arguments.inner_pat(&pat("S(a, b)")),
1053 &pat("__destruct_1")
1054 );
1055 assert_eq!(
1056 info.arguments.inner_pat(&pat("T{s, t}")),
1057 &pat("__destruct_2")
1058 );
1059 }
1060
1061 #[test]
1062 fn doc_comment_in_values_attribute_used_as_description() {
1063 let mut item_fn = r#"
1064 fn test_fn(
1065 #[values(
1066 /// the answer
1067 42,
1068 /// bigger entry
1069 100,
1070 2
1071 )]
1072 arg: u32
1073 ) {
1074 }
1075 "#
1076 .ast();
1077
1078 let mut info = RsTestInfo::default();
1079
1080 info.extend_with_function_attrs(&mut item_fn).unwrap();
1081
1082 let list_values = info.data.list_values().cloned().collect::<Vec<_>>();
1083
1084 assert_eq!(1, list_values.len());
1085 let values = &list_values[0].values;
1086
1087 assert_eq!(3, values.len());
1088
1089 assert_eq!("the_answer", values[0].description());
1090 assert_eq!("42", values[0].expr.to_token_stream().to_string());
1091
1092 assert_eq!("bigger_entry", values[1].description());
1093 assert_eq!("100", values[1].expr.to_token_stream().to_string());
1094
1095 assert_eq!("2", values[2].description());
1096 assert_eq!("2", values[2].expr.to_token_stream().to_string());
1097 }
1098 }
1099
1100 #[test]
1101 fn should_reject_values_attribute_marked_more_than_once() {
1102 let mut item_fn = r#"
1103 fn test_fn(#[values(1, 2, 1+2)] #[values(1, 2, 1+2)] arg1: u32, ) {
1104 }
1105 "#
1106 .ast();
1107
1108 let mut info = RsTestInfo::default();
1109
1110 let errors = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
1111
1112 assert_eq!(1, errors.len());
1113 assert_in!(errors[0].to_string(), "more than once");
1114 }
1115 }
1116
1117 mod integrated {
1118 use super::{assert_eq, *};
1119
1120 #[test]
1121 fn should_parse_fixture_cases_and_matrix_in_any_order() {
1122 let data = parse_rstest(
1123 r#"
1124 u,
1125 m => [1, 2],
1126 case(42, A{}, D{}),
1127 a,
1128 case(43, A{}, D{}),
1129 the_fixture(42),
1130 mm => ["f", "oo", "BAR"],
1131 d
1132 "#,
1133 )
1134 .data;
1135
1136 let fixtures = data.fixtures().cloned().collect::<Vec<_>>();
1137 assert_eq!(vec![fixture("the_fixture", &["42"])], fixtures);
1138
1139 assert_eq!(
1140 to_strs!(vec!["u", "a", "d"]),
1141 data.case_args()
1142 .map(DisplayCode::display_code)
1143 .collect::<Vec<_>>()
1144 );
1145
1146 let cases = data.cases().collect::<Vec<_>>();
1147 assert_eq!(2, cases.len());
1148 assert_eq!(to_args!(["42", "A{}", "D{}"]), cases[0].args());
1149 assert_eq!(to_args!(["43", "A{}", "D{}"]), cases[1].args());
1150
1151 let value_ranges = data.list_values().collect::<Vec<_>>();
1152 assert_eq!(2, value_ranges.len());
1153 assert_eq!(to_args!(["1", "2"]), value_ranges[0].args());
1154 assert_eq!(
1155 to_args!([r#""f""#, r#""oo""#, r#""BAR""#]),
1156 value_ranges[1].args()
1157 );
1158 }
1159 }
1160 }