1#![unstable(feature = "test", issue = "50297")]
18#![doc(test(attr(deny(warnings))))]
19#![doc(rust_logo)]
20#![feature(rustdoc_internals)]
21#![feature(exitcode_exit_method)]
22#![feature(file_buffered)]
23#![feature(internal_output_capture)]
24#![feature(io_const_error)]
25#![feature(staged_api)]
26#![feature(process_exitcode_internals)]
27#![feature(panic_can_unwind)]
28#![cfg_attr(test, feature(test))]
29#![feature(thread_spawn_hook)]
30#![allow(internal_features)]
31#![warn(rustdoc::unescaped_backticks)]
32#![warn(unreachable_pub)]
33
34pub use cli::TestOpts;
35
36pub use self::ColorConfig::*;
37pub use self::bench::{Bencher, black_box};
38pub use self::console::run_tests_console;
39pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic};
40pub use self::types::TestName::*;
41pub use self::types::*;
42
43pub mod test {
45 pub use crate::bench::Bencher;
46 pub use crate::cli::{TestOpts, parse_opts};
47 pub use crate::helpers::metrics::{Metric, MetricMap};
48 pub use crate::options::{Options, RunIgnored, RunStrategy, ShouldPanic};
49 pub use crate::test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk};
50 pub use crate::time::{TestExecTime, TestTimeOptions};
51 pub use crate::types::{
52 DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc,
53 TestDescAndFn, TestId, TestList, TestListOrder, TestName, TestType,
54 };
55 pub use crate::{assert_test_result, filter_tests, run_test, test_main, test_main_env_args};
56}
57
58use std::collections::VecDeque;
59use std::io::prelude::Write;
60use std::mem::ManuallyDrop;
61use std::panic::{self, AssertUnwindSafe, PanicHookInfo, catch_unwind};
62use std::process::{self, Command, ExitCode, Termination};
63use std::sync::mpsc::{Sender, channel};
64use std::sync::{Arc, Mutex};
65use std::time::{Duration, Instant};
66use std::{env, io, thread};
67
68pub mod bench;
69mod cli;
70mod console;
71mod event;
72mod formatters;
73mod helpers;
74mod options;
75pub mod stats;
76mod term;
77mod test_result;
78mod time;
79mod types;
80
81#[cfg(test)]
82mod tests;
83
84use core::any::Any;
85
86use event::{CompletedTest, TestEvent};
87use helpers::concurrency::get_concurrency;
88use helpers::shuffle::{get_shuffle_seed, shuffle_tests};
89use options::RunStrategy;
90use test_result::*;
91use time::TestExecTime;
92
93pub const ERROR_EXIT_CODE: u8 = 101;
95
96const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE";
97const SECONDARY_TEST_BENCH_BENCHMARKS_VAR: &str = "__RUST_TEST_BENCH_BENCHMARKS";
98
99pub fn test_main(args: &[String], tests: &[&TestDescAndFn]) -> ExitCode {
102 let tests = TestList::new(tests, TestListOrder::Unsorted);
103 test_main_inner(args, tests, None)
104}
105
106fn test_main_inner(args: &[String], tests: TestList<'_>, options: Option<Options>) -> ExitCode {
107 let mut opts = match cli::parse_opts(args) {
108 Some(Ok(o)) => o,
109 Some(Err(msg)) => {
110 eprintln!("error: {msg}");
111 return ERROR_EXIT_CODE.into();
112 }
113 None => return ExitCode::SUCCESS, };
115 if let Some(options) = options {
116 opts.options = options;
117 }
118 if opts.list {
119 if let Err(e) = console::list_tests_console(&opts, tests) {
120 eprintln!("error: io error when listing tests: {e:?}");
121 return ERROR_EXIT_CODE.into();
122 }
123 } else {
124 if !opts.nocapture {
125 let builtin_panic_hook = panic::take_hook();
130 let hook = Box::new({
131 move |info: &'_ PanicHookInfo<'_>| {
132 if !info.can_unwind() {
133 std::mem::forget(std::io::stderr().lock());
134 let mut stdout = ManuallyDrop::new(std::io::stdout().lock());
135 if let Some(captured) = io::set_output_capture(None) {
136 if let Ok(data) = captured.lock() {
137 let _ = stdout.write_all(&data);
138 let _ = stdout.flush();
139 }
140 }
141 }
142 builtin_panic_hook(info);
143 }
144 });
145 panic::set_hook(hook);
146 std::thread::add_spawn_hook(|_| {
148 let output_capture = io::set_output_capture(None);
150 io::set_output_capture(output_capture.clone());
151 || {
153 io::set_output_capture(output_capture);
154 }
155 });
156 }
157 let res = console::run_tests_console(&opts, tests);
158 drop(panic::take_hook());
160 match res {
161 Ok(true) => {}
162 Ok(false) => return ExitCode::from(ERROR_EXIT_CODE),
163 Err(e) => {
164 eprintln!("error: io error when listing tests: {e:?}");
165 return ExitCode::from(ERROR_EXIT_CODE);
166 }
167 }
168 }
169
170 ExitCode::SUCCESS
171}
172
173pub fn test_main_env_args(tests: &[&TestDescAndFn]) {
179 let args = env::args().collect::<Vec<_>>();
183 let tests = TestList::new(tests, TestListOrder::Sorted);
185 let exit = test_main_inner(&args, tests, None);
186 if exit != std::process::ExitCode::SUCCESS {
188 exit.exit_process();
189 }
190}
191
192pub fn test_main_env_args_abort(tests: &[&TestDescAndFn]) {
201 if let Ok(name) = env::var(SECONDARY_TEST_INVOKER_VAR) {
204 unsafe {
213 env::remove_var(SECONDARY_TEST_INVOKER_VAR);
214 }
215
216 let mut tests = tests.iter().copied().cloned().collect::<Vec<_>>();
218 if env::var(SECONDARY_TEST_BENCH_BENCHMARKS_VAR).is_ok() {
219 unsafe {
221 env::remove_var(SECONDARY_TEST_BENCH_BENCHMARKS_VAR);
222 }
223 } else {
224 tests = convert_benchmarks_to_tests(tests);
225 };
226
227 let test = tests
228 .into_iter()
229 .find(|test| test.desc.name.as_slice() == name)
230 .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{name}'"));
231 let TestDescAndFn { desc, testfn } = test;
232 match testfn.into_runnable() {
233 Runnable::Test(runnable_test) => {
234 if runnable_test.is_dynamic() {
235 panic!("only static tests are supported");
236 }
237 run_test_in_spawned_subprocess(desc, runnable_test);
238 }
239 Runnable::Bench(_) => {
240 panic!("benchmarks should not be executed into child processes")
241 }
242 }
243 }
245
246 let args = env::args().collect::<Vec<_>>();
247 let tests = TestList::new(tests, TestListOrder::Sorted);
249 let exit = test_main_inner(&args, tests, Some(Options::new().panic_abort(true)));
250 if exit != std::process::ExitCode::SUCCESS {
251 exit.exit_process();
252 }
253}
254
255pub fn print_merged_doctests_times(args: &[String], total_time: f64, compilation_time: f64) {
258 let opts = match cli::parse_opts(args) {
259 Some(Ok(o)) => o,
260 Some(Err(msg)) => {
261 eprintln!("error: {msg}");
262 process::exit(ERROR_EXIT_CODE.into());
263 }
264 None => return,
265 };
266 let mut formatter = console::get_formatter(&opts, 0);
267 formatter.write_merged_doctests_times(total_time, compilation_time).unwrap();
268}
269
270pub fn assert_test_result<T: Termination>(result: T) -> Result<(), String> {
274 let code = result.report().to_i32();
275 if code == 0 {
276 Ok(())
277 } else {
278 Err(format!(
279 "the test returned a termination value with a non-zero status code \
280 ({code}) which indicates a failure"
281 ))
282 }
283}
284
285struct FilteredTests {
286 tests: Vec<(TestId, TestDescAndFn)>,
287 benches: Vec<(TestId, TestDescAndFn)>,
288 next_id: usize,
289}
290
291impl FilteredTests {
292 fn add_bench(&mut self, desc: TestDesc, testfn: TestFn) {
293 let test = TestDescAndFn { desc, testfn };
294 self.benches.push((TestId(self.next_id), test));
295 self.next_id += 1;
296 }
297 fn add_test(&mut self, desc: TestDesc, testfn: TestFn) {
298 let test = TestDescAndFn { desc, testfn };
299 self.tests.push((TestId(self.next_id), test));
300 self.next_id += 1;
301 }
302 fn total_len(&self) -> usize {
303 self.tests.len() + self.benches.len()
304 }
305}
306
307pub fn run_tests<F>(
308 opts: &TestOpts,
309 mut filtered_tests: Vec<TestDescAndFn>,
310 all_tests_len: usize,
311 mut notify_about_test_event: F,
312) -> io::Result<()>
313where
314 F: FnMut(TestEvent) -> io::Result<()>,
315{
316 use std::collections::HashMap;
317 use std::hash::{BuildHasherDefault, DefaultHasher};
318 use std::sync::mpsc::RecvTimeoutError;
319
320 struct RunningTest {
321 join_handle: Option<thread::JoinHandle<()>>,
322 }
323
324 impl RunningTest {
325 fn join(self, completed_test: &mut CompletedTest) {
326 if let Some(join_handle) = self.join_handle {
327 if let Err(_) = join_handle.join() {
328 if let TrOk = completed_test.result {
329 completed_test.result =
330 TrFailedMsg("panicked after reporting success".to_string());
331 }
332 }
333 }
334 }
335 }
336
337 type TestMap = HashMap<TestId, RunningTest, BuildHasherDefault<DefaultHasher>>;
339
340 struct TimeoutEntry {
341 id: TestId,
342 desc: TestDesc,
343 timeout: Instant,
344 }
345
346 let mut filtered = FilteredTests { tests: Vec::new(), benches: Vec::new(), next_id: 0 };
347
348 if !opts.bench_benchmarks {
349 filtered_tests = convert_benchmarks_to_tests(filtered_tests);
350 }
351
352 for test in filtered_tests {
353 let mut desc = test.desc;
354 desc.name = desc.name.with_padding(test.testfn.padding());
355
356 match test.testfn {
357 DynBenchFn(_) | StaticBenchFn(_) => {
358 filtered.add_bench(desc, test.testfn);
359 }
360 testfn => {
361 filtered.add_test(desc, testfn);
362 }
363 };
364 }
365
366 let filtered_out = all_tests_len - filtered.total_len();
367 let event = TestEvent::TeFilteredOut(filtered_out);
368 notify_about_test_event(event)?;
369
370 let shuffle_seed = get_shuffle_seed(opts);
371
372 let event = TestEvent::TeFiltered(filtered.total_len(), shuffle_seed);
373 notify_about_test_event(event)?;
374
375 let concurrency = opts.test_threads.unwrap_or_else(get_concurrency);
376
377 let mut remaining = filtered.tests;
378 if let Some(shuffle_seed) = shuffle_seed {
379 shuffle_tests(shuffle_seed, &mut remaining);
380 }
381 let mut remaining = VecDeque::from(remaining);
384 let mut pending = 0;
385
386 let (tx, rx) = channel::<CompletedTest>();
387 let run_strategy = if opts.options.panic_abort && !opts.force_run_in_process {
388 RunStrategy::SpawnPrimary
389 } else {
390 RunStrategy::InProcess
391 };
392
393 let mut running_tests: TestMap = HashMap::default();
394 let mut timeout_queue: VecDeque<TimeoutEntry> = VecDeque::new();
395
396 fn get_timed_out_tests(
397 running_tests: &TestMap,
398 timeout_queue: &mut VecDeque<TimeoutEntry>,
399 ) -> Vec<TestDesc> {
400 let now = Instant::now();
401 let mut timed_out = Vec::new();
402 while let Some(timeout_entry) = timeout_queue.front() {
403 if now < timeout_entry.timeout {
404 break;
405 }
406 let timeout_entry = timeout_queue.pop_front().unwrap();
407 if running_tests.contains_key(&timeout_entry.id) {
408 timed_out.push(timeout_entry.desc);
409 }
410 }
411 timed_out
412 }
413
414 fn calc_timeout(timeout_queue: &VecDeque<TimeoutEntry>) -> Option<Duration> {
415 timeout_queue.front().map(|&TimeoutEntry { timeout: next_timeout, .. }| {
416 let now = Instant::now();
417 if next_timeout >= now { next_timeout - now } else { Duration::new(0, 0) }
418 })
419 }
420
421 if concurrency == 1 {
422 while !remaining.is_empty() {
423 let (id, test) = remaining.pop_front().unwrap();
424 let event = TestEvent::TeWait(test.desc.clone());
425 notify_about_test_event(event)?;
426 let join_handle = run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone());
427 let mut completed_test = rx.recv().unwrap();
429 RunningTest { join_handle }.join(&mut completed_test);
430
431 let fail_fast = match completed_test.result {
432 TrIgnored | TrOk | TrBench(_) => false,
433 TrFailed | TrFailedMsg(_) | TrTimedFail => opts.fail_fast,
434 };
435
436 let event = TestEvent::TeResult(completed_test);
437 notify_about_test_event(event)?;
438
439 if fail_fast {
440 return Ok(());
441 }
442 }
443 } else {
444 while pending > 0 || !remaining.is_empty() {
445 while pending < concurrency && !remaining.is_empty() {
446 let (id, test) = remaining.pop_front().unwrap();
447 let timeout = time::get_default_test_timeout();
448 let desc = test.desc.clone();
449
450 let event = TestEvent::TeWait(desc.clone());
451 notify_about_test_event(event)?; let join_handle =
453 run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone());
454 running_tests.insert(id, RunningTest { join_handle });
455 timeout_queue.push_back(TimeoutEntry { id, desc, timeout });
456 pending += 1;
457 }
458
459 let mut res;
460 loop {
461 if let Some(timeout) = calc_timeout(&timeout_queue) {
462 res = rx.recv_timeout(timeout);
463 for test in get_timed_out_tests(&running_tests, &mut timeout_queue) {
464 let event = TestEvent::TeTimeout(test);
465 notify_about_test_event(event)?;
466 }
467
468 match res {
469 Err(RecvTimeoutError::Timeout) => {
470 }
472 _ => {
473 break;
475 }
476 }
477 } else {
478 res = rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
479 break;
480 }
481 }
482
483 let mut completed_test = res.unwrap();
484 let running_test = running_tests.remove(&completed_test.id).unwrap();
485 running_test.join(&mut completed_test);
486
487 let fail_fast = match completed_test.result {
488 TrIgnored | TrOk | TrBench(_) => false,
489 TrFailed | TrFailedMsg(_) | TrTimedFail => opts.fail_fast,
490 };
491
492 let event = TestEvent::TeResult(completed_test);
493 notify_about_test_event(event)?;
494 pending -= 1;
495
496 if fail_fast {
497 std::mem::forget(rx);
499 return Ok(());
500 }
501 }
502 }
503
504 if opts.bench_benchmarks {
505 for (id, b) in filtered.benches {
507 let event = TestEvent::TeWait(b.desc.clone());
508 notify_about_test_event(event)?;
509 let join_handle = run_test(opts, false, id, b, run_strategy, tx.clone());
510 let mut completed_test = rx.recv().unwrap();
512 RunningTest { join_handle }.join(&mut completed_test);
513
514 let event = TestEvent::TeResult(completed_test);
515 notify_about_test_event(event)?;
516 }
517 }
518 Ok(())
519}
520
521pub fn filter_tests(opts: &TestOpts, tests: TestList<'_>) -> Vec<TestDescAndFn> {
522 let TestList { tests, order } = tests;
523
524 let mut filtered = if opts.filters.is_empty() {
526 tests.iter().copied().cloned().collect::<Vec<_>>()
527 } else if opts.filter_exact && order == TestListOrder::Sorted {
528 filter_exact_match(tests, &opts.filters)
538 } else {
539 tests
540 .iter()
541 .copied()
542 .filter(|test| {
543 let test_name = test.desc.name.as_slice();
544 opts.filters.iter().any(|filter| {
545 if opts.filter_exact {
546 test_name == filter.as_str()
547 } else {
548 test_name.contains(filter.as_str())
549 }
550 })
551 })
552 .cloned()
553 .collect::<Vec<_>>()
554 };
555
556 if !opts.skip.is_empty() {
561 filtered.retain(|test| {
562 let name = test.desc.name.as_slice();
563 !opts.skip.iter().any(|sf| {
564 if opts.filter_exact { name == sf.as_str() } else { name.contains(sf.as_str()) }
565 })
566 });
567 }
568
569 if opts.exclude_should_panic {
571 filtered.retain(|test| test.desc.should_panic == ShouldPanic::No);
572 }
573
574 match opts.run_ignored {
576 RunIgnored::Yes => {
577 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
578 }
579 RunIgnored::Only => {
580 filtered.retain(|test| test.desc.ignore);
581 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
582 }
583 RunIgnored::No => {}
584 }
585
586 filtered
587}
588
589fn filter_exact_match<'a>(tests: &[&'a TestDescAndFn], filters: &[String]) -> Vec<TestDescAndFn> {
592 let mut indexes: Vec<usize> = filters
594 .iter()
595 .filter_map(|f| tests.binary_search_by(|t| t.desc.name.as_slice().cmp(f.as_str())).ok())
596 .collect();
597 indexes.sort_unstable();
598 indexes.dedup();
599
600 let mut result = Vec::with_capacity(indexes.len());
602 for &idx in indexes.iter() {
603 result.push(tests[idx].clone());
604 }
605 result
606}
607
608pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
609 tests
611 .into_iter()
612 .map(|x| {
613 let testfn = match x.testfn {
614 DynBenchFn(benchfn) => DynBenchAsTestFn(benchfn),
615 StaticBenchFn(benchfn) => StaticBenchAsTestFn(benchfn),
616 f => f,
617 };
618 TestDescAndFn { desc: x.desc, testfn }
619 })
620 .collect()
621}
622
623pub fn run_test(
624 opts: &TestOpts,
625 force_ignore: bool,
626 id: TestId,
627 test: TestDescAndFn,
628 strategy: RunStrategy,
629 monitor_ch: Sender<CompletedTest>,
630) -> Option<thread::JoinHandle<()>> {
631 let TestDescAndFn { desc, testfn } = test;
632
633 let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No
635 && (cfg!(target_family = "wasm") || cfg!(target_os = "zkvm"))
636 && !cfg!(target_os = "emscripten");
637
638 if force_ignore || desc.ignore || ignore_because_no_process_support {
639 let message = CompletedTest::new(id, desc, TrIgnored, None, Vec::new());
640 monitor_ch.send(message).unwrap();
641 return None;
642 }
643
644 match testfn.into_runnable() {
645 Runnable::Test(runnable_test) => {
646 if runnable_test.is_dynamic() {
647 match strategy {
648 RunStrategy::InProcess => (),
649 _ => panic!("Cannot run dynamic test fn out-of-process"),
650 };
651 }
652
653 let name = desc.name.clone();
654 let nocapture = opts.nocapture;
655 let time_options = opts.time_options;
656 let bench_benchmarks = opts.bench_benchmarks;
657
658 let runtest = move || match strategy {
659 RunStrategy::InProcess => run_test_in_process(
660 id,
661 desc,
662 nocapture,
663 time_options.is_some(),
664 runnable_test,
665 monitor_ch,
666 time_options,
667 ),
668 RunStrategy::SpawnPrimary => spawn_test_subprocess(
669 id,
670 desc,
671 nocapture,
672 time_options.is_some(),
673 monitor_ch,
674 time_options,
675 bench_benchmarks,
676 ),
677 };
678
679 let supports_threads = !cfg!(target_os = "emscripten")
683 && !cfg!(target_family = "wasm")
684 && !cfg!(target_os = "zkvm");
685 if supports_threads {
686 let cfg = thread::Builder::new().name(name.as_slice().to_owned());
687 let mut runtest = Arc::new(Mutex::new(Some(runtest)));
688 let runtest2 = runtest.clone();
689 match cfg.spawn(move || runtest2.lock().unwrap().take().unwrap()()) {
690 Ok(handle) => Some(handle),
691 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
692 Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()();
695 None
696 }
697 Err(e) => panic!("failed to spawn thread to run test: {e}"),
698 }
699 } else {
700 runtest();
701 None
702 }
703 }
704 Runnable::Bench(runnable_bench) => {
705 runnable_bench.run(id, &desc, &monitor_ch, opts.nocapture);
707 None
708 }
709 }
710}
711
712#[inline(never)]
714fn __rust_begin_short_backtrace<T, F: FnOnce() -> T>(f: F) -> T {
715 let result = f();
716
717 black_box(result)
719}
720
721fn run_test_in_process(
722 id: TestId,
723 desc: TestDesc,
724 nocapture: bool,
725 report_time: bool,
726 runnable_test: RunnableTest,
727 monitor_ch: Sender<CompletedTest>,
728 time_opts: Option<time::TestTimeOptions>,
729) {
730 let data = Arc::new(Mutex::new(Vec::new()));
732
733 if !nocapture {
734 io::set_output_capture(Some(data.clone()));
735 }
736
737 let start = report_time.then(Instant::now);
738 let result = fold_err(catch_unwind(AssertUnwindSafe(|| runnable_test.run())));
739 let exec_time = start.map(|start| {
740 let duration = start.elapsed();
741 TestExecTime(duration)
742 });
743
744 io::set_output_capture(None);
745
746 let test_result =
750 calc_result(&desc, result.err().as_deref(), time_opts.as_ref(), exec_time.as_ref());
751 let stdout = data.lock().unwrap_or_else(|e| e.into_inner()).to_vec();
752 let message = CompletedTest::new(id, desc, test_result, exec_time, stdout);
753 monitor_ch.send(message).unwrap();
754}
755
756fn fold_err<T, E>(
757 result: Result<Result<T, E>, Box<dyn Any + Send>>,
758) -> Result<T, Box<dyn Any + Send>>
759where
760 E: Send + 'static,
761{
762 match result {
763 Ok(Err(e)) => Err(Box::new(e)),
764 Ok(Ok(v)) => Ok(v),
765 Err(e) => Err(e),
766 }
767}
768
769fn spawn_test_subprocess(
770 id: TestId,
771 desc: TestDesc,
772 nocapture: bool,
773 report_time: bool,
774 monitor_ch: Sender<CompletedTest>,
775 time_opts: Option<time::TestTimeOptions>,
776 bench_benchmarks: bool,
777) {
778 let (result, test_output, exec_time) = (|| {
779 let args = env::args().collect::<Vec<_>>();
780 let current_exe = &args[0];
781
782 let mut command = Command::new(current_exe);
783 command.env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice());
784 if bench_benchmarks {
785 command.env(SECONDARY_TEST_BENCH_BENCHMARKS_VAR, "1");
786 }
787 if nocapture {
788 command.stdout(process::Stdio::inherit());
789 command.stderr(process::Stdio::inherit());
790 }
791
792 let start = report_time.then(Instant::now);
793 let output = match command.output() {
794 Ok(out) => out,
795 Err(e) => {
796 let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e);
797 return (TrFailed, err.into_bytes(), None);
798 }
799 };
800 let exec_time = start.map(|start| {
801 let duration = start.elapsed();
802 TestExecTime(duration)
803 });
804
805 let std::process::Output { stdout, stderr, status } = output;
806 let mut test_output = stdout;
807 formatters::write_stderr_delimiter(&mut test_output, &desc.name);
808 test_output.extend_from_slice(&stderr);
809
810 let result =
811 get_result_from_exit_code(&desc, status, time_opts.as_ref(), exec_time.as_ref());
812 (result, test_output, exec_time)
813 })();
814
815 let message = CompletedTest::new(id, desc, result, exec_time, test_output);
816 monitor_ch.send(message).unwrap();
817}
818
819fn run_test_in_spawned_subprocess(desc: TestDesc, runnable_test: RunnableTest) -> ! {
820 let builtin_panic_hook = panic::take_hook();
821 let record_result = Arc::new(move |panic_info: Option<&'_ PanicHookInfo<'_>>| {
822 let test_result = calc_result(&desc, panic_info.map(|info| info.payload()), None, None);
823
824 if let TrFailedMsg(msg) = &test_result {
827 eprintln!("{msg}");
828 }
829
830 if let Some(info) = panic_info {
831 builtin_panic_hook(info);
832 }
833
834 if let TrOk = test_result {
835 process::exit(test_result::TR_OK);
836 } else {
837 process::abort();
838 }
839 });
840 let record_result2 = record_result.clone();
841 panic::set_hook(Box::new(move |info| record_result2(Some(info))));
842 if let Err(message) = runnable_test.run() {
843 panic!("{}", message);
844 }
845 record_result(None);
846 unreachable!("panic=abort callback should have exited the process")
847}