use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use crate::{Codex, CodexBuilder};
#[cfg(not(target_os = "fuchsia"))]
pub(crate) fn inheritable_pipe_writer() -> std::os::fd::OwnedFd {
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
let (_, writer) = std::io::pipe().unwrap();
let fd = unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 64) };
assert!(fd >= 64, "dup failed: {}", std::io::Error::last_os_error());
let writer = unsafe { OwnedFd::from_raw_fd(fd) };
let result = unsafe { libc::fcntl(writer.as_raw_fd(), libc::F_SETFD, 0) };
assert_eq!(
result,
0,
"fcntl failed: {}",
std::io::Error::last_os_error()
);
writer
}
pub(crate) fn stdin_echo_codex() -> CodexBuilder {
let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake-codex-echo-stdin.sh");
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
}
pub(crate) struct PidFile {
path: PathBuf,
}
pub(crate) struct EnvCapture {
path: PathBuf,
}
impl EnvCapture {
pub(crate) fn new(label: &str) -> Self {
let path =
std::env::temp_dir().join(format!("codex-wrapper-{}-{label}.env", std::process::id()));
let _ = std::fs::remove_file(&path);
Self { path }
}
pub(crate) fn read(&self) -> std::collections::BTreeMap<String, String> {
let contents = std::fs::read_to_string(&self.path)
.unwrap_or_else(|e| panic!("failed to read {}: {e}", self.path.display()));
contents
.lines()
.filter_map(|line| {
let (key, value) = line.split_once('=')?;
Some((key.to_string(), value.to_string()))
})
.collect()
}
}
impl Drop for EnvCapture {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
pub(crate) fn env_capturing_codex(capture: &EnvCapture) -> CodexBuilder {
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-capture-env.sh");
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().expect("fixture path is utf-8"))
.env(
"CODEX_WRAPPER_ENV_CAPTURE",
capture.path.to_str().expect("capture path is utf-8"),
)
}
impl PidFile {
pub(crate) fn new(label: &str) -> Self {
let path =
std::env::temp_dir().join(format!("codex-wrapper-{}-{label}.pid", std::process::id()));
let _ = std::fs::remove_file(&path);
Self { path }
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
pub(crate) async fn read_pid(&self) -> u32 {
for _ in 0..100 {
if let Ok(contents) = std::fs::read_to_string(&self.path)
&& let Ok(pid) = contents.trim().parse()
{
return pid;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("fake codex never recorded a pid at {}", self.path.display());
}
}
impl Drop for PidFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
pub(crate) fn blocking_codex(pid_file: &PidFile) -> CodexBuilder {
let script = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-blocks.sh");
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().expect("fixture path is utf-8"))
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().expect("pid file path is utf-8"),
)
}
pub(crate) struct GracePeriodFixture {
pid_file: PidFile,
cleanup_armed: AtomicBool,
}
impl GracePeriodFixture {
pub(crate) fn new(label: &str) -> Self {
let fixture = Self {
pid_file: PidFile::new(label),
cleanup_armed: AtomicBool::new(true),
};
for suffix in [".ready", ".term"] {
let _ = std::fs::remove_file(fixture.marker(suffix));
}
fixture
}
fn marker(&self, suffix: &str) -> PathBuf {
let mut path = self.pid_file.path().as_os_str().to_owned();
path.push(suffix);
PathBuf::from(path)
}
pub(crate) fn configure(&self, builder: CodexBuilder) -> CodexBuilder {
builder
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
self.pid_file.path().to_str().unwrap(),
)
.env("CODEX_WRAPPER_TEST_IGNORE_TERM", "1")
.termination_grace(Duration::from_secs(30))
}
pub(crate) fn builder(&self) -> CodexBuilder {
let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake-codex-spawns-child.sh");
self.configure(
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap()),
)
}
fn pids(&self) -> Option<(u32, u32)> {
let contents = std::fs::read_to_string(self.pid_file.path()).ok()?;
let field = |key: &str| {
contents
.lines()
.find_map(|line| line.strip_prefix(key))
.and_then(|value| value.parse().ok())
};
Some((field("parent=")?, field("child=")?))
}
pub(crate) async fn ready(&self) {
tokio::time::timeout(Duration::from_secs(10), async {
while self.pids().is_none() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the fixture never recorded its ready process group");
}
pub(crate) async fn assert_drop_during_grace(&self, run: impl std::future::Future) {
let mut run = Box::pin(run);
let term = self.marker(".term");
tokio::select! {
_ = &mut run => panic!("the run finished before its grace period was observed"),
observed = tokio::time::timeout(Duration::from_secs(10), async {
while !term.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
}) => observed.expect("the fixture never received SIGTERM"),
}
let (parent, child) = self.pids().expect("the fixture recorded its process group");
assert!(is_running(child), "the descendant must survive SIGTERM");
drop(run);
let (parent_gone, child_gone) =
tokio::join!(wait_until_gone(parent), wait_until_gone(child));
if parent_gone && child_gone {
self.cleanup_armed.store(false, Ordering::Relaxed);
}
assert!(parent_gone, "the direct child ({parent}) survived the drop");
assert!(
child_gone,
"the SIGTERM-ignoring descendant ({child}) survived dropping during grace"
);
}
}
impl Drop for GracePeriodFixture {
fn drop(&mut self) {
if self.cleanup_armed.load(Ordering::Relaxed)
&& let Some((parent, _)) = self.pids()
{
crate::exec::signal_group(parent, libc::SIGKILL);
}
for suffix in [".ready", ".term"] {
let _ = std::fs::remove_file(self.marker(suffix));
}
}
}
pub(crate) struct InterruptFixture {
pid_file: PidFile,
cleanup_armed: AtomicBool,
}
impl InterruptFixture {
pub(crate) fn new(label: &str) -> Self {
let fixture = Self {
pid_file: PidFile::new(label),
cleanup_armed: AtomicBool::new(true),
};
for suffix in [".ready", ".int", ".term", ".cleaned", ".int-ignored"] {
let _ = std::fs::remove_file(fixture.marker(suffix));
}
fixture
}
pub(crate) fn marker(&self, suffix: &str) -> PathBuf {
let mut path = self.pid_file.path().as_os_str().to_owned();
path.push(suffix);
PathBuf::from(path)
}
pub(crate) fn builder(&self) -> CodexBuilder {
let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fake-codex-interrupt.sh");
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
self.pid_file.path().to_str().unwrap(),
)
.termination_grace(Duration::from_secs(1))
}
pub(crate) fn pids(&self) -> Option<(u32, u32)> {
let contents = std::fs::read_to_string(self.pid_file.path()).ok()?;
let field = |key: &str| {
contents
.lines()
.find_map(|line| line.strip_prefix(key))
.and_then(|value| value.parse().ok())
};
Some((field("parent=")?, field("child=")?))
}
pub(crate) async fn ready(&self) {
self.wait_for(".ready").await;
assert!(self.pids().is_some(), "ready requires recorded process IDs");
assert!(
!self.marker(".int-ignored").exists(),
"SIGINT was ignored when the fixture started, so its trap could not be installed; run the tests with SIGINT at its default disposition"
);
}
pub(crate) async fn wait_for(&self, suffix: &str) {
tokio::time::timeout(Duration::from_secs(10), async {
while !self.marker(suffix).exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the fixture never reached its marker");
}
pub(crate) async fn detached_ready(&self) {
self.ready().await;
let (parent, child) = self.pids().unwrap();
let (parent_group, child_group) =
unsafe { (libc::getpgid(parent as i32), libc::getpgid(child as i32)) };
assert!(parent_group > 0 && child_group > 0);
assert_ne!(
parent_group, child_group,
"the tool must escape the CLI group"
);
}
pub(crate) async fn assert_stopped(&self) {
let (parent, child) = self.pids().unwrap();
let (parent_gone, child_gone) =
tokio::join!(wait_until_gone(parent), wait_until_gone(child),);
assert!(parent_gone, "the direct child survived shutdown");
assert!(child_gone, "the tool survived shutdown");
self.cleanup_armed.store(false, Ordering::Relaxed);
}
}
impl Drop for InterruptFixture {
fn drop(&mut self) {
if self.cleanup_armed.load(Ordering::Relaxed)
&& let Some((parent, child)) = self.pids()
{
if unsafe { libc::getpgid(parent as i32) } == parent as i32 {
crate::exec::signal_group(parent, libc::SIGKILL);
}
unsafe {
libc::kill(child as i32, libc::SIGKILL);
}
}
for suffix in [".ready", ".int", ".term", ".cleaned", ".int-ignored"] {
let _ = std::fs::remove_file(self.marker(suffix));
}
}
}
pub(crate) async fn wait_until_gone(pid: u32) -> bool {
for _ in 0..250 {
if !is_running(pid) {
return true;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
false
}
pub(crate) fn is_running_for_test(pid: u32) -> bool {
is_running(pid)
}
fn is_running(pid: u32) -> bool {
let output = std::process::Command::new("ps")
.args(["-o", "state=", "-p", &pid.to_string()])
.output()
.expect("ps must be available");
let state = String::from_utf8_lossy(&output.stdout);
let state = state.trim();
!state.is_empty() && !state.starts_with('Z')
}