#![cfg(unix)]
use capy_cli::{new_project_with_frontend, FrontendDriver};
use nix::{
sys::signal::{kill, Signal},
unistd::Pid,
};
use std::{
fs,
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
time::{Duration, Instant},
};
struct Fixture {
_temp: tempfile::TempDir,
root: PathBuf,
bin: PathBuf,
}
fn script(path: &Path, contents: &str) {
fs::write(path, format!("#!/bin/sh\nset -eu\n{contents}\n")).unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap();
}
impl Fixture {
fn new(driver: FrontendDriver) -> Self {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("sample");
let bin = temp.path().join("bin");
fs::create_dir(&bin).unwrap();
new_project_with_frontend(&root, "sample", driver).unwrap();
script(
&bin.join("cargo"),
r#"
printf 'cargo %s\n' "$*" >> "$CAPY_TEST_LOG"
case "$1" in
metadata) printf '%s\n' "$CAPY_TEST_METADATA" ;;
build)
test ! -f build.fail || exit 42
if test -f build.wait; then
printf '%s\n' "$$" > compile.pid
exec sleep 300
fi
case "$*" in
*--release*) test "${CAPY_TEST_RUST_EXIT:-0}" = 0 || exit "$CAPY_TEST_RUST_EXIT"
printf '%s\n' "$CAPY_TEST_ARTIFACT" ;;
*) printf '%s\n' "$CAPY_TEST_ARTIFACT" ;;
esac ;;
esac
"#,
);
script(
&bin.join("backend"),
r#"
if test "${1:-}" = __capy_contract; then
printf 'contract export\n' >> "$CAPY_TEST_LOG"
printf '%s\n' '{"openapi":"3.1.0","info":{"title":"Test","version":"1"},"paths":{}}'
exit 0
fi
printf '%s\n' "$$" > "$CAPY_TEST_BACKEND_PID"
exec sleep 300
"#,
);
script(
&bin.join("pnpm"),
r#"
printf 'pnpm %s\n' "$*" >> "$CAPY_TEST_LOG"
case "$1 ${2:-}" in
'install '*) exit "${CAPY_TEST_INSTALL_EXIT:-0}" ;;
'run build')
test "${CAPY_TEST_FRONTEND_EXIT:-0}" = 0 || exit "$CAPY_TEST_FRONTEND_EXIT"
if test "${CAPY_TEST_SKIP_DIST:-0}" = 0; then mkdir -p dist; printf SPA > dist/index.html; fi ;;
'run dev')
printf '%s\n' "$$" > "$CAPY_TEST_FRONTEND_PID"
printf '%s\n' "$CAPY_BACKEND_URL" > "$CAPY_TEST_ORIGIN"
if test "${CAPY_TEST_FRONTEND_EXIT:-0}" != 0; then sleep 0.2; exit "$CAPY_TEST_FRONTEND_EXIT"; fi
sleep 300 &
descendant=$!
printf '%s\n' "$descendant" > "$CAPY_TEST_DESCENDANT_PID"
trap 'kill "$descendant" 2>/dev/null || true; wait "$descendant" 2>/dev/null || true; exit 0' INT TERM HUP
wait "$descendant" ;;
esac
"#,
);
Self {
_temp: temp,
root,
bin,
}
}
fn command(&self, subcommand: &str) -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_capy"));
for (name, _) in std::env::vars()
.filter(|(name, _)| name.starts_with("APP_") || name.starts_with("DATABASE_"))
{
command.env_remove(name);
}
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = listener.local_addr().unwrap().port();
command.env("CAPY_FRONTEND_PORT", port.to_string());
command.arg(subcommand).current_dir(&self.root)
.env("PATH", std::env::join_paths(std::iter::once(self.bin.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap()))).unwrap())
.env("CAPY_TEST_LOG", self.root.join("commands.log"))
.env("CAPY_TEST_METADATA", serde_json::json!({"packages":[{"manifest_path":self.root.join("Cargo.toml").canonicalize().unwrap(),"targets":[{"kind":["bin"],"name":"sample"}]}]}).to_string())
.env("CAPY_TEST_ARTIFACT", serde_json::json!({"reason":"compiler-artifact","target":{"name":"sample"},"executable":self.bin.join("backend")}).to_string())
.env("CAPY_TEST_BACKEND_PID", self.root.join("backend.pid"))
.env("CAPY_TEST_FRONTEND_PID", self.root.join("frontend.pid"))
.env("CAPY_TEST_DESCENDANT_PID", self.root.join("descendant.pid"))
.env("CAPY_TEST_ORIGIN", self.root.join("origin"));
command
}
fn log(&self) -> String {
fs::read_to_string(self.root.join("commands.log")).unwrap()
}
fn installed(&self) {
fs::create_dir_all(self.root.join("frontend/node_modules/.bin")).unwrap();
fs::write(
self.root.join("frontend/node_modules/.bin/vite"),
"installed",
)
.unwrap();
}
fn pid(&self, name: &str) -> i32 {
let path = self.root.join(format!("{name}.pid"));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if let Ok(text) = fs::read_to_string(&path) {
if let Ok(pid) = text.trim().parse() {
return pid;
}
}
std::thread::sleep(Duration::from_millis(20));
}
panic!("Missing PID: {name}");
}
}
struct Running(Child);
impl Running {
fn wait(&mut self) -> std::process::ExitStatus {
let deadline = Instant::now() + Duration::from_secs(10);
while Instant::now() < deadline {
if let Some(status) = self.0.try_wait().unwrap() {
return status;
}
std::thread::sleep(Duration::from_millis(20));
}
panic!("Capy did not terminate");
}
}
impl Drop for Running {
fn drop(&mut self) {
if self.0.try_wait().unwrap().is_none() {
let _ = kill(Pid::from_raw(self.0.id() as i32), Signal::SIGTERM);
let _ = self.0.wait();
}
}
}
fn assert_gone(pid: i32) {
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
if kill(Pid::from_raw(pid), None).is_err() {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
panic!("Orphan process {pid}");
}
fn wait_until(message: &str, mut condition: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(8);
while !condition() {
assert!(Instant::now() < deadline, "{message}");
std::thread::sleep(Duration::from_millis(20));
}
}
#[test]
fn dev_watches_sources_and_generators_without_restarting_frontend() {
for driver in [FrontendDriver::None, FrontendDriver::React] {
let f = Fixture::new(driver);
if driver == FrontendDriver::React {
f.installed();
}
let mut process = Running(
f.command("dev")
.arg("--inline")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let mut backend = f.pid("backend");
let frontend = (driver == FrontendDriver::React).then(|| f.pid("frontend"));
for change in 0..5 {
let builds = f.log().matches("cargo build").count();
match change {
0 => {
assert!(f
.command("make:controller")
.arg("PostController")
.output()
.unwrap()
.status
.success());
fs::write(f.root.join("routes/api.rs"), "// new route\n").unwrap();
}
1 => {
fs::write(
f.root.join("app/controllers/post_controller.rs"),
"// edit\n",
)
.unwrap();
}
2 => {
fs::rename(
f.root.join("app/controllers/post_controller.rs"),
f.root.join("app/controllers/renamed.rs"),
)
.unwrap();
}
3 => fs::remove_file(f.root.join("app/controllers/renamed.rs")).unwrap(),
_ => {
let manifest = f.root.join("Cargo.toml");
let contents = fs::read_to_string(&manifest).unwrap();
fs::write(manifest, format!("{contents}\n# updated\n")).unwrap();
}
}
wait_until("Source change did not restart the backend", || {
f.pid("backend") != backend
});
assert_gone(backend);
backend = f.pid("backend");
assert_eq!(f.log().matches("cargo build").count(), builds + 1);
if let Some(frontend) = frontend {
assert_eq!(f.pid("frontend"), frontend);
}
}
for path in [
"target/generated.rs",
"frontend/generated.rs",
"node_modules/generated.rs",
] {
fs::create_dir_all(f.root.join(path).parent().unwrap()).unwrap();
fs::write(f.root.join(path), "ignored").unwrap();
}
fs::write(f.root.join("database/app.sqlite"), "runtime data").unwrap();
fs::write(f.root.join("Cargo.lock"), "generated lockfile").unwrap();
std::thread::sleep(Duration::from_millis(1100));
assert_eq!(f.pid("backend"), backend);
assert_eq!(f.log().matches("cargo build").count(), 6);
kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
assert!(process.wait().success());
assert_gone(backend);
if let Some(frontend) = frontend {
assert_gone(frontend);
}
}
}
#[test]
fn dev_recovers_from_initial_and_subsequent_compile_errors() {
let f = Fixture::new(FrontendDriver::React);
f.installed();
fs::write(f.root.join("build.fail"), "").unwrap();
let output = fs::File::create(f.root.join("dev.log")).unwrap();
let mut process = Running(
f.command("dev")
.arg("--inline")
.stdout(output.try_clone().unwrap())
.stderr(output)
.spawn()
.unwrap(),
);
let mut backend = None;
let mut frontend = None;
for attempt in 1..=2 {
wait_until("Compiler failure did not leave the watcher running", || {
fs::read_to_string(f.root.join("dev.log"))
.unwrap()
.matches("Waiting for source changes")
.count()
== attempt
});
assert!(process.0.try_wait().unwrap().is_none());
if let Some(pid) = backend {
assert_gone(pid);
}
fs::remove_file(f.root.join("build.fail")).unwrap();
fs::write(
f.root.join("routes/api.rs"),
format!("// fixed {attempt}\n"),
)
.unwrap();
wait_until("Fixed sources did not start the backend", || {
let pid = f.pid("backend");
Some(pid) != backend
});
backend = Some(f.pid("backend"));
let pid = f.pid("frontend");
if let Some(frontend) = frontend {
assert_eq!(pid, frontend);
}
frontend = Some(pid);
if attempt == 1 {
fs::write(f.root.join("build.fail"), "").unwrap();
fs::write(f.root.join("routes/api.rs"), "// broken\n").unwrap();
}
}
kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
assert!(process.wait().success());
assert_gone(backend.unwrap());
assert_gone(frontend.unwrap());
}
#[test]
fn dev_picks_up_edits_during_compilation_and_stops_the_old_build() {
let f = Fixture::new(FrontendDriver::None);
fs::write(f.root.join("build.wait"), "").unwrap();
let mut process = Running(
f.command("dev")
.arg("--inline")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let compiler = f.pid("compile");
fs::remove_file(f.root.join("build.wait")).unwrap();
fs::write(
f.root.join("routes/api.rs"),
"// edited during compilation\n",
)
.unwrap();
let backend = f.pid("backend");
assert_gone(compiler);
assert_eq!(f.log().matches("cargo build").count(), 2);
kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
assert!(process.wait().success());
assert_gone(backend);
}
#[test]
fn build_compiles_rust_and_contracts_before_frontend_and_honors_lockfiles() {
let f = Fixture::new(FrontendDriver::React);
fs::write(
f.root.join("frontend/pnpm-lock.yaml"),
"lockfileVersion: '9.0'\n",
)
.unwrap();
let output = f.command("build").output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
f.log(),
"pnpm install --frozen-lockfile\ncargo metadata --no-deps --format-version=1\ncargo build --quiet --bin sample --message-format=json-render-diagnostics --release\ncontract export\npnpm run build\n"
);
f.installed();
fs::write(f.root.join("commands.log"), "").unwrap();
assert!(f.command("build").output().unwrap().status.success());
assert_eq!(f.log(), "cargo metadata --no-deps --format-version=1\ncargo build --quiet --bin sample --message-format=json-render-diagnostics --release\ncontract export\npnpm run build\n");
}
#[test]
fn failed_build_steps_stop_the_pipeline_and_propagate_exit_codes() {
for (variable, expected_log) in [
("CAPY_TEST_INSTALL_EXIT", "pnpm install --frozen-lockfile\n"),
(
"CAPY_TEST_FRONTEND_EXIT",
"pnpm install --frozen-lockfile\ncargo metadata --no-deps --format-version=1\ncargo build --quiet --bin sample --message-format=json-render-diagnostics --release\ncontract export\npnpm run build\n",
),
(
"CAPY_TEST_RUST_EXIT",
"pnpm install --frozen-lockfile\ncargo metadata --no-deps --format-version=1\ncargo build --quiet --bin sample --message-format=json-render-diagnostics --release\n",
),
] {
let f = Fixture::new(FrontendDriver::React);
assert_eq!(
f.command("build")
.env(variable, "42")
.output()
.unwrap()
.status
.code(),
Some(42)
);
assert_eq!(f.log(), expected_log);
}
let f = Fixture::new(FrontendDriver::React);
let output = f
.command("build")
.env("CAPY_TEST_SKIP_DIST", "1")
.output()
.unwrap();
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr)
.contains("did not produce frontend/dist/index.html"));
assert!(f.log().ends_with("contract export\npnpm run build\n"));
}
#[test]
fn api_build_needs_no_frontend_tools() {
let f = Fixture::new(FrontendDriver::None);
assert!(f.command("build").output().unwrap().status.success());
assert_eq!(f.log(), "cargo metadata --no-deps --format-version=1\ncargo build --quiet --bin sample --message-format=json-render-diagnostics --release\ncontract export\n");
}
#[test]
fn dev_signals_stop_both_servers_and_frontend_descendants() {
for signal in [Signal::SIGINT, Signal::SIGTERM] {
let f = Fixture::new(FrontendDriver::React);
f.installed();
fs::write(f.root.join(".env"), "APP_PORT=8123\n").unwrap();
let mut process = Running(
f.command("dev")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let pids = [f.pid("backend"), f.pid("frontend"), f.pid("descendant")];
assert_eq!(
fs::read_to_string(f.root.join("origin")).unwrap().trim(),
"http://127.0.0.1:8123"
);
kill(Pid::from_raw(process.0.id() as i32), signal).unwrap();
assert!(process.wait().success());
for pid in pids {
assert_gone(pid);
}
}
}
#[test]
fn frontend_startup_failure_terminates_backend() {
let f = Fixture::new(FrontendDriver::React);
f.installed();
let mut process = Running(
f.command("dev")
.env("CAPY_TEST_FRONTEND_EXIT", "42")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let backend = f.pid("backend");
assert_eq!(process.wait().code(), Some(42));
assert_gone(backend);
}
#[test]
fn api_dev_and_serve_do_not_start_frontend() {
for (driver, command) in [
(FrontendDriver::None, "dev"),
(FrontendDriver::React, "serve"),
] {
let f = Fixture::new(driver);
let mut process = Running(
f.command(command)
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let backend = f.pid("backend");
kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
process.wait();
assert_gone(backend);
assert!(!f.log().contains("pnpm"));
}
}
struct TerminalRun {
running: Running,
master: fs::File,
slave: fs::File,
original: nix::sys::termios::Termios,
bytes: Vec<u8>,
}
impl TerminalRun {
fn start(mut command: Command) -> Self {
use nix::{
fcntl::{fcntl, FcntlArg, OFlag},
pty::{openpty, Winsize},
sys::termios::tcgetattr,
};
let pty = openpty(
Some(&Winsize {
ws_row: 24,
ws_col: 110,
ws_xpixel: 0,
ws_ypixel: 0,
}),
None,
)
.unwrap();
let master = fs::File::from(pty.master);
let slave = fs::File::from(pty.slave);
let original = tcgetattr(&slave).unwrap();
fcntl(&master, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)).unwrap();
let child = command
.env("TERM", "xterm-256color")
.env_remove("CI")
.stdin(slave.try_clone().unwrap())
.stdout(slave.try_clone().unwrap())
.stderr(slave.try_clone().unwrap())
.spawn()
.unwrap();
Self {
running: Running(child),
master,
slave,
original,
bytes: vec![],
}
}
fn drain(&mut self) {
use std::io::Read;
let mut bytes = [0; 8192];
while let Ok(n) = self.master.read(&mut bytes) {
if n == 0 {
break;
}
self.bytes.extend_from_slice(&bytes[..n]);
}
}
fn send(&mut self, text: &[u8]) {
use std::io::Write;
self.drain();
self.master.write_all(text).unwrap();
}
fn wait_text(&mut self, text: &str) {
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
self.drain();
if String::from_utf8_lossy(&self.bytes).contains(text) {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
panic!(
"Missing terminal text {text:?}: {}",
String::from_utf8_lossy(&self.bytes)
);
}
fn finish(&mut self) -> std::process::ExitStatus {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
self.drain();
if let Some(status) = self.running.0.try_wait().unwrap() {
self.drain();
let restored = nix::sys::termios::tcgetattr(&self.slave).unwrap();
assert_eq!(
restored.local_flags, self.original.local_flags,
"terminal local flags not restored"
);
assert_eq!(
restored.input_flags, self.original.input_flags,
"terminal input flags not restored"
);
assert!(
self.bytes.windows(8).any(|bytes| bytes == b"\x1b[?1049l"),
"alternate screen not restored"
);
return status;
}
assert!(Instant::now() < deadline, "TUI did not exit");
std::thread::sleep(Duration::from_millis(20));
}
}
}
fn await_new_pid(fixture: &Fixture, name: &str, previous: i32, terminal: &mut TerminalRun) -> i32 {
let deadline = Instant::now() + Duration::from_secs(8);
loop {
terminal.drain();
let pid = fixture.pid(name);
if pid != previous {
return pid;
}
assert!(Instant::now() < deadline, "{name} was not restarted");
std::thread::sleep(Duration::from_millis(30));
}
}
#[test]
fn tui_restarts_process_trees_and_restores_terminal_on_q_and_ctrl_c() {
for quit in [b"q".as_slice(), b"\x03".as_slice()] {
let f = Fixture::new(FrontendDriver::React);
f.installed();
let mut terminal = TerminalRun::start(f.command("dev"));
let backend = f.pid("backend");
let frontend = f.pid("frontend");
let descendant = f.pid("descendant");
terminal.wait_text("capy dev");
terminal.send(b"1r");
let restarted_backend = await_new_pid(&f, "backend", backend, &mut terminal);
assert_gone(backend);
fs::write(f.root.join("routes/api.rs"), "// saved from an editor\n").unwrap();
let new_backend = await_new_pid(&f, "backend", restarted_backend, &mut terminal);
assert_gone(restarted_backend);
terminal.send(b"3r");
let new_frontend = await_new_pid(&f, "frontend", frontend, &mut terminal);
let new_descendant = await_new_pid(&f, "descendant", descendant, &mut terminal);
assert_gone(frontend);
assert_gone(descendant);
terminal.send(b"2r");
terminal.wait_text("cannot be restarted");
terminal.send(b"s");
terminal.wait_text("· stream");
terminal.send(b"t/qr123");
std::thread::sleep(Duration::from_millis(100));
assert!(
terminal.running.0.try_wait().unwrap().is_none(),
"search typing dispatched a shortcut"
);
terminal.send(b"\x1b");
std::thread::sleep(Duration::from_millis(80));
terminal.send(quit);
assert!(terminal.finish().success());
for pid in [new_backend, new_frontend, new_descendant] {
assert_gone(pid);
}
}
}
#[test]
fn child_failure_restores_terminal_and_retains_error() {
let f = Fixture::new(FrontendDriver::React);
f.installed();
let mut command = f.command("dev");
command.env("CAPY_TEST_FRONTEND_EXIT", "42");
let mut terminal = TerminalRun::start(command);
let backend = f.pid("backend");
assert_eq!(terminal.finish().code(), Some(42));
assert_gone(backend);
assert!(String::from_utf8_lossy(&terminal.bytes).contains("Stopping the application"));
}
#[test]
fn redirected_output_is_prefixed_sanitized_and_routes_application_logs() {
let f = Fixture::new(FrontendDriver::None);
script(
&f.bin.join("backend"),
r#"
if test "${1:-}" = __capy_contract; then
printf '%s\n' '{"openapi":"3.1.0","info":{"title":"Test","version":"1"},"paths":{}}'
exit 0
fi
printf '\033[31mhello\033[0m\033[2J\n'
printf 'CAPY_LOG_V1 {"timestamp":"now","target":"application","level":"INFO","fields":{"message":"created"}}\n' >&2
printf 'CAPY_LOG_V1 {"timestamp":"now","target":"capy_framework::diagnostics","level":"INFO","fields":{"message":"request completed"}}\n' >&2
exit 42
"#,
);
for flags in [vec![], vec!["--inline"], vec!["--tui"], vec!["--stream"]] {
let output = f.command("dev").args(flags).output().unwrap();
assert_eq!(output.status.code(), Some(42));
assert!(!output.stdout.contains(&0x1b));
assert!(!output.stderr.contains(&0x1b));
assert!(String::from_utf8_lossy(&output.stdout).contains("[server] hello"));
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(stderr.contains("[logs] now INFO created"), "{stderr}");
assert!(stderr.contains("[server] now INFO request completed"));
}
}
#[test]
fn shutdown_during_frontend_install_or_backend_compile_reaps_child() {
for stage in ["pnpm", "cargo"] {
let f = Fixture::new(if stage == "pnpm" {
FrontendDriver::React
} else {
FrontendDriver::None
});
script(
&f.bin.join(stage),
r#"
if test "${1:-}" = __capy_contract; then
printf 'contract export\n' >> "$CAPY_TEST_LOG"
printf '%s\n' '{"openapi":"3.1.0","info":{"title":"Test","version":"1"},"paths":{}}'
exit 0
fi
printf '%s\n' "$$" > "$CAPY_TEST_BACKEND_PID"
exec sleep 300
"#,
);
let mut process = Running(
f.command("dev")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let child = f.pid("backend");
kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
assert!(process.wait().success());
assert_gone(child);
}
}
#[test]
fn failed_spawn_stops_already_started_backend() {
let f = Fixture::new(FrontendDriver::React);
f.installed();
fs::write(f.bin.join("pnpm"), "#!/capy-test-missing-interpreter\n").unwrap();
script(
&f.bin.join("backend"),
r#"if test "${1:-}" = __capy_contract; then
printf 'contract export\n' >> "$CAPY_TEST_LOG"
printf '%s\n' '{"openapi":"3.1.0","info":{"title":"Test","version":"1"},"paths":{}}'
exit 0
fi
printf '%s\n' "$$" > "$CAPY_TEST_BACKEND_PID"
exec /bin/sleep 300"#,
);
let output = f.command("dev").env("PATH", &f.bin).output().unwrap();
assert!(!output.status.success());
assert!(
String::from_utf8_lossy(&output.stderr).contains("Could not start pnpm"),
"{}",
String::from_utf8_lossy(&output.stderr)
);
if let Ok(pid) = fs::read_to_string(f.root.join("backend.pid")) {
assert_gone(pid.trim().parse().unwrap());
}
let processes = Command::new("ps")
.args(["-axo", "command="])
.output()
.unwrap();
assert!(!String::from_utf8_lossy(&processes.stdout)
.contains(f.bin.join("backend").to_str().unwrap()));
}
#[test]
fn shutdown_allows_graceful_handlers_and_forces_uncooperative_children() {
for graceful in [true, false] {
let f = Fixture::new(FrontendDriver::None);
script(
&f.bin.join("backend"),
if graceful {
r#"
if test "${1:-}" = __capy_contract; then
printf 'contract export\n' >> "$CAPY_TEST_LOG"
printf '%s\n' '{"openapi":"3.1.0","info":{"title":"Test","version":"1"},"paths":{}}'
exit 0
fi
printf '%s\n' "$$" > "$CAPY_TEST_BACKEND_PID"
sleep 300 &
child=$!
trap 'printf graceful > shutdown.marker; kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 0' TERM
wait "$child"
"#
} else {
r#"
trap '' TERM
if test "${1:-}" = __capy_contract; then
printf 'contract export\n' >> "$CAPY_TEST_LOG"
printf '%s\n' '{"openapi":"3.1.0","info":{"title":"Test","version":"1"},"paths":{}}'
exit 0
fi
printf '%s\n' "$$" > "$CAPY_TEST_BACKEND_PID"
exec sleep 300
"#
},
);
let mut process = Running(
f.command("dev")
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let pid = f.pid("backend");
std::thread::sleep(Duration::from_millis(50));
kill(Pid::from_raw(process.0.id() as i32), Signal::SIGTERM).unwrap();
assert!(process.wait().success());
assert_gone(pid);
if graceful {
assert_eq!(
fs::read_to_string(f.root.join("shutdown.marker")).unwrap(),
"graceful"
);
}
}
}