cosca 0.9.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
use super::{Classify, SpawnFailure};
use crate::child::drop_teardown::Torn;
use crate::error::{ChildFate, Error};
use crate::test_child::over_fake::exited_unreaped;

// Compile-fail shape, see the `failure` module doc.
static_assertions::assert_not_impl_any!(SpawnFailure: From<Error>, From<std::io::Error>);
static_assertions::assert_not_impl_any!(Result<(), SpawnFailure>: Classify<()>);
static_assertions::assert_impl_all!(Result<(), Error>: Classify<()>);
static_assertions::assert_impl_all!(Result<(), std::io::Error>: Classify<()>);

fn io(what: &str) -> Error {
    Error::Io(std::io::Error::other(what.to_string()))
}

/// Mutant: `From<SpawnFailure>` drops the answer, or the fate, of a may-have-started failure.
#[skuld::test]
fn a_may_have_started_failure_becomes_the_wrapping_variant() {
    let fate = ChildFate::Running {
        id: Some(crate::identity::ProcessId::current()),
    };
    let error = Error::from(SpawnFailure::started(io("attach"), fate, None));
    let Error::MayHaveStarted { fate: got, source, .. } = &error else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    assert_eq!(*got, fate);
    assert!(
        matches!(**source, Error::Io(ref e) if e.to_string() == "attach"),
        "{source:?}"
    );
    assert_eq!(error.fate(), Some(fate), "`fate` reads the wrapping variant");
    assert_eq!(
        Error::Io(std::io::Error::other("x")).fate(),
        None,
        "any other variant did not start"
    );
    let text = error.to_string();
    let pid = std::process::id();
    assert!(
        text.contains("may have started") && text.contains(&format!("pid {pid}")),
        "{text}"
    );
    assert!(
        std::error::Error::source(&error).is_some_and(|s| crate::error::said(s) == crate::error::io_said("attach")),
        "the cause is the source"
    );
}

/// Mutant: `From<SpawnFailure>` wraps a not-started failure.
#[skuld::test]
fn a_not_started_failure_is_its_cause_unchanged() {
    let error = Error::from(SpawnFailure::NotStarted(io("exec")));
    assert!(
        matches!(error, Error::Io(ref e) if e.to_string() == "exec"),
        "{error:?}"
    );
}

/// A cause that is itself a `MayHaveStarted` is a contract breach, and asserts in debug.
///
/// Mutant: `From<SpawnFailure>` wraps it again, or passes it through, without the assertion.
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "is itself `may have started`"))]
fn a_cause_that_is_itself_may_have_started_asserts() {
    let once = Error::from(SpawnFailure::started(io("identity"), ChildFate::Reaped, None));
    drop(Error::from(SpawnFailure::started(once, ChildFate::Unknown, None)));
}

/// `behind_front` sets the flag alone.
///
/// Mutant: `behind_front` drops the flag, changes the fate, or marks a not-started failure.
#[skuld::test]
fn behind_front_sets_the_flag_alone() {
    let marked = Error::from(SpawnFailure::started(io("attach"), ChildFate::Killed, None).behind_front());
    let Error::MayHaveStarted {
        fate,
        wrapper_elevated,
        source,
        ..
    } = &marked
    else {
        panic!("expected MayHaveStarted, got {marked:?}");
    };
    assert_eq!(*fate, ChildFate::Killed);
    assert!(*wrapper_elevated);
    assert!(
        matches!(**source, Error::Io(ref e) if e.to_string() == "attach"),
        "{source:?}"
    );
    let plain = Error::from(SpawnFailure::started(io("attach"), ChildFate::Killed, None));
    assert!(
        matches!(
            plain,
            Error::MayHaveStarted {
                wrapper_elevated: false,
                ..
            }
        ),
        "{plain:?}"
    );
    let not = Error::from(SpawnFailure::NotStarted(io("exec")).behind_front());
    assert!(matches!(not, Error::Io(_)), "{not:?}");
}

