Lines
100 %
Functions
Branches
//! Helpers shared by the integration tests that run the built `nms` binary.
use std::path::PathBuf;
use std::process::{Command, Output};
pub fn nms_bin() -> PathBuf {
// CARGO_BIN_EXE_<name> is set by cargo when building integration
// tests for a crate with a `[[bin]]` of that name.
PathBuf::from(env!("CARGO_BIN_EXE_nms"))
}
pub fn tempfile_dir(prefix: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"{prefix}{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
dir
/// Runs `source` through `nms` in a subprocess limited to a `stack_kib`
/// native stack, so a compiler stack overflow kills only the child.
#[cfg(unix)]
pub fn run_nms_with_stack_limit(prefix: &str, source: &str, stack_kib: u32) -> Output {
nms_with_stack_limit(prefix, source, stack_kib, &[])
/// [`run_nms_with_stack_limit`] with extra `nms` flags before the source path.
pub fn nms_with_stack_limit(prefix: &str, source: &str, stack_kib: u32, flags: &[&str]) -> Output {
let dir = tempfile_dir(prefix);
let path = dir.join("chain.nms");
std::fs::write(&path, source).unwrap();
let out = Command::new("sh")
.arg("-c")
.arg(format!("ulimit -s {stack_kib} && exec \"$@\""))
.arg("sh")
.arg(nms_bin())
.args(flags)
.arg(&path)
.current_dir(&dir)
.output()
.expect("invoke nms under a constrained stack");
std::fs::remove_dir_all(&dir).ok();
out
/// Asserts the child was not killed by a signal (a stack overflow aborts)
/// and failed with `needle` in its stderr.
pub fn assert_fails_cleanly_with(out: &Output, needle: &str) {
use std::os::unix::process::ExitStatusExt;
assert_eq!(
out.status.signal(),
None,
"must fail cleanly, not crash: {:?}",
out.status
);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "expected failure, stderr: {stderr}");
assert!(stderr.contains(needle), "stderr: {stderr}");
/// Runs `source` under a `stack_kib` stack and asserts it prints
/// `expected_value`. A constrained stack (2 MiB) is deliberate: an 8 MiB
/// stack survives overflows an ordinary thread stack would not.
pub fn assert_nms_source_prints_with_stack_limit(
name_prefix: &str,
source: &str,
expected_value: &str,
stack_kib: u32,
) {
let out = run_nms_with_stack_limit(name_prefix, source, stack_kib);
"nms subprocess was killed by a signal (status: {:?}) under a {stack_kib} KiB stack — \
likely a native stack overflow (SIGABRT)",
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
out.status.success(),
"expected success, got {:?}\nstdout: {stdout}\nstderr: {stderr}",
stdout.trim() == expected_value,
"expected {expected_value:?}, got stdout: {stdout}\nstderr: {stderr}"