5 console::OutputLocation,
6 formatters::PrettyFormatter,
24 // FIXME (introduced by #65251)
25 // ShouldPanic, StaticTestName, TestDesc, TestDescAndFn, TestOpts, TestTimeOptions,
26 // TestType, TrFailedMsg, TrIgnored, TrOk,
28 time::{TestTimeOptions, TimeThreshold},
30 use std::sync::mpsc::channel;
31 use std::time::Duration;
34 fn new() -> TestOpts {
39 force_run_in_process: false,
40 exclude_should_panic: false,
41 run_ignored: RunIgnored::No,
43 bench_benchmarks: false,
47 format: OutputFormat::Pretty,
53 options: Options::new(),
58 fn one_ignored_one_unignored_test() -> Vec<TestDescAndFn> {
62 name: StaticTestName("1"),
64 should_panic: ShouldPanic::No,
68 test_type: TestType::Unknown,
70 testfn: DynTestFn(Box::new(move || {})),
74 name: StaticTestName("2"),
76 should_panic: ShouldPanic::No,
80 test_type: TestType::Unknown,
82 testfn: DynTestFn(Box::new(move || {})),
88 pub fn do_not_run_ignored_tests() {
92 let desc = TestDescAndFn {
94 name: StaticTestName("whatever"),
96 should_panic: ShouldPanic::No,
100 test_type: TestType::Unknown,
102 testfn: DynTestFn(Box::new(f)),
104 let (tx, rx) = channel();
105 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
106 let result = rx.recv().unwrap().result;
107 assert_ne!(result, TrOk);
111 pub fn ignored_tests_result_in_ignored() {
113 let desc = TestDescAndFn {
115 name: StaticTestName("whatever"),
117 should_panic: ShouldPanic::No,
121 test_type: TestType::Unknown,
123 testfn: DynTestFn(Box::new(f)),
125 let (tx, rx) = channel();
126 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
127 let result = rx.recv().unwrap().result;
128 assert_eq!(result, TrIgnored);
131 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
133 #[cfg(not(target_os = "emscripten"))]
134 fn test_should_panic() {
138 let desc = TestDescAndFn {
140 name: StaticTestName("whatever"),
142 should_panic: ShouldPanic::Yes,
146 test_type: TestType::Unknown,
148 testfn: DynTestFn(Box::new(f)),
150 let (tx, rx) = channel();
151 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
152 let result = rx.recv().unwrap().result;
153 assert_eq!(result, TrOk);
156 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
158 #[cfg(not(target_os = "emscripten"))]
159 fn test_should_panic_good_message() {
161 panic!("an error message");
163 let desc = TestDescAndFn {
165 name: StaticTestName("whatever"),
167 should_panic: ShouldPanic::YesWithMessage("error message"),
171 test_type: TestType::Unknown,
173 testfn: DynTestFn(Box::new(f)),
175 let (tx, rx) = channel();
176 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
177 let result = rx.recv().unwrap().result;
178 assert_eq!(result, TrOk);
181 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
183 #[cfg(not(target_os = "emscripten"))]
184 fn test_should_panic_bad_message() {
185 use crate::tests::TrFailedMsg;
187 panic!("an error message");
189 let expected = "foobar";
190 let failed_msg = r#"panic did not contain expected string
191 panic message: `"an error message"`,
192 expected substring: `"foobar"`"#;
193 let desc = TestDescAndFn {
195 name: StaticTestName("whatever"),
197 should_panic: ShouldPanic::YesWithMessage(expected),
201 test_type: TestType::Unknown,
203 testfn: DynTestFn(Box::new(f)),
205 let (tx, rx) = channel();
206 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
207 let result = rx.recv().unwrap().result;
208 assert_eq!(result, TrFailedMsg(failed_msg.to_string()));
211 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
213 #[cfg(not(target_os = "emscripten"))]
214 fn test_should_panic_non_string_message_type() {
215 use crate::tests::TrFailedMsg;
216 use std::any::TypeId;
218 std::panic::panic_any(1i32);
220 let expected = "foobar";
221 let failed_msg = format!(
222 r#"expected panic with string value,
223 found non-string value: `{:?}`
224 expected substring: `"foobar"`"#,
227 let desc = TestDescAndFn {
229 name: StaticTestName("whatever"),
231 should_panic: ShouldPanic::YesWithMessage(expected),
235 test_type: TestType::Unknown,
237 testfn: DynTestFn(Box::new(f)),
239 let (tx, rx) = channel();
240 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
241 let result = rx.recv().unwrap().result;
242 assert_eq!(result, TrFailedMsg(failed_msg));
245 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
247 #[cfg(not(target_os = "emscripten"))]
248 fn test_should_panic_but_succeeds() {
249 let should_panic_variants = [ShouldPanic::Yes, ShouldPanic::YesWithMessage("error message")];
251 for &should_panic in should_panic_variants.iter() {
253 let desc = TestDescAndFn {
255 name: StaticTestName("whatever"),
261 test_type: TestType::Unknown,
263 testfn: DynTestFn(Box::new(f)),
265 let (tx, rx) = channel();
271 RunStrategy::InProcess,
275 let result = rx.recv().unwrap().result;
278 TrFailedMsg("test did not panic as expected".to_string()),
279 "should_panic == {:?}",
285 fn report_time_test_template(report_time: bool) -> Option<TestExecTime> {
287 let desc = TestDescAndFn {
289 name: StaticTestName("whatever"),
291 should_panic: ShouldPanic::No,
295 test_type: TestType::Unknown,
297 testfn: DynTestFn(Box::new(f)),
299 let time_options = if report_time { Some(TestTimeOptions::default()) } else { None };
301 let test_opts = TestOpts { time_options, ..TestOpts::new() };
302 let (tx, rx) = channel();
303 run_test(&test_opts, false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
304 let exec_time = rx.recv().unwrap().exec_time;
309 fn test_should_not_report_time() {
310 let exec_time = report_time_test_template(false);
311 assert!(exec_time.is_none());
315 fn test_should_report_time() {
316 let exec_time = report_time_test_template(true);
317 assert!(exec_time.is_some());
320 fn time_test_failure_template(test_type: TestType) -> TestResult {
322 let desc = TestDescAndFn {
324 name: StaticTestName("whatever"),
326 should_panic: ShouldPanic::No,
332 testfn: DynTestFn(Box::new(f)),
334 // `Default` will initialize all the thresholds to 0 milliseconds.
335 let mut time_options = TestTimeOptions::default();
336 time_options.error_on_excess = true;
338 let test_opts = TestOpts { time_options: Some(time_options), ..TestOpts::new() };
339 let (tx, rx) = channel();
340 run_test(&test_opts, false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
341 let result = rx.recv().unwrap().result;
347 fn test_error_on_exceed() {
348 let types = [TestType::UnitTest, TestType::IntegrationTest, TestType::DocTest];
350 for test_type in types.iter() {
351 let result = time_test_failure_template(*test_type);
353 assert_eq!(result, TestResult::TrTimedFail);
356 // Check that for unknown tests thresholds aren't applied.
357 let result = time_test_failure_template(TestType::Unknown);
358 assert_eq!(result, TestResult::TrOk);
361 fn typed_test_desc(test_type: TestType) -> TestDesc {
363 name: StaticTestName("whatever"),
365 should_panic: ShouldPanic::No,
373 fn test_exec_time(millis: u64) -> TestExecTime {
374 TestExecTime(Duration::from_millis(millis))
378 fn test_time_options_threshold() {
379 let unit = TimeThreshold::new(Duration::from_millis(50), Duration::from_millis(100));
380 let integration = TimeThreshold::new(Duration::from_millis(500), Duration::from_millis(1000));
381 let doc = TimeThreshold::new(Duration::from_millis(5000), Duration::from_millis(10000));
383 let options = TestTimeOptions {
384 error_on_excess: false,
386 unit_threshold: unit.clone(),
387 integration_threshold: integration.clone(),
388 doctest_threshold: doc.clone(),
392 (TestType::UnitTest, unit.warn.as_millis() - 1, false, false),
393 (TestType::UnitTest, unit.warn.as_millis(), true, false),
394 (TestType::UnitTest, unit.critical.as_millis(), true, true),
395 (TestType::IntegrationTest, integration.warn.as_millis() - 1, false, false),
396 (TestType::IntegrationTest, integration.warn.as_millis(), true, false),
397 (TestType::IntegrationTest, integration.critical.as_millis(), true, true),
398 (TestType::DocTest, doc.warn.as_millis() - 1, false, false),
399 (TestType::DocTest, doc.warn.as_millis(), true, false),
400 (TestType::DocTest, doc.critical.as_millis(), true, true),
403 for (test_type, time, expected_warn, expected_critical) in test_vector.iter() {
404 let test_desc = typed_test_desc(*test_type);
405 let exec_time = test_exec_time(*time as u64);
407 assert_eq!(options.is_warn(&test_desc, &exec_time), *expected_warn);
408 assert_eq!(options.is_critical(&test_desc, &exec_time), *expected_critical);
413 fn parse_ignored_flag() {
414 let args = vec!["progname".to_string(), "filter".to_string(), "--ignored".to_string()];
415 let opts = parse_opts(&args).unwrap().unwrap();
416 assert_eq!(opts.run_ignored, RunIgnored::Only);
420 fn parse_show_output_flag() {
421 let args = vec!["progname".to_string(), "filter".to_string(), "--show-output".to_string()];
422 let opts = parse_opts(&args).unwrap().unwrap();
423 assert!(opts.options.display_output);
427 fn parse_include_ignored_flag() {
428 let args = vec!["progname".to_string(), "filter".to_string(), "--include-ignored".to_string()];
429 let opts = parse_opts(&args).unwrap().unwrap();
430 assert_eq!(opts.run_ignored, RunIgnored::Yes);
434 pub fn filter_for_ignored_option() {
435 // When we run ignored tests the test filter should filter out all the
436 // unignored tests and flip the ignore flag on the rest to false
438 let mut opts = TestOpts::new();
439 opts.run_tests = true;
440 opts.run_ignored = RunIgnored::Only;
442 let tests = one_ignored_one_unignored_test();
443 let filtered = filter_tests(&opts, tests);
445 assert_eq!(filtered.len(), 1);
446 assert_eq!(filtered[0].desc.name.to_string(), "1");
447 assert!(!filtered[0].desc.ignore);
451 pub fn run_include_ignored_option() {
452 // When we "--include-ignored" tests, the ignore flag should be set to false on
453 // all tests and no test filtered out
455 let mut opts = TestOpts::new();
456 opts.run_tests = true;
457 opts.run_ignored = RunIgnored::Yes;
459 let tests = one_ignored_one_unignored_test();
460 let filtered = filter_tests(&opts, tests);
462 assert_eq!(filtered.len(), 2);
463 assert!(!filtered[0].desc.ignore);
464 assert!(!filtered[1].desc.ignore);
468 pub fn exclude_should_panic_option() {
469 let mut opts = TestOpts::new();
470 opts.run_tests = true;
471 opts.exclude_should_panic = true;
473 let mut tests = one_ignored_one_unignored_test();
474 tests.push(TestDescAndFn {
476 name: StaticTestName("3"),
478 should_panic: ShouldPanic::Yes,
482 test_type: TestType::Unknown,
484 testfn: DynTestFn(Box::new(move || {})),
487 let filtered = filter_tests(&opts, tests);
489 assert_eq!(filtered.len(), 2);
490 assert!(filtered.iter().all(|test| test.desc.should_panic == ShouldPanic::No));
494 pub fn exact_filter_match() {
495 fn tests() -> Vec<TestDescAndFn> {
496 ["base", "base::test", "base::test1", "base::test2"]
498 .map(|name| TestDescAndFn {
500 name: StaticTestName(name),
502 should_panic: ShouldPanic::No,
506 test_type: TestType::Unknown,
508 testfn: DynTestFn(Box::new(move || {})),
514 filter_tests(&TestOpts { filters: vec!["base".into()], ..TestOpts::new() }, tests());
515 assert_eq!(substr.len(), 4);
518 filter_tests(&TestOpts { filters: vec!["bas".into()], ..TestOpts::new() }, tests());
519 assert_eq!(substr.len(), 4);
522 filter_tests(&TestOpts { filters: vec!["::test".into()], ..TestOpts::new() }, tests());
523 assert_eq!(substr.len(), 3);
526 filter_tests(&TestOpts { filters: vec!["base::test".into()], ..TestOpts::new() }, tests());
527 assert_eq!(substr.len(), 3);
529 let substr = filter_tests(
530 &TestOpts { filters: vec!["test1".into(), "test2".into()], ..TestOpts::new() },
533 assert_eq!(substr.len(), 2);
535 let exact = filter_tests(
536 &TestOpts { filters: vec!["base".into()], filter_exact: true, ..TestOpts::new() },
539 assert_eq!(exact.len(), 1);
541 let exact = filter_tests(
542 &TestOpts { filters: vec!["bas".into()], filter_exact: true, ..TestOpts::new() },
545 assert_eq!(exact.len(), 0);
547 let exact = filter_tests(
548 &TestOpts { filters: vec!["::test".into()], filter_exact: true, ..TestOpts::new() },
551 assert_eq!(exact.len(), 0);
553 let exact = filter_tests(
554 &TestOpts { filters: vec!["base::test".into()], filter_exact: true, ..TestOpts::new() },
557 assert_eq!(exact.len(), 1);
559 let exact = filter_tests(
561 filters: vec!["base".into(), "base::test".into()],
567 assert_eq!(exact.len(), 2);
570 fn sample_tests() -> Vec<TestDescAndFn> {
572 "sha1::test".to_string(),
573 "isize::test_to_str".to_string(),
574 "isize::test_pow".to_string(),
575 "test::do_not_run_ignored_tests".to_string(),
576 "test::ignored_tests_result_in_ignored".to_string(),
577 "test::first_free_arg_should_be_a_filter".to_string(),
578 "test::parse_ignored_flag".to_string(),
579 "test::parse_include_ignored_flag".to_string(),
580 "test::filter_for_ignored_option".to_string(),
581 "test::run_include_ignored_option".to_string(),
582 "test::sort_tests".to_string(),
585 let mut tests = Vec::new();
587 let test = TestDescAndFn {
589 name: DynTestName((*name).clone()),
591 should_panic: ShouldPanic::No,
595 test_type: TestType::Unknown,
597 testfn: DynTestFn(Box::new(testfn)),
605 pub fn sort_tests() {
606 let mut opts = TestOpts::new();
607 opts.run_tests = true;
609 let tests = sample_tests();
610 let filtered = filter_tests(&opts, tests);
613 "isize::test_pow".to_string(),
614 "isize::test_to_str".to_string(),
615 "sha1::test".to_string(),
616 "test::do_not_run_ignored_tests".to_string(),
617 "test::filter_for_ignored_option".to_string(),
618 "test::first_free_arg_should_be_a_filter".to_string(),
619 "test::ignored_tests_result_in_ignored".to_string(),
620 "test::parse_ignored_flag".to_string(),
621 "test::parse_include_ignored_flag".to_string(),
622 "test::run_include_ignored_option".to_string(),
623 "test::sort_tests".to_string(),
626 for (a, b) in expected.iter().zip(filtered) {
627 assert_eq!(*a, b.desc.name.to_string());
632 pub fn shuffle_tests() {
633 let mut opts = TestOpts::new();
636 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
639 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
641 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
643 assert!(left.iter().zip(&right).all(|(a, b)| a.1.desc.name == b.1.desc.name));
645 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
647 assert!(left.iter().zip(right).any(|(a, b)| a.1.desc.name != b.1.desc.name));
651 pub fn shuffle_tests_with_seed() {
652 let mut opts = TestOpts::new();
655 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
658 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
660 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
662 helpers::shuffle::shuffle_tests(shuffle_seed, left.as_mut_slice());
663 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
665 assert!(left.iter().zip(right).all(|(a, b)| a.1.desc.name == b.1.desc.name));
669 pub fn order_depends_on_more_than_seed() {
670 let mut opts = TestOpts::new();
673 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
675 let mut left_tests = sample_tests();
676 let mut right_tests = sample_tests();
679 right_tests.remove(0);
682 left_tests.into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
684 right_tests.into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
686 assert_eq!(left.len(), right.len());
688 assert!(left.iter().zip(&right).all(|(a, b)| a.0 == b.0));
690 helpers::shuffle::shuffle_tests(shuffle_seed, left.as_mut_slice());
691 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
693 assert!(left.iter().zip(right).any(|(a, b)| a.0 != b.0));
697 pub fn test_metricmap_compare() {
698 let mut m1 = MetricMap::new();
699 let mut m2 = MetricMap::new();
700 m1.insert_metric("in-both-noise", 1000.0, 200.0);
701 m2.insert_metric("in-both-noise", 1100.0, 200.0);
703 m1.insert_metric("in-first-noise", 1000.0, 2.0);
704 m2.insert_metric("in-second-noise", 1000.0, 2.0);
706 m1.insert_metric("in-both-want-downwards-but-regressed", 1000.0, 10.0);
707 m2.insert_metric("in-both-want-downwards-but-regressed", 2000.0, 10.0);
709 m1.insert_metric("in-both-want-downwards-and-improved", 2000.0, 10.0);
710 m2.insert_metric("in-both-want-downwards-and-improved", 1000.0, 10.0);
712 m1.insert_metric("in-both-want-upwards-but-regressed", 2000.0, -10.0);
713 m2.insert_metric("in-both-want-upwards-but-regressed", 1000.0, -10.0);
715 m1.insert_metric("in-both-want-upwards-and-improved", 1000.0, -10.0);
716 m2.insert_metric("in-both-want-upwards-and-improved", 2000.0, -10.0);
720 pub fn test_bench_once_no_iter() {
721 fn f(_: &mut Bencher) {}
726 pub fn test_bench_once_iter() {
727 fn f(b: &mut Bencher) {
734 pub fn test_bench_no_iter() {
735 fn f(_: &mut Bencher) {}
737 let (tx, rx) = channel();
739 let desc = TestDesc {
740 name: StaticTestName("f"),
742 should_panic: ShouldPanic::No,
746 test_type: TestType::Unknown,
749 crate::bench::benchmark(TestId(0), desc, tx, true, f);
754 pub fn test_bench_iter() {
755 fn f(b: &mut Bencher) {
759 let (tx, rx) = channel();
761 let desc = TestDesc {
762 name: StaticTestName("f"),
764 should_panic: ShouldPanic::No,
768 test_type: TestType::Unknown,
771 crate::bench::benchmark(TestId(0), desc, tx, true, f);
776 fn should_sort_failures_before_printing_them() {
777 let test_a = TestDesc {
778 name: StaticTestName("a"),
780 should_panic: ShouldPanic::No,
784 test_type: TestType::Unknown,
787 let test_b = TestDesc {
788 name: StaticTestName("b"),
790 should_panic: ShouldPanic::No,
794 test_type: TestType::Unknown,
797 let mut out = PrettyFormatter::new(OutputLocation::Raw(Vec::new()), false, 10, false, None);
799 let st = console::ConsoleTestState {
809 metrics: MetricMap::new(),
810 failures: vec![(test_b, Vec::new()), (test_a, Vec::new())],
811 options: Options::new(),
812 not_failures: Vec::new(),
813 time_failures: Vec::new(),
816 out.write_failures(&st).unwrap();
817 let s = match out.output_location() {
818 &OutputLocation::Raw(ref m) => String::from_utf8_lossy(&m[..]),
819 &OutputLocation::Pretty(_) => unreachable!(),
822 let apos = s.find("a").unwrap();
823 let bpos = s.find("b").unwrap();
824 assert!(apos < bpos);