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