]> git.lizzy.rs Git - rust.git/blob - library/test/src/lib.rs
Rollup merge of #106175 - compiler-errors:bad-import-sugg, r=oli-obk
[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              ({code}) which indicates a failure"
217         ))
218     }
219 }
220
221 struct FilteredTests {
222     tests: Vec<(TestId, TestDescAndFn)>,
223     benchs: Vec<(TestId, TestDescAndFn)>,
224     next_id: usize,
225 }
226
227 impl FilteredTests {
228     fn add_bench(&mut self, desc: TestDesc, testfn: TestFn) {
229         let test = TestDescAndFn { desc, testfn };
230         self.benchs.push((TestId(self.next_id), test));
231         self.next_id += 1;
232     }
233     fn add_test(&mut self, desc: TestDesc, testfn: TestFn) {
234         let test = TestDescAndFn { desc, testfn };
235         self.tests.push((TestId(self.next_id), test));
236         self.next_id += 1;
237     }
238     fn add_bench_as_test(
239         &mut self,
240         desc: TestDesc,
241         benchfn: impl Fn(&mut Bencher) -> Result<(), String> + Send + 'static,
242     ) {
243         let testfn = DynTestFn(Box::new(move || {
244             bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
245         }));
246         self.add_test(desc, testfn);
247     }
248     fn total_len(&self) -> usize {
249         self.tests.len() + self.benchs.len()
250     }
251 }
252
253 pub fn run_tests<F>(
254     opts: &TestOpts,
255     tests: Vec<TestDescAndFn>,
256     mut notify_about_test_event: F,
257 ) -> io::Result<()>
258 where
259     F: FnMut(TestEvent) -> io::Result<()>,
260 {
261     use std::collections::{self, HashMap};
262     use std::hash::BuildHasherDefault;
263     use std::sync::mpsc::RecvTimeoutError;
264
265     struct RunningTest {
266         join_handle: Option<thread::JoinHandle<()>>,
267     }
268
269     impl RunningTest {
270         fn join(self, completed_test: &mut CompletedTest) {
271             if let Some(join_handle) = self.join_handle {
272                 if let Err(_) = join_handle.join() {
273                     if let TrOk = completed_test.result {
274                         completed_test.result =
275                             TrFailedMsg("panicked after reporting success".to_string());
276                     }
277                 }
278             }
279         }
280     }
281
282     // Use a deterministic hasher
283     type TestMap =
284         HashMap<TestId, RunningTest, BuildHasherDefault<collections::hash_map::DefaultHasher>>;
285
286     struct TimeoutEntry {
287         id: TestId,
288         desc: TestDesc,
289         timeout: Instant,
290     }
291
292     let tests_len = tests.len();
293
294     let mut filtered = FilteredTests { tests: Vec::new(), benchs: Vec::new(), next_id: 0 };
295
296     for test in filter_tests(opts, tests) {
297         let mut desc = test.desc;
298         desc.name = desc.name.with_padding(test.testfn.padding());
299
300         match test.testfn {
301             DynBenchFn(benchfn) => {
302                 if opts.bench_benchmarks {
303                     filtered.add_bench(desc, DynBenchFn(benchfn));
304                 } else {
305                     filtered.add_bench_as_test(desc, benchfn);
306                 }
307             }
308             StaticBenchFn(benchfn) => {
309                 if opts.bench_benchmarks {
310                     filtered.add_bench(desc, StaticBenchFn(benchfn));
311                 } else {
312                     filtered.add_bench_as_test(desc, benchfn);
313                 }
314             }
315             testfn => {
316                 filtered.add_test(desc, testfn);
317             }
318         };
319     }
320
321     let filtered_out = tests_len - filtered.total_len();
322     let event = TestEvent::TeFilteredOut(filtered_out);
323     notify_about_test_event(event)?;
324
325     let shuffle_seed = get_shuffle_seed(opts);
326
327     let event = TestEvent::TeFiltered(filtered.total_len(), shuffle_seed);
328     notify_about_test_event(event)?;
329
330     let concurrency = opts.test_threads.unwrap_or_else(get_concurrency);
331
332     let mut remaining = filtered.tests;
333     if let Some(shuffle_seed) = shuffle_seed {
334         shuffle_tests(shuffle_seed, &mut remaining);
335     }
336     // Store the tests in a VecDeque so we can efficiently remove the first element to run the
337     // tests in the order they were passed (unless shuffled).
338     let mut remaining = VecDeque::from(remaining);
339     let mut pending = 0;
340
341     let (tx, rx) = channel::<CompletedTest>();
342     let run_strategy = if opts.options.panic_abort && !opts.force_run_in_process {
343         RunStrategy::SpawnPrimary
344     } else {
345         RunStrategy::InProcess
346     };
347
348     let mut running_tests: TestMap = HashMap::default();
349     let mut timeout_queue: VecDeque<TimeoutEntry> = VecDeque::new();
350
351     fn get_timed_out_tests(
352         running_tests: &TestMap,
353         timeout_queue: &mut VecDeque<TimeoutEntry>,
354     ) -> Vec<TestDesc> {
355         let now = Instant::now();
356         let mut timed_out = Vec::new();
357         while let Some(timeout_entry) = timeout_queue.front() {
358             if now < timeout_entry.timeout {
359                 break;
360             }
361             let timeout_entry = timeout_queue.pop_front().unwrap();
362             if running_tests.contains_key(&timeout_entry.id) {
363                 timed_out.push(timeout_entry.desc);
364             }
365         }
366         timed_out
367     }
368
369     fn calc_timeout(timeout_queue: &VecDeque<TimeoutEntry>) -> Option<Duration> {
370         timeout_queue.front().map(|&TimeoutEntry { timeout: next_timeout, .. }| {
371             let now = Instant::now();
372             if next_timeout >= now { next_timeout - now } else { Duration::new(0, 0) }
373         })
374     }
375
376     if concurrency == 1 {
377         while !remaining.is_empty() {
378             let (id, test) = remaining.pop_front().unwrap();
379             let event = TestEvent::TeWait(test.desc.clone());
380             notify_about_test_event(event)?;
381             let join_handle = run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone());
382             // Wait for the test to complete.
383             let mut completed_test = rx.recv().unwrap();
384             RunningTest { join_handle }.join(&mut completed_test);
385
386             let fail_fast = match completed_test.result {
387                 TrIgnored | TrOk | TrBench(_) => false,
388                 TrFailed | TrFailedMsg(_) | TrTimedFail => opts.fail_fast,
389             };
390
391             let event = TestEvent::TeResult(completed_test);
392             notify_about_test_event(event)?;
393
394             if fail_fast {
395                 return Ok(());
396             }
397         }
398     } else {
399         while pending > 0 || !remaining.is_empty() {
400             while pending < concurrency && !remaining.is_empty() {
401                 let (id, test) = remaining.pop_front().unwrap();
402                 let timeout = time::get_default_test_timeout();
403                 let desc = test.desc.clone();
404
405                 let event = TestEvent::TeWait(desc.clone());
406                 notify_about_test_event(event)?; //here no pad
407                 let join_handle =
408                     run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone());
409                 running_tests.insert(id, RunningTest { join_handle });
410                 timeout_queue.push_back(TimeoutEntry { id, desc, timeout });
411                 pending += 1;
412             }
413
414             let mut res;
415             loop {
416                 if let Some(timeout) = calc_timeout(&timeout_queue) {
417                     res = rx.recv_timeout(timeout);
418                     for test in get_timed_out_tests(&running_tests, &mut timeout_queue) {
419                         let event = TestEvent::TeTimeout(test);
420                         notify_about_test_event(event)?;
421                     }
422
423                     match res {
424                         Err(RecvTimeoutError::Timeout) => {
425                             // Result is not yet ready, continue waiting.
426                         }
427                         _ => {
428                             // We've got a result, stop the loop.
429                             break;
430                         }
431                     }
432                 } else {
433                     res = rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
434                     break;
435                 }
436             }
437
438             let mut completed_test = res.unwrap();
439             let running_test = running_tests.remove(&completed_test.id).unwrap();
440             running_test.join(&mut completed_test);
441
442             let fail_fast = match completed_test.result {
443                 TrIgnored | TrOk | TrBench(_) => false,
444                 TrFailed | TrFailedMsg(_) | TrTimedFail => opts.fail_fast,
445             };
446
447             let event = TestEvent::TeResult(completed_test);
448             notify_about_test_event(event)?;
449             pending -= 1;
450
451             if fail_fast {
452                 // Prevent remaining test threads from panicking
453                 std::mem::forget(rx);
454                 return Ok(());
455             }
456         }
457     }
458
459     if opts.bench_benchmarks {
460         // All benchmarks run at the end, in serial.
461         for (id, b) in filtered.benchs {
462             let event = TestEvent::TeWait(b.desc.clone());
463             notify_about_test_event(event)?;
464             let join_handle = run_test(opts, false, id, b, run_strategy, tx.clone());
465             // Wait for the test to complete.
466             let mut completed_test = rx.recv().unwrap();
467             RunningTest { join_handle }.join(&mut completed_test);
468
469             let event = TestEvent::TeResult(completed_test);
470             notify_about_test_event(event)?;
471         }
472     }
473     Ok(())
474 }
475
476 pub fn filter_tests(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
477     let mut filtered = tests;
478     let matches_filter = |test: &TestDescAndFn, filter: &str| {
479         let test_name = test.desc.name.as_slice();
480
481         match opts.filter_exact {
482             true => test_name == filter,
483             false => test_name.contains(filter),
484         }
485     };
486
487     // Remove tests that don't match the test filter
488     if !opts.filters.is_empty() {
489         filtered.retain(|test| opts.filters.iter().any(|filter| matches_filter(test, filter)));
490     }
491
492     // Skip tests that match any of the skip filters
493     if !opts.skip.is_empty() {
494         filtered.retain(|test| !opts.skip.iter().any(|sf| matches_filter(test, sf)));
495     }
496
497     // Excludes #[should_panic] tests
498     if opts.exclude_should_panic {
499         filtered.retain(|test| test.desc.should_panic == ShouldPanic::No);
500     }
501
502     // maybe unignore tests
503     match opts.run_ignored {
504         RunIgnored::Yes => {
505             filtered.iter_mut().for_each(|test| test.desc.ignore = false);
506         }
507         RunIgnored::Only => {
508             filtered.retain(|test| test.desc.ignore);
509             filtered.iter_mut().for_each(|test| test.desc.ignore = false);
510         }
511         RunIgnored::No => {}
512     }
513
514     filtered
515 }
516
517 pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
518     // convert benchmarks to tests, if we're not benchmarking them
519     tests
520         .into_iter()
521         .map(|x| {
522             let testfn = match x.testfn {
523                 DynBenchFn(benchfn) => DynTestFn(Box::new(move || {
524                     bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
525                 })),
526                 StaticBenchFn(benchfn) => DynTestFn(Box::new(move || {
527                     bench::run_once(|b| __rust_begin_short_backtrace(|| benchfn(b)))
528                 })),
529                 f => f,
530             };
531             TestDescAndFn { desc: x.desc, testfn }
532         })
533         .collect()
534 }
535
536 pub fn run_test(
537     opts: &TestOpts,
538     force_ignore: bool,
539     id: TestId,
540     test: TestDescAndFn,
541     strategy: RunStrategy,
542     monitor_ch: Sender<CompletedTest>,
543 ) -> Option<thread::JoinHandle<()>> {
544     let TestDescAndFn { desc, testfn } = test;
545
546     // Emscripten can catch panics but other wasm targets cannot
547     let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No
548         && cfg!(target_family = "wasm")
549         && !cfg!(target_os = "emscripten");
550
551     if force_ignore || desc.ignore || ignore_because_no_process_support {
552         let message = CompletedTest::new(id, desc, TrIgnored, None, Vec::new());
553         monitor_ch.send(message).unwrap();
554         return None;
555     }
556
557     struct TestRunOpts {
558         pub strategy: RunStrategy,
559         pub nocapture: bool,
560         pub time: Option<time::TestTimeOptions>,
561     }
562
563     fn run_test_inner(
564         id: TestId,
565         desc: TestDesc,
566         monitor_ch: Sender<CompletedTest>,
567         testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
568         opts: TestRunOpts,
569     ) -> Option<thread::JoinHandle<()>> {
570         let name = desc.name.clone();
571
572         let runtest = move || match opts.strategy {
573             RunStrategy::InProcess => run_test_in_process(
574                 id,
575                 desc,
576                 opts.nocapture,
577                 opts.time.is_some(),
578                 testfn,
579                 monitor_ch,
580                 opts.time,
581             ),
582             RunStrategy::SpawnPrimary => spawn_test_subprocess(
583                 id,
584                 desc,
585                 opts.nocapture,
586                 opts.time.is_some(),
587                 monitor_ch,
588                 opts.time,
589             ),
590         };
591
592         // If the platform is single-threaded we're just going to run
593         // the test synchronously, regardless of the concurrency
594         // level.
595         let supports_threads = !cfg!(target_os = "emscripten") && !cfg!(target_family = "wasm");
596         if supports_threads {
597             let cfg = thread::Builder::new().name(name.as_slice().to_owned());
598             let mut runtest = Arc::new(Mutex::new(Some(runtest)));
599             let runtest2 = runtest.clone();
600             match cfg.spawn(move || runtest2.lock().unwrap().take().unwrap()()) {
601                 Ok(handle) => Some(handle),
602                 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
603                     // `ErrorKind::WouldBlock` means hitting the thread limit on some
604                     // platforms, so run the test synchronously here instead.
605                     Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()();
606                     None
607                 }
608                 Err(e) => panic!("failed to spawn thread to run test: {e}"),
609             }
610         } else {
611             runtest();
612             None
613         }
614     }
615
616     let test_run_opts =
617         TestRunOpts { strategy, nocapture: opts.nocapture, time: opts.time_options };
618
619     match testfn {
620         DynBenchFn(benchfn) => {
621             // Benchmarks aren't expected to panic, so we run them all in-process.
622             crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
623             None
624         }
625         StaticBenchFn(benchfn) => {
626             // Benchmarks aren't expected to panic, so we run them all in-process.
627             crate::bench::benchmark(id, desc, monitor_ch, opts.nocapture, benchfn);
628             None
629         }
630         DynTestFn(f) => {
631             match strategy {
632                 RunStrategy::InProcess => (),
633                 _ => panic!("Cannot run dynamic test fn out-of-process"),
634             };
635             run_test_inner(
636                 id,
637                 desc,
638                 monitor_ch,
639                 Box::new(move || __rust_begin_short_backtrace(f)),
640                 test_run_opts,
641             )
642         }
643         StaticTestFn(f) => run_test_inner(
644             id,
645             desc,
646             monitor_ch,
647             Box::new(move || __rust_begin_short_backtrace(f)),
648             test_run_opts,
649         ),
650     }
651 }
652
653 /// Fixed frame used to clean the backtrace with `RUST_BACKTRACE=1`.
654 #[inline(never)]
655 fn __rust_begin_short_backtrace<T, F: FnOnce() -> T>(f: F) -> T {
656     let result = f();
657
658     // prevent this frame from being tail-call optimised away
659     black_box(result)
660 }
661
662 fn run_test_in_process(
663     id: TestId,
664     desc: TestDesc,
665     nocapture: bool,
666     report_time: bool,
667     testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
668     monitor_ch: Sender<CompletedTest>,
669     time_opts: Option<time::TestTimeOptions>,
670 ) {
671     // Buffer for capturing standard I/O
672     let data = Arc::new(Mutex::new(Vec::new()));
673
674     if !nocapture {
675         io::set_output_capture(Some(data.clone()));
676     }
677
678     let start = report_time.then(Instant::now);
679     let result = fold_err(catch_unwind(AssertUnwindSafe(testfn)));
680     let exec_time = start.map(|start| {
681         let duration = start.elapsed();
682         TestExecTime(duration)
683     });
684
685     io::set_output_capture(None);
686
687     let test_result = match result {
688         Ok(()) => calc_result(&desc, Ok(()), &time_opts, &exec_time),
689         Err(e) => calc_result(&desc, Err(e.as_ref()), &time_opts, &exec_time),
690     };
691     let stdout = data.lock().unwrap_or_else(|e| e.into_inner()).to_vec();
692     let message = CompletedTest::new(id, desc, test_result, exec_time, stdout);
693     monitor_ch.send(message).unwrap();
694 }
695
696 fn fold_err<T, E>(
697     result: Result<Result<T, E>, Box<dyn Any + Send>>,
698 ) -> Result<T, Box<dyn Any + Send>>
699 where
700     E: Send + 'static,
701 {
702     match result {
703         Ok(Err(e)) => Err(Box::new(e)),
704         Ok(Ok(v)) => Ok(v),
705         Err(e) => Err(e),
706     }
707 }
708
709 fn spawn_test_subprocess(
710     id: TestId,
711     desc: TestDesc,
712     nocapture: bool,
713     report_time: bool,
714     monitor_ch: Sender<CompletedTest>,
715     time_opts: Option<time::TestTimeOptions>,
716 ) {
717     let (result, test_output, exec_time) = (|| {
718         let args = env::args().collect::<Vec<_>>();
719         let current_exe = &args[0];
720
721         let mut command = Command::new(current_exe);
722         command.env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice());
723         if nocapture {
724             command.stdout(process::Stdio::inherit());
725             command.stderr(process::Stdio::inherit());
726         }
727
728         let start = report_time.then(Instant::now);
729         let output = match command.output() {
730             Ok(out) => out,
731             Err(e) => {
732                 let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e);
733                 return (TrFailed, err.into_bytes(), None);
734             }
735         };
736         let exec_time = start.map(|start| {
737             let duration = start.elapsed();
738             TestExecTime(duration)
739         });
740
741         let std::process::Output { stdout, stderr, status } = output;
742         let mut test_output = stdout;
743         formatters::write_stderr_delimiter(&mut test_output, &desc.name);
744         test_output.extend_from_slice(&stderr);
745
746         let result = match (|| -> Result<TestResult, String> {
747             let exit_code = get_exit_code(status)?;
748             Ok(get_result_from_exit_code(&desc, exit_code, &time_opts, &exec_time))
749         })() {
750             Ok(r) => r,
751             Err(e) => {
752                 write!(&mut test_output, "Unexpected error: {e}").unwrap();
753                 TrFailed
754             }
755         };
756
757         (result, test_output, exec_time)
758     })();
759
760     let message = CompletedTest::new(id, desc, result, exec_time, test_output);
761     monitor_ch.send(message).unwrap();
762 }
763
764 fn run_test_in_spawned_subprocess(
765     desc: TestDesc,
766     testfn: Box<dyn FnOnce() -> Result<(), String> + Send>,
767 ) -> ! {
768     let builtin_panic_hook = panic::take_hook();
769     let record_result = Arc::new(move |panic_info: Option<&'_ PanicInfo<'_>>| {
770         let test_result = match panic_info {
771             Some(info) => calc_result(&desc, Err(info.payload()), &None, &None),
772             None => calc_result(&desc, Ok(()), &None, &None),
773         };
774
775         // We don't support serializing TrFailedMsg, so just
776         // print the message out to stderr.
777         if let TrFailedMsg(msg) = &test_result {
778             eprintln!("{msg}");
779         }
780
781         if let Some(info) = panic_info {
782             builtin_panic_hook(info);
783         }
784
785         if let TrOk = test_result {
786             process::exit(test_result::TR_OK);
787         } else {
788             process::exit(test_result::TR_FAILED);
789         }
790     });
791     let record_result2 = record_result.clone();
792     panic::set_hook(Box::new(move |info| record_result2(Some(info))));
793     if let Err(message) = testfn() {
794         panic!("{}", message);
795     }
796     record_result(None);
797     unreachable!("panic=abort callback should have exited the process")
798 }