]> git.lizzy.rs Git - rust.git/blob - library/test/src/lib.rs
Auto merge of #95399 - gilescope:plan_b, r=scottmcm
[rust.git] / library / test / src / lib.rs
1 //! Support code for rustc's built in unit-test and micro-benchmarking
2 //! framework.
3 //!
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.
8 //!
9 //! See the [Testing Chapter](../book/ch11-00-testing.html) of the book for more details.
10
11 // Currently, not much of this is meant for users. It is intended to
12 // support the simplest interface possible for representing and
13 // running tests while providing a base that other test frameworks may
14 // build off of.
15
16 #![unstable(feature = "test", issue = "50297")]
17 #![doc(test(attr(deny(warnings))))]
18 #![feature(nll)]
19 #![feature(bench_black_box)]
20 #![feature(internal_output_capture)]
21 #![feature(staged_api)]
22 #![feature(process_exitcode_internals)]
23 #![feature(test)]
24
25 // Public reexports
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;
33
34 // Module to be used by rustc to compile tests in libtest
35 pub mod test {
36     pub use crate::{
37         assert_test_result,
38         bench::Bencher,
39         cli::{parse_opts, TestOpts},
40         filter_tests,
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},
46         types::{
47             DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc,
48             TestDescAndFn, TestId, TestName, TestType,
49         },
50     };
51 }
52
53 use std::{
54     collections::VecDeque,
55     env, io,
56     io::prelude::Write,
57     panic::{self, catch_unwind, AssertUnwindSafe, PanicInfo},
58     process::{self, Command, Termination},
59     sync::mpsc::{channel, Sender},
60     sync::{Arc, Mutex},
61     thread,
62     time::{Duration, Instant},
63 };
64
65 pub mod bench;
66 mod cli;
67 mod console;
68 mod event;
69 mod formatters;
70 mod helpers;
71 mod options;
72 pub mod stats;
73 mod term;
74 mod test_result;
75 mod time;
76 mod types;
77
78 #[cfg(test)]
79 mod tests;
80
81 use event::{CompletedTest, TestEvent};
82 use helpers::concurrency::get_concurrency;
83 use helpers::exit_code::get_exit_code;
84 use helpers::shuffle::{get_shuffle_seed, shuffle_tests};
85 use options::{Concurrent, RunStrategy};
86 use test_result::*;
87 use time::TestExecTime;
88
89 // Process exit code to be used to indicate test failures.
90 const ERROR_EXIT_CODE: i32 = 101;
91
92 const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE";
93
94 // The default console test runner. It accepts the command line
95 // arguments and a vector of test_descs.
96 pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>, options: Option<Options>) {
97     let mut opts = match cli::parse_opts(args) {
98         Some(Ok(o)) => o,
99         Some(Err(msg)) => {
100             eprintln!("error: {msg}");
101             process::exit(ERROR_EXIT_CODE);
102         }
103         None => return,
104     };
105     if let Some(options) = options {
106         opts.options = options;
107     }
108     if opts.list {
109         if let Err(e) = console::list_tests_console(&opts, tests) {
110             eprintln!("error: io error when listing tests: {e:?}");
111             process::exit(ERROR_EXIT_CODE);
112         }
113     } else {
114         match console::run_tests_console(&opts, tests) {
115             Ok(true) => {}
116             Ok(false) => process::exit(ERROR_EXIT_CODE),
117             Err(e) => {
118                 eprintln!("error: io error when listing tests: {e:?}");
119                 process::exit(ERROR_EXIT_CODE);
120             }
121         }
122     }
123 }
124
125 /// A variant optimized for invocation with a static test vector.
126 /// This will panic (intentionally) when fed any dynamic tests.
127 ///
128 /// This is the entry point for the main function generated by `rustc --test`
129 /// when panic=unwind.
130 pub fn test_main_static(tests: &[&TestDescAndFn]) {
131     let args = env::args().collect::<Vec<_>>();
132     let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
133     test_main(&args, owned_tests, None)
134 }
135
136 /// A variant optimized for invocation with a static test vector.
137 /// This will panic (intentionally) when fed any dynamic tests.
138 ///
139 /// Runs tests in panic=abort mode, which involves spawning subprocesses for
140 /// tests.
141 ///
142 /// This is the entry point for the main function generated by `rustc --test`
143 /// when panic=abort.
144 pub fn test_main_static_abort(tests: &[&TestDescAndFn]) {
145     // If we're being run in SpawnedSecondary mode, run the test here. run_test
146     // will then exit the process.
147     if let Ok(name) = env::var(SECONDARY_TEST_INVOKER_VAR) {
148         env::remove_var(SECONDARY_TEST_INVOKER_VAR);
149         let test = tests
150             .iter()
151             .filter(|test| test.desc.name.as_slice() == name)
152             .map(make_owned_test)
153             .next()
154             .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{name}'"));
155         let TestDescAndFn { desc, testfn } = test;
156         let testfn = match testfn {
157             StaticTestFn(f) => f,
158             _ => panic!("only static tests are supported"),
159         };
160         run_test_in_spawned_subprocess(desc, Box::new(testfn));
161     }
162
163     let args = env::args().collect::<Vec<_>>();
164     let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
165     test_main(&args, owned_tests, Some(Options::new().panic_abort(true)))
166 }
167
168 /// Clones static values for putting into a dynamic vector, which test_main()
169 /// needs to hand out ownership of tests to parallel test runners.
170 ///
171 /// This will panic when fed any dynamic tests, because they cannot be cloned.
172 fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn {
173     match test.testfn {
174         StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: test.desc.clone() },
175         StaticBenchFn(f) => TestDescAndFn { testfn: StaticBenchFn(f), desc: test.desc.clone() },
176         _ => panic!("non-static tests passed to test::test_main_static"),
177     }
178 }
179
180 /// Invoked when unit tests terminate. Should panic if the unit
181 /// Tests is considered a failure. By default, invokes `report()`
182 /// and checks for a `0` result.
183 pub fn assert_test_result<T: Termination>(result: T) {
184     let code = result.report().to_i32();
185     assert_eq!(
186         code, 0,
187         "the test returned a termination value with a non-zero status code ({}) \
188          which indicates a failure",
189         code
190     );
191 }
192
193 pub fn run_tests<F>(
194     opts: &TestOpts,
195     tests: Vec<TestDescAndFn>,
196     mut notify_about_test_event: F,
197 ) -> io::Result<()>
198 where
199     F: FnMut(TestEvent) -> io::Result<()>,
200 {
201     use std::collections::{self, HashMap};
202     use std::hash::BuildHasherDefault;
203     use std::sync::mpsc::RecvTimeoutError;
204
205     struct RunningTest {
206         join_handle: Option<thread::JoinHandle<()>>,
207     }
208
209     // Use a deterministic hasher
210     type TestMap =
211         HashMap<TestId, RunningTest, BuildHasherDefault<collections::hash_map::DefaultHasher>>;
212
213     struct TimeoutEntry {
214         id: TestId,
215         desc: TestDesc,
216         timeout: Instant,
217     }
218
219     let tests_len = tests.len();
220
221     let mut filtered_tests = filter_tests(opts, tests);
222     if !opts.bench_benchmarks {
223         filtered_tests = convert_benchmarks_to_tests(filtered_tests);
224     }
225
226     let filtered_tests = {
227         let mut filtered_tests = filtered_tests;
228         for test in filtered_tests.iter_mut() {
229             test.desc.name = test.desc.name.with_padding(test.testfn.padding());
230         }
231
232         filtered_tests
233     };
234
235     let filtered_out = tests_len - filtered_tests.len();
236     let event = TestEvent::TeFilteredOut(filtered_out);
237     notify_about_test_event(event)?;
238
239     let filtered_descs = filtered_tests.iter().map(|t| t.desc.clone()).collect();
240
241     let shuffle_seed = get_shuffle_seed(opts);
242
243     let event = TestEvent::TeFiltered(filtered_descs, shuffle_seed);
244     notify_about_test_event(event)?;
245
246     let (filtered_tests, filtered_benchs): (Vec<_>, _) = filtered_tests
247         .into_iter()
248         .enumerate()
249         .map(|(i, e)| (TestId(i), e))
250         .partition(|(_, e)| matches!(e.testfn, StaticTestFn(_) | DynTestFn(_)));
251
252     let concurrency = opts.test_threads.unwrap_or_else(get_concurrency);
253
254     let mut remaining = filtered_tests;
255     if let Some(shuffle_seed) = shuffle_seed {
256         shuffle_tests(shuffle_seed, &mut remaining);
257     } else {
258         remaining.reverse();
259     }
260     let mut pending = 0;
261
262     let (tx, rx) = channel::<CompletedTest>();
263     let run_strategy = if opts.options.panic_abort && !opts.force_run_in_process {
264         RunStrategy::SpawnPrimary
265     } else {
266         RunStrategy::InProcess
267     };
268
269     let mut running_tests: TestMap = HashMap::default();
270     let mut timeout_queue: VecDeque<TimeoutEntry> = VecDeque::new();
271
272     fn get_timed_out_tests(
273         running_tests: &TestMap,
274         timeout_queue: &mut VecDeque<TimeoutEntry>,
275     ) -> Vec<TestDesc> {
276         let now = Instant::now();
277         let mut timed_out = Vec::new();
278         while let Some(timeout_entry) = timeout_queue.front() {
279             if now < timeout_entry.timeout {
280                 break;
281             }
282             let timeout_entry = timeout_queue.pop_front().unwrap();
283             if running_tests.contains_key(&timeout_entry.id) {
284                 timed_out.push(timeout_entry.desc);
285             }
286         }
287         timed_out
288     }
289
290     fn calc_timeout(timeout_queue: &VecDeque<TimeoutEntry>) -> Option<Duration> {
291         timeout_queue.front().map(|&TimeoutEntry { timeout: next_timeout, .. }| {
292             let now = Instant::now();
293             if next_timeout >= now { next_timeout - now } else { Duration::new(0, 0) }
294         })
295     }
296
297     if concurrency == 1 {
298         while !remaining.is_empty() {
299             let (id, test) = remaining.pop().unwrap();
300             let event = TestEvent::TeWait(test.desc.clone());
301             notify_about_test_event(event)?;
302             let join_handle =
303                 run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone(), Concurrent::No);
304             assert!(join_handle.is_none());
305             let completed_test = rx.recv().unwrap();
306
307             let event = TestEvent::TeResult(completed_test);
308             notify_about_test_event(event)?;
309         }
310     } else {
311         while pending > 0 || !remaining.is_empty() {
312             while pending < concurrency && !remaining.is_empty() {
313                 let (id, test) = remaining.pop().unwrap();
314                 let timeout = time::get_default_test_timeout();
315                 let desc = test.desc.clone();
316
317                 let event = TestEvent::TeWait(desc.clone());
318                 notify_about_test_event(event)?; //here no pad
319                 let join_handle = run_test(
320                     opts,
321                     !opts.run_tests,
322                     id,
323                     test,
324                     run_strategy,
325                     tx.clone(),
326                     Concurrent::Yes,
327                 );
328                 running_tests.insert(id, RunningTest { join_handle });
329                 timeout_queue.push_back(TimeoutEntry { id, desc, timeout });
330                 pending += 1;
331             }
332
333             let mut res;
334             loop {
335                 if let Some(timeout) = calc_timeout(&timeout_queue) {
336                     res = rx.recv_timeout(timeout);
337                     for test in get_timed_out_tests(&running_tests, &mut timeout_queue) {
338                         let event = TestEvent::TeTimeout(test);
339                         notify_about_test_event(event)?;
340                     }
341
342                     match res {
343                         Err(RecvTimeoutError::Timeout) => {
344                             // Result is not yet ready, continue waiting.
345                         }
346                         _ => {
347                             // We've got a result, stop the loop.
348                             break;
349                         }
350                     }
351                 } else {
352                     res = rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
353                     break;
354                 }
355             }
356
357             let mut completed_test = res.unwrap();
358             let running_test = running_tests.remove(&completed_test.id).unwrap();
359             if let Some(join_handle) = running_test.join_handle {
360                 if let Err(_) = join_handle.join() {
361                     if let TrOk = completed_test.result {
362                         completed_test.result =
363                             TrFailedMsg("panicked after reporting success".to_string());
364                     }
365                 }
366             }
367
368             let event = TestEvent::TeResult(completed_test);
369             notify_about_test_event(event)?;
370             pending -= 1;
371         }
372     }
373
374     if opts.bench_benchmarks {
375         // All benchmarks run at the end, in serial.
376         for (id, b) in filtered_benchs {
377             let event = TestEvent::TeWait(b.desc.clone());
378             notify_about_test_event(event)?;
379             run_test(opts, false, id, b, run_strategy, tx.clone(), Concurrent::No);
380             let completed_test = rx.recv().unwrap();
381
382             let event = TestEvent::TeResult(completed_test);
383             notify_about_test_event(event)?;
384         }
385     }
386     Ok(())
387 }
388
389 pub fn filter_tests(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
390     let mut filtered = tests;
391     let matches_filter = |test: &TestDescAndFn, filter: &str| {
392         let test_name = test.desc.name.as_slice();
393
394         match opts.filter_exact {
395             true => test_name == filter,
396             false => test_name.contains(filter),
397         }
398     };
399
400     // Remove tests that don't match the test filter
401     if !opts.filters.is_empty() {
402         filtered.retain(|test| opts.filters.iter().any(|filter| matches_filter(test, filter)));
403     }
404
405     // Skip tests that match any of the skip filters
406     filtered.retain(|test| !opts.skip.iter().any(|sf| matches_filter(test, sf)));
407
408     // Excludes #[should_panic] tests
409     if opts.exclude_should_panic {
410         filtered.retain(|test| test.desc.should_panic == ShouldPanic::No);
411     }
412
413     // maybe unignore tests
414     match opts.run_ignored {
415         RunIgnored::Yes => {
416             filtered.iter_mut().for_each(|test| test.desc.ignore = false);
417         }
418         RunIgnored::Only => {
419             filtered.retain(|test| test.desc.ignore);
420             filtered.iter_mut().for_each(|test| test.desc.ignore = false);
421         }
422         RunIgnored::No => {}
423     }
424
425     // Sort the tests alphabetically
426     filtered.sort_by(|t1, t2| t1.desc.name.as_slice().cmp(t2.desc.name.as_slice()));
427
428     filtered
429 }
430
431 pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
432     // convert benchmarks to tests, if we're not benchmarking them
433     tests
434         .into_iter()
435         .map(|x| {
436             let testfn = match x.testfn {
437                 DynBenchFn(benchfn) => DynTestFn(Box::new(move || {
438                     bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
439                 })),
440                 StaticBenchFn(benchfn) => DynTestFn(Box::new(move || {
441                     bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
442                 })),
443                 f => f,
444             };
445             TestDescAndFn { desc: x.desc, testfn }
446         })
447         .collect()
448 }
449
450 pub fn run_test(
451     opts: &TestOpts,
452     force_ignore: bool,
453     id: TestId,
454     test: TestDescAndFn,
455     strategy: RunStrategy,
456     monitor_ch: Sender<CompletedTest>,
457     concurrency: Concurrent,
458 ) -> Option<thread::JoinHandle<()>> {
459     let TestDescAndFn { desc, testfn } = test;
460
461     // Emscripten can catch panics but other wasm targets cannot
462     let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No
463         && cfg!(target_family = "wasm")
464         && !cfg!(target_os = "emscripten");
465
466     if force_ignore || desc.ignore || ignore_because_no_process_support {
467         let message = CompletedTest::new(id, desc, TrIgnored, None, Vec::new());
468         monitor_ch.send(message).unwrap();
469         return None;
470     }
471
472     struct TestRunOpts {
473         pub strategy: RunStrategy,
474         pub nocapture: bool,
475         pub concurrency: Concurrent,
476         pub time: Option<time::TestTimeOptions>,
477     }
478
479     fn run_test_inner(
480         id: TestId,
481         desc: TestDesc,
482         monitor_ch: Sender<CompletedTest>,
483         testfn: Box<dyn FnOnce() + Send>,
484         opts: TestRunOpts,
485     ) -> Option<thread::JoinHandle<()>> {
486         let concurrency = opts.concurrency;
487         let name = desc.name.clone();
488
489         let runtest = move || match opts.strategy {
490             RunStrategy::InProcess => run_test_in_process(
491                 id,
492                 desc,
493                 opts.nocapture,
494                 opts.time.is_some(),
495                 testfn,
496                 monitor_ch,
497                 opts.time,
498             ),
499             RunStrategy::SpawnPrimary => spawn_test_subprocess(
500                 id,
501                 desc,
502                 opts.nocapture,
503                 opts.time.is_some(),
504                 monitor_ch,
505                 opts.time,
506             ),
507         };
508
509         // If the platform is single-threaded we're just going to run
510         // the test synchronously, regardless of the concurrency
511         // level.
512         let supports_threads = !cfg!(target_os = "emscripten") && !cfg!(target_family = "wasm");
513         if concurrency == Concurrent::Yes && supports_threads {
514             let cfg = thread::Builder::new().name(name.as_slice().to_owned());
515             let mut runtest = Arc::new(Mutex::new(Some(runtest)));
516             let runtest2 = runtest.clone();
517             match cfg.spawn(move || runtest2.lock().unwrap().take().unwrap()()) {
518                 Ok(handle) => Some(handle),
519                 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
520                     // `ErrorKind::WouldBlock` means hitting the thread limit on some
521                     // platforms, so run the test synchronously here instead.
522                     Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()();
523                     None
524                 }
525                 Err(e) => panic!("failed to spawn thread to run test: {e}"),
526             }
527         } else {
528             runtest();
529             None
530         }
531     }
532
533     let test_run_opts =
534         TestRunOpts { strategy, nocapture: opts.nocapture, concurrency, time: opts.time_options };
535
536     match testfn {
537         DynBenchFn(benchfn) => {
538             // Benchmarks aren't expected to panic, so we run them all in-process.
539             crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
540             None
541         }
542         StaticBenchFn(benchfn) => {
543             // Benchmarks aren't expected to panic, so we run them all in-process.
544             crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
545             None
546         }
547         DynTestFn(f) => {
548             match strategy {
549                 RunStrategy::InProcess => (),
550                 _ => panic!("Cannot run dynamic test fn out-of-process"),
551             };
552             run_test_inner(
553                 id,
554                 desc,
555                 monitor_ch,
556                 Box::new(move || __rust_begin_short_backtrace(f)),
557                 test_run_opts,
558             )
559         }
560         StaticTestFn(f) => run_test_inner(
561             id,
562             desc,
563             monitor_ch,
564             Box::new(move || __rust_begin_short_backtrace(f)),
565             test_run_opts,
566         ),
567     }
568 }
569
570 /// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`.
571 #[inline(never)]
572 fn __rust_begin_short_backtrace<F: FnOnce()>(f: F) {
573     f();
574
575     // prevent this frame from being tail-call optimised away
576     black_box(());
577 }
578
579 fn run_test_in_process(
580     id: TestId,
581     desc: TestDesc,
582     nocapture: bool,
583     report_time: bool,
584     testfn: Box<dyn FnOnce() + Send>,
585     monitor_ch: Sender<CompletedTest>,
586     time_opts: Option<time::TestTimeOptions>,
587 ) {
588     // Buffer for capturing standard I/O
589     let data = Arc::new(Mutex::new(Vec::new()));
590
591     if !nocapture {
592         io::set_output_capture(Some(data.clone()));
593     }
594
595     let start = report_time.then(Instant::now);
596     let result = catch_unwind(AssertUnwindSafe(testfn));
597     let exec_time = start.map(|start| {
598         let duration = start.elapsed();
599         TestExecTime(duration)
600     });
601
602     io::set_output_capture(None);
603
604     let test_result = match result {
605         Ok(()) => calc_result(&desc, Ok(()), &time_opts, &exec_time),
606         Err(e) => calc_result(&desc, Err(e.as_ref()), &time_opts, &exec_time),
607     };
608     let stdout = data.lock().unwrap_or_else(|e| e.into_inner()).to_vec();
609     let message = CompletedTest::new(id, desc, test_result, exec_time, stdout);
610     monitor_ch.send(message).unwrap();
611 }
612
613 fn spawn_test_subprocess(
614     id: TestId,
615     desc: TestDesc,
616     nocapture: bool,
617     report_time: bool,
618     monitor_ch: Sender<CompletedTest>,
619     time_opts: Option<time::TestTimeOptions>,
620 ) {
621     let (result, test_output, exec_time) = (|| {
622         let args = env::args().collect::<Vec<_>>();
623         let current_exe = &args[0];
624
625         let mut command = Command::new(current_exe);
626         command.env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice());
627         if nocapture {
628             command.stdout(process::Stdio::inherit());
629             command.stderr(process::Stdio::inherit());
630         }
631
632         let start = report_time.then(Instant::now);
633         let output = match command.output() {
634             Ok(out) => out,
635             Err(e) => {
636                 let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e);
637                 return (TrFailed, err.into_bytes(), None);
638             }
639         };
640         let exec_time = start.map(|start| {
641             let duration = start.elapsed();
642             TestExecTime(duration)
643         });
644
645         let std::process::Output { stdout, stderr, status } = output;
646         let mut test_output = stdout;
647         formatters::write_stderr_delimiter(&mut test_output, &desc.name);
648         test_output.extend_from_slice(&stderr);
649
650         let result = match (|| -> Result<TestResult, String> {
651             let exit_code = get_exit_code(status)?;
652             Ok(get_result_from_exit_code(&desc, exit_code, &time_opts, &exec_time))
653         })() {
654             Ok(r) => r,
655             Err(e) => {
656                 write!(&mut test_output, "Unexpected error: {}", e).unwrap();
657                 TrFailed
658             }
659         };
660
661         (result, test_output, exec_time)
662     })();
663
664     let message = CompletedTest::new(id, desc, result, exec_time, test_output);
665     monitor_ch.send(message).unwrap();
666 }
667
668 fn run_test_in_spawned_subprocess(desc: TestDesc, testfn: Box<dyn FnOnce() + Send>) -> ! {
669     let builtin_panic_hook = panic::take_hook();
670     let record_result = Arc::new(move |panic_info: Option<&'_ PanicInfo<'_>>| {
671         let test_result = match panic_info {
672             Some(info) => calc_result(&desc, Err(info.payload()), &None, &None),
673             None => calc_result(&desc, Ok(()), &None, &None),
674         };
675
676         // We don't support serializing TrFailedMsg, so just
677         // print the message out to stderr.
678         if let TrFailedMsg(msg) = &test_result {
679             eprintln!("{msg}");
680         }
681
682         if let Some(info) = panic_info {
683             builtin_panic_hook(info);
684         }
685
686         if let TrOk = test_result {
687             process::exit(test_result::TR_OK);
688         } else {
689             process::exit(test_result::TR_FAILED);
690         }
691     });
692     let record_result2 = record_result.clone();
693     panic::set_hook(Box::new(move |info| record_result2(Some(&info))));
694     testfn();
695     record_result(None);
696     unreachable!("panic=abort callback should have exited the process")
697 }