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