meerkat-mobkit 0.8.46

Companion orchestration platform for the Meerkat multi-agent runtime
//! Run one unit test as the only test of a child process of its own binary.
//!
//! A few tests assert on meerkat's process-wide cost counters (full
//! transcript graph validations, content-digest bytes) that have no per-test
//! scope in the pinned meerkat release. Under the threaded `cargo test`
//! harness every other test that validates or digests moves those counters,
//! and the SQLite stores under test do that work on blocking worker threads,
//! so a thread-local count would miss the very work being asserted on. Such a
//! test re-runs itself here: in the child it is the only test, so the
//! process-wide counters see its work alone, at full assertion strength, under
//! both `cargo test` and nextest.

use std::process::Command;

/// Environment marker that selects the isolated child's test.
const ISOLATED_TEST_ENV: &str = "MEERKAT_MOBKIT_ISOLATED_TEST";

/// Whether this process should run the body of the test `name` declared in
/// `module_path` (pass `module_path!()` and the test function's name).
///
/// In the isolated child, selected by the exact test name in the environment
/// marker, this returns `true` and the caller runs its body. Anywhere else it
/// runs that test as the only test of a child process of the same test
/// binary, asserts that the child ran exactly this one test and passed
/// (forwarding the child's stdout and stderr when it did not), and returns
/// `false`: the caller returns without running the body a second time.
pub(crate) fn run_body_in_isolated_process(module_path: &str, name: &str) -> bool {
    let module = module_path
        .split_once("::")
        .map_or("", |(_crate_name, module)| module);
    let test = if module.is_empty() {
        name.to_string()
    } else {
        format!("{module}::{name}")
    };
    if std::env::var(ISOLATED_TEST_ENV).is_ok_and(|selected| selected == test) {
        return true;
    }
    let binary = std::env::current_exe()
        .unwrap_or_else(|error| panic!("locate the test binary to isolate `{test}`: {error}"));
    let output = Command::new(&binary)
        .args([test.as_str(), "--exact", "--test-threads=1", "--nocapture"])
        .env(ISOLATED_TEST_ENV, &test)
        .output()
        .unwrap_or_else(|error| panic!("spawn the isolated child for `{test}`: {error}"));
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    // `1 passed` also proves the exact filter selected this test: a wrong name
    // would run zero tests and still exit successfully.
    assert!(
        output.status.success() && stdout.contains("test result: ok. 1 passed"),
        "the isolated child for `{test}` did not pass exactly this one test ({})\n\
         --- child stdout ---\n{stdout}\n--- child stderr ---\n{stderr}",
        output.status
    );
    false
}