use std::ffi::{OsStr, OsString};
use std::process::{Child, Command};
pub(crate) type Spawn = fn(&mut Command) -> std::io::Result<Child>;
pub(crate) const ENV: &str = "COSCA_TESTCFG_OWN_PROCESS";
#[allow(
unused_macros,
reason = "unused in the integration binaries that mount this file only for `tests/common`"
)]
macro_rules! test_path {
($name:ident) => {{
let _ = $name;
concat!(module_path!(), "::", stringify!($name))
}};
}
pub(crate) fn test_filter(path: &str) -> &str {
path.split_once("::")
.unwrap_or_else(|| panic!("{path:?} has no crate segment"))
.1
}
pub(crate) fn child_args(test: &str) -> Vec<&str> {
let mut args = vec!["--exact", test, "--test-threads=1", super::test_reexec::NOCAPTURE];
if cfg!(windows) {
args.extend(super::test_reexec::JSON_FORMAT);
}
args
}
pub(crate) fn env_value(transport: &str, test: &str) -> String {
format!("{}:{transport}:{test}", std::process::id())
}
pub(crate) fn gate<'a>(inherited: Option<&'a str>, parent_pid: u32, args: &[OsString], test: &str) -> Option<&'a str> {
let mut parts = inherited?.splitn(3, ':');
let (Some(pid), Some(transport), Some(named)) = (parts.next(), parts.next(), parts.next()) else {
return None;
};
let exact_argv = args
.iter()
.map(OsString::as_os_str)
.eq(child_args(test).into_iter().map(OsStr::new));
(pid == parent_pid.to_string() && named == test && exact_argv).then_some(transport)
}
pub(crate) fn is_reexecution(inherited: Option<&str>, parent_pid: u32, test: &str) -> bool {
let mut parts = inherited.unwrap_or_default().splitn(3, ':');
matches!(
(parts.next(), parts.next(), parts.next()),
(Some(pid), Some(_), Some(named)) if pid == parent_pid.to_string() && named == test
)
}
pub(crate) fn child_role<T>(
test: &str,
parent_pid: u32,
classify: impl FnOnce(Option<&str>, u32, &[OsString], &str) -> Option<T>,
) -> Option<T> {
let inherited = std::env::var(ENV).ok();
let args: Vec<OsString> = std::env::args_os().skip(1).collect();
if let Some(role) = classify(inherited.as_deref(), parent_pid, &args, test) {
return Some(role);
}
assert!(
!is_reexecution(inherited.as_deref(), parent_pid, test),
"re-executed for {test} but not accepted as its own process: got {args:?} with {ENV}={inherited:?}, \
expected {:?}",
child_args(test)
);
None
}
#[cfg(unix)]
pub(crate) type Reporter = std::fs::File;
#[cfg(windows)]
pub(crate) type Reporter = ();
#[must_use = "the body's completion is reported when this drops; bind it for the whole body"]
pub(crate) struct Completion(pub(crate) Reporter);
pub(crate) use test_path;