test/
test_result.rs

1use std::any::Any;
2#[cfg(unix)]
3use std::os::unix::process::ExitStatusExt;
4use std::process::ExitStatus;
5
6pub use self::TestResult::*;
7use super::bench::BenchSamples;
8use super::options::ShouldPanic;
9use super::time;
10use super::types::TestDesc;
11
12// Return code for secondary process.
13// Start somewhere other than 0 so we know the return code means what we think
14// it means.
15pub(crate) const TR_OK: i32 = 50;
16
17// On Windows we use __fastfail to abort, which is documented to use this
18// exception code.
19#[cfg(windows)]
20const STATUS_FAIL_FAST_EXCEPTION: i32 = 0xC0000409u32 as i32;
21
22// On Zircon (the Fuchsia kernel), an abort from userspace calls the
23// LLVM implementation of __builtin_trap(), e.g., ud2 on x86, which
24// raises a kernel exception. If a userspace process does not
25// otherwise arrange exception handling, the kernel kills the process
26// with this return code.
27#[cfg(target_os = "fuchsia")]
28const ZX_TASK_RETCODE_EXCEPTION_KILL: i32 = -1028;
29
30#[derive(Debug, Clone, PartialEq)]
31pub enum TestResult {
32    TrOk,
33    TrFailed,
34    TrFailedMsg(String),
35    TrIgnored,
36    TrBench(BenchSamples),
37    TrTimedFail,
38}
39
40/// Creates a `TestResult` depending on the raw result of test execution
41/// and associated data.
42pub(crate) fn calc_result(
43    desc: &TestDesc,
44    panic_payload: Option<&(dyn Any + Send)>,
45    time_opts: Option<&time::TestTimeOptions>,
46    exec_time: Option<&time::TestExecTime>,
47) -> TestResult {
48    let result = match (desc.should_panic, panic_payload) {
49        // The test did or didn't panic, as expected.
50        (ShouldPanic::No, None) | (ShouldPanic::Yes, Some(_)) => TestResult::TrOk,
51
52        // Check the actual panic message against the expected message.
53        (ShouldPanic::YesWithMessage(msg), Some(err)) => {
54            let maybe_panic_str = err
55                .downcast_ref::<String>()
56                .map(|e| &**e)
57                .or_else(|| err.downcast_ref::<&'static str>().copied());
58
59            if maybe_panic_str.map(|e| e.contains(msg)).unwrap_or(false) {
60                TestResult::TrOk
61            } else if let Some(panic_str) = maybe_panic_str {
62                TestResult::TrFailedMsg(format!(
63                    r#"panic did not contain expected string
64      panic message: `{panic_str:?}`,
65 expected substring: `{msg:?}`"#
66                ))
67            } else {
68                TestResult::TrFailedMsg(format!(
69                    r#"expected panic with string value,
70 found non-string value: `{:?}`
71     expected substring: `{:?}`"#,
72                    (*err).type_id(),
73                    msg
74                ))
75            }
76        }
77
78        // The test should have panicked, but didn't panic.
79        (ShouldPanic::Yes, None) | (ShouldPanic::YesWithMessage(_), None) => {
80            let fn_location = if !desc.source_file.is_empty() {
81                &format!(" at {}:{}:{}", desc.source_file, desc.start_line, desc.start_col)
82            } else {
83                ""
84            };
85            TestResult::TrFailedMsg(format!("test did not panic as expected{}", fn_location))
86        }
87
88        // The test should not have panicked, but did panic.
89        (ShouldPanic::No, Some(_)) => TestResult::TrFailed,
90    };
91
92    // If test is already failed (or allowed to fail), do not change the result.
93    if result != TestResult::TrOk {
94        return result;
95    }
96
97    // Check if test is failed due to timeout.
98    if let (Some(opts), Some(time)) = (time_opts, exec_time) {
99        if opts.error_on_excess && opts.is_critical(desc, time) {
100            return TestResult::TrTimedFail;
101        }
102    }
103
104    result
105}
106
107/// Creates a `TestResult` depending on the exit code of test subprocess.
108pub(crate) fn get_result_from_exit_code(
109    desc: &TestDesc,
110    status: ExitStatus,
111    time_opts: Option<&time::TestTimeOptions>,
112    exec_time: Option<&time::TestExecTime>,
113) -> TestResult {
114    let result = match status.code() {
115        Some(TR_OK) => TestResult::TrOk,
116        #[cfg(windows)]
117        Some(STATUS_FAIL_FAST_EXCEPTION) => TestResult::TrFailed,
118        #[cfg(unix)]
119        None => match status.signal() {
120            Some(libc::SIGABRT) => TestResult::TrFailed,
121            Some(signal) => {
122                TestResult::TrFailedMsg(format!("child process exited with signal {signal}"))
123            }
124            None => unreachable!("status.code() returned None but status.signal() was None"),
125        },
126        // Upon an abort, Fuchsia returns the status code ZX_TASK_RETCODE_EXCEPTION_KILL.
127        #[cfg(target_os = "fuchsia")]
128        Some(ZX_TASK_RETCODE_EXCEPTION_KILL) => TestResult::TrFailed,
129        #[cfg(not(unix))]
130        None => TestResult::TrFailedMsg(format!("unknown return code")),
131        #[cfg(any(windows, unix))]
132        Some(code) => TestResult::TrFailedMsg(format!("got unexpected return code {code}")),
133        #[cfg(not(any(windows, unix)))]
134        Some(_) => TestResult::TrFailed,
135    };
136
137    // If test is already failed (or allowed to fail), do not change the result.
138    if result != TestResult::TrOk {
139        return result;
140    }
141
142    // Check if test is failed due to timeout.
143    if let (Some(opts), Some(time)) = (time_opts, exec_time) {
144        if opts.error_on_excess && opts.is_critical(desc, time) {
145            return TestResult::TrTimedFail;
146        }
147    }
148
149    result
150}