/// `after_the_spawn` keeps the cause, the fate and the wrapper flag.
///
/// Mutant: `after_the_spawn` drops the flag.
#[skuld::test]
fn after_the_spawn_keeps_the_cause_the_fate_and_the_wrapper_flag() {
    for wrapper in [false, true] {
        let error = super::after_the_spawn(io("wait"), Torn::left(ChildFate::Reaped), wrapper);
        let Error::MayHaveStarted {
            fate,
            wrapper_elevated,
            detail: None,
            source,
            unreaped: None,
            cleanup: None,
        } = &error
        else {
            panic!("expected MayHaveStarted around no child, got {error:?}");
        };
        assert_eq!(*fate, ChildFate::Reaped);
        assert_eq!(*wrapper_elevated, wrapper);
        assert!(
            matches!(**source, Error::Io(ref e) if e.to_string() == "wait"),
            "{source:?}"
        );
    }
}

/// A helper that hands its child back puts it in the error with a `Running` fate.
///
/// Mutant: `after_the_spawn` drops the child it is given.
#[skuld::test]
fn after_the_spawn_with_a_child_carries_it_with_a_running_fate() {
    let id = crate::identity::ProcessId::current();
    let running = ChildFate::Running { id: Some(id) };
    for wrapper in [false, true] {
        let torn = Torn {
            fate: running,
            unreaped: Some(*exited_unreaped(id)),
            cleanup: None,
        };
        let error = super::after_the_spawn(io("wait"), torn, wrapper);
        assert_eq!(error.fate(), Some(running), "{error}");
        let Error::MayHaveStarted {
            unreaped: Some(child),
            wrapper_elevated,
            ..
        } = error
        else {
            panic!("expected MayHaveStarted around a child");
        };
        assert_eq!(wrapper_elevated, wrapper);
        assert_eq!(child.pid(), Some(id.pid()));
    }
}

/// A failure keeps its child through `map`, `behind_front` and the conversion to an `Error`.
///
/// Mutants: any of the three drops `unreaped`; `started` invents one.
#[skuld::test]
fn a_failure_carries_its_unreaped_child_through_map_behind_front_and_from() {
    let id = crate::identity::ProcessId::current();
    let failure = SpawnFailure::started(
        io("attach"),
        ChildFate::Running { id: Some(id) },
        Some(*exited_unreaped(id)),
    );
    let error = Error::from(failure.map(|_| io("mapped")).behind_front());
    let Error::MayHaveStarted {
        unreaped: Some(child),
        wrapper_elevated: true,
        ..
    } = error
    else {
        panic!("expected MayHaveStarted around a child, got {error:?}");
    };
    assert_eq!(child.pid(), Some(id.pid()));
    let none = Error::from(SpawnFailure::started(io("attach"), ChildFate::Reaped, None));
    assert!(matches!(none, Error::MayHaveStarted { unreaped: None, .. }), "{none:?}");
}

/// A handed-back child needs a `Running` fate, or debug asserts.
///
/// Mutant: `From` does not check the fate against the child.
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "is `Running` with its identity"))]
fn an_unreaped_child_whose_fate_is_not_running_asserts_in_debug() {
    let id = crate::identity::ProcessId::current();
    drop(Error::from(SpawnFailure::MayHaveStarted {
        cause: Box::new(io("attach")),
        fate: ChildFate::Reaped,
        wrapper_elevated: false,
        detail: None,
        unreaped: Some(exited_unreaped(id)),
        cleanup: None,
    }));
}

/// As above, for a `Running` fate that names no identity.
///
/// Mutant: `From` checks the variant of the fate and not its identity.
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "is `Running` with its identity"))]
fn an_unreaped_child_whose_fate_names_no_identity_asserts_in_debug() {
    let id = crate::identity::ProcessId::current();
    drop(Error::from(SpawnFailure::MayHaveStarted {
        cause: Box::new(io("attach")),
        fate: ChildFate::Running { id: None },
        wrapper_elevated: false,
        detail: None,
        unreaped: Some(exited_unreaped(id)),
        cleanup: None,
    }));
}

/// As above, for a `Running` fate that names another process.
///
/// Mutant: `From` checks that the fate carries some identity, not the child's.
#[skuld::test]
#[cfg_attr(debug_assertions, should_panic(expected = "is `Running` with its identity"))]
fn an_unreaped_child_whose_fate_names_another_process_asserts_in_debug() {
    let id = crate::identity::ProcessId::current();
    let other = crate::identity::ProcessId::from_parts_for_test(id.pid() + 1, crate::identity::Key::for_test(1));
    drop(Error::from(SpawnFailure::MayHaveStarted {
        cause: Box::new(io("attach")),
        fate: ChildFate::Running { id: Some(other) },
        wrapper_elevated: false,
        detail: None,
        unreaped: Some(exited_unreaped(id)),
        cleanup: None,
    }));
}

