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)]
26 pub use self::bench::{black_box, Bencher};
27 pub use self::console::run_tests_console;
28 pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic};
29 pub use self::types::TestName::*;
30 pub use self::types::*;
31 pub use self::ColorConfig::*;
32 pub use cli::TestOpts;
34 // Module to be used by rustc to compile tests in libtest
39 cli::{parse_opts, TestOpts},
41 helpers::metrics::{Metric, MetricMap},
42 options::{Concurrent, Options, RunIgnored, RunStrategy, ShouldPanic},
43 run_test, test_main, test_main_static,
44 test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk},
45 time::{TestExecTime, TestTimeOptions},
47 DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc,
48 TestDescAndFn, TestId, TestName, TestType,
54 collections::VecDeque,
57 panic::{self, catch_unwind, AssertUnwindSafe, PanicInfo},
58 process::{self, Command, Termination},
59 sync::mpsc::{channel, Sender},
62 time::{Duration, Instant},
82 use event::{CompletedTest, TestEvent};
83 use helpers::concurrency::get_concurrency;
84 use helpers::exit_code::get_exit_code;
85 use helpers::shuffle::{get_shuffle_seed, shuffle_tests};
86 use options::{Concurrent, RunStrategy};
88 use time::TestExecTime;
90 // Process exit code to be used to indicate test failures.
91 const ERROR_EXIT_CODE: i32 = 101;
93 const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE";
95 // The default console test runner. It accepts the command line
96 // arguments and a vector of test_descs.
97 pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>, options: Option<Options>) {
98 let mut opts = match cli::parse_opts(args) {
101 eprintln!("error: {msg}");
102 process::exit(ERROR_EXIT_CODE);
106 if let Some(options) = options {
107 opts.options = options;
110 if let Err(e) = console::list_tests_console(&opts, tests) {
111 eprintln!("error: io error when listing tests: {e:?}");
112 process::exit(ERROR_EXIT_CODE);
115 match console::run_tests_console(&opts, tests) {
117 Ok(false) => process::exit(ERROR_EXIT_CODE),
119 eprintln!("error: io error when listing tests: {e:?}");
120 process::exit(ERROR_EXIT_CODE);
126 /// A variant optimized for invocation with a static test vector.
127 /// This will panic (intentionally) when fed any dynamic tests.
129 /// This is the entry point for the main function generated by `rustc --test`
130 /// when panic=unwind.
131 pub fn test_main_static(tests: &[&TestDescAndFn]) {
132 let args = env::args().collect::<Vec<_>>();
133 let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
134 test_main(&args, owned_tests, None)
137 /// A variant optimized for invocation with a static test vector.
138 /// This will panic (intentionally) when fed any dynamic tests.
140 /// Runs tests in panic=abort mode, which involves spawning subprocesses for
143 /// This is the entry point for the main function generated by `rustc --test`
144 /// when panic=abort.
145 pub fn test_main_static_abort(tests: &[&TestDescAndFn]) {
146 // If we're being run in SpawnedSecondary mode, run the test here. run_test
147 // will then exit the process.
148 if let Ok(name) = env::var(SECONDARY_TEST_INVOKER_VAR) {
149 env::remove_var(SECONDARY_TEST_INVOKER_VAR);
152 .filter(|test| test.desc.name.as_slice() == name)
153 .map(make_owned_test)
155 .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{name}'"));
156 let TestDescAndFn { desc, testfn } = test;
157 let testfn = match testfn {
158 StaticTestFn(f) => f,
159 _ => panic!("only static tests are supported"),
161 run_test_in_spawned_subprocess(desc, Box::new(testfn));
164 let args = env::args().collect::<Vec<_>>();
165 let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
166 test_main(&args, owned_tests, Some(Options::new().panic_abort(true)))
169 /// Clones static values for putting into a dynamic vector, which test_main()
170 /// needs to hand out ownership of tests to parallel test runners.
172 /// This will panic when fed any dynamic tests, because they cannot be cloned.
173 fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn {
175 StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: test.desc.clone() },
176 StaticBenchFn(f) => TestDescAndFn { testfn: StaticBenchFn(f), desc: test.desc.clone() },
177 _ => panic!("non-static tests passed to test::test_main_static"),
181 /// Invoked when unit tests terminate. Returns `Result::Err` if the test is
182 /// considered a failure. By default, invokes `report() and checks for a `0`
184 pub fn assert_test_result<T: Termination>(result: T) -> Result<(), String> {
185 let code = result.report().to_i32();
190 "the test returned a termination value with a non-zero status code \
191 ({}) which indicates a failure",
199 tests: Vec<TestDescAndFn>,
200 mut notify_about_test_event: F,
203 F: FnMut(TestEvent) -> io::Result<()>,
205 use std::collections::{self, HashMap};
206 use std::hash::BuildHasherDefault;
207 use std::sync::mpsc::RecvTimeoutError;
210 join_handle: Option<thread::JoinHandle<()>>,
213 // Use a deterministic hasher
215 HashMap<TestId, RunningTest, BuildHasherDefault<collections::hash_map::DefaultHasher>>;
217 struct TimeoutEntry {
223 let tests_len = tests.len();
225 let mut filtered_tests = filter_tests(opts, tests);
226 if !opts.bench_benchmarks {
227 filtered_tests = convert_benchmarks_to_tests(filtered_tests);
230 let filtered_tests = {
231 let mut filtered_tests = filtered_tests;
232 for test in filtered_tests.iter_mut() {
233 test.desc.name = test.desc.name.with_padding(test.testfn.padding());
239 let filtered_out = tests_len - filtered_tests.len();
240 let event = TestEvent::TeFilteredOut(filtered_out);
241 notify_about_test_event(event)?;
243 let filtered_descs = filtered_tests.iter().map(|t| t.desc.clone()).collect();
245 let shuffle_seed = get_shuffle_seed(opts);
247 let event = TestEvent::TeFiltered(filtered_descs, shuffle_seed);
248 notify_about_test_event(event)?;
250 let (filtered_tests, filtered_benchs): (Vec<_>, _) = filtered_tests
253 .map(|(i, e)| (TestId(i), e))
254 .partition(|(_, e)| matches!(e.testfn, StaticTestFn(_) | DynTestFn(_)));
256 let concurrency = opts.test_threads.unwrap_or_else(get_concurrency);
258 let mut remaining = filtered_tests;
259 if let Some(shuffle_seed) = shuffle_seed {
260 shuffle_tests(shuffle_seed, &mut remaining);
266 let (tx, rx) = channel::<CompletedTest>();
267 let run_strategy = if opts.options.panic_abort && !opts.force_run_in_process {
268 RunStrategy::SpawnPrimary
270 RunStrategy::InProcess
273 let mut running_tests: TestMap = HashMap::default();
274 let mut timeout_queue: VecDeque<TimeoutEntry> = VecDeque::new();
276 fn get_timed_out_tests(
277 running_tests: &TestMap,
278 timeout_queue: &mut VecDeque<TimeoutEntry>,
280 let now = Instant::now();
281 let mut timed_out = Vec::new();
282 while let Some(timeout_entry) = timeout_queue.front() {
283 if now < timeout_entry.timeout {
286 let timeout_entry = timeout_queue.pop_front().unwrap();
287 if running_tests.contains_key(&timeout_entry.id) {
288 timed_out.push(timeout_entry.desc);
294 fn calc_timeout(timeout_queue: &VecDeque<TimeoutEntry>) -> Option<Duration> {
295 timeout_queue.front().map(|&TimeoutEntry { timeout: next_timeout, .. }| {
296 let now = Instant::now();
297 if next_timeout >= now { next_timeout - now } else { Duration::new(0, 0) }
301 if concurrency == 1 {
302 while !remaining.is_empty() {
303 let (id, test) = remaining.pop().unwrap();
304 let event = TestEvent::TeWait(test.desc.clone());
305 notify_about_test_event(event)?;
307 run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone(), Concurrent::No);
308 assert!(join_handle.is_none());
309 let completed_test = rx.recv().unwrap();
311 let event = TestEvent::TeResult(completed_test);
312 notify_about_test_event(event)?;
315 while pending > 0 || !remaining.is_empty() {
316 while pending < concurrency && !remaining.is_empty() {
317 let (id, test) = remaining.pop().unwrap();
318 let timeout = time::get_default_test_timeout();
319 let desc = test.desc.clone();
321 let event = TestEvent::TeWait(desc.clone());
322 notify_about_test_event(event)?; //here no pad
323 let join_handle = run_test(
332 running_tests.insert(id, RunningTest { join_handle });
333 timeout_queue.push_back(TimeoutEntry { id, desc, timeout });
339 if let Some(timeout) = calc_timeout(&timeout_queue) {
340 res = rx.recv_timeout(timeout);
341 for test in get_timed_out_tests(&running_tests, &mut timeout_queue) {
342 let event = TestEvent::TeTimeout(test);
343 notify_about_test_event(event)?;
347 Err(RecvTimeoutError::Timeout) => {
348 // Result is not yet ready, continue waiting.
351 // We've got a result, stop the loop.
356 res = rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
361 let mut completed_test = res.unwrap();
362 let running_test = running_tests.remove(&completed_test.id).unwrap();
363 if let Some(join_handle) = running_test.join_handle {
364 if let Err(_) = join_handle.join() {
365 if let TrOk = completed_test.result {
366 completed_test.result =
367 TrFailedMsg("panicked after reporting success".to_string());
372 let event = TestEvent::TeResult(completed_test);
373 notify_about_test_event(event)?;
378 if opts.bench_benchmarks {
379 // All benchmarks run at the end, in serial.
380 for (id, b) in filtered_benchs {
381 let event = TestEvent::TeWait(b.desc.clone());
382 notify_about_test_event(event)?;
383 run_test(opts, false, id, b, run_strategy, tx.clone(), Concurrent::No);
384 let completed_test = rx.recv().unwrap();
386 let event = TestEvent::TeResult(completed_test);
387 notify_about_test_event(event)?;
393 pub fn filter_tests(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
394 let mut filtered = tests;
395 let matches_filter = |test: &TestDescAndFn, filter: &str| {
396 let test_name = test.desc.name.as_slice();
398 match opts.filter_exact {
399 true => test_name == filter,
400 false => test_name.contains(filter),
404 // Remove tests that don't match the test filter
405 if !opts.filters.is_empty() {
406 filtered.retain(|test| opts.filters.iter().any(|filter| matches_filter(test, filter)));
409 // Skip tests that match any of the skip filters
410 filtered.retain(|test| !opts.skip.iter().any(|sf| matches_filter(test, sf)));
412 // Excludes #[should_panic] tests
413 if opts.exclude_should_panic {
414 filtered.retain(|test| test.desc.should_panic == ShouldPanic::No);
417 // maybe unignore tests
418 match opts.run_ignored {
420 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
422 RunIgnored::Only => {
423 filtered.retain(|test| test.desc.ignore);
424 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
429 // Sort the tests alphabetically
430 filtered.sort_by(|t1, t2| t1.desc.name.as_slice().cmp(t2.desc.name.as_slice()));
435 pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
436 // convert benchmarks to tests, if we're not benchmarking them
440 let testfn = match x.testfn {
441 DynBenchFn(benchfn) => DynTestFn(Box::new(move || {
442 bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
444 StaticBenchFn(benchfn) => DynTestFn(Box::new(move || {
445 bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
449 TestDescAndFn { desc: x.desc, testfn }
459 strategy: RunStrategy,
460 monitor_ch: Sender<CompletedTest>,
461 concurrency: Concurrent,
462 ) -> Option<thread::JoinHandle<()>> {
463 let TestDescAndFn { desc, testfn } = test;
465 // Emscripten can catch panics but other wasm targets cannot
466 let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No
467 && cfg!(target_family = "wasm")
468 && !cfg!(target_os = "emscripten");
470 if force_ignore || desc.ignore || ignore_because_no_process_support {
471 let message = CompletedTest::new(id, desc, TrIgnored, None, Vec::new());
472 monitor_ch.send(message).unwrap();
477 pub strategy: RunStrategy,
479 pub concurrency: Concurrent,
480 pub time: Option<time::TestTimeOptions>,
486 monitor_ch: Sender<CompletedTest>,
487 testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
489 ) -> Option<thread::JoinHandle<()>> {
490 let concurrency = opts.concurrency;
491 let name = desc.name.clone();
493 let runtest = move || match opts.strategy {
494 RunStrategy::InProcess => run_test_in_process(
503 RunStrategy::SpawnPrimary => spawn_test_subprocess(
513 // If the platform is single-threaded we're just going to run
514 // the test synchronously, regardless of the concurrency
516 let supports_threads = !cfg!(target_os = "emscripten") && !cfg!(target_family = "wasm");
517 if concurrency == Concurrent::Yes && supports_threads {
518 let cfg = thread::Builder::new().name(name.as_slice().to_owned());
519 let mut runtest = Arc::new(Mutex::new(Some(runtest)));
520 let runtest2 = runtest.clone();
521 match cfg.spawn(move || runtest2.lock().unwrap().take().unwrap()()) {
522 Ok(handle) => Some(handle),
523 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
524 // `ErrorKind::WouldBlock` means hitting the thread limit on some
525 // platforms, so run the test synchronously here instead.
526 Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()();
529 Err(e) => panic!("failed to spawn thread to run test: {e}"),
538 TestRunOpts { strategy, nocapture: opts.nocapture, concurrency, time: opts.time_options };
541 DynBenchFn(benchfn) => {
542 // Benchmarks aren't expected to panic, so we run them all in-process.
543 crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
546 StaticBenchFn(benchfn) => {
547 // Benchmarks aren't expected to panic, so we run them all in-process.
548 crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
553 RunStrategy::InProcess => (),
554 _ => panic!("Cannot run dynamic test fn out-of-process"),
560 Box::new(move || __rust_begin_short_backtrace(f)),
564 StaticTestFn(f) => run_test_inner(
568 Box::new(move || __rust_begin_short_backtrace(f)),
574 /// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`.
576 fn __rust_begin_short_backtrace<T, F: FnOnce() -> T>(f: F) -> T {
579 // prevent this frame from being tail-call optimised away
583 fn run_test_in_process(
588 testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
589 monitor_ch: Sender<CompletedTest>,
590 time_opts: Option<time::TestTimeOptions>,
592 // Buffer for capturing standard I/O
593 let data = Arc::new(Mutex::new(Vec::new()));
596 io::set_output_capture(Some(data.clone()));
599 let start = report_time.then(Instant::now);
600 let result = fold_err(catch_unwind(AssertUnwindSafe(testfn)));
601 let exec_time = start.map(|start| {
602 let duration = start.elapsed();
603 TestExecTime(duration)
606 io::set_output_capture(None);
608 let test_result = match result {
609 Ok(()) => calc_result(&desc, Ok(()), &time_opts, &exec_time),
610 Err(e) => calc_result(&desc, Err(e.as_ref()), &time_opts, &exec_time),
612 let stdout = data.lock().unwrap_or_else(|e| e.into_inner()).to_vec();
613 let message = CompletedTest::new(id, desc, test_result, exec_time, stdout);
614 monitor_ch.send(message).unwrap();
618 result: Result<Result<T, E>, Box<dyn Any + Send>>,
619 ) -> Result<T, Box<dyn Any + Send>>
624 Ok(Err(e)) => Err(Box::new(e)),
630 fn spawn_test_subprocess(
635 monitor_ch: Sender<CompletedTest>,
636 time_opts: Option<time::TestTimeOptions>,
638 let (result, test_output, exec_time) = (|| {
639 let args = env::args().collect::<Vec<_>>();
640 let current_exe = &args[0];
642 let mut command = Command::new(current_exe);
643 command.env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice());
645 command.stdout(process::Stdio::inherit());
646 command.stderr(process::Stdio::inherit());
649 let start = report_time.then(Instant::now);
650 let output = match command.output() {
653 let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e);
654 return (TrFailed, err.into_bytes(), None);
657 let exec_time = start.map(|start| {
658 let duration = start.elapsed();
659 TestExecTime(duration)
662 let std::process::Output { stdout, stderr, status } = output;
663 let mut test_output = stdout;
664 formatters::write_stderr_delimiter(&mut test_output, &desc.name);
665 test_output.extend_from_slice(&stderr);
667 let result = match (|| -> Result<TestResult, String> {
668 let exit_code = get_exit_code(status)?;
669 Ok(get_result_from_exit_code(&desc, exit_code, &time_opts, &exec_time))
673 write!(&mut test_output, "Unexpected error: {}", e).unwrap();
678 (result, test_output, exec_time)
681 let message = CompletedTest::new(id, desc, result, exec_time, test_output);
682 monitor_ch.send(message).unwrap();
685 fn run_test_in_spawned_subprocess(
687 testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
689 let builtin_panic_hook = panic::take_hook();
690 let record_result = Arc::new(move |panic_info: Option<&'_ PanicInfo<'_>>| {
691 let test_result = match panic_info {
692 Some(info) => calc_result(&desc, Err(info.payload()), &None, &None),
693 None => calc_result(&desc, Ok(()), &None, &None),
696 // We don't support serializing TrFailedMsg, so just
697 // print the message out to stderr.
698 if let TrFailedMsg(msg) = &test_result {
702 if let Some(info) = panic_info {
703 builtin_panic_hook(info);
706 if let TrOk = test_result {
707 process::exit(test_result::TR_OK);
709 process::exit(test_result::TR_FAILED);
712 let record_result2 = record_result.clone();
713 panic::set_hook(Box::new(move |info| record_result2(Some(&info))));
714 if let Err(message) = testfn() {
715 panic!("{}", message);
718 unreachable!("panic=abort callback should have exited the process")