1 //! Support code for rustc's built in unit-test and micro-benchmarking
4 //! Almost all user code will only be interested in `Bencher` and
5 //! `black_box`. All other interactions (such as writing tests and
6 //! benchmarks themselves) should be done via the `#[test]` and
7 //! `#[bench]` attributes.
9 //! See the [Testing Chapter](../book/ch11-00-testing.html) of the book for more
12 // Currently, not much of this is meant for users. It is intended to
13 // support the simplest interface possible for representing and
14 // running tests while providing a base that other test frameworks may
17 #![unstable(feature = "test", issue = "50297")]
18 #![doc(test(attr(deny(warnings))))]
19 #![feature(internal_output_capture)]
20 #![feature(is_terminal)]
21 #![feature(staged_api)]
22 #![feature(process_exitcode_internals)]
23 #![feature(panic_can_unwind)]
27 pub use self::bench::{black_box, Bencher};
28 pub use self::console::run_tests_console;
29 pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic};
30 pub use self::types::TestName::*;
31 pub use self::types::*;
32 pub use self::ColorConfig::*;
33 pub use cli::TestOpts;
35 // Module to be used by rustc to compile tests in libtest
40 cli::{parse_opts, TestOpts},
42 helpers::metrics::{Metric, MetricMap},
43 options::{Concurrent, Options, RunIgnored, RunStrategy, ShouldPanic},
44 run_test, test_main, test_main_static,
45 test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk},
46 time::{TestExecTime, TestTimeOptions},
48 DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc,
49 TestDescAndFn, TestId, TestName, TestType,
55 collections::VecDeque,
59 panic::{self, catch_unwind, AssertUnwindSafe, PanicInfo},
60 process::{self, Command, Termination},
61 sync::mpsc::{channel, Sender},
64 time::{Duration, Instant},
84 use event::{CompletedTest, TestEvent};
85 use helpers::concurrency::get_concurrency;
86 use helpers::exit_code::get_exit_code;
87 use helpers::shuffle::{get_shuffle_seed, shuffle_tests};
88 use options::{Concurrent, RunStrategy};
90 use time::TestExecTime;
92 // Process exit code to be used to indicate test failures.
93 const ERROR_EXIT_CODE: i32 = 101;
95 const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE";
97 // The default console test runner. It accepts the command line
98 // arguments and a vector of test_descs.
99 pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>, options: Option<Options>) {
100 let mut opts = match cli::parse_opts(args) {
103 eprintln!("error: {msg}");
104 process::exit(ERROR_EXIT_CODE);
108 if let Some(options) = options {
109 opts.options = options;
112 if let Err(e) = console::list_tests_console(&opts, tests) {
113 eprintln!("error: io error when listing tests: {e:?}");
114 process::exit(ERROR_EXIT_CODE);
118 // If we encounter a non-unwinding panic, flush any captured output from the current test,
119 // and stop capturing output to ensure that the non-unwinding panic message is visible.
120 // We also acquire the locks for both output streams to prevent output from other threads
121 // from interleaving with the panic message or appearing after it.
122 let builtin_panic_hook = panic::take_hook();
123 let hook = Box::new({
124 move |info: &'_ PanicInfo<'_>| {
125 if !info.can_unwind() {
126 std::mem::forget(std::io::stderr().lock());
127 let mut stdout = ManuallyDrop::new(std::io::stdout().lock());
128 if let Some(captured) = io::set_output_capture(None) {
129 if let Ok(data) = captured.lock() {
130 let _ = stdout.write_all(&data);
131 let _ = stdout.flush();
135 builtin_panic_hook(info);
138 panic::set_hook(hook);
140 match console::run_tests_console(&opts, tests) {
142 Ok(false) => process::exit(ERROR_EXIT_CODE),
144 eprintln!("error: io error when listing tests: {e:?}");
145 process::exit(ERROR_EXIT_CODE);
151 /// A variant optimized for invocation with a static test vector.
152 /// This will panic (intentionally) when fed any dynamic tests.
154 /// This is the entry point for the main function generated by `rustc --test`
155 /// when panic=unwind.
156 pub fn test_main_static(tests: &[&TestDescAndFn]) {
157 let args = env::args().collect::<Vec<_>>();
158 let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
159 test_main(&args, owned_tests, None)
162 /// A variant optimized for invocation with a static test vector.
163 /// This will panic (intentionally) when fed any dynamic tests.
165 /// Runs tests in panic=abort mode, which involves spawning subprocesses for
168 /// This is the entry point for the main function generated by `rustc --test`
169 /// when panic=abort.
170 pub fn test_main_static_abort(tests: &[&TestDescAndFn]) {
171 // If we're being run in SpawnedSecondary mode, run the test here. run_test
172 // will then exit the process.
173 if let Ok(name) = env::var(SECONDARY_TEST_INVOKER_VAR) {
174 env::remove_var(SECONDARY_TEST_INVOKER_VAR);
177 .filter(|test| test.desc.name.as_slice() == name)
178 .map(make_owned_test)
180 .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{name}'"));
181 let TestDescAndFn { desc, testfn } = test;
182 let testfn = match testfn {
183 StaticTestFn(f) => f,
184 _ => panic!("only static tests are supported"),
186 run_test_in_spawned_subprocess(desc, Box::new(testfn));
189 let args = env::args().collect::<Vec<_>>();
190 let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
191 test_main(&args, owned_tests, Some(Options::new().panic_abort(true)))
194 /// Clones static values for putting into a dynamic vector, which test_main()
195 /// needs to hand out ownership of tests to parallel test runners.
197 /// This will panic when fed any dynamic tests, because they cannot be cloned.
198 fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn {
200 StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: test.desc.clone() },
201 StaticBenchFn(f) => TestDescAndFn { testfn: StaticBenchFn(f), desc: test.desc.clone() },
202 _ => panic!("non-static tests passed to test::test_main_static"),
206 /// Invoked when unit tests terminate. Returns `Result::Err` if the test is
207 /// considered a failure. By default, invokes `report() and checks for a `0`
209 pub fn assert_test_result<T: Termination>(result: T) -> Result<(), String> {
210 let code = result.report().to_i32();
215 "the test returned a termination value with a non-zero status code \
216 ({}) which indicates a failure",
222 struct FilteredTests {
223 tests: Vec<(TestId, TestDescAndFn)>,
224 benchs: Vec<(TestId, TestDescAndFn)>,
229 fn add_bench(&mut self, desc: TestDesc, testfn: TestFn) {
230 let test = TestDescAndFn { desc, testfn };
231 self.benchs.push((TestId(self.next_id), test));
234 fn add_test(&mut self, desc: TestDesc, testfn: TestFn) {
235 let test = TestDescAndFn { desc, testfn };
236 self.tests.push((TestId(self.next_id), test));
239 fn add_bench_as_test(
242 benchfn: impl Fn(&mut Bencher) -> Result<(), String> + Send + 'static,
244 let testfn = DynTestFn(Box::new(move || {
245 bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
247 self.add_test(desc, testfn);
253 tests: Vec<TestDescAndFn>,
254 mut notify_about_test_event: F,
257 F: FnMut(TestEvent) -> io::Result<()>,
259 use std::collections::{self, HashMap};
260 use std::hash::BuildHasherDefault;
261 use std::sync::mpsc::RecvTimeoutError;
264 join_handle: Option<thread::JoinHandle<()>>,
267 // Use a deterministic hasher
269 HashMap<TestId, RunningTest, BuildHasherDefault<collections::hash_map::DefaultHasher>>;
271 struct TimeoutEntry {
277 let tests_len = tests.len();
279 let mut filtered = FilteredTests { tests: Vec::new(), benchs: Vec::new(), next_id: 0 };
281 for test in filter_tests(opts, tests) {
282 let mut desc = test.desc;
283 desc.name = desc.name.with_padding(test.testfn.padding());
286 DynBenchFn(benchfn) => {
287 if opts.bench_benchmarks {
288 filtered.add_bench(desc, DynBenchFn(benchfn));
290 filtered.add_bench_as_test(desc, benchfn);
293 StaticBenchFn(benchfn) => {
294 if opts.bench_benchmarks {
295 filtered.add_bench(desc, StaticBenchFn(benchfn));
297 filtered.add_bench_as_test(desc, benchfn);
301 filtered.add_test(desc, testfn);
306 let filtered_out = tests_len - filtered.tests.len();
307 let event = TestEvent::TeFilteredOut(filtered_out);
308 notify_about_test_event(event)?;
310 let shuffle_seed = get_shuffle_seed(opts);
312 let event = TestEvent::TeFiltered(filtered.tests.len(), shuffle_seed);
313 notify_about_test_event(event)?;
315 let concurrency = opts.test_threads.unwrap_or_else(get_concurrency);
317 let mut remaining = filtered.tests;
318 if let Some(shuffle_seed) = shuffle_seed {
319 shuffle_tests(shuffle_seed, &mut remaining);
321 // Store the tests in a VecDeque so we can efficiently remove the first element to run the
322 // tests in the order they were passed (unless shuffled).
323 let mut remaining = VecDeque::from(remaining);
326 let (tx, rx) = channel::<CompletedTest>();
327 let run_strategy = if opts.options.panic_abort && !opts.force_run_in_process {
328 RunStrategy::SpawnPrimary
330 RunStrategy::InProcess
333 let mut running_tests: TestMap = HashMap::default();
334 let mut timeout_queue: VecDeque<TimeoutEntry> = VecDeque::new();
336 fn get_timed_out_tests(
337 running_tests: &TestMap,
338 timeout_queue: &mut VecDeque<TimeoutEntry>,
340 let now = Instant::now();
341 let mut timed_out = Vec::new();
342 while let Some(timeout_entry) = timeout_queue.front() {
343 if now < timeout_entry.timeout {
346 let timeout_entry = timeout_queue.pop_front().unwrap();
347 if running_tests.contains_key(&timeout_entry.id) {
348 timed_out.push(timeout_entry.desc);
354 fn calc_timeout(timeout_queue: &VecDeque<TimeoutEntry>) -> Option<Duration> {
355 timeout_queue.front().map(|&TimeoutEntry { timeout: next_timeout, .. }| {
356 let now = Instant::now();
357 if next_timeout >= now { next_timeout - now } else { Duration::new(0, 0) }
361 if concurrency == 1 {
362 while !remaining.is_empty() {
363 let (id, test) = remaining.pop_front().unwrap();
364 let event = TestEvent::TeWait(test.desc.clone());
365 notify_about_test_event(event)?;
367 run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone(), Concurrent::No);
368 assert!(join_handle.is_none());
369 let completed_test = rx.recv().unwrap();
371 let event = TestEvent::TeResult(completed_test);
372 notify_about_test_event(event)?;
375 while pending > 0 || !remaining.is_empty() {
376 while pending < concurrency && !remaining.is_empty() {
377 let (id, test) = remaining.pop_front().unwrap();
378 let timeout = time::get_default_test_timeout();
379 let desc = test.desc.clone();
381 let event = TestEvent::TeWait(desc.clone());
382 notify_about_test_event(event)?; //here no pad
383 let join_handle = run_test(
392 running_tests.insert(id, RunningTest { join_handle });
393 timeout_queue.push_back(TimeoutEntry { id, desc, timeout });
399 if let Some(timeout) = calc_timeout(&timeout_queue) {
400 res = rx.recv_timeout(timeout);
401 for test in get_timed_out_tests(&running_tests, &mut timeout_queue) {
402 let event = TestEvent::TeTimeout(test);
403 notify_about_test_event(event)?;
407 Err(RecvTimeoutError::Timeout) => {
408 // Result is not yet ready, continue waiting.
411 // We've got a result, stop the loop.
416 res = rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
421 let mut completed_test = res.unwrap();
422 let running_test = running_tests.remove(&completed_test.id).unwrap();
423 if let Some(join_handle) = running_test.join_handle {
424 if let Err(_) = join_handle.join() {
425 if let TrOk = completed_test.result {
426 completed_test.result =
427 TrFailedMsg("panicked after reporting success".to_string());
432 let event = TestEvent::TeResult(completed_test);
433 notify_about_test_event(event)?;
438 if opts.bench_benchmarks {
439 // All benchmarks run at the end, in serial.
440 for (id, b) in filtered.benchs {
441 let event = TestEvent::TeWait(b.desc.clone());
442 notify_about_test_event(event)?;
443 run_test(opts, false, id, b, run_strategy, tx.clone(), Concurrent::No);
444 let completed_test = rx.recv().unwrap();
446 let event = TestEvent::TeResult(completed_test);
447 notify_about_test_event(event)?;
453 pub fn filter_tests(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
454 let mut filtered = tests;
455 let matches_filter = |test: &TestDescAndFn, filter: &str| {
456 let test_name = test.desc.name.as_slice();
458 match opts.filter_exact {
459 true => test_name == filter,
460 false => test_name.contains(filter),
464 // Remove tests that don't match the test filter
465 if !opts.filters.is_empty() {
466 filtered.retain(|test| opts.filters.iter().any(|filter| matches_filter(test, filter)));
469 // Skip tests that match any of the skip filters
470 if !opts.skip.is_empty() {
471 filtered.retain(|test| !opts.skip.iter().any(|sf| matches_filter(test, sf)));
474 // Excludes #[should_panic] tests
475 if opts.exclude_should_panic {
476 filtered.retain(|test| test.desc.should_panic == ShouldPanic::No);
479 // maybe unignore tests
480 match opts.run_ignored {
482 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
484 RunIgnored::Only => {
485 filtered.retain(|test| test.desc.ignore);
486 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
494 pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
495 // convert benchmarks to tests, if we're not benchmarking them
499 let testfn = match x.testfn {
500 DynBenchFn(benchfn) => DynTestFn(Box::new(move || {
501 bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
503 StaticBenchFn(benchfn) => DynTestFn(Box::new(move || {
504 bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
508 TestDescAndFn { desc: x.desc, testfn }
518 strategy: RunStrategy,
519 monitor_ch: Sender<CompletedTest>,
520 concurrency: Concurrent,
521 ) -> Option<thread::JoinHandle<()>> {
522 let TestDescAndFn { desc, testfn } = test;
524 // Emscripten can catch panics but other wasm targets cannot
525 let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No
526 && cfg!(target_family = "wasm")
527 && !cfg!(target_os = "emscripten");
529 if force_ignore || desc.ignore || ignore_because_no_process_support {
530 let message = CompletedTest::new(id, desc, TrIgnored, None, Vec::new());
531 monitor_ch.send(message).unwrap();
536 pub strategy: RunStrategy,
538 pub concurrency: Concurrent,
539 pub time: Option<time::TestTimeOptions>,
545 monitor_ch: Sender<CompletedTest>,
546 testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
548 ) -> Option<thread::JoinHandle<()>> {
549 let concurrency = opts.concurrency;
550 let name = desc.name.clone();
552 let runtest = move || match opts.strategy {
553 RunStrategy::InProcess => run_test_in_process(
562 RunStrategy::SpawnPrimary => spawn_test_subprocess(
572 // If the platform is single-threaded we're just going to run
573 // the test synchronously, regardless of the concurrency
575 let supports_threads = !cfg!(target_os = "emscripten") && !cfg!(target_family = "wasm");
576 if concurrency == Concurrent::Yes && supports_threads {
577 let cfg = thread::Builder::new().name(name.as_slice().to_owned());
578 let mut runtest = Arc::new(Mutex::new(Some(runtest)));
579 let runtest2 = runtest.clone();
580 match cfg.spawn(move || runtest2.lock().unwrap().take().unwrap()()) {
581 Ok(handle) => Some(handle),
582 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
583 // `ErrorKind::WouldBlock` means hitting the thread limit on some
584 // platforms, so run the test synchronously here instead.
585 Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()();
588 Err(e) => panic!("failed to spawn thread to run test: {e}"),
597 TestRunOpts { strategy, nocapture: opts.nocapture, concurrency, time: opts.time_options };
600 DynBenchFn(benchfn) => {
601 // Benchmarks aren't expected to panic, so we run them all in-process.
602 crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
605 StaticBenchFn(benchfn) => {
606 // Benchmarks aren't expected to panic, so we run them all in-process.
607 crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
612 RunStrategy::InProcess => (),
613 _ => panic!("Cannot run dynamic test fn out-of-process"),
619 Box::new(move || __rust_begin_short_backtrace(f)),
623 StaticTestFn(f) => run_test_inner(
627 Box::new(move || __rust_begin_short_backtrace(f)),
633 /// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`.
635 fn __rust_begin_short_backtrace<T, F: FnOnce() -> T>(f: F) -> T {
638 // prevent this frame from being tail-call optimised away
642 fn run_test_in_process(
647 testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
648 monitor_ch: Sender<CompletedTest>,
649 time_opts: Option<time::TestTimeOptions>,
651 // Buffer for capturing standard I/O
652 let data = Arc::new(Mutex::new(Vec::new()));
655 io::set_output_capture(Some(data.clone()));
658 let start = report_time.then(Instant::now);
659 let result = fold_err(catch_unwind(AssertUnwindSafe(testfn)));
660 let exec_time = start.map(|start| {
661 let duration = start.elapsed();
662 TestExecTime(duration)
665 io::set_output_capture(None);
667 let test_result = match result {
668 Ok(()) => calc_result(&desc, Ok(()), &time_opts, &exec_time),
669 Err(e) => calc_result(&desc, Err(e.as_ref()), &time_opts, &exec_time),
671 let stdout = data.lock().unwrap_or_else(|e| e.into_inner()).to_vec();
672 let message = CompletedTest::new(id, desc, test_result, exec_time, stdout);
673 monitor_ch.send(message).unwrap();
677 result: Result<Result<T, E>, Box<dyn Any + Send>>,
678 ) -> Result<T, Box<dyn Any + Send>>
683 Ok(Err(e)) => Err(Box::new(e)),
689 fn spawn_test_subprocess(
694 monitor_ch: Sender<CompletedTest>,
695 time_opts: Option<time::TestTimeOptions>,
697 let (result, test_output, exec_time) = (|| {
698 let args = env::args().collect::<Vec<_>>();
699 let current_exe = &args[0];
701 let mut command = Command::new(current_exe);
702 command.env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice());
704 command.stdout(process::Stdio::inherit());
705 command.stderr(process::Stdio::inherit());
708 let start = report_time.then(Instant::now);
709 let output = match command.output() {
712 let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e);
713 return (TrFailed, err.into_bytes(), None);
716 let exec_time = start.map(|start| {
717 let duration = start.elapsed();
718 TestExecTime(duration)
721 let std::process::Output { stdout, stderr, status } = output;
722 let mut test_output = stdout;
723 formatters::write_stderr_delimiter(&mut test_output, &desc.name);
724 test_output.extend_from_slice(&stderr);
726 let result = match (|| -> Result<TestResult, String> {
727 let exit_code = get_exit_code(status)?;
728 Ok(get_result_from_exit_code(&desc, exit_code, &time_opts, &exec_time))
732 write!(&mut test_output, "Unexpected error: {}", e).unwrap();
737 (result, test_output, exec_time)
740 let message = CompletedTest::new(id, desc, result, exec_time, test_output);
741 monitor_ch.send(message).unwrap();
744 fn run_test_in_spawned_subprocess(
746 testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
748 let builtin_panic_hook = panic::take_hook();
749 let record_result = Arc::new(move |panic_info: Option<&'_ PanicInfo<'_>>| {
750 let test_result = match panic_info {
751 Some(info) => calc_result(&desc, Err(info.payload()), &None, &None),
752 None => calc_result(&desc, Ok(()), &None, &None),
755 // We don't support serializing TrFailedMsg, so just
756 // print the message out to stderr.
757 if let TrFailedMsg(msg) = &test_result {
761 if let Some(info) = panic_info {
762 builtin_panic_hook(info);
765 if let TrOk = test_result {
766 process::exit(test_result::TR_OK);
768 process::exit(test_result::TR_FAILED);
771 let record_result2 = record_result.clone();
772 panic::set_hook(Box::new(move |info| record_result2(Some(&info))));
773 if let Err(message) = testfn() {
774 panic!("{}", message);
777 unreachable!("panic=abort callback should have exited the process")