#[skuld::test]
fn classify_names_not_started() {
    let not: Result<(), _> = Err::<(), _>(std::io::Error::other("pipe")).not_started();
    assert!(matches!(not, Err(SpawnFailure::NotStarted(Error::Io(_)))), "{not:?}");
}

#[skuld::test]
fn map_keeps_the_answer_the_fate_and_the_flag() {
    let mapped = SpawnFailure::started(io("a"), ChildFate::Killed, None)
        .behind_front()
        .map(|_| io("b"));
    assert!(
        matches!(
            mapped,
            SpawnFailure::MayHaveStarted {
                ref cause,
                fate: ChildFate::Killed,
                wrapper_elevated: true,
                ..
            } if matches!(&**cause, Error::Io(e) if e.to_string() == "b")
        ),
        "{mapped:?}"
    );
    let mapped = SpawnFailure::NotStarted(io("a")).map(|_| io("b"));
    assert!(matches!(mapped, SpawnFailure::NotStarted(Error::Io(ref e)) if e.to_string() == "b"));
}

/// A note on a may-have-started error with no `detail` is its `detail`; the cause is left alone.
///
/// Mutant: the note goes to the cause, or is dropped.
#[skuld::test]
fn a_note_on_a_may_have_started_error_is_its_detail() {
    let error = Error::from(SpawnFailure::started(
        Error::Containment {
            detail: "x".into(),
            source: None,
        },
        ChildFate::Gone,
        None,
    ))
    .with_note("front left");
    let Error::MayHaveStarted {
        fate, detail, source, ..
    } = &error
    else {
        panic!("expected MayHaveStarted, got {error:?}");
    };
    assert_eq!(*fate, ChildFate::Gone);
    assert_eq!(detail.as_deref(), Some("front left"));
    assert!(
        matches!(**source, Error::Containment { ref detail, .. } if detail == "x"),
        "{source:?}"
    );
}

/// Each fate reads as what it says.
///
/// Mutant: two fates share a message.
#[skuld::test]
fn each_fate_has_its_own_message() {
    let all = [
        ChildFate::Reaped,
        ChildFate::Killed,
        ChildFate::Running {
            id: Some(crate::identity::ProcessId::current()),
        },
        ChildFate::Running { id: None },
        ChildFate::Gone,
        ChildFate::Unknown,
    ];
    for (i, a) in all.iter().enumerate() {
        for b in &all[i + 1..] {
            assert_ne!(a.to_string(), b.to_string(), "{a:?} vs {b:?}");
        }
    }
    let running = ChildFate::Running {
        id: Some(crate::identity::ProcessId::current()),
    };
    assert!(running.to_string().contains(&format!("pid {}", std::process::id())));
}

/// A failed attach that says the program never ran stays a not-started failure when its teardown
/// has nothing to report.
///
/// Mutant: `failed_attach` answers `MayHaveStarted` whatever the teardown says.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_not_started_attach_with_a_clean_teardown_stays_not_started() {
    let torn = Torn::left(ChildFate::Reaped);

    let failure = super::failed_attach(true, io("refused"), None, None, torn);

    assert!(
        matches!(
            failure,
            SpawnFailure::NotStartedWithChild {
                fate: ChildFate::Reaped,
                ..
            }
        ),
        "{failure:?}"
    );
}

/// A failed attach that did not say the program never ran is `MayHaveStarted`, a clean teardown or
/// not.
///
/// Mutant: `failed_attach` reads a clean teardown as proof the program did not run.
#[cfg(target_os = "linux")]
#[skuld::test]
fn an_attach_that_does_not_say_not_started_may_have_started() {
    let failure = super::failed_attach(false, io("attach"), None, None, Torn::left(ChildFate::Reaped));

    assert!(matches!(failure, SpawnFailure::MayHaveStarted { .. }), "{failure:?}");
}