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,
67 test_type: TestType::Unknown,
71 testfn: DynTestFn(Box::new(move || {})),
75 name: StaticTestName("2"),
77 should_panic: ShouldPanic::No,
80 test_type: TestType::Unknown,
84 testfn: DynTestFn(Box::new(move || {})),
90 pub fn do_not_run_ignored_tests() {
94 let desc = TestDescAndFn {
96 name: StaticTestName("whatever"),
98 should_panic: ShouldPanic::No,
101 test_type: TestType::Unknown,
105 testfn: DynTestFn(Box::new(f)),
107 let (tx, rx) = channel();
108 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
109 let result = rx.recv().unwrap().result;
110 assert_ne!(result, TrOk);
114 pub fn ignored_tests_result_in_ignored() {
116 let desc = TestDescAndFn {
118 name: StaticTestName("whatever"),
120 should_panic: ShouldPanic::No,
123 test_type: TestType::Unknown,
127 testfn: DynTestFn(Box::new(f)),
129 let (tx, rx) = channel();
130 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
131 let result = rx.recv().unwrap().result;
132 assert_eq!(result, TrIgnored);
135 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
137 #[cfg(not(target_os = "emscripten"))]
138 fn test_should_panic() {
142 let desc = TestDescAndFn {
144 name: StaticTestName("whatever"),
146 should_panic: ShouldPanic::Yes,
149 test_type: TestType::Unknown,
153 testfn: DynTestFn(Box::new(f)),
155 let (tx, rx) = channel();
156 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
157 let result = rx.recv().unwrap().result;
158 assert_eq!(result, TrOk);
161 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
163 #[cfg(not(target_os = "emscripten"))]
164 fn test_should_panic_good_message() {
166 panic!("an error message");
168 let desc = TestDescAndFn {
170 name: StaticTestName("whatever"),
172 should_panic: ShouldPanic::YesWithMessage("error message"),
175 test_type: TestType::Unknown,
179 testfn: DynTestFn(Box::new(f)),
181 let (tx, rx) = channel();
182 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
183 let result = rx.recv().unwrap().result;
184 assert_eq!(result, TrOk);
187 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
189 #[cfg(not(target_os = "emscripten"))]
190 fn test_should_panic_bad_message() {
191 use crate::tests::TrFailedMsg;
193 panic!("an error message");
195 let expected = "foobar";
196 let failed_msg = r#"panic did not contain expected string
197 panic message: `"an error message"`,
198 expected substring: `"foobar"`"#;
199 let desc = TestDescAndFn {
201 name: StaticTestName("whatever"),
203 should_panic: ShouldPanic::YesWithMessage(expected),
206 test_type: TestType::Unknown,
210 testfn: DynTestFn(Box::new(f)),
212 let (tx, rx) = channel();
213 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
214 let result = rx.recv().unwrap().result;
215 assert_eq!(result, TrFailedMsg(failed_msg.to_string()));
218 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
220 #[cfg(not(target_os = "emscripten"))]
221 fn test_should_panic_non_string_message_type() {
222 use crate::tests::TrFailedMsg;
223 use std::any::TypeId;
225 std::panic::panic_any(1i32);
227 let expected = "foobar";
228 let failed_msg = format!(
229 r#"expected panic with string value,
230 found non-string value: `{:?}`
231 expected substring: `"foobar"`"#,
234 let desc = TestDescAndFn {
236 name: StaticTestName("whatever"),
238 should_panic: ShouldPanic::YesWithMessage(expected),
241 test_type: TestType::Unknown,
245 testfn: DynTestFn(Box::new(f)),
247 let (tx, rx) = channel();
248 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
249 let result = rx.recv().unwrap().result;
250 assert_eq!(result, TrFailedMsg(failed_msg));
253 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
255 #[cfg(not(target_os = "emscripten"))]
256 fn test_should_panic_but_succeeds() {
257 let should_panic_variants = [ShouldPanic::Yes, ShouldPanic::YesWithMessage("error message")];
259 for &should_panic in should_panic_variants.iter() {
261 let desc = TestDescAndFn {
263 name: StaticTestName("whatever"),
268 test_type: TestType::Unknown,
272 testfn: DynTestFn(Box::new(f)),
274 let (tx, rx) = channel();
280 RunStrategy::InProcess,
284 let result = rx.recv().unwrap().result;
287 TrFailedMsg("test did not panic as expected".to_string()),
288 "should_panic == {:?}",
294 fn report_time_test_template(report_time: bool) -> Option<TestExecTime> {
296 let desc = TestDescAndFn {
298 name: StaticTestName("whatever"),
300 should_panic: ShouldPanic::No,
303 test_type: TestType::Unknown,
307 testfn: DynTestFn(Box::new(f)),
309 let time_options = if report_time { Some(TestTimeOptions::default()) } else { None };
311 let test_opts = TestOpts { time_options, ..TestOpts::new() };
312 let (tx, rx) = channel();
313 run_test(&test_opts, false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
314 let exec_time = rx.recv().unwrap().exec_time;
319 fn test_should_not_report_time() {
320 let exec_time = report_time_test_template(false);
321 assert!(exec_time.is_none());
325 fn test_should_report_time() {
326 let exec_time = report_time_test_template(true);
327 assert!(exec_time.is_some());
330 fn time_test_failure_template(test_type: TestType) -> TestResult {
332 let desc = TestDescAndFn {
334 name: StaticTestName("whatever"),
336 should_panic: ShouldPanic::No,
343 testfn: DynTestFn(Box::new(f)),
345 // `Default` will initialize all the thresholds to 0 milliseconds.
346 let mut time_options = TestTimeOptions::default();
347 time_options.error_on_excess = true;
349 let test_opts = TestOpts { time_options: Some(time_options), ..TestOpts::new() };
350 let (tx, rx) = channel();
351 run_test(&test_opts, false, TestId(0), desc, RunStrategy::InProcess, tx, Concurrent::No);
352 let result = rx.recv().unwrap().result;
358 fn test_error_on_exceed() {
359 let types = [TestType::UnitTest, TestType::IntegrationTest, TestType::DocTest];
361 for test_type in types.iter() {
362 let result = time_test_failure_template(*test_type);
364 assert_eq!(result, TestResult::TrTimedFail);
367 // Check that for unknown tests thresholds aren't applied.
368 let result = time_test_failure_template(TestType::Unknown);
369 assert_eq!(result, TestResult::TrOk);
372 fn typed_test_desc(test_type: TestType) -> TestDesc {
374 name: StaticTestName("whatever"),
376 should_panic: ShouldPanic::No,
385 fn test_exec_time(millis: u64) -> TestExecTime {
386 TestExecTime(Duration::from_millis(millis))
390 fn test_time_options_threshold() {
391 let unit = TimeThreshold::new(Duration::from_millis(50), Duration::from_millis(100));
392 let integration = TimeThreshold::new(Duration::from_millis(500), Duration::from_millis(1000));
393 let doc = TimeThreshold::new(Duration::from_millis(5000), Duration::from_millis(10000));
395 let options = TestTimeOptions {
396 error_on_excess: false,
398 unit_threshold: unit.clone(),
399 integration_threshold: integration.clone(),
400 doctest_threshold: doc.clone(),
404 (TestType::UnitTest, unit.warn.as_millis() - 1, false, false),
405 (TestType::UnitTest, unit.warn.as_millis(), true, false),
406 (TestType::UnitTest, unit.critical.as_millis(), true, true),
407 (TestType::IntegrationTest, integration.warn.as_millis() - 1, false, false),
408 (TestType::IntegrationTest, integration.warn.as_millis(), true, false),
409 (TestType::IntegrationTest, integration.critical.as_millis(), true, true),
410 (TestType::DocTest, doc.warn.as_millis() - 1, false, false),
411 (TestType::DocTest, doc.warn.as_millis(), true, false),
412 (TestType::DocTest, doc.critical.as_millis(), true, true),
415 for (test_type, time, expected_warn, expected_critical) in test_vector.iter() {
416 let test_desc = typed_test_desc(*test_type);
417 let exec_time = test_exec_time(*time as u64);
419 assert_eq!(options.is_warn(&test_desc, &exec_time), *expected_warn);
420 assert_eq!(options.is_critical(&test_desc, &exec_time), *expected_critical);
425 fn parse_ignored_flag() {
426 let args = vec!["progname".to_string(), "filter".to_string(), "--ignored".to_string()];
427 let opts = parse_opts(&args).unwrap().unwrap();
428 assert_eq!(opts.run_ignored, RunIgnored::Only);
432 fn parse_show_output_flag() {
433 let args = vec!["progname".to_string(), "filter".to_string(), "--show-output".to_string()];
434 let opts = parse_opts(&args).unwrap().unwrap();
435 assert!(opts.options.display_output);
439 fn parse_include_ignored_flag() {
440 let args = vec!["progname".to_string(), "filter".to_string(), "--include-ignored".to_string()];
441 let opts = parse_opts(&args).unwrap().unwrap();
442 assert_eq!(opts.run_ignored, RunIgnored::Yes);
446 pub fn filter_for_ignored_option() {
447 // When we run ignored tests the test filter should filter out all the
448 // unignored tests and flip the ignore flag on the rest to false
450 let mut opts = TestOpts::new();
451 opts.run_tests = true;
452 opts.run_ignored = RunIgnored::Only;
454 let tests = one_ignored_one_unignored_test();
455 let filtered = filter_tests(&opts, tests);
457 assert_eq!(filtered.len(), 1);
458 assert_eq!(filtered[0].desc.name.to_string(), "1");
459 assert!(!filtered[0].desc.ignore);
463 pub fn run_include_ignored_option() {
464 // When we "--include-ignored" tests, the ignore flag should be set to false on
465 // all tests and no test filtered out
467 let mut opts = TestOpts::new();
468 opts.run_tests = true;
469 opts.run_ignored = RunIgnored::Yes;
471 let tests = one_ignored_one_unignored_test();
472 let filtered = filter_tests(&opts, tests);
474 assert_eq!(filtered.len(), 2);
475 assert!(!filtered[0].desc.ignore);
476 assert!(!filtered[1].desc.ignore);
480 pub fn exclude_should_panic_option() {
481 let mut opts = TestOpts::new();
482 opts.run_tests = true;
483 opts.exclude_should_panic = true;
485 let mut tests = one_ignored_one_unignored_test();
486 tests.push(TestDescAndFn {
488 name: StaticTestName("3"),
490 should_panic: ShouldPanic::Yes,
493 test_type: TestType::Unknown,
497 testfn: DynTestFn(Box::new(move || {})),
500 let filtered = filter_tests(&opts, tests);
502 assert_eq!(filtered.len(), 2);
503 assert!(filtered.iter().all(|test| test.desc.should_panic == ShouldPanic::No));
507 pub fn exact_filter_match() {
508 fn tests() -> Vec<TestDescAndFn> {
509 ["base", "base::test", "base::test1", "base::test2"]
511 .map(|name| TestDescAndFn {
513 name: StaticTestName(name),
515 should_panic: ShouldPanic::No,
518 test_type: TestType::Unknown,
522 testfn: DynTestFn(Box::new(move || {})),
528 filter_tests(&TestOpts { filters: vec!["base".into()], ..TestOpts::new() }, tests());
529 assert_eq!(substr.len(), 4);
532 filter_tests(&TestOpts { filters: vec!["bas".into()], ..TestOpts::new() }, tests());
533 assert_eq!(substr.len(), 4);
536 filter_tests(&TestOpts { filters: vec!["::test".into()], ..TestOpts::new() }, tests());
537 assert_eq!(substr.len(), 3);
540 filter_tests(&TestOpts { filters: vec!["base::test".into()], ..TestOpts::new() }, tests());
541 assert_eq!(substr.len(), 3);
543 let substr = filter_tests(
544 &TestOpts { filters: vec!["test1".into(), "test2".into()], ..TestOpts::new() },
547 assert_eq!(substr.len(), 2);
549 let exact = filter_tests(
550 &TestOpts { filters: vec!["base".into()], filter_exact: true, ..TestOpts::new() },
553 assert_eq!(exact.len(), 1);
555 let exact = filter_tests(
556 &TestOpts { filters: vec!["bas".into()], filter_exact: true, ..TestOpts::new() },
559 assert_eq!(exact.len(), 0);
561 let exact = filter_tests(
562 &TestOpts { filters: vec!["::test".into()], filter_exact: true, ..TestOpts::new() },
565 assert_eq!(exact.len(), 0);
567 let exact = filter_tests(
568 &TestOpts { filters: vec!["base::test".into()], filter_exact: true, ..TestOpts::new() },
571 assert_eq!(exact.len(), 1);
573 let exact = filter_tests(
575 filters: vec!["base".into(), "base::test".into()],
581 assert_eq!(exact.len(), 2);
584 fn sample_tests() -> Vec<TestDescAndFn> {
586 "sha1::test".to_string(),
587 "isize::test_to_str".to_string(),
588 "isize::test_pow".to_string(),
589 "test::do_not_run_ignored_tests".to_string(),
590 "test::ignored_tests_result_in_ignored".to_string(),
591 "test::first_free_arg_should_be_a_filter".to_string(),
592 "test::parse_ignored_flag".to_string(),
593 "test::parse_include_ignored_flag".to_string(),
594 "test::filter_for_ignored_option".to_string(),
595 "test::run_include_ignored_option".to_string(),
596 "test::sort_tests".to_string(),
599 let mut tests = Vec::new();
601 let test = TestDescAndFn {
603 name: DynTestName((*name).clone()),
605 should_panic: ShouldPanic::No,
608 test_type: TestType::Unknown,
612 testfn: DynTestFn(Box::new(testfn)),
620 pub fn sort_tests() {
621 let mut opts = TestOpts::new();
622 opts.run_tests = true;
624 let tests = sample_tests();
625 let filtered = filter_tests(&opts, tests);
628 "isize::test_pow".to_string(),
629 "isize::test_to_str".to_string(),
630 "sha1::test".to_string(),
631 "test::do_not_run_ignored_tests".to_string(),
632 "test::filter_for_ignored_option".to_string(),
633 "test::first_free_arg_should_be_a_filter".to_string(),
634 "test::ignored_tests_result_in_ignored".to_string(),
635 "test::parse_ignored_flag".to_string(),
636 "test::parse_include_ignored_flag".to_string(),
637 "test::run_include_ignored_option".to_string(),
638 "test::sort_tests".to_string(),
641 for (a, b) in expected.iter().zip(filtered) {
642 assert_eq!(*a, b.desc.name.to_string());
647 pub fn shuffle_tests() {
648 let mut opts = TestOpts::new();
651 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
654 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
656 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
658 assert!(left.iter().zip(&right).all(|(a, b)| a.1.desc.name == b.1.desc.name));
660 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
662 assert!(left.iter().zip(right).any(|(a, b)| a.1.desc.name != b.1.desc.name));
666 pub fn shuffle_tests_with_seed() {
667 let mut opts = TestOpts::new();
670 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
673 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
675 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
677 helpers::shuffle::shuffle_tests(shuffle_seed, left.as_mut_slice());
678 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
680 assert!(left.iter().zip(right).all(|(a, b)| a.1.desc.name == b.1.desc.name));
684 pub fn order_depends_on_more_than_seed() {
685 let mut opts = TestOpts::new();
688 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
690 let mut left_tests = sample_tests();
691 let mut right_tests = sample_tests();
694 right_tests.remove(0);
697 left_tests.into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
699 right_tests.into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
701 assert_eq!(left.len(), right.len());
703 assert!(left.iter().zip(&right).all(|(a, b)| a.0 == b.0));
705 helpers::shuffle::shuffle_tests(shuffle_seed, left.as_mut_slice());
706 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
708 assert!(left.iter().zip(right).any(|(a, b)| a.0 != b.0));
712 pub fn test_metricmap_compare() {
713 let mut m1 = MetricMap::new();
714 let mut m2 = MetricMap::new();
715 m1.insert_metric("in-both-noise", 1000.0, 200.0);
716 m2.insert_metric("in-both-noise", 1100.0, 200.0);
718 m1.insert_metric("in-first-noise", 1000.0, 2.0);
719 m2.insert_metric("in-second-noise", 1000.0, 2.0);
721 m1.insert_metric("in-both-want-downwards-but-regressed", 1000.0, 10.0);
722 m2.insert_metric("in-both-want-downwards-but-regressed", 2000.0, 10.0);
724 m1.insert_metric("in-both-want-downwards-and-improved", 2000.0, 10.0);
725 m2.insert_metric("in-both-want-downwards-and-improved", 1000.0, 10.0);
727 m1.insert_metric("in-both-want-upwards-but-regressed", 2000.0, -10.0);
728 m2.insert_metric("in-both-want-upwards-but-regressed", 1000.0, -10.0);
730 m1.insert_metric("in-both-want-upwards-and-improved", 1000.0, -10.0);
731 m2.insert_metric("in-both-want-upwards-and-improved", 2000.0, -10.0);
735 pub fn test_bench_once_no_iter() {
736 fn f(_: &mut Bencher) {}
741 pub fn test_bench_once_iter() {
742 fn f(b: &mut Bencher) {
749 pub fn test_bench_no_iter() {
750 fn f(_: &mut Bencher) {}
752 let (tx, rx) = channel();
754 let desc = TestDesc {
755 name: StaticTestName("f"),
757 should_panic: ShouldPanic::No,
760 test_type: TestType::Unknown,
765 crate::bench::benchmark(TestId(0), desc, tx, true, f);
770 pub fn test_bench_iter() {
771 fn f(b: &mut Bencher) {
775 let (tx, rx) = channel();
777 let desc = TestDesc {
778 name: StaticTestName("f"),
780 should_panic: ShouldPanic::No,
783 test_type: TestType::Unknown,
788 crate::bench::benchmark(TestId(0), desc, tx, true, f);
793 fn should_sort_failures_before_printing_them() {
794 let test_a = TestDesc {
795 name: StaticTestName("a"),
797 should_panic: ShouldPanic::No,
800 test_type: TestType::Unknown,
805 let test_b = TestDesc {
806 name: StaticTestName("b"),
808 should_panic: ShouldPanic::No,
811 test_type: TestType::Unknown,
816 let mut out = PrettyFormatter::new(OutputLocation::Raw(Vec::new()), false, 10, false, None);
818 let st = console::ConsoleTestState {
827 metrics: MetricMap::new(),
828 failures: vec![(test_b, Vec::new()), (test_a, Vec::new())],
829 options: Options::new(),
830 not_failures: Vec::new(),
831 time_failures: Vec::new(),
834 out.write_failures(&st).unwrap();
835 let s = match out.output_location() {
836 &OutputLocation::Raw(ref m) => String::from_utf8_lossy(&m[..]),
837 &OutputLocation::Pretty(_) => unreachable!(),
840 let apos = s.find("a").unwrap();
841 let bpos = s.find("b").unwrap();
842 assert!(apos < bpos);