Skip to main content

oxdock_sys_test_utils/
lib.rs

1/// Shared test helpers used by multiple crates' tests.
2///
3/// Keep functionality here minimal and test-only.
4use std::collections::HashMap;
5use std::env;
6use std::sync::{Mutex, MutexGuard, OnceLock};
7use std::thread::{ThreadId, current};
8
9/// Per-key locks so simultaneous guards for *different* variables keep
10/// working, while mutations of the *same* variable serialize process-wide.
11/// `std::env` access mutates process-global state and is not thread-safe,
12/// so every guard holds its key's lock for its entire lifetime.
13static KEY_LOCKS: OnceLock<Mutex<HashMap<&'static str, &'static Mutex<()>>>> = OnceLock::new();
14
15/// Which thread currently holds each key's lock, so same-thread re-entrancy
16/// can fail fast with a clear message instead of deadlocking.
17static KEY_OWNERS: OnceLock<Mutex<HashMap<&'static str, ThreadId>>> = OnceLock::new();
18
19fn key_owners() -> &'static Mutex<HashMap<&'static str, ThreadId>> {
20    KEY_OWNERS.get_or_init(|| Mutex::new(HashMap::new()))
21}
22
23// TODO: Remove the Box::leak
24#[allow(clippy::disallowed_methods)] // Box::leak: one lock per distinct key; bounded by test-suite vocabulary
25fn key_lock(key: &'static str) -> &'static Mutex<()> {
26    let locks = KEY_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
27    let mut map = locks
28        .lock()
29        .unwrap_or_else(|poisoned| poisoned.into_inner());
30    map.entry(key)
31        .or_insert_with(|| Box::leak(Box::new(Mutex::new(()))))
32}
33
34fn acquire_key_lock(key: &'static str) -> MutexGuard<'static, ()> {
35    let thread = current();
36    {
37        let owners = key_owners()
38            .lock()
39            .unwrap_or_else(|poisoned| poisoned.into_inner());
40        if owners.get(key) == Some(&thread.id()) {
41            panic!("TestEnvGuard: environment variable {key} is already guarded on this thread");
42        }
43    }
44
45    let guard = key_lock(key)
46        .lock()
47        .unwrap_or_else(|poisoned| poisoned.into_inner());
48    key_owners()
49        .lock()
50        .unwrap_or_else(|poisoned| poisoned.into_inner())
51        .insert(key, thread.id());
52    guard
53}
54
55pub struct TestEnvGuard {
56    key: &'static str,
57    value: Option<String>,
58    _lock: MutexGuard<'static, ()>,
59}
60
61impl TestEnvGuard {
62    /// Set `key` to `value`, restoring the prior state on drop.
63    ///
64    /// Blocks while another thread holds a live guard for the same variable;
65    /// panics if the same thread nests a second guard for it.
66    pub fn set(key: &'static str, value: &str) -> Self {
67        let lock = acquire_key_lock(key);
68        let prev = env::var(key).ok();
69        unsafe { env::set_var(key, value) };
70        Self {
71            key,
72            value: prev,
73            _lock: lock,
74        }
75    }
76
77    /// Remove `key` from the environment, restoring the prior state on drop:
78    /// re-set to its previous value if it had one, otherwise left absent.
79    ///
80    /// Blocking/panic behavior matches [`TestEnvGuard::set`].
81    pub fn remove(key: &'static str) -> Self {
82        let lock = acquire_key_lock(key);
83        let prev = env::var(key).ok();
84        unsafe { env::remove_var(key) };
85        Self {
86            key,
87            value: prev,
88            _lock: lock,
89        }
90    }
91}
92
93impl Drop for TestEnvGuard {
94    fn drop(&mut self) {
95        match &self.value {
96            Some(value) => unsafe { env::set_var(self.key, value) },
97            None => unsafe { env::remove_var(self.key) },
98        }
99        key_owners()
100            .lock()
101            .unwrap_or_else(|poisoned| poisoned.into_inner())
102            .remove(self.key);
103    }
104}
105
106#[allow(clippy::disallowed_types)]
107use std::path::Path;
108
109/// Detect whether the current process can create filesystem symlinks.
110/// On Unix always returns true without probing; on Windows probes symlink
111/// creation under the provided target directory. Accepts a `&Path` to avoid
112/// depending on `oxdock-fs` and creating a circular crate dependency.
113#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
114pub fn can_create_symlinks(target: &Path) -> bool {
115    // The synthetic Miri filesystem has no symlinks: resolver links bail
116    // instead of creating them, so guarded tests skip the same way they
117    // do on hosts without symlink privilege.
118    #[cfg(miri)]
119    {
120        let _ = target;
121        false
122    }
123
124    #[cfg(all(unix, not(miri)))]
125    {
126        let _ = target;
127        true
128    }
129
130    #[cfg(all(windows, not(miri)))]
131    {
132        use std::fs;
133        use std::os::windows::fs::symlink_dir;
134        let test_src = target.join("__oxdock_test_symlink_src");
135        let test_dst = target.join("__oxdock_test_symlink_dst");
136        // Localized allowance: sys test helper may create/remove test dirs.
137        let _ = fs::create_dir_all(&test_src);
138        let ok = symlink_dir(&test_src, &test_dst).is_ok();
139        let _ = fs::remove_dir_all(&test_dst);
140        let _ = fs::remove_dir_all(&test_src);
141        ok
142    }
143
144    #[cfg(not(any(unix, windows, miri)))]
145    {
146        let _ = target;
147        false
148    }
149}
150
151/// Locate a binary the current `cargo test` invocation built, climbing
152/// from the test executable and checking every ancestor directory.
153/// Older cargo places test binaries in `target/<profile>/deps/`, newer
154/// ones in `target/<profile>/build/<pkg>/out/`, so no layout or profile
155/// name is assumed; the first match climbing outward is the current
156/// profile's artifact. Returns `None` when nothing is found (build it
157/// first with `cargo build -p <package>`). The `.exe` suffix lands on
158/// Windows only, so callers pass the bare stem and get back a path
159/// string ready for `set_interpreter` and friends.
160pub fn find_built_binary(stem: &str) -> Option<String> {
161    let exe = std::env::current_exe().ok()?;
162    #[cfg(windows)]
163    let file_name = format!("{stem}.exe");
164    #[cfg(not(windows))]
165    let file_name = stem.to_string();
166    let mut dir = exe.parent();
167    while let Some(parent) = dir {
168        let candidate = parent.join(&file_name);
169        if candidate.is_file() {
170            return Some(candidate.to_string_lossy().into_owned());
171        }
172        dir = parent.parent();
173    }
174    None
175}
176
177/// Build a process [`std::process::ExitStatus`] from a raw exit code.
178///
179/// Canonical shared definition used by the mock manager, the Miri synthetic
180/// backend, and most executor tests (all need to fabricate statuses without
181/// spawning). Note: `ChildHandle` and `exec::steps` retain small local
182/// duplicates.
183#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
184pub fn exit_status_from_code(code: i32) -> std::process::ExitStatus {
185    #[cfg(unix)]
186    {
187        use std::os::unix::process::ExitStatusExt;
188        ExitStatusExt::from_raw(code << 8)
189    }
190    #[cfg(windows)]
191    {
192        use std::os::windows::process::ExitStatusExt;
193        ExitStatusExt::from_raw(code as u32)
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::TestEnvGuard;
200    use std::env;
201
202    const SET_RESTORE_ABSENT: &str = "OXDOCK_SYS_TEST_UTILS_SET_RESTORE_ABSENT";
203    const SET_RESTORE_PREVIOUS: &str = "OXDOCK_SYS_TEST_UTILS_SET_RESTORE_PREVIOUS";
204    const REMOVE_RESTORE: &str = "OXDOCK_SYS_TEST_UTILS_REMOVE_RESTORE";
205    const KEY_A: &str = "OXDOCK_SYS_TEST_UTILS_KEY_A";
206    const KEY_B: &str = "OXDOCK_SYS_TEST_UTILS_KEY_B";
207    const NESTED: &str = "OXDOCK_SYS_TEST_UTILS_NESTED";
208
209    #[test]
210    #[cfg_attr(
211        miri,
212        ignore = "current_exe is an unsupported isolation operation under Miri"
213    )]
214    fn find_built_binary_resolves_layout_free() {
215        // The test executable itself always resolves: its parent dir
216        // holds it under its own file name on every cargo layout.
217        let exe = std::env::current_exe().expect("test executable path");
218        let stem = exe
219            .file_stem()
220            .expect("executable file name")
221            .to_string_lossy()
222            .into_owned();
223        let found = super::find_built_binary(&stem).expect("own test binary must resolve");
224        assert_eq!(
225            found,
226            exe.display().to_string(),
227            "the walk starts at the executable's own directory"
228        );
229        // A name no build produces resolves to nothing instead of
230        // wandering: the miss path is what failing harnesses report.
231        assert!(super::find_built_binary("oxdock-no-such-binary-xyz").is_none());
232    }
233
234    #[test]
235    fn set_guard_restores_absent_state_on_drop() {
236        drop(TestEnvGuard::remove(SET_RESTORE_ABSENT));
237
238        let guard = TestEnvGuard::set(SET_RESTORE_ABSENT, "value");
239        assert_eq!(env::var(SET_RESTORE_ABSENT).as_deref(), Ok("value"));
240        drop(guard);
241
242        assert!(env::var(SET_RESTORE_ABSENT).is_err());
243    }
244
245    #[test]
246    fn set_guard_restores_previous_value_on_drop() {
247        // Arrange a pre-existing value directly; unique key => no other test
248        // touches it and no guard is held for it here.
249        unsafe { env::set_var(SET_RESTORE_PREVIOUS, "original") };
250
251        let guard = TestEnvGuard::set(SET_RESTORE_PREVIOUS, "temporary");
252        assert_eq!(env::var(SET_RESTORE_PREVIOUS).as_deref(), Ok("temporary"));
253        drop(guard);
254
255        assert_eq!(env::var(SET_RESTORE_PREVIOUS).as_deref(), Ok("original"));
256        unsafe { env::remove_var(SET_RESTORE_PREVIOUS) };
257    }
258
259    #[test]
260    fn remove_guard_restores_previous_value_on_drop() {
261        unsafe { env::set_var(REMOVE_RESTORE, "keep-me") };
262
263        let guard = TestEnvGuard::remove(REMOVE_RESTORE);
264        assert!(env::var(REMOVE_RESTORE).is_err());
265        drop(guard);
266
267        assert_eq!(env::var(REMOVE_RESTORE).as_deref(), Ok("keep-me"));
268        unsafe { env::remove_var(REMOVE_RESTORE) };
269    }
270
271    #[test]
272    fn guards_for_different_keys_coexist() {
273        let a = TestEnvGuard::set(KEY_A, "1");
274        let b = TestEnvGuard::set(KEY_B, "2");
275
276        assert_eq!(env::var(KEY_A).as_deref(), Ok("1"));
277        assert_eq!(env::var(KEY_B).as_deref(), Ok("2"));
278
279        drop(b);
280        drop(a);
281    }
282
283    #[test]
284    #[should_panic(expected = "already guarded")]
285    fn same_key_nesting_panics_rather_than_deadlocking() {
286        let _outer = TestEnvGuard::set(NESTED, "outer");
287        let _inner = TestEnvGuard::set(NESTED, "inner");
288    }
289}