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"),
65 should_panic: ShouldPanic::No,
68 test_type: TestType::Unknown,
70 testfn: DynTestFn(Box::new(move || Ok(()))),
74 name: StaticTestName("2"),
77 should_panic: ShouldPanic::No,
80 test_type: TestType::Unknown,
82 testfn: DynTestFn(Box::new(move || Ok(()))),
88 pub fn do_not_run_ignored_tests() {
89 fn f() -> Result<(), String> {
92 let desc = TestDescAndFn {
94 name: StaticTestName("whatever"),
97 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);
106 let result = rx.recv().unwrap().result;
107 assert_ne!(result, TrOk);
111 pub fn ignored_tests_result_in_ignored() {
112 fn f() -> Result<(), String> {
115 let desc = TestDescAndFn {
117 name: StaticTestName("whatever"),
119 ignore_message: None,
120 should_panic: ShouldPanic::No,
123 test_type: TestType::Unknown,
125 testfn: DynTestFn(Box::new(f)),
127 let (tx, rx) = channel();
128 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx);
129 let result = rx.recv().unwrap().result;
130 assert_eq!(result, TrIgnored);
133 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
135 #[cfg(not(target_os = "emscripten"))]
136 fn test_should_panic() {
137 fn f() -> Result<(), String> {
140 let desc = TestDescAndFn {
142 name: StaticTestName("whatever"),
144 ignore_message: None,
145 should_panic: ShouldPanic::Yes,
148 test_type: TestType::Unknown,
150 testfn: DynTestFn(Box::new(f)),
152 let (tx, rx) = channel();
153 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx);
154 let result = rx.recv().unwrap().result;
155 assert_eq!(result, TrOk);
158 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
160 #[cfg(not(target_os = "emscripten"))]
161 fn test_should_panic_good_message() {
162 fn f() -> Result<(), String> {
163 panic!("an error message");
165 let desc = TestDescAndFn {
167 name: StaticTestName("whatever"),
169 ignore_message: None,
170 should_panic: ShouldPanic::YesWithMessage("error message"),
173 test_type: TestType::Unknown,
175 testfn: DynTestFn(Box::new(f)),
177 let (tx, rx) = channel();
178 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx);
179 let result = rx.recv().unwrap().result;
180 assert_eq!(result, TrOk);
183 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
185 #[cfg(not(target_os = "emscripten"))]
186 fn test_should_panic_bad_message() {
187 use crate::tests::TrFailedMsg;
188 fn f() -> Result<(), String> {
189 panic!("an error message");
191 let expected = "foobar";
192 let failed_msg = r#"panic did not contain expected string
193 panic message: `"an error message"`,
194 expected substring: `"foobar"`"#;
195 let desc = TestDescAndFn {
197 name: StaticTestName("whatever"),
199 ignore_message: None,
200 should_panic: ShouldPanic::YesWithMessage(expected),
203 test_type: TestType::Unknown,
205 testfn: DynTestFn(Box::new(f)),
207 let (tx, rx) = channel();
208 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx);
209 let result = rx.recv().unwrap().result;
210 assert_eq!(result, TrFailedMsg(failed_msg.to_string()));
213 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
215 #[cfg(not(target_os = "emscripten"))]
216 fn test_should_panic_non_string_message_type() {
217 use crate::tests::TrFailedMsg;
218 use std::any::TypeId;
219 fn f() -> Result<(), String> {
220 std::panic::panic_any(1i32);
222 let expected = "foobar";
223 let failed_msg = format!(
224 r#"expected panic with string value,
225 found non-string value: `{:?}`
226 expected substring: `"foobar"`"#,
229 let desc = TestDescAndFn {
231 name: StaticTestName("whatever"),
233 ignore_message: None,
234 should_panic: ShouldPanic::YesWithMessage(expected),
237 test_type: TestType::Unknown,
239 testfn: DynTestFn(Box::new(f)),
241 let (tx, rx) = channel();
242 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx);
243 let result = rx.recv().unwrap().result;
244 assert_eq!(result, TrFailedMsg(failed_msg));
247 // FIXME: Re-enable emscripten once it can catch panics again (introduced by #65251)
249 #[cfg(not(target_os = "emscripten"))]
250 fn test_should_panic_but_succeeds() {
251 let should_panic_variants = [ShouldPanic::Yes, ShouldPanic::YesWithMessage("error message")];
253 for &should_panic in should_panic_variants.iter() {
254 fn f() -> Result<(), String> {
257 let desc = TestDescAndFn {
259 name: StaticTestName("whatever"),
261 ignore_message: None,
265 test_type: TestType::Unknown,
267 testfn: DynTestFn(Box::new(f)),
269 let (tx, rx) = channel();
270 run_test(&TestOpts::new(), false, TestId(0), desc, RunStrategy::InProcess, tx);
271 let result = rx.recv().unwrap().result;
274 TrFailedMsg("test did not panic as expected".to_string()),
275 "should_panic == {:?}",
281 fn report_time_test_template(report_time: bool) -> Option<TestExecTime> {
282 fn f() -> Result<(), String> {
285 let desc = TestDescAndFn {
287 name: StaticTestName("whatever"),
289 ignore_message: None,
290 should_panic: ShouldPanic::No,
293 test_type: TestType::Unknown,
295 testfn: DynTestFn(Box::new(f)),
297 let time_options = if report_time { Some(TestTimeOptions::default()) } else { None };
299 let test_opts = TestOpts { time_options, ..TestOpts::new() };
300 let (tx, rx) = channel();
301 run_test(&test_opts, false, TestId(0), desc, RunStrategy::InProcess, tx);
302 let exec_time = rx.recv().unwrap().exec_time;
307 fn test_should_not_report_time() {
308 let exec_time = report_time_test_template(false);
309 assert!(exec_time.is_none());
313 fn test_should_report_time() {
314 let exec_time = report_time_test_template(true);
315 assert!(exec_time.is_some());
318 fn time_test_failure_template(test_type: TestType) -> TestResult {
319 fn f() -> Result<(), String> {
322 let desc = TestDescAndFn {
324 name: StaticTestName("whatever"),
326 ignore_message: None,
327 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);
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 ignore_message: None,
366 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,
385 unit_threshold: unit.clone(),
386 integration_threshold: integration.clone(),
387 doctest_threshold: doc.clone(),
391 (TestType::UnitTest, unit.warn.as_millis() - 1, false, false),
392 (TestType::UnitTest, unit.warn.as_millis(), true, false),
393 (TestType::UnitTest, unit.critical.as_millis(), true, true),
394 (TestType::IntegrationTest, integration.warn.as_millis() - 1, false, false),
395 (TestType::IntegrationTest, integration.warn.as_millis(), true, false),
396 (TestType::IntegrationTest, integration.critical.as_millis(), true, true),
397 (TestType::DocTest, doc.warn.as_millis() - 1, false, false),
398 (TestType::DocTest, doc.warn.as_millis(), true, false),
399 (TestType::DocTest, doc.critical.as_millis(), true, true),
402 for (test_type, time, expected_warn, expected_critical) in test_vector.iter() {
403 let test_desc = typed_test_desc(*test_type);
404 let exec_time = test_exec_time(*time as u64);
406 assert_eq!(options.is_warn(&test_desc, &exec_time), *expected_warn);
407 assert_eq!(options.is_critical(&test_desc, &exec_time), *expected_critical);
412 fn parse_ignored_flag() {
413 let args = vec!["progname".to_string(), "filter".to_string(), "--ignored".to_string()];
414 let opts = parse_opts(&args).unwrap().unwrap();
415 assert_eq!(opts.run_ignored, RunIgnored::Only);
419 fn parse_show_output_flag() {
420 let args = vec!["progname".to_string(), "filter".to_string(), "--show-output".to_string()];
421 let opts = parse_opts(&args).unwrap().unwrap();
422 assert!(opts.options.display_output);
426 fn parse_include_ignored_flag() {
427 let args = vec!["progname".to_string(), "filter".to_string(), "--include-ignored".to_string()];
428 let opts = parse_opts(&args).unwrap().unwrap();
429 assert_eq!(opts.run_ignored, RunIgnored::Yes);
433 pub fn filter_for_ignored_option() {
434 // When we run ignored tests the test filter should filter out all the
435 // unignored tests and flip the ignore flag on the rest to false
437 let mut opts = TestOpts::new();
438 opts.run_tests = true;
439 opts.run_ignored = RunIgnored::Only;
441 let tests = one_ignored_one_unignored_test();
442 let filtered = filter_tests(&opts, tests);
444 assert_eq!(filtered.len(), 1);
445 assert_eq!(filtered[0].desc.name.to_string(), "1");
446 assert!(!filtered[0].desc.ignore);
450 pub fn run_include_ignored_option() {
451 // When we "--include-ignored" tests, the ignore flag should be set to false on
452 // all tests and no test filtered out
454 let mut opts = TestOpts::new();
455 opts.run_tests = true;
456 opts.run_ignored = RunIgnored::Yes;
458 let tests = one_ignored_one_unignored_test();
459 let filtered = filter_tests(&opts, tests);
461 assert_eq!(filtered.len(), 2);
462 assert!(!filtered[0].desc.ignore);
463 assert!(!filtered[1].desc.ignore);
467 pub fn exclude_should_panic_option() {
468 let mut opts = TestOpts::new();
469 opts.run_tests = true;
470 opts.exclude_should_panic = true;
472 let mut tests = one_ignored_one_unignored_test();
473 tests.push(TestDescAndFn {
475 name: StaticTestName("3"),
477 ignore_message: None,
478 should_panic: ShouldPanic::Yes,
481 test_type: TestType::Unknown,
483 testfn: DynTestFn(Box::new(move || Ok(()))),
486 let filtered = filter_tests(&opts, tests);
488 assert_eq!(filtered.len(), 2);
489 assert!(filtered.iter().all(|test| test.desc.should_panic == ShouldPanic::No));
493 pub fn exact_filter_match() {
494 fn tests() -> Vec<TestDescAndFn> {
495 ["base", "base::test", "base::test1", "base::test2"]
497 .map(|name| TestDescAndFn {
499 name: StaticTestName(name),
501 ignore_message: None,
502 should_panic: ShouldPanic::No,
505 test_type: TestType::Unknown,
507 testfn: DynTestFn(Box::new(move || Ok(()))),
513 filter_tests(&TestOpts { filters: vec!["base".into()], ..TestOpts::new() }, tests());
514 assert_eq!(substr.len(), 4);
517 filter_tests(&TestOpts { filters: vec!["bas".into()], ..TestOpts::new() }, tests());
518 assert_eq!(substr.len(), 4);
521 filter_tests(&TestOpts { filters: vec!["::test".into()], ..TestOpts::new() }, tests());
522 assert_eq!(substr.len(), 3);
525 filter_tests(&TestOpts { filters: vec!["base::test".into()], ..TestOpts::new() }, tests());
526 assert_eq!(substr.len(), 3);
528 let substr = filter_tests(
529 &TestOpts { filters: vec!["test1".into(), "test2".into()], ..TestOpts::new() },
532 assert_eq!(substr.len(), 2);
534 let exact = filter_tests(
535 &TestOpts { filters: vec!["base".into()], filter_exact: true, ..TestOpts::new() },
538 assert_eq!(exact.len(), 1);
540 let exact = filter_tests(
541 &TestOpts { filters: vec!["bas".into()], filter_exact: true, ..TestOpts::new() },
544 assert_eq!(exact.len(), 0);
546 let exact = filter_tests(
547 &TestOpts { filters: vec!["::test".into()], filter_exact: true, ..TestOpts::new() },
550 assert_eq!(exact.len(), 0);
552 let exact = filter_tests(
553 &TestOpts { filters: vec!["base::test".into()], filter_exact: true, ..TestOpts::new() },
556 assert_eq!(exact.len(), 1);
558 let exact = filter_tests(
560 filters: vec!["base".into(), "base::test".into()],
566 assert_eq!(exact.len(), 2);
569 fn sample_tests() -> Vec<TestDescAndFn> {
571 "sha1::test".to_string(),
572 "isize::test_to_str".to_string(),
573 "isize::test_pow".to_string(),
574 "test::do_not_run_ignored_tests".to_string(),
575 "test::ignored_tests_result_in_ignored".to_string(),
576 "test::first_free_arg_should_be_a_filter".to_string(),
577 "test::parse_ignored_flag".to_string(),
578 "test::parse_include_ignored_flag".to_string(),
579 "test::filter_for_ignored_option".to_string(),
580 "test::run_include_ignored_option".to_string(),
581 "test::sort_tests".to_string(),
583 fn testfn() -> Result<(), String> {
586 let mut tests = Vec::new();
588 let test = TestDescAndFn {
590 name: DynTestName((*name).clone()),
592 ignore_message: None,
593 should_panic: ShouldPanic::No,
596 test_type: TestType::Unknown,
598 testfn: DynTestFn(Box::new(testfn)),
606 pub fn shuffle_tests() {
607 let mut opts = TestOpts::new();
610 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
613 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
615 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
617 assert!(left.iter().zip(&right).all(|(a, b)| a.1.desc.name == b.1.desc.name));
619 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
621 assert!(left.iter().zip(right).any(|(a, b)| a.1.desc.name != b.1.desc.name));
625 pub fn shuffle_tests_with_seed() {
626 let mut opts = TestOpts::new();
629 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
632 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
634 sample_tests().into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
636 helpers::shuffle::shuffle_tests(shuffle_seed, left.as_mut_slice());
637 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
639 assert!(left.iter().zip(right).all(|(a, b)| a.1.desc.name == b.1.desc.name));
643 pub fn order_depends_on_more_than_seed() {
644 let mut opts = TestOpts::new();
647 let shuffle_seed = get_shuffle_seed(&opts).unwrap();
649 let mut left_tests = sample_tests();
650 let mut right_tests = sample_tests();
653 right_tests.remove(0);
656 left_tests.into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
658 right_tests.into_iter().enumerate().map(|(i, e)| (TestId(i), e)).collect::<Vec<_>>();
660 assert_eq!(left.len(), right.len());
662 assert!(left.iter().zip(&right).all(|(a, b)| a.0 == b.0));
664 helpers::shuffle::shuffle_tests(shuffle_seed, left.as_mut_slice());
665 helpers::shuffle::shuffle_tests(shuffle_seed, right.as_mut_slice());
667 assert!(left.iter().zip(right).any(|(a, b)| a.0 != b.0));
671 pub fn test_metricmap_compare() {
672 let mut m1 = MetricMap::new();
673 let mut m2 = MetricMap::new();
674 m1.insert_metric("in-both-noise", 1000.0, 200.0);
675 m2.insert_metric("in-both-noise", 1100.0, 200.0);
677 m1.insert_metric("in-first-noise", 1000.0, 2.0);
678 m2.insert_metric("in-second-noise", 1000.0, 2.0);
680 m1.insert_metric("in-both-want-downwards-but-regressed", 1000.0, 10.0);
681 m2.insert_metric("in-both-want-downwards-but-regressed", 2000.0, 10.0);
683 m1.insert_metric("in-both-want-downwards-and-improved", 2000.0, 10.0);
684 m2.insert_metric("in-both-want-downwards-and-improved", 1000.0, 10.0);
686 m1.insert_metric("in-both-want-upwards-but-regressed", 2000.0, -10.0);
687 m2.insert_metric("in-both-want-upwards-but-regressed", 1000.0, -10.0);
689 m1.insert_metric("in-both-want-upwards-and-improved", 1000.0, -10.0);
690 m2.insert_metric("in-both-want-upwards-and-improved", 2000.0, -10.0);
694 pub fn test_bench_once_no_iter() {
695 fn f(_: &mut Bencher) -> Result<(), String> {
698 bench::run_once(f).unwrap();
702 pub fn test_bench_once_iter() {
703 fn f(b: &mut Bencher) -> Result<(), String> {
707 bench::run_once(f).unwrap();
711 pub fn test_bench_no_iter() {
712 fn f(_: &mut Bencher) -> Result<(), String> {
716 let (tx, rx) = channel();
718 let desc = TestDesc {
719 name: StaticTestName("f"),
721 ignore_message: None,
722 should_panic: ShouldPanic::No,
725 test_type: TestType::Unknown,
728 crate::bench::benchmark(TestId(0), desc, tx, true, f);
733 pub fn test_bench_iter() {
734 fn f(b: &mut Bencher) -> Result<(), String> {
739 let (tx, rx) = channel();
741 let desc = TestDesc {
742 name: StaticTestName("f"),
744 ignore_message: None,
745 should_panic: ShouldPanic::No,
748 test_type: TestType::Unknown,
751 crate::bench::benchmark(TestId(0), desc, tx, true, f);
756 fn should_sort_failures_before_printing_them() {
757 let test_a = TestDesc {
758 name: StaticTestName("a"),
760 ignore_message: None,
761 should_panic: ShouldPanic::No,
764 test_type: TestType::Unknown,
767 let test_b = TestDesc {
768 name: StaticTestName("b"),
770 ignore_message: None,
771 should_panic: ShouldPanic::No,
774 test_type: TestType::Unknown,
777 let mut out = PrettyFormatter::new(OutputLocation::Raw(Vec::new()), false, 10, false, None);
779 let st = console::ConsoleTestState {
788 metrics: MetricMap::new(),
789 failures: vec![(test_b, Vec::new()), (test_a, Vec::new())],
790 options: Options::new(),
791 not_failures: Vec::new(),
792 time_failures: Vec::new(),
795 out.write_failures(&st).unwrap();
796 let s = match out.output_location() {
797 &OutputLocation::Raw(ref m) => String::from_utf8_lossy(&m[..]),
798 &OutputLocation::Pretty(_) => unreachable!(),
801 let apos = s.find("a").unwrap();
802 let bpos = s.find("b").unwrap();
803 assert!(apos < bpos);
807 #[cfg(not(target_os = "emscripten"))]
808 fn test_dyn_bench_returning_err_fails_when_run_as_test() {
809 fn f(_: &mut Bencher) -> Result<(), String> {
810 Result::Err("An error".into())
812 let desc = TestDescAndFn {
814 name: StaticTestName("whatever"),
816 ignore_message: None,
817 should_panic: ShouldPanic::No,
820 test_type: TestType::Unknown,
822 testfn: DynBenchFn(Box::new(f)),
824 let (tx, rx) = channel();
825 let notify = move |event: TestEvent| {
826 if let TestEvent::TeResult(result) = event {
827 tx.send(result).unwrap();
831 run_tests(&TestOpts { run_tests: true, ..TestOpts::new() }, vec![desc], notify).unwrap();
832 let result = rx.recv().unwrap().result;
833 assert_eq!(result, TrFailed);