// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Ports, temporary directories, external binaries and child processes. use std::net::SocketAddr; use std::path::{Path, PathBuf}; use std::process::Child; use std::sync::atomic::{AtomicU32, Ordering}; use std::time::{Duration, Instant}; /// A port on 127.0.0.1 that was free a moment ago, and never handed out before by this /// process (parallel tests otherwise can get the same port and talk to each other's servers). pub fn free_port() -> u16 { static GIVEN: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); loop { let port = std::net::TcpListener::bind("127.0.0.1:0") .unwrap() .local_addr() .unwrap() .port(); let mut given = GIVEN.lock().unwrap(); if !given.contains(&port) { given.push(port); return port; } } } pub fn local(port: u16) -> SocketAddr { SocketAddr::from(([127, 0, 0, 1], port)) } /// Wait until something accepts TCP connections on `addr`. pub fn wait_for_port(addr: SocketAddr, timeout: Duration) -> bool { let deadline = Instant::now() + timeout; while Instant::now() < deadline { if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() { return true; } std::thread::sleep(Duration::from_millis(50)); } false } /// A directory removed on drop (kept when `IANITOR_KEEP_TMP` is set, for debugging). pub struct TempDir(PathBuf); impl TempDir { pub fn new(label: &str) -> TempDir { static N: AtomicU32 = AtomicU32::new(0); let p = std::env::temp_dir().join(format!( "ianitor-{label}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::SeqCst) )); let _ = std::fs::remove_dir_all(&p); std::fs::create_dir_all(&p).unwrap(); TempDir(p) } pub fn path(&self) -> &Path { &self.0 } pub fn join(&self, p: &str) -> PathBuf { self.0.join(p) } pub fn str(&self, p: &str) -> String { self.join(p).to_string_lossy().into_owned() } } impl Drop for TempDir { fn drop(&mut self) { if std::env::var_os("IANITOR_KEEP_TMP").is_none() { let _ = std::fs::remove_dir_all(&self.0); } } } /// Locate an external tool: `$IANITOR__BIN`, then `$PATH`. pub fn find_binary(name: &str) -> Option { let var = format!( "IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_") ); if let Some(p) = std::env::var_os(&var) { return Some(PathBuf::from(p)); } let path = std::env::var_os("PATH")?; std::env::split_paths(&path) .map(|d| d.join(name)) .find(|p| p.is_file()) } /// Like [`find_binary`], but a missing tool fails the test, unless `IANITOR_ALLOW_SKIP=1`, /// in which case the test prints SKIPPED and the caller returns early. pub fn require_binary(name: &str) -> Option { match find_binary(name) { Some(p) => Some(p), None if std::env::var("IANITOR_ALLOW_SKIP").as_deref() == Ok("1") => { eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)"); None } None => { let var = format!( "IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_") ); panic!( "`{name}` is needed for this test but was not found on PATH (or ${var}). \ In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead." ) } } } /// Kills the child on drop. pub struct ChildGuard(pub Child); impl Drop for ChildGuard { fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); } }