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