use crate::error::{chain, first_os_code, io_said, said, ChildFate, Error, Failures, QuoteError, QuoteErrorKind};
use crate::test_child::over_fake::exited_unreaped;
use std::sync::Arc;
#[skuld::test]
fn containment_error_displays_detail() {
let e = Error::Containment {
detail: "cgroup leaf not writable".into(),
source: None,
};
assert!(e.to_string().contains("cgroup leaf not writable"), "{e}");
}
#[skuld::test]
fn no_console_error_names_the_cause() {
let e = Error::NoConsole {
detail: "CTRL_BREAK to group 1234".into(),
};
let s = e.to_string();
assert!(s.contains("no attached console"), "{s}");
assert!(s.contains("CTRL_BREAK to group 1234"), "{s}");
assert!(matches!(e, Error::NoConsole { .. }));
}
#[skuld::test]
fn quote_error_displays_kind_and_offset() {
let e = QuoteError::new(7, QuoteErrorKind::UnterminatedSingleQuote);
assert_eq!(e.to_string(), "unterminated single quote at offset 7");
}
#[skuld::test]
fn quote_error_kinds_have_distinct_messages() {
assert_eq!(
QuoteErrorKind::UnterminatedDoubleQuote.to_string(),
"unterminated double quote"
);
assert_eq!(QuoteErrorKind::TrailingBackslash.to_string(), "trailing backslash");
assert_eq!(QuoteErrorKind::NonUtf8.to_string(), "not valid UTF-8");
assert_eq!(
QuoteErrorKind::UnrepresentableChar.to_string(),
"character cannot be represented in this grammar"
);
let all = [
QuoteErrorKind::UnterminatedSingleQuote,
QuoteErrorKind::UnterminatedDoubleQuote,
QuoteErrorKind::TrailingBackslash,
QuoteErrorKind::NonUtf8,
QuoteErrorKind::UnrepresentableChar,
];
for (i, a) in all.iter().enumerate() {
for b in &all[i + 1..] {
assert_ne!(a.to_string(), b.to_string(), "{a:?} vs {b:?}");
}
}
}
#[skuld::test]
fn error_wraps_quote_error_via_from() {
let e: Error = QuoteError::new(0, QuoteErrorKind::TrailingBackslash).into();
assert!(matches!(e, Error::Quote(_)));
assert_eq!(e.to_string(), "argument parsing failed");
assert_eq!(said(&e), "argument parsing failed: trailing backslash at offset 0");
}
#[skuld::test]
fn unsupported_displays_op_platform_and_detail() {
let e = Error::Unsupported {
op: "fd 3".into(),
platform: "windows",
detail: "arbitrary fds require the raw backend".into(),
source: None,
};
let s = e.to_string();
assert!(s.contains("fd 3"), "{s}");
assert!(s.contains("windows"), "{s}");
assert!(s.contains("raw backend"), "{s}");
}
#[skuld::test]
fn elevation_error_displays_kind_and_detail() {
use crate::error::ElevationErrorKind;
let e = Error::Elevation {
kind: ElevationErrorKind::NoTty,
detail: "interactive auth requested with no controlling terminal".into(),
source: None,
};
let s = e.to_string();
assert!(s.contains("no controlling terminal"), "{s}");
assert!(matches!(
e,
Error::Elevation {
kind: ElevationErrorKind::NoTty,
..
}
));
}
#[skuld::test]
fn command_too_long_names_the_host_not_the_platform() {
let m = crate::error::ElevationErrorKind::CommandTooLong.to_string();
assert_eq!(m, "the elevation command is too long for this host");
}
#[skuld::test]
fn elevation_error_kinds_have_distinct_messages() {
use crate::error::ElevationErrorKind::*;
let all = [
BackendUnavailable,
AuthFailed,
AuthDeclined,
NoTty,
Unkillable,
Untracked,
CommandTooLong,
];
for (i, a) in all.iter().enumerate() {
for b in &all[i + 1..] {
assert_ne!(a.to_string(), b.to_string(), "{a:?} vs {b:?}");
}
}
}
#[skuld::test]
fn untracked_message_does_not_assert_termination() {
use crate::error::ElevationErrorKind::Untracked;
let s = Untracked.to_string();
assert!(
!s.contains("terminated"),
"Untracked Display must not claim termination: {s}"
);
}
#[skuld::test]
fn unkillable_message_is_about_the_failed_signal_not_the_childs_fate() {
use crate::error::ElevationErrorKind::Unkillable;
let s = Unkillable.to_string();
assert!(
!s.contains("terminated"),
"Unkillable Display must not claim termination: {s}"
);
assert!(
s.contains("terminate") || s.contains("signal") || s.contains("kill"),
"{s}"
);
}
#[skuld::test]
fn unassessable_reads_as_a_refusal_not_a_failure() {
let e = crate::error::Error::Unassessable {
detail: "pid 4 could not be opened".into(),
source: Some(Arc::new(Error::Io(std::io::Error::from(
std::io::ErrorKind::PermissionDenied,
)))),
};
let s = e.to_string();
assert!(
s.contains("could not determine"),
"must not read as a failure of the target: {s}"
);
assert!(s.contains("pid 4 could not be opened"), "detail must survive: {s}");
assert!(std::error::Error::source(&e).is_some(), "source is preserved");
}
#[skuld::test]
fn unassessable_carries_no_source_when_there_is_no_os_error() {
let e = crate::error::Error::Unassessable {
detail: "identity could not be confirmed".into(),
source: None,
};
assert!(std::error::Error::source(&e).is_none());
}
#[skuld::test]
fn io_context_keeps_the_os_error_as_its_source() {
let code = if cfg!(windows) { 5 } else { 13 };
let e = crate::error::io_context("could not check C:\\t.exe", std::io::Error::from_raw_os_error(code));
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(e.to_string(), "could not check C:\\t.exe");
let source = std::error::Error::source(e.get_ref().expect("a custom error"))
.and_then(|s| s.downcast_ref::<std::io::Error>())
.expect("the OS error is the source");
assert_eq!(source.raw_os_error(), Some(code));
}
#[skuld::test]
fn a_shared_io_context_cause_reports_as_the_original_and_keeps_its_code() {
let code = if cfg!(windows) { 5 } else { 13 };
let shared = Arc::new(crate::error::io_context("w", std::io::Error::from_raw_os_error(code)));
let handed = crate::error::shared_io(&shared);
assert_eq!(said(&handed), said(&*shared));
assert_eq!(first_os_code(&handed), Some(code));
assert_eq!(handed.kind(), shared.kind());
}
#[skuld::test]
fn a_shared_bare_os_error_is_handed_out_with_its_raw_code() {
let code = if cfg!(windows) { 5 } else { 13 };
let shared = Arc::new(std::io::Error::from_raw_os_error(code));
let handed = crate::error::shared_io(&shared);
assert_eq!(handed.raw_os_error(), Some(code));
assert_eq!(handed.kind(), shared.kind());
}
#[skuld::test]
fn a_shared_wrapped_io_error_reports_as_the_original() {
let code = if cfg!(windows) { 5 } else { 13 };
let os = || std::io::Error::from_raw_os_error(code);
let timed_out = || std::io::Error::new(std::io::ErrorKind::TimedOut, "ran out");
let ctx = crate::error::io_context;
let note = |e: std::io::Error| Error::Io(e).with_note("n").into_io();
let originals = [
("a note", note(os()), Some(code)),
("a context and a note", note(ctx("w", os())), Some(code)),
("two contexts", ctx("outer", ctx("w", os())), Some(code)),
("a note and a context", ctx("w", note(os())), Some(code)),
("two notes", note(note(os())), Some(code)),
("no code, plain", timed_out(), None),
("no code, a context", ctx("w", timed_out()), None),
("no code, a note", note(timed_out()), None),
];
for (what, original, expected) in originals {
let shared = Arc::new(original);
let handed = crate::error::shared_io(&shared);
assert_eq!(said(&handed), said(&*shared), "{what}");
assert_eq!(first_os_code(&handed), expected, "{what}");
assert_eq!(handed.kind(), shared.kind(), "{what}");
}
}
#[skuld::test]
fn first_os_code_walks_an_error_io_to_the_first_os_code() {
let code = if cfg!(windows) { 5 } else { 13 };
let os = || std::io::Error::from_raw_os_error(code);
let context = || crate::error::io_context("pidfd_open", os());
assert_eq!(first_os_code(&Error::Io(os())), Some(code), "bare");
assert_eq!(first_os_code(&Error::Io(context())), Some(code), "io_context");
assert_eq!(
first_os_code(&Error::Io(os()).with_note("while tearing down")),
Some(code),
"a note"
);
assert_eq!(
first_os_code(&Error::Io(context()).with_note("while tearing down")),
Some(code),
"io_context and a note"
);
assert_eq!(
first_os_code(&Error::Io(std::io::Error::other("no code"))),
None,
"no code anywhere"
);
assert_eq!(
first_os_code(&Error::Containment {
detail: "d".into(),
source: None
}),
None,
"a variant with no cause"
);
}
#[skuld::test]
fn first_os_code_walks_the_chain_of_any_variant() {
let code = if cfg!(windows) { 5 } else { 13 };
let os = || Arc::new(Error::Io(std::io::Error::from_raw_os_error(code)));
let context = || {
Arc::new(Error::Io(crate::error::io_context(
"pidfd_open",
std::io::Error::from_raw_os_error(code),
)))
};
let unassessable = Error::Unassessable {
detail: "d".into(),
source: Some(os()),
};
assert_eq!(first_os_code(&unassessable), Some(code), "Unassessable");
let leader = Error::NotThreadGroupLeader {
pid: 1,
detail: "d".into(),
source: context(),
};
assert_eq!(
first_os_code(&leader),
Some(code),
"NotThreadGroupLeader, under io_context"
);
let record = Error::IdentityRecord {
kind: crate::error::RecordErrorKind::ScopeUnreadable,
detail: "d".into(),
source: Some(os()),
};
assert_eq!(first_os_code(&record), Some(code), "IdentityRecord");
let containment = Error::Containment {
detail: "d".into(),
source: Some(os()),
};
assert_eq!(first_os_code(&containment), Some(code), "Containment");
let unsupported = Error::Unsupported {
op: "op".into(),
platform: "p",
detail: "d".into(),
source: Some(os()),
};
assert_eq!(first_os_code(&unsupported), Some(code), "Unsupported");
let elevation = Error::Elevation {
kind: crate::error::ElevationErrorKind::AuthFailed,
detail: "d".into(),
source: Some(os()),
};
assert_eq!(first_os_code(&elevation), Some(code), "Elevation");
let member = Error::MemberNotKilled {
pid: 1,
source: Arc::new(Error::Unassessable {
detail: "d".into(),
source: Some(os()),
}),
};
assert_eq!(first_os_code(&member), Some(code), "through two causes");
let no_code = Error::Unassessable {
detail: "d".into(),
source: Some(Arc::new(Error::Io(std::io::Error::other("no code")))),
};
assert_eq!(first_os_code(&no_code), None, "no code anywhere");
}
#[skuld::test]
fn an_error_io_over_io_context_has_the_code_one_io_error_down() {
let code = if cfg!(windows) { 5 } else { 13 };
let e = Error::Io(crate::error::io_context(
"could not check C:\\t.exe",
std::io::Error::from_raw_os_error(code),
));
assert_eq!(codes_down(&e), [None, Some(code)]);
}
#[skuld::test]
fn a_noted_error_io_has_the_code_one_io_error_down() {
let code = if cfg!(windows) { 5 } else { 13 };
let e = Error::Io(std::io::Error::from_raw_os_error(code)).with_note("while tearing down");
assert_eq!(codes_down(&e), [None, Some(code)]);
}
#[skuld::test]
fn a_note_on_a_context_error_io_has_the_code_under_both_wrappers() {
let code = if cfg!(windows) { 5 } else { 13 };
let e = Error::Io(crate::error::io_context(
"pidfd_open",
std::io::Error::from_raw_os_error(code),
))
.with_note("while tearing down");
assert_eq!(codes_down(&e), [None, None, Some(code)]);
}
#[skuld::test]
fn io_errors_of_any_variant_lists_the_io_errors_of_its_chain() {
let code = if cfg!(windows) { 5 } else { 13 };
let os = || std::io::Error::from_raw_os_error(code);
let leader = Error::NotThreadGroupLeader {
pid: 1,
detail: "d".into(),
source: Arc::new(Error::Io(os())),
};
assert!(
chain(&leader).any(|layer| layer.is::<std::io::Error>()),
"the chain holds an io::Error"
);
assert_eq!(codes_down(&leader), [Some(code)]);
let member = Error::MemberNotKilled {
pid: 1,
source: Arc::new(Error::Io(os())),
};
assert_eq!(codes_down(&member), [Some(code)]);
let bare = Error::Containment {
detail: "d".into(),
source: None,
};
assert_eq!(codes_down(&bare), []);
}
#[cfg(unix)]
#[skuld::test]
fn with_note_keeps_each_variant_and_appends() {
use crate::error::{ElevationErrorKind, RecordErrorKind};
let os = || std::io::Error::from_raw_os_error(libc::EACCES);
let cause = || Arc::new(Error::Io(os()));
let note = "left running";
let noted = Error::Io(os()).with_note(note);
assert_eq!(
first_os_code(¬ed),
Some(libc::EACCES),
"the original is below the note"
);
let Error::Io(io) = noted else {
panic!("an Io error stays Io");
};
assert_eq!(io.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(io.to_string(), "left running", "the note is a layer above the cause");
let e = Error::Unsupported {
op: "op".into(),
platform: "linux",
detail: "d".into(),
source: Some(cause()),
}
.with_note(note);
assert!(
matches!(&e, Error::Unsupported { op, platform: "linux", detail, .. } if op == "op" && detail == "d; left running")
);
assert_eq!(first_os_code(&e), Some(libc::EACCES));
let e = Error::Containment {
detail: "d".into(),
source: Some(cause()),
}
.with_note(note);
assert!(matches!(&e, Error::Containment { detail, .. } if detail == "d; left running"));
assert_eq!(first_os_code(&e), Some(libc::EACCES));
let e = Error::NoConsole { detail: "d".into() }.with_note(note);
assert!(matches!(&e, Error::NoConsole { detail } if detail == "d; left running"));
let e = Error::Elevation {
kind: ElevationErrorKind::AuthFailed,
detail: "d".into(),
source: Some(cause()),
}
.with_note(note);
assert!(matches!(
&e,
Error::Elevation { kind: ElevationErrorKind::AuthFailed, detail, .. } if detail == "d; left running"
));
assert_eq!(first_os_code(&e), Some(libc::EACCES));
let e = Error::Unassessable {
detail: "d".into(),
source: Some(cause()),
}
.with_note(note);
assert!(matches!(&e, Error::Unassessable { detail, .. } if detail == "d; left running"));
assert_eq!(first_os_code(&e), Some(libc::EACCES));
let e = Error::NotThreadGroupLeader {
pid: 7,
detail: "d".into(),
source: cause(),
}
.with_note(note);
assert!(matches!(&e, Error::NotThreadGroupLeader { pid: 7, detail, .. } if detail == "d; left running"));
assert_eq!(first_os_code(&e), Some(libc::EACCES));
let e = Error::IdentityRecord {
kind: RecordErrorKind::ForeignPlatform,
detail: "d".into(),
source: Some(cause()),
}
.with_note(note);
assert!(matches!(
&e,
Error::IdentityRecord { kind: RecordErrorKind::ForeignPlatform, detail, .. } if detail == "d; left running"
));
assert_eq!(first_os_code(&e), Some(libc::EACCES));
}
#[skuld::test]
fn the_elevated_program_note_is_for_a_wrapper_elevated_spawn_only() {
let note = "an elevated program behind it may still run";
let message = |fate: ChildFate, wrapper_elevated: bool| {
Error::MayHaveStarted {
fate,
wrapper_elevated,
detail: None,
source: Arc::new(Error::Io(std::io::Error::other("cause"))),
unreaped: None,
cleanup: None,
}
.to_string()
};
for fate in [ChildFate::Reaped, ChildFate::Killed, ChildFate::Gone] {
assert!(!message(fate, false).contains(note), "{fate:?}, not wrapper-elevated");
assert!(message(fate, true).contains(note), "{fate:?}, wrapper-elevated");
}
for fate in [ChildFate::Running { id: None }, ChildFate::Unknown] {
assert!(!message(fate, true).contains(note), "{fate:?}");
}
}
#[skuld::test]
fn an_error_with_an_unreaped_child_still_reports_its_fate_and_message() {
let id = crate::identity::ProcessId::current();
let fate = ChildFate::Running { id: Some(id) };
let error = |unreaped| Error::MayHaveStarted {
fate,
wrapper_elevated: false,
detail: None,
source: Arc::new(Error::Io(std::io::Error::other("cause"))),
unreaped,
cleanup: None,
};
let with_child = error(Some(exited_unreaped(id)));
assert_eq!(with_child.fate(), Some(fate));
assert_eq!(with_child.to_string(), error(None).to_string());
}
#[skuld::test]
fn with_note_keeps_the_unreaped_child_and_extends_the_detail() {
let id = crate::identity::ProcessId::current();
let error = Error::MayHaveStarted {
fate: ChildFate::Running { id: Some(id) },
wrapper_elevated: false,
detail: Some("it was left".into()),
source: Arc::new(Error::Containment {
detail: "x".into(),
source: None,
}),
unreaped: Some(exited_unreaped(id)),
cleanup: Some(failures_of([coded(CODES[0])])),
}
.with_note("front left");
let Error::MayHaveStarted {
detail,
source,
unreaped,
cleanup,
..
} = &error
else {
panic!("expected MayHaveStarted, got {error:?}");
};
assert_eq!(unreaped.as_ref().map(|child| child.pid()), Some(Some(id.pid())));
assert_eq!(cleanup.as_ref().map(codes_of), Some(vec![Some(CODES[0])]));
assert_eq!(detail.as_deref(), Some("it was left; front left"));
assert!(
matches!(**source, Error::Containment { ref detail, .. } if detail == "x"),
"{source:?}"
);
}
#[cfg(windows)]
#[skuld::test]
fn win32_io_error_unwraps_a_win32_hresult() {
use crate::error::win32_io_error;
use windows::core::{Error, HRESULT};
let dir = win32_io_error(Error::from_hresult(HRESULT(0x8007_010Bu32 as i32)));
assert_eq!(dir.raw_os_error(), Some(267));
assert_eq!(dir.kind(), std::io::ErrorKind::NotADirectory);
let e_fail = win32_io_error(Error::from_hresult(HRESULT(0x8000_4005u32 as i32)));
assert_eq!(e_fail.raw_os_error(), Some(0x8000_4005u32 as i32));
}
#[cfg(windows)]
#[skuld::test]
fn nt_io_error_maps_a_status_to_its_win32_code() {
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, STATUS_ACCESS_DENIED};
let e = crate::error::nt_io_error(STATUS_ACCESS_DENIED);
assert_eq!(e.raw_os_error(), Some(ERROR_ACCESS_DENIED.0 as i32));
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
}
#[cfg(windows)]
#[skuld::test]
fn nt_io_error_logs_a_status_with_no_win32_code() {
use windows::Win32::Foundation::{ERROR_MR_MID_NOT_FOUND, NTSTATUS};
crate::log_capture::install();
let mark = crate::log_capture::mark();
let e = crate::error::nt_io_error(NTSTATUS(0xC0FF_EE01u32 as i32));
assert_eq!(e.raw_os_error(), Some(ERROR_MR_MID_NOT_FOUND.0 as i32));
let levels = crate::log_capture::levels_since(mark, "0xc0ffee01");
assert_eq!(levels, [log::Level::Debug], "one debug record names the status");
}
#[skuld::test]
fn io_error_source_is_the_wrapped_io_error() {
let e = Error::Io(std::io::Error::from_raw_os_error(13));
let source = std::error::Error::source(&e).expect("Error::Io has a source");
let io = source
.downcast_ref::<std::io::Error>()
.expect("the source is the io::Error");
assert_eq!(io.raw_os_error(), Some(13));
}
#[skuld::test]
fn an_error_io_says_its_own_words_and_the_io_error_is_its_source() {
let e = Error::Io(std::io::Error::other("disk on fire"));
assert_eq!(e.to_string(), "an I/O operation failed");
assert_eq!(said(&e), "an I/O operation failed: disk on fire");
let source = std::error::Error::source(&e).expect("the io::Error");
assert_eq!(source.to_string(), "disk on fire");
assert!(source.is::<std::io::Error>(), "the source is the io::Error itself");
}
#[skuld::test]
fn an_io_context_says_only_its_context() {
let e = crate::error::io_context("could not check x", std::io::Error::from_raw_os_error(CODES[0]));
assert_eq!(e.to_string(), "could not check x");
assert_eq!(said(&e), format!("could not check x: {}", os_text(CODES[0])));
}
#[skuld::test]
fn a_note_on_an_error_io_is_a_context_above_the_cause() {
let e = Error::Io(std::io::Error::from_raw_os_error(CODES[0])).with_note("while tearing down");
assert_eq!(said(&e), io_said(format!("while tearing down: {}", os_text(CODES[0]))));
assert_eq!(first_os_code(&e), Some(CODES[0]));
}
#[skuld::test]
fn a_wrapper_says_its_own_words_and_not_its_causes() {
let quote = Error::Quote(QuoteError::new(3, QuoteErrorKind::UnterminatedDoubleQuote));
assert_eq!(quote.to_string(), "argument parsing failed");
let source = std::error::Error::source("e).expect("the quote error");
assert_eq!(source.to_string(), "unterminated double quote at offset 3");
let member = Error::MemberNotKilled {
pid: 7,
source: coded(CODES[0]),
};
assert_eq!(member.to_string(), "pid 7 was not killed");
let started = |wrapper_elevated, cleanup| Error::MayHaveStarted {
fate: ChildFate::Killed,
wrapper_elevated,
detail: None,
source: coded(CODES[0]),
unreaped: None,
cleanup,
};
assert_eq!(
started(false, None).to_string(),
"the program may have started, and its child was killed, its exit not collected"
);
assert_eq!(
started(true, None).to_string(),
"the program may have started, and its child was killed, its exit not collected \
(an elevated program behind it may still run)"
);
assert_eq!(
started(false, Some(failures_of([coded(CODES[1])]))).to_string(),
"the program may have started, and its child was killed, its exit not collected; \
its teardown failed too (1 failure, in `cleanup`)"
);
}
#[skuld::test]
fn a_may_have_started_says_its_detail_in_its_own_words_above_its_cause() {
let started = |cause: Error, cleanup| Error::MayHaveStarted {
fate: ChildFate::Running { id: None },
wrapper_elevated: false,
detail: Some("it was sent nothing, so the elevated program may be running".into()),
source: Arc::new(cause),
unreaped: None,
cleanup,
};
let own = "the program may have started, and its child may still be running; \
it was sent nothing, so the elevated program may be running";
let io = started(Error::Io(std::io::Error::other("Broken pipe")), None);
assert_eq!(io.to_string(), own);
assert_eq!(said(&io), format!("{own}: {}", io_said("Broken pipe")));
let unassessable = started(
Error::Unassessable {
detail: "reading pid 7".into(),
source: None,
},
None,
);
assert_eq!(unassessable.to_string(), own);
assert_eq!(
said(&unassessable),
format!("{own}: could not determine the target process's state: reading pid 7")
);
let torn = started(
Error::Io(std::io::Error::other("Broken pipe")),
Some(failures_of([coded(CODES[1])])),
);
assert_eq!(
torn.to_string(),
format!("{own}; its teardown failed too (1 failure, in `cleanup`)")
);
}
fn codes_down(e: &Error) -> Vec<Option<i32>> {
e.io_errors().map(std::io::Error::raw_os_error).collect()
}
#[derive(Debug)]
struct Layer(&'static str, Option<Box<Layer>>);
impl std::fmt::Display for Layer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for Layer {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.1.as_deref().map(|l| l as _)
}
}
#[skuld::test]
fn report_joins_every_layer_with_a_colon() {
let e = Layer(
"outer",
Some(Box::new(Layer("middle", Some(Box::new(Layer("inner", None)))))),
);
assert_eq!(said(&e), "outer: middle: inner");
}
#[skuld::test]
fn report_keeps_a_layer_whose_display_is_empty() {
let e = Layer("outer", Some(Box::new(Layer("", Some(Box::new(Layer("inner", None)))))));
assert_eq!(said(&e), "outer: : inner");
}
#[derive(Debug)]
struct Holder(&'static str, Arc<Error>);
impl std::fmt::Display for Holder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for Holder {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.1)
}
}
#[skuld::test]
fn report_of_a_list_behind_an_arc_layer_prints_every_member() {
let [a, b] = [coded_text(CODES[0]), coded_text(CODES[1])];
let holder = Holder("holder", Arc::new(several(&[CODES[0], CODES[1]])));
assert_eq!(said(&holder), format!("holder: 2 failures: (1) {a}; (2) {b}"));
let started = Holder(
"holder",
Arc::new(may_have_started(coded(CODES[0]), Some(failures_of([coded(CODES[1])])))),
);
let words = started.1.to_string();
assert_eq!(said(&started), format!("holder: {words}: {a}; cleanup: [(1) {b}]"));
let left = Holder(
"holder",
Arc::new(Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0]))]),
others: Some(walk_not_made()),
}),
);
assert_eq!(
said(&left),
format!(
"holder: 1 member of the tree was left running: (1) pid 7 was not killed: {a}; \
others: could not determine the target process's state: the table could not be read"
)
);
}
#[derive(Debug)]
struct BoxHolder(&'static str, Box<Error>);
impl std::fmt::Display for BoxHolder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for BoxHolder {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.1)
}
}
#[skuld::test]
fn report_of_a_list_behind_a_box_layer_prints_its_display_and_source() {
let first = coded_text(CODES[0]);
let holder = BoxHolder("holder", Box::new(several(&[CODES[0], CODES[1]])));
assert_eq!(said(&holder), format!("holder: 2 failures: {first}"));
}
#[skuld::test]
fn report_of_a_leaf_is_its_display() {
let leaf = Error::Containment {
detail: "d".into(),
source: None,
};
assert_eq!(said(&leaf), leaf.to_string());
}
#[skuld::test]
fn report_of_an_io_error_with_context_prints_the_context_and_the_os_error() {
let code = if cfg!(windows) { 5 } else { 13 };
let os = std::io::Error::from_raw_os_error(code);
let os_text = os.to_string();
let e = Error::Io(crate::error::io_context("pidfd_open", os));
let report = said(&e);
assert_eq!(report, io_said(format!("pidfd_open: {os_text}")), "each layer once");
assert_eq!(first_os_code(&e), Some(code));
assert_eq!(
chain(&e).last().map(ToString::to_string),
Some(os_text),
"the last layer is the OS error"
);
}
const CODES: [i32; 3] = if cfg!(windows) { [5, 2, 3] } else { [13, 2, 1] };
fn os_text(code: i32) -> String {
std::io::Error::from_raw_os_error(code).to_string()
}
fn coded_text(code: i32) -> String {
io_said(os_text(code))
}
fn coded(code: i32) -> Arc<Error> {
Error::io_cause(std::io::Error::from_raw_os_error(code))
}
fn several(codes: &[i32]) -> Error {
Error::Several(failures_of(codes.iter().map(|&code| coded(code))))
}
fn failures_of(members: impl IntoIterator<Item = Arc<Error>>) -> Failures {
Failures::collect(members).expect("a member")
}
fn not_killed(pid: u32, source: Arc<Error>) -> Arc<Error> {
Arc::new(Error::MemberNotKilled { pid, source })
}
#[skuld::test]
fn failures_hold_their_members_in_order_with_the_count_from_iter() {
let members = failures_of(CODES.map(coded));
assert_eq!(members.iter().len(), 3);
assert!(Arc::ptr_eq(members.first(), members.iter().next().expect("a member")));
let codes: Vec<_> = members.iter().map(|m| first_os_code(&**m)).collect();
assert_eq!(codes, CODES.map(Some));
assert!(
Failures::collect(std::iter::empty()).is_none(),
"an empty list is not built"
);
}
#[skuld::test]
fn one_failure_is_its_own_cause_and_two_or_more_are_a_several() {
let one = coded(CODES[0]);
let cause = failures_of([Arc::clone(&one)]).into_cause();
assert!(Arc::ptr_eq(&cause, &one), "{cause:?}");
let cause = failures_of([coded(CODES[0]), coded(CODES[1])]).into_cause();
let Error::Several(members) = &*cause else {
panic!("expected Several, got {cause:?}");
};
assert_eq!(members.iter().len(), 2);
}
#[skuld::test]
fn a_several_says_its_count_and_its_source_is_the_first_member() {
let e = several(&CODES);
assert_eq!(e.to_string(), "3 failures");
let source = std::error::Error::source(&e)
.and_then(|source| source.downcast_ref::<Error>())
.expect("the first member");
let Error::Several(members) = &e else { unreachable!() };
assert!(std::ptr::eq(source, &**members.first()));
}
#[skuld::test]
fn members_left_says_its_count_and_its_source_is_the_first_member() {
let e = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0])), not_killed(9, coded(CODES[1]))]),
others: None,
};
assert_eq!(e.to_string(), "2 members of the tree were left running");
let source = std::error::Error::source(&e).expect("the first member");
assert!(
matches!(
source.downcast_ref::<Error>(),
Some(Error::MemberNotKilled { pid: 7, .. })
),
"{source:?}"
);
}
#[skuld::test]
fn members_left_counts_its_members_not_the_walk_that_was_not_made() {
let one = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0]))]),
others: Some(walk_not_made()),
};
assert_eq!(one.to_string(), "1 member of the tree was left running");
let two = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0])), not_killed(9, coded(CODES[1]))]),
others: Some(walk_not_made()),
};
assert_eq!(two.to_string(), "2 members of the tree were left running");
}
fn walk_not_made() -> Arc<Error> {
Arc::new(Error::Unassessable {
detail: "the table could not be read".into(),
source: None,
})
}
#[skuld::test]
fn the_os_code_of_a_compound_error_is_the_first_members() {
assert_eq!(first_os_code(&several(&[CODES[1], CODES[0]])), Some(CODES[1]));
let left = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[2])), not_killed(9, coded(CODES[0]))]),
others: None,
};
assert_eq!(first_os_code(&left), Some(CODES[2]));
let left = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[2]))]),
others: Some(walk_not_made()),
};
assert_eq!(first_os_code(&left), Some(CODES[2]));
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "is a MemberNotKilled"))]
fn a_members_left_of_an_error_that_is_no_member_is_a_contract_breach() {
let _ = Error::members_left(failures_of([walk_not_made()]), None);
}
#[skuld::test]
fn report_of_a_several_prints_every_members_chain() {
let [a, b] = [coded_text(CODES[0]), coded_text(CODES[1])];
assert_eq!(
said(&several(&[CODES[0], CODES[1]])),
format!("2 failures: (1) {a}; (2) {b}")
);
}
#[skuld::test]
fn report_of_members_left_prints_every_members_chain() {
let [a, b] = [coded_text(CODES[0]), coded_text(CODES[1])];
let left = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0])), not_killed(9, coded(CODES[1]))]),
others: None,
};
assert_eq!(
said(&left),
format!(
"2 members of the tree were left running: (1) pid 7 was not killed: {a}; \
(2) pid 9 was not killed: {b}"
)
);
}
#[skuld::test]
fn report_of_members_left_with_other_failures_prints_them_after_the_members() {
let [a, b] = [coded_text(CODES[0]), coded_text(CODES[1])];
let left = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0])), not_killed(9, coded(CODES[1]))]),
others: Some(walk_not_made()),
};
assert_eq!(
said(&left),
format!(
"2 members of the tree were left running: (1) pid 7 was not killed: {a}; \
(2) pid 9 was not killed: {b}; \
others: could not determine the target process's state: the table could not be read"
)
);
}
#[skuld::test]
fn report_of_a_list_in_a_member_brackets_the_inner_list() {
let [a, b, c] = CODES.map(coded_text);
let inner = Arc::new(several(&[CODES[0], CODES[1]]));
let left = Error::MembersLeft {
members: failures_of([not_killed(7, inner), not_killed(9, coded(CODES[2]))]),
others: None,
};
assert_eq!(
said(&left),
format!(
"2 members of the tree were left running: \
(1) pid 7 was not killed: 2 failures: [(1) {a}; (2) {b}]; \
(2) pid 9 was not killed: {c}"
)
);
}
#[skuld::test]
fn report_of_a_several_under_a_variant_prints_the_variant_then_every_member() {
let [a, b] = [coded_text(CODES[0]), coded_text(CODES[1])];
let e = Error::Unassessable {
detail: "d".into(),
source: Some(Arc::new(several(&[CODES[0], CODES[1]]))),
};
assert_eq!(
said(&e),
format!("could not determine the target process's state: d: 2 failures: (1) {a}; (2) {b}")
);
}
fn may_have_started(cause: Arc<Error>, cleanup: Option<Failures>) -> Error {
Error::MayHaveStarted {
fate: ChildFate::Reaped,
wrapper_elevated: false,
detail: None,
source: cause,
unreaped: None,
cleanup,
}
}
#[skuld::test]
fn report_of_a_may_have_started_without_cleanup_is_its_words_and_its_cause() {
let a = coded_text(CODES[0]);
let e = may_have_started(coded(CODES[0]), None);
assert_eq!(said(&e), format!("{e}: {a}"));
}
#[skuld::test]
fn report_of_a_may_have_started_prints_the_cause_then_every_cleanup_failure() {
let [a, b, c] = CODES.map(coded_text);
let e = may_have_started(coded(CODES[0]), Some(failures_of([coded(CODES[1]), coded(CODES[2])])));
assert_eq!(said(&e), format!("{e}: {a}; cleanup: [(1) {b}; (2) {c}]"));
}
#[skuld::test]
fn a_may_have_started_says_in_its_display_that_its_teardown_failed_too() {
assert_eq!(
may_have_started(coded(CODES[0]), None).to_string(),
"the program may have started, and its child was reaped"
);
let one = may_have_started(coded(CODES[0]), Some(failures_of([coded(CODES[1])])));
assert_eq!(
one.to_string(),
"the program may have started, and its child was reaped; its teardown failed too (1 failure, in `cleanup`)"
);
let two = may_have_started(coded(CODES[0]), Some(failures_of([coded(CODES[1]), coded(CODES[2])])));
assert_eq!(
two.to_string(),
"the program may have started, and its child was reaped; its teardown failed too (2 failures, in `cleanup`)"
);
}
#[skuld::test]
fn report_of_a_may_have_started_in_a_member_brackets_its_cause_and_cleanup() {
let [a, b, c] = CODES.map(coded_text);
let member = Arc::new(may_have_started(coded(CODES[0]), Some(failures_of([coded(CODES[1])]))));
let outer = Error::Several(failures_of([member.clone(), coded(CODES[2])]));
assert_eq!(
said(&outer),
format!("2 failures: (1) {member}: [{a}; cleanup: [(1) {b}]]; (2) {c}")
);
}
#[skuld::test]
fn report_of_a_may_have_started_brackets_a_list_in_its_cause() {
let [a, b, c] = CODES.map(coded_text);
let e = may_have_started(
Arc::new(several(&[CODES[0], CODES[1]])),
Some(failures_of([coded(CODES[2])])),
);
assert_eq!(
said(&e),
format!("{e}: 2 failures: [(1) {a}; (2) {b}]; cleanup: [(1) {c}]")
);
}
#[skuld::test]
fn a_may_have_started_with_cleanup_has_the_causes_os_code_first() {
let e = may_have_started(coded(CODES[0]), Some(failures_of([coded(CODES[1])])));
assert_eq!(first_os_code(&e), Some(CODES[0]));
let cleanup = e.failures().expect("the cleanup");
assert_eq!(codes_of(cleanup), [Some(CODES[1])]);
assert!(may_have_started(coded(CODES[0]), None).failures().is_none());
}
fn codes_of(list: &Failures) -> Vec<Option<i32>> {
list.iter().map(|member| first_os_code(&**member)).collect()
}
#[skuld::test]
fn peers_join_the_own_cause_in_a_several_under_the_same_variant() {
let e = Error::Unassessable {
detail: "d".into(),
source: Some(coded(CODES[0])),
}
.with_peers([coded(CODES[1]), coded(CODES[2])]);
let Error::Unassessable {
detail,
source: Some(source),
} = &e
else {
panic!("the variant is kept: {e:?}");
};
assert_eq!(detail, "d");
let Error::Several(list) = &**source else {
panic!("expected Several, got {source:?}");
};
assert_eq!(codes_of(list), CODES.map(Some));
assert_eq!(first_os_code(&e), Some(CODES[0]));
}
#[skuld::test]
fn one_peer_and_no_own_cause_makes_the_peer_the_cause() {
let e = Error::Containment {
detail: "d".into(),
source: None,
}
.with_peers([coded(CODES[1])]);
let Error::Containment {
source: Some(source), ..
} = &e
else {
panic!("{e:?}");
};
assert!(
matches!(&**source, Error::Io(io) if io.raw_os_error() == Some(CODES[1])),
"{source:?}"
);
}
#[skuld::test]
fn peers_join_a_member_not_killed_and_a_several() {
let e = Error::MemberNotKilled {
pid: 7,
source: coded(CODES[0]),
}
.with_peers([coded(CODES[1])]);
let Error::MemberNotKilled { pid: 7, source } = &e else {
panic!("{e:?}");
};
assert!(matches!(&**source, Error::Several(list) if codes_of(list) == [Some(CODES[0]), Some(CODES[1])]));
let e = several(&[CODES[0], CODES[1]]).with_peers([coded(CODES[2])]);
assert!(
matches!(&e, Error::Several(list) if codes_of(list) == CODES.map(Some)),
"{e:?}"
);
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "has no cause to hold peers"))]
fn with_peers_on_an_io_error_is_a_contract_breach() {
let _ = Error::Io(std::io::Error::from_raw_os_error(CODES[0])).with_peers([coded(CODES[1])]);
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "has no cause to hold peers"))]
fn with_peers_on_a_no_console_error_is_a_contract_breach() {
let _ = Error::NoConsole { detail: "d".into() }.with_peers([coded(CODES[1])]);
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "has no cause to hold peers"))]
fn with_peers_on_a_quote_error_is_a_contract_breach() {
let _ = Error::Quote(QuoteError::new(7, QuoteErrorKind::TrailingBackslash)).with_peers([coded(CODES[1])]);
}
#[skuld::test]
fn peers_of_members_left_join_its_others_and_not_its_members() {
let one_member = || failures_of([not_killed(7, coded(CODES[0]))]);
let e = Error::MembersLeft {
members: one_member(),
others: None,
}
.with_peers([coded(CODES[1])]);
let Error::MembersLeft { members, others } = &e else {
panic!("the variant is kept: {e:?}");
};
assert_eq!(members.iter().len(), 1);
assert!(
matches!(others.as_deref(), Some(Error::Io(io)) if io.raw_os_error() == Some(CODES[1])),
"{e:?}"
);
let e = Error::MembersLeft {
members: one_member(),
others: Some(walk_not_made()),
}
.with_peers([coded(CODES[1]), coded(CODES[2])]);
let Error::MembersLeft { members, others } = &e else {
panic!("the variant is kept: {e:?}");
};
assert_eq!(members.iter().len(), 1);
let Some(Error::Several(list)) = others.as_deref() else {
panic!("expected a Several of the three: {e:?}");
};
assert_eq!(list.iter().len(), 3);
assert!(
matches!(&**list.iter().last().expect("a member"), Error::Unassessable { .. }),
"{e:?}"
);
assert_eq!(first_os_code(&e), Some(CODES[0]), "the first member stays the source");
let e = Error::MembersLeft {
members: one_member(),
others: Some(Arc::new(Error::Several(failures_of([
walk_not_made(),
coded(CODES[0]),
])))),
}
.with_peers([coded(CODES[1]), coded(CODES[2])]);
let Error::MembersLeft { others, .. } = &e else {
panic!("the variant is kept: {e:?}");
};
let Some(Error::Several(list)) = others.as_deref() else {
panic!("expected a Several: {e:?}");
};
let shapes: Vec<_> = list
.iter()
.map(|member| match &**member {
Error::Io(io) => io.raw_os_error(),
Error::Unassessable { .. } => None,
other => panic!("a nested or unexpected member: {other:?}"),
})
.collect();
assert_eq!(shapes, [Some(CODES[1]), Some(CODES[2]), None, Some(CODES[0])], "{e:?}");
}
fn raw(code: i32) -> Error {
Error::Io(std::io::Error::from_raw_os_error(code))
}
#[skuld::test]
fn with_peers_or_warn_leaves_a_lone_failure_as_it_is() {
let e = raw(CODES[0]).with_peers_or_warn("the call", []);
assert!(
matches!(&e, Error::Io(io) if io.raw_os_error() == Some(CODES[0])),
"{e:?}"
);
}
#[skuld::test]
fn a_leaf_with_peers_stays_the_answer_and_each_peer_is_a_warn() {
crate::log_capture::install();
let leaves = [
raw(CODES[0]),
Error::NoConsole { detail: "d".into() },
Error::Quote(QuoteError::new(7, QuoteErrorKind::TrailingBackslash)),
];
for leaf in leaves {
let shown = leaf.to_string();
let mark = crate::log_capture::mark();
let e = leaf.with_peers_or_warn("the leaf call", [raw(CODES[1]), raw(CODES[2])]);
assert_eq!(e.to_string(), shown, "the answer is the leaf as it was: {e:?}");
let logged = crate::log_capture::records_since_on_current_thread(mark, "the leaf call");
assert!(
matches!(&logged[..], [(log::Level::Warn, a), (log::Level::Warn, b)]
if a.contains(&os_text(CODES[1])) && b.contains(&os_text(CODES[2]))),
"{shown}: {logged:?}"
);
}
}
#[skuld::test]
fn a_failure_with_a_slot_keeps_its_variant_and_takes_the_peers_below_it() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let e = Error::Containment {
detail: "d".into(),
source: None,
}
.with_peers_or_warn("the slot call", [raw(CODES[1])]);
assert!(
matches!(&e, Error::Containment { source: Some(s), .. }
if matches!(&**s, Error::Io(io) if io.raw_os_error() == Some(CODES[1]))),
"{e:?}"
);
assert!(crate::log_capture::records_since_on_current_thread(mark, "the slot call").is_empty());
}
#[skuld::test]
fn failures_below_unpacks_the_cause_of_a_slot_variant() {
let slot = |source| Error::Containment {
detail: "d".into(),
source,
};
assert!(slot(None).failures_below().is_empty());
let one = slot(Some(coded(CODES[0])));
assert_eq!(one.failures_below().len(), 1);
let two = slot(Some(Arc::new(several(&[CODES[0], CODES[1]]))));
let codes: Vec<_> = two.failures_below().into_iter().map(|e| first_os_code(e)).collect();
assert_eq!(codes, [Some(CODES[0]), Some(CODES[1])]);
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "never to a compound error"))]
fn with_note_on_a_several_is_a_contract_breach() {
let _ = several(&CODES).with_note("n");
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "never to a compound error"))]
fn with_note_on_members_left_is_a_contract_breach() {
let left = Error::MembersLeft {
members: failures_of([not_killed(7, coded(CODES[0]))]),
others: None,
};
let _ = left.with_note("n");
}
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "never to a compound error"))]
fn with_note_on_a_member_not_killed_is_a_contract_breach() {
let _ = Error::MemberNotKilled {
pid: 7,
source: coded(CODES[0]),
}
.with_note("n");
}