1#![unstable(feature = "test", issue = "50297")]
18#![doc(test(attr(deny(warnings))))]
19#![doc(rust_logo)]
20#![feature(rustdoc_internals)]
21#![feature(file_buffered)]
22#![feature(internal_output_capture)]
23#![feature(io_const_error)]
24#![feature(staged_api)]
25#![feature(process_exitcode_internals)]
26#![feature(panic_can_unwind)]
27#![cfg_attr(test, feature(test))]
28#![feature(thread_spawn_hook)]
29#![allow(internal_features)]
30#![warn(rustdoc::unescaped_backticks)]
31#![warn(unreachable_pub)]
32
33pub use cli::TestOpts;
34
35pub use self::ColorConfig::*;
36pub use self::bench::{Bencher, black_box};
37pub use self::console::run_tests_console;
38pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic};
39pub use self::types::TestName::*;
40pub use self::types::*;
41
42pub mod test {
44 pub use crate::bench::Bencher;
45 pub use crate::cli::{TestOpts, parse_opts};
46 pub use crate::helpers::metrics::{Metric, MetricMap};
47 pub use crate::options::{Options, RunIgnored, RunStrategy, ShouldPanic};
48 pub use crate::test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk};
49 pub use crate::time::{TestExecTime, TestTimeOptions};
50 pub use crate::types::{
51 DynTestFn, DynTestName, StaticBenchFn, StaticTestFn, StaticTestName, TestDesc,
52 TestDescAndFn, TestId, TestList, TestListOrder, TestName, TestType,
53 };
54 pub use crate::{assert_test_result, filter_tests, run_test, test_main, test_main_static};
55}
56
57use std::collections::VecDeque;
58use std::io::prelude::Write;
59use std::mem::ManuallyDrop;
60use std::panic::{self, AssertUnwindSafe, PanicHookInfo, catch_unwind};
61use std::process::{self, Command, Termination};
62use std::sync::mpsc::{Sender, channel};
63use std::sync::{Arc, Mutex};
64use std::time::{Duration, Instant};
65use std::{env, io, thread};
66
67pub mod bench;
68mod cli;
69mod console;
70mod event;
71mod formatters;
72mod helpers;
73mod options;
74pub mod stats;
75mod term;
76mod test_result;
77mod time;
78mod types;
79
80#[cfg(test)]
81mod tests;
82
83use core::any::Any;
84
85use event::{CompletedTest, TestEvent};
86use helpers::concurrency::get_concurrency;
87use helpers::shuffle::{get_shuffle_seed, shuffle_tests};
88use options::RunStrategy;
89use test_result::*;
90use time::TestExecTime;
91
92pub const ERROR_EXIT_CODE: i32 = 101;
94
95const SECONDARY_TEST_INVOKER_VAR: &str = "__RUST_TEST_INVOKE";
96const SECONDARY_TEST_BENCH_BENCHMARKS_VAR: &str = "__RUST_TEST_BENCH_BENCHMARKS";
97
98pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>, options: Option<Options>) {
101 test_main_with_exit_callback(args, tests, options, || {})
102}
103
104pub fn test_main_with_exit_callback<F: FnOnce()>(
105 args: &[String],
106 tests: Vec<TestDescAndFn>,
107 options: Option<Options>,
108 exit_callback: F,
109) {
110 let tests = TestList::new(tests, TestListOrder::Unsorted);
111 test_main_inner(args, tests, options, exit_callback)
112}
113
114fn test_main_inner<F: FnOnce()>(
115 args: &[String],
116 tests: TestList,
117 options: Option<Options>,
118 exit_callback: F,
119) {
120 let mut opts = match cli::parse_opts(args) {
121 Some(Ok(o)) => o,
122 Some(Err(msg)) => {
123 eprintln!("error: {msg}");
124 process::exit(ERROR_EXIT_CODE);
125 }
126 None => return,
127 };
128 if let Some(options) = options {
129 opts.options = options;
130 }
131 if opts.list {
132 if let Err(e) = console::list_tests_console(&opts, tests) {
133 eprintln!("error: io error when listing tests: {e:?}");
134 process::exit(ERROR_EXIT_CODE);
135 }
136 } else {
137 if !opts.nocapture {
138 let builtin_panic_hook = panic::take_hook();
143 let hook = Box::new({
144 move |info: &'_ PanicHookInfo<'_>| {
145 if !info.can_unwind() {
146 std::mem::forget(std::io::stderr().lock());
147 let mut stdout = ManuallyDrop::new(std::io::stdout().lock());
148 if let Some(captured) = io::set_output_capture(None) {
149 if let Ok(data) = captured.lock() {
150 let _ = stdout.write_all(&data);
151 let _ = stdout.flush();
152 }
153 }
154 }
155 builtin_panic_hook(info);
156 }
157 });
158 panic::set_hook(hook);
159 std::thread::add_spawn_hook(|_| {
161 let output_capture = io::set_output_capture(None);
163 io::set_output_capture(output_capture.clone());
164 || {
166 io::set_output_capture(output_capture);
167 }
168 });
169 }
170 let res = console::run_tests_console(&opts, tests);
171 drop(panic::take_hook());
173 exit_callback();
174 match res {
175 Ok(true) => {}
176 Ok(false) => process::exit(ERROR_EXIT_CODE),
177 Err(e) => {
178 eprintln!("error: io error when listing tests: {e:?}");
179 process::exit(ERROR_EXIT_CODE);
180 }
181 }
182 }
183}
184
185pub fn test_main_static(tests: &[&TestDescAndFn]) {
191 let args = env::args().collect::<Vec<_>>();
192 let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
193 let tests = TestList::new(owned_tests, TestListOrder::Sorted);
195 test_main_inner(&args, tests, None, || {})
196}
197
198pub fn test_main_static_abort(tests: &[&TestDescAndFn]) {
207 if let Ok(name) = env::var(SECONDARY_TEST_INVOKER_VAR) {
210 unsafe {
219 env::remove_var(SECONDARY_TEST_INVOKER_VAR);
220 }
221
222 let mut tests = tests.iter().map(make_owned_test).collect::<Vec<_>>();
224 if env::var(SECONDARY_TEST_BENCH_BENCHMARKS_VAR).is_ok() {
225 unsafe {
227 env::remove_var(SECONDARY_TEST_BENCH_BENCHMARKS_VAR);
228 }
229 } else {
230 tests = convert_benchmarks_to_tests(tests);
231 };
232
233 let test = tests
234 .into_iter()
235 .find(|test| test.desc.name.as_slice() == name)
236 .unwrap_or_else(|| panic!("couldn't find a test with the provided name '{name}'"));
237 let TestDescAndFn { desc, testfn } = test;
238 match testfn.into_runnable() {
239 Runnable::Test(runnable_test) => {
240 if runnable_test.is_dynamic() {
241 panic!("only static tests are supported");
242 }
243 run_test_in_spawned_subprocess(desc, runnable_test);
244 }
245 Runnable::Bench(_) => {
246 panic!("benchmarks should not be executed into child processes")
247 }
248 }
249 }
250
251 let args = env::args().collect::<Vec<_>>();
252 let owned_tests: Vec<_> = tests.iter().map(make_owned_test).collect();
253 let tests = TestList::new(owned_tests, TestListOrder::Sorted);
255 test_main_inner(&args, tests, Some(Options::new().panic_abort(true)), || {})
256}
257
258fn make_owned_test(test: &&TestDescAndFn) -> TestDescAndFn {
263 match test.testfn {
264 StaticTestFn(f) => TestDescAndFn { testfn: StaticTestFn(f), desc: test.desc.clone() },
265 StaticBenchFn(f) => TestDescAndFn { testfn: StaticBenchFn(f), desc: test.desc.clone() },
266 _ => panic!("non-static tests passed to test::test_main_static"),
267 }
268}
269
270pub fn print_merged_doctests_times(args: &[String], total_time: f64, compilation_time: f64) {
273 let opts = match cli::parse_opts(args) {
274 Some(Ok(o)) => o,
275 Some(Err(msg)) => {
276 eprintln!("error: {msg}");
277 process::exit(ERROR_EXIT_CODE);
278 }
279 None => return,
280 };
281 let mut formatter = console::get_formatter(&opts, 0);
282 formatter.write_merged_doctests_times(total_time, compilation_time).unwrap();
283}
284
285pub fn assert_test_result<T: Termination>(result: T) -> Result<(), String> {
289 let code = result.report().to_i32();
290 if code == 0 {
291 Ok(())
292 } else {
293 Err(format!(
294 "the test returned a termination value with a non-zero status code \
295 ({code}) which indicates a failure"
296 ))
297 }
298}
299
300struct FilteredTests {
301 tests: Vec<(TestId, TestDescAndFn)>,
302 benches: Vec<(TestId, TestDescAndFn)>,
303 next_id: usize,
304}
305
306impl FilteredTests {
307 fn add_bench(&mut self, desc: TestDesc, testfn: TestFn) {
308 let test = TestDescAndFn { desc, testfn };
309 self.benches.push((TestId(self.next_id), test));
310 self.next_id += 1;
311 }
312 fn add_test(&mut self, desc: TestDesc, testfn: TestFn) {
313 let test = TestDescAndFn { desc, testfn };
314 self.tests.push((TestId(self.next_id), test));
315 self.next_id += 1;
316 }
317 fn total_len(&self) -> usize {
318 self.tests.len() + self.benches.len()
319 }
320}
321
322pub fn run_tests<F>(
323 opts: &TestOpts,
324 tests: TestList,
325 mut notify_about_test_event: F,
326) -> io::Result<()>
327where
328 F: FnMut(TestEvent) -> io::Result<()>,
329{
330 use std::collections::HashMap;
331 use std::hash::{BuildHasherDefault, DefaultHasher};
332 use std::sync::mpsc::RecvTimeoutError;
333
334 struct RunningTest {
335 join_handle: Option<thread::JoinHandle<()>>,
336 }
337
338 impl RunningTest {
339 fn join(self, completed_test: &mut CompletedTest) {
340 if let Some(join_handle) = self.join_handle {
341 if let Err(_) = join_handle.join() {
342 if let TrOk = completed_test.result {
343 completed_test.result =
344 TrFailedMsg("panicked after reporting success".to_string());
345 }
346 }
347 }
348 }
349 }
350
351 type TestMap = HashMap<TestId, RunningTest, BuildHasherDefault<DefaultHasher>>;
353
354 struct TimeoutEntry {
355 id: TestId,
356 desc: TestDesc,
357 timeout: Instant,
358 }
359
360 let tests_len = tests.tests.len();
361
362 let mut filtered = FilteredTests { tests: Vec::new(), benches: Vec::new(), next_id: 0 };
363
364 let mut filtered_tests = filter_tests(opts, tests);
365 if !opts.bench_benchmarks {
366 filtered_tests = convert_benchmarks_to_tests(filtered_tests);
367 }
368
369 for test in filtered_tests {
370 let mut desc = test.desc;
371 desc.name = desc.name.with_padding(test.testfn.padding());
372
373 match test.testfn {
374 DynBenchFn(_) | StaticBenchFn(_) => {
375 filtered.add_bench(desc, test.testfn);
376 }
377 testfn => {
378 filtered.add_test(desc, testfn);
379 }
380 };
381 }
382
383 let filtered_out = tests_len - filtered.total_len();
384 let event = TestEvent::TeFilteredOut(filtered_out);
385 notify_about_test_event(event)?;
386
387 let shuffle_seed = get_shuffle_seed(opts);
388
389 let event = TestEvent::TeFiltered(filtered.total_len(), shuffle_seed);
390 notify_about_test_event(event)?;
391
392 let concurrency = opts.test_threads.unwrap_or_else(get_concurrency);
393
394 let mut remaining = filtered.tests;
395 if let Some(shuffle_seed) = shuffle_seed {
396 shuffle_tests(shuffle_seed, &mut remaining);
397 }
398 let mut remaining = VecDeque::from(remaining);
401 let mut pending = 0;
402
403 let (tx, rx) = channel::<CompletedTest>();
404 let run_strategy = if opts.options.panic_abort && !opts.force_run_in_process {
405 RunStrategy::SpawnPrimary
406 } else {
407 RunStrategy::InProcess
408 };
409
410 let mut running_tests: TestMap = HashMap::default();
411 let mut timeout_queue: VecDeque<TimeoutEntry> = VecDeque::new();
412
413 fn get_timed_out_tests(
414 running_tests: &TestMap,
415 timeout_queue: &mut VecDeque<TimeoutEntry>,
416 ) -> Vec<TestDesc> {
417 let now = Instant::now();
418 let mut timed_out = Vec::new();
419 while let Some(timeout_entry) = timeout_queue.front() {
420 if now < timeout_entry.timeout {
421 break;
422 }
423 let timeout_entry = timeout_queue.pop_front().unwrap();
424 if running_tests.contains_key(&timeout_entry.id) {
425 timed_out.push(timeout_entry.desc);
426 }
427 }
428 timed_out
429 }
430
431 fn calc_timeout(timeout_queue: &VecDeque<TimeoutEntry>) -> Option<Duration> {
432 timeout_queue.front().map(|&TimeoutEntry { timeout: next_timeout, .. }| {
433 let now = Instant::now();
434 if next_timeout >= now { next_timeout - now } else { Duration::new(0, 0) }
435 })
436 }
437
438 if concurrency == 1 {
439 while !remaining.is_empty() {
440 let (id, test) = remaining.pop_front().unwrap();
441 let event = TestEvent::TeWait(test.desc.clone());
442 notify_about_test_event(event)?;
443 let join_handle = run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone());
444 let mut completed_test = rx.recv().unwrap();
446 RunningTest { join_handle }.join(&mut completed_test);
447
448 let fail_fast = match completed_test.result {
449 TrIgnored | TrOk | TrBench(_) => false,
450 TrFailed | TrFailedMsg(_) | TrTimedFail => opts.fail_fast,
451 };
452
453 let event = TestEvent::TeResult(completed_test);
454 notify_about_test_event(event)?;
455
456 if fail_fast {
457 return Ok(());
458 }
459 }
460 } else {
461 while pending > 0 || !remaining.is_empty() {
462 while pending < concurrency && !remaining.is_empty() {
463 let (id, test) = remaining.pop_front().unwrap();
464 let timeout = time::get_default_test_timeout();
465 let desc = test.desc.clone();
466
467 let event = TestEvent::TeWait(desc.clone());
468 notify_about_test_event(event)?; let join_handle =
470 run_test(opts, !opts.run_tests, id, test, run_strategy, tx.clone());
471 running_tests.insert(id, RunningTest { join_handle });
472 timeout_queue.push_back(TimeoutEntry { id, desc, timeout });
473 pending += 1;
474 }
475
476 let mut res;
477 loop {
478 if let Some(timeout) = calc_timeout(&timeout_queue) {
479 res = rx.recv_timeout(timeout);
480 for test in get_timed_out_tests(&running_tests, &mut timeout_queue) {
481 let event = TestEvent::TeTimeout(test);
482 notify_about_test_event(event)?;
483 }
484
485 match res {
486 Err(RecvTimeoutError::Timeout) => {
487 }
489 _ => {
490 break;
492 }
493 }
494 } else {
495 res = rx.recv().map_err(|_| RecvTimeoutError::Disconnected);
496 break;
497 }
498 }
499
500 let mut completed_test = res.unwrap();
501 let running_test = running_tests.remove(&completed_test.id).unwrap();
502 running_test.join(&mut completed_test);
503
504 let fail_fast = match completed_test.result {
505 TrIgnored | TrOk | TrBench(_) => false,
506 TrFailed | TrFailedMsg(_) | TrTimedFail => opts.fail_fast,
507 };
508
509 let event = TestEvent::TeResult(completed_test);
510 notify_about_test_event(event)?;
511 pending -= 1;
512
513 if fail_fast {
514 std::mem::forget(rx);
516 return Ok(());
517 }
518 }
519 }
520
521 if opts.bench_benchmarks {
522 for (id, b) in filtered.benches {
524 let event = TestEvent::TeWait(b.desc.clone());
525 notify_about_test_event(event)?;
526 let join_handle = run_test(opts, false, id, b, run_strategy, tx.clone());
527 let mut completed_test = rx.recv().unwrap();
529 RunningTest { join_handle }.join(&mut completed_test);
530
531 let event = TestEvent::TeResult(completed_test);
532 notify_about_test_event(event)?;
533 }
534 }
535 Ok(())
536}
537
538pub fn filter_tests(opts: &TestOpts, tests: TestList) -> Vec<TestDescAndFn> {
539 let TestList { tests, order } = tests;
540 let mut filtered = tests;
541
542 if !opts.filters.is_empty() {
544 if opts.filter_exact && order == TestListOrder::Sorted {
545 filtered = filter_exact_match(filtered, &opts.filters);
555 } else {
556 filtered.retain(|test| {
557 let test_name = test.desc.name.as_slice();
558 opts.filters.iter().any(|filter| {
559 if opts.filter_exact {
560 test_name == filter.as_str()
561 } else {
562 test_name.contains(filter.as_str())
563 }
564 })
565 });
566 }
567 }
568
569 if !opts.skip.is_empty() {
574 filtered.retain(|test| {
575 let name = test.desc.name.as_slice();
576 !opts.skip.iter().any(|sf| {
577 if opts.filter_exact { name == sf.as_str() } else { name.contains(sf.as_str()) }
578 })
579 });
580 }
581
582 if opts.exclude_should_panic {
584 filtered.retain(|test| test.desc.should_panic == ShouldPanic::No);
585 }
586
587 match opts.run_ignored {
589 RunIgnored::Yes => {
590 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
591 }
592 RunIgnored::Only => {
593 filtered.retain(|test| test.desc.ignore);
594 filtered.iter_mut().for_each(|test| test.desc.ignore = false);
595 }
596 RunIgnored::No => {}
597 }
598
599 filtered
600}
601
602fn filter_exact_match(mut tests: Vec<TestDescAndFn>, filters: &[String]) -> Vec<TestDescAndFn> {
605 let mut indexes: Vec<usize> = filters
607 .iter()
608 .filter_map(|f| tests.binary_search_by(|t| t.desc.name.as_slice().cmp(f.as_str())).ok())
609 .collect();
610 indexes.sort_unstable();
611 indexes.dedup();
612
613 let mut result = Vec::with_capacity(indexes.len());
617 for &idx in indexes.iter().rev() {
618 result.push(tests.swap_remove(idx));
619 }
620 result.reverse();
623 result
624}
625
626pub fn convert_benchmarks_to_tests(tests: Vec<TestDescAndFn>) -> Vec<TestDescAndFn> {
627 tests
629 .into_iter()
630 .map(|x| {
631 let testfn = match x.testfn {
632 DynBenchFn(benchfn) => DynBenchAsTestFn(benchfn),
633 StaticBenchFn(benchfn) => StaticBenchAsTestFn(benchfn),
634 f => f,
635 };
636 TestDescAndFn { desc: x.desc, testfn }
637 })
638 .collect()
639}
640
641pub fn run_test(
642 opts: &TestOpts,
643 force_ignore: bool,
644 id: TestId,
645 test: TestDescAndFn,
646 strategy: RunStrategy,
647 monitor_ch: Sender<CompletedTest>,
648) -> Option<thread::JoinHandle<()>> {
649 let TestDescAndFn { desc, testfn } = test;
650
651 let ignore_because_no_process_support = desc.should_panic != ShouldPanic::No
653 && (cfg!(target_family = "wasm") || cfg!(target_os = "zkvm"))
654 && !cfg!(target_os = "emscripten");
655
656 if force_ignore || desc.ignore || ignore_because_no_process_support {
657 let message = CompletedTest::new(id, desc, TrIgnored, None, Vec::new());
658 monitor_ch.send(message).unwrap();
659 return None;
660 }
661
662 match testfn.into_runnable() {
663 Runnable::Test(runnable_test) => {
664 if runnable_test.is_dynamic() {
665 match strategy {
666 RunStrategy::InProcess => (),
667 _ => panic!("Cannot run dynamic test fn out-of-process"),
668 };
669 }
670
671 let name = desc.name.clone();
672 let nocapture = opts.nocapture;
673 let time_options = opts.time_options;
674 let bench_benchmarks = opts.bench_benchmarks;
675
676 let runtest = move || match strategy {
677 RunStrategy::InProcess => run_test_in_process(
678 id,
679 desc,
680 nocapture,
681 time_options.is_some(),
682 runnable_test,
683 monitor_ch,
684 time_options,
685 ),
686 RunStrategy::SpawnPrimary => spawn_test_subprocess(
687 id,
688 desc,
689 nocapture,
690 time_options.is_some(),
691 monitor_ch,
692 time_options,
693 bench_benchmarks,
694 ),
695 };
696
697 let supports_threads = !cfg!(target_os = "emscripten")
701 && !cfg!(target_family = "wasm")
702 && !cfg!(target_os = "zkvm");
703 if supports_threads {
704 let cfg = thread::Builder::new().name(name.as_slice().to_owned());
705 let mut runtest = Arc::new(Mutex::new(Some(runtest)));
706 let runtest2 = runtest.clone();
707 match cfg.spawn(move || runtest2.lock().unwrap().take().unwrap()()) {
708 Ok(handle) => Some(handle),
709 Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
710 Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()();
713 None
714 }
715 Err(e) => panic!("failed to spawn thread to run test: {e}"),
716 }
717 } else {
718 runtest();
719 None
720 }
721 }
722 Runnable::Bench(runnable_bench) => {
723 runnable_bench.run(id, &desc, &monitor_ch, opts.nocapture);
725 None
726 }
727 }
728}
729
730#[inline(never)]
732fn __rust_begin_short_backtrace<T, F: FnOnce() -> T>(f: F) -> T {
733 let result = f();
734
735 black_box(result)
737}
738
739fn run_test_in_process(
740 id: TestId,
741 desc: TestDesc,
742 nocapture: bool,
743 report_time: bool,
744 runnable_test: RunnableTest,
745 monitor_ch: Sender<CompletedTest>,
746 time_opts: Option<time::TestTimeOptions>,
747) {
748 let data = Arc::new(Mutex::new(Vec::new()));
750
751 if !nocapture {
752 io::set_output_capture(Some(data.clone()));
753 }
754
755 let start = report_time.then(Instant::now);
756 let result = fold_err(catch_unwind(AssertUnwindSafe(|| runnable_test.run())));
757 let exec_time = start.map(|start| {
758 let duration = start.elapsed();
759 TestExecTime(duration)
760 });
761
762 io::set_output_capture(None);
763
764 let test_result =
768 calc_result(&desc, result.err().as_deref(), time_opts.as_ref(), exec_time.as_ref());
769 let stdout = data.lock().unwrap_or_else(|e| e.into_inner()).to_vec();
770 let message = CompletedTest::new(id, desc, test_result, exec_time, stdout);
771 monitor_ch.send(message).unwrap();
772}
773
774fn fold_err<T, E>(
775 result: Result<Result<T, E>, Box<dyn Any + Send>>,
776) -> Result<T, Box<dyn Any + Send>>
777where
778 E: Send + 'static,
779{
780 match result {
781 Ok(Err(e)) => Err(Box::new(e)),
782 Ok(Ok(v)) => Ok(v),
783 Err(e) => Err(e),
784 }
785}
786
787fn spawn_test_subprocess(
788 id: TestId,
789 desc: TestDesc,
790 nocapture: bool,
791 report_time: bool,
792 monitor_ch: Sender<CompletedTest>,
793 time_opts: Option<time::TestTimeOptions>,
794 bench_benchmarks: bool,
795) {
796 let (result, test_output, exec_time) = (|| {
797 let args = env::args().collect::<Vec<_>>();
798 let current_exe = &args[0];
799
800 let mut command = Command::new(current_exe);
801 command.env(SECONDARY_TEST_INVOKER_VAR, desc.name.as_slice());
802 if bench_benchmarks {
803 command.env(SECONDARY_TEST_BENCH_BENCHMARKS_VAR, "1");
804 }
805 if nocapture {
806 command.stdout(process::Stdio::inherit());
807 command.stderr(process::Stdio::inherit());
808 }
809
810 let start = report_time.then(Instant::now);
811 let output = match command.output() {
812 Ok(out) => out,
813 Err(e) => {
814 let err = format!("Failed to spawn {} as child for test: {:?}", args[0], e);
815 return (TrFailed, err.into_bytes(), None);
816 }
817 };
818 let exec_time = start.map(|start| {
819 let duration = start.elapsed();
820 TestExecTime(duration)
821 });
822
823 let std::process::Output { stdout, stderr, status } = output;
824 let mut test_output = stdout;
825 formatters::write_stderr_delimiter(&mut test_output, &desc.name);
826 test_output.extend_from_slice(&stderr);
827
828 let result =
829 get_result_from_exit_code(&desc, status, time_opts.as_ref(), exec_time.as_ref());
830 (result, test_output, exec_time)
831 })();
832
833 let message = CompletedTest::new(id, desc, result, exec_time, test_output);
834 monitor_ch.send(message).unwrap();
835}
836
837fn run_test_in_spawned_subprocess(desc: TestDesc, runnable_test: RunnableTest) -> ! {
838 let builtin_panic_hook = panic::take_hook();
839 let record_result = Arc::new(move |panic_info: Option<&'_ PanicHookInfo<'_>>| {
840 let test_result = calc_result(&desc, panic_info.map(|info| info.payload()), None, None);
841
842 if let TrFailedMsg(msg) = &test_result {
845 eprintln!("{msg}");
846 }
847
848 if let Some(info) = panic_info {
849 builtin_panic_hook(info);
850 }
851
852 if let TrOk = test_result {
853 process::exit(test_result::TR_OK);
854 } else {
855 process::abort();
856 }
857 });
858 let record_result2 = record_result.clone();
859 panic::set_hook(Box::new(move |info| record_result2(Some(info))));
860 if let Err(message) = runnable_test.run() {
861 panic!("{}", message);
862 }
863 record_result(None);
864 unreachable!("panic=abort callback should have exited the process")
865}