From 651005e29b7a6087c1e31567b5ce632bfec50ecd Mon Sep 17 00:00:00 2001 From: OzzyHelper <346962152+OzzyHelper@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:20:02 +0000 Subject: [PATCH 1/2] test: isolate filesystem tests from the real ~/.foc-devnet Unit tests exercised production write paths (key generation, mnemonic storage, run-ID persistence) against the real home directory. Running cargo test therefore overwrote ~/.foc-devnet/keys and, worse, deleted the active ~/.foc-devnet/state/current_runid.json. Add a test-only home override in paths::foc_devnet_home, guarded by a process-wide lock so parallel tests cannot race on it, and use it in every test that touches foc-devnet paths. Also fix two tests that verified nothing: - create_latest_symlink's test reimplemented the logic with temp dirs instead of calling the function; it now calls it. - print_running_status's test only asserted is_ok() while shelling out to Docker; it is removed. --- src/commands/init/keys.rs | 19 ++++++ src/commands/status/build_status.rs | 7 ++- src/commands/status/disk_usage.rs | 5 +- src/commands/status/running.rs | 15 ++--- src/crypto/mnemonic.rs | 29 ++++++++++ src/paths.rs | 90 ++++++++++++++++++++++++----- src/run_id/mod.rs | 84 ++++++++++++--------------- src/run_id/persistence.rs | 11 +++- 8 files changed, 187 insertions(+), 73 deletions(-) diff --git a/src/commands/init/keys.rs b/src/commands/init/keys.rs index e2e2f249..fc659645 100644 --- a/src/commands/init/keys.rs +++ b/src/commands/init/keys.rs @@ -136,9 +136,14 @@ pub fn load_keys() -> Result, Box> { #[cfg(test)] mod tests { use super::*; + use crate::paths::TestHome; #[test] fn test_generate_keys_includes_bls_keys() { + // Keep generated mnemonics and keys out of the real ~/.foc-devnet. + let home = tempfile::TempDir::new().unwrap(); + let _home = TestHome::new(home.path()); + let keys = generate_keys(false).unwrap(); // Check that we have the expected number of keys @@ -162,6 +167,20 @@ mod tests { assert!(key_names.contains(&"BLS_SIGNER_1")); assert!(key_names.contains(&"BLS_SIGNER_2")); assert!(key_names.contains(&"GLOBAL_FIL_FAUCET")); + + // Mnemonic and addresses are persisted under the isolated home and + // load_keys() reads back exactly what was generated. + let keys_dir = foc_devnet_keys(); + assert!(keys_dir.join("mnemonic.txt").is_file()); + assert!(keys_dir.join("addresses.json").is_file()); + + let persisted = load_keys().unwrap(); + let generated: Vec<_> = keys.iter().map(|k| (&k.name, &k.private_key)).collect(); + let reloaded: Vec<_> = persisted + .iter() + .map(|k| (&k.name, &k.private_key)) + .collect(); + assert_eq!(generated, reloaded); } #[test] diff --git a/src/commands/status/build_status.rs b/src/commands/status/build_status.rs index 4ad0283f..d3913287 100644 --- a/src/commands/status/build_status.rs +++ b/src/commands/status/build_status.rs @@ -89,9 +89,10 @@ mod tests { #[test] fn test_print_build_status() { - // This test mainly verifies that the function doesn't panic - // In a real scenario, you'd mock the foc_devnet_bin function - // or set up the environment properly + // Point the binary lookup at an empty throwaway home, not the real one. + let home = tempfile::TempDir::new().unwrap(); + let _home = crate::paths::TestHome::new(home.path()); + let result = print_build_status(); // We expect this to work even if no binaries exist assert!(result.is_ok()); diff --git a/src/commands/status/disk_usage.rs b/src/commands/status/disk_usage.rs index f5086c88..1cad3b5b 100644 --- a/src/commands/status/disk_usage.rs +++ b/src/commands/status/disk_usage.rs @@ -107,7 +107,10 @@ mod tests { #[test] fn test_print_disk_usage() { - // This test verifies that the function doesn't panic + // Measure a throwaway home instead of the real ~/.foc-devnet. + let home = tempfile::TempDir::new().unwrap(); + let _home = crate::paths::TestHome::new(home.path()); + let result = print_disk_usage(); // We expect this to work even if directories don't exist assert!(result.is_ok()); diff --git a/src/commands/status/running.rs b/src/commands/status/running.rs index 670f9fff..c7bdc3ca 100644 --- a/src/commands/status/running.rs +++ b/src/commands/status/running.rs @@ -172,15 +172,10 @@ fn format_container_ports(container_name: &str) -> Result Result> { let mnemonic = Mnemonic::parse_in_normalized(Language::English, &mnemonic_str)?; Ok(mnemonic) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::paths::TestHome; + + #[test] + fn store_then_load_mnemonic_round_trips() { + let home = tempfile::TempDir::new().unwrap(); + let _home = TestHome::new(home.path()); + + let original = Mnemonic::from_entropy_in(Language::English, &[42u8; 32]).unwrap(); + store_mnemonic(&original).unwrap(); + + let mnemonic_file = foc_devnet_keys().join("mnemonic.txt"); + assert!(mnemonic_file.is_file()); + + let loaded = load_mnemonic().unwrap(); + assert_eq!(loaded.to_string(), original.to_string()); + } + + #[test] + fn load_mnemonic_fails_when_no_mnemonic_was_stored() { + let home = tempfile::TempDir::new().unwrap(); + let _home = TestHome::new(home.path()); + + assert!(load_mnemonic().is_err()); + } +} diff --git a/src/paths.rs b/src/paths.rs index 85e26561..0727124f 100644 --- a/src/paths.rs +++ b/src/paths.rs @@ -2,11 +2,79 @@ use std::path::PathBuf; use tracing::warn; +/// Test-only home directory override. +/// +/// Tests that touch the filesystem must never read or write the real +/// `~/.foc-devnet`. An environment variable would work, but it is +/// process-global and leaks across the parallel test threads; this override is +/// guarded by a process-wide lock so only one test can point path resolution at +/// a temporary directory at a time. +#[cfg(test)] +mod test_support { + use std::path::{Path, PathBuf}; + use std::sync::{Mutex, MutexGuard}; + + static OVERRIDE: Mutex> = Mutex::new(None); + static TEST_LOCK: Mutex<()> = Mutex::new(()); + + fn test_lock() -> MutexGuard<'static, ()> { + // A panicking test poisons the lock; later tests should still run. + TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn override_slot() -> MutexGuard<'static, Option> { + OVERRIDE.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Holds the shared path-resolution lock for the duration of a test. + /// + /// Constructed with [`TestHome::new`], it redirects `foc_devnet_home()` to + /// the supplied directory. Constructed with [`TestHome::lock_only`], it + /// only serializes against other path tests, for cases that exercise + /// `FOC_DEVNET_BASEDIR` handling directly. + pub struct TestHome { + _lock: MutexGuard<'static, ()>, + } + + impl TestHome { + pub fn new(dir: &Path) -> Self { + let guard = test_lock(); + *override_slot() = Some(dir.to_path_buf()); + Self { _lock: guard } + } + + pub fn lock_only() -> Self { + let lock = test_lock(); + Self { _lock: lock } + } + } + + impl Drop for TestHome { + fn drop(&mut self) { + *override_slot() = None; + } + } + + pub(super) fn override_dir() -> Option { + override_slot().clone() + } +} + +#[cfg(test)] +pub(crate) use test_support::TestHome; + /// Returns the path to the foc-devnet home directory. /// First checks for $FOC_DEVNET_BASEDIR environment variable. /// If not set, defaults to ~/.foc-devnet /// Supports tilde expansion for paths like ~/my-foc-devnet pub fn foc_devnet_home() -> PathBuf { + #[cfg(test)] + { + if let Some(test_home) = test_support::override_dir() { + return test_home; + } + } + let default_path = || { dirs::home_dir() .unwrap_or_else(|| PathBuf::from("/tmp")) @@ -261,26 +329,28 @@ pub const CONTAINER_FILECOIN_PROOF_PARAMS_PATH: &str = "/var/tmp/filecoin-proof- mod tests { use super::*; use std::env; - use std::sync::Mutex; - - /// Serializes all tests that mutate FOC_DEVNET_BASEDIR to prevent - /// race conditions when the test suite uses multiple threads. - static ENV_MUTEX: Mutex<()> = Mutex::new(()); - /// Helper to safely set and restore environment variables in tests + /// Sets and restores an environment variable while holding the shared + /// path-resolution lock, so no concurrent test observes the change. struct EnvGuard { key: &'static str, original: Option, + _lock: TestHome, } impl EnvGuard { fn new(key: &'static str, value: Option<&str>) -> Self { + let lock = TestHome::lock_only(); let original = env::var(key).ok(); match value { Some(v) => env::set_var(key, v), None => env::remove_var(key), } - EnvGuard { key, original } + EnvGuard { + key, + original, + _lock: lock, + } } } @@ -295,7 +365,6 @@ mod tests { #[test] fn test_foc_devnet_home_with_custom_basedir() { - let _lock = ENV_MUTEX.lock().unwrap(); let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some("/tmp/my-foc-devnet")); let path = foc_devnet_home(); assert_eq!(path, PathBuf::from("/tmp/my-foc-devnet")); @@ -303,7 +372,6 @@ mod tests { #[test] fn test_foc_devnet_home_with_tilde_expansion() { - let _lock = ENV_MUTEX.lock().unwrap(); let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some("~/my-foc-devnet")); let path = foc_devnet_home(); @@ -315,7 +383,6 @@ mod tests { #[test] fn test_foc_devnet_home_with_empty_basedir() { - let _lock = ENV_MUTEX.lock().unwrap(); let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some("")); let path = foc_devnet_home(); @@ -328,7 +395,6 @@ mod tests { #[test] fn test_foc_devnet_home_with_whitespace_basedir() { - let _lock = ENV_MUTEX.lock().unwrap(); let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some(" ")); let path = foc_devnet_home(); @@ -341,7 +407,6 @@ mod tests { #[test] fn test_foc_devnet_home_no_env_var() { - let _lock = ENV_MUTEX.lock().unwrap(); let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", None); let path = foc_devnet_home(); @@ -355,7 +420,6 @@ mod tests { #[test] fn test_dependent_paths_use_foc_devnet_home() { - let _lock = ENV_MUTEX.lock().unwrap(); let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some("/tmp/test-foc")); // All dependent paths should use the custom base directory diff --git a/src/run_id/mod.rs b/src/run_id/mod.rs index feb3affe..081b109a 100644 --- a/src/run_id/mod.rs +++ b/src/run_id/mod.rs @@ -139,64 +139,56 @@ mod tests { assert!(temp_dir.path().join(id2).is_dir()); } + #[cfg(unix)] #[test] - fn test_create_latest_symlink_handles_broken_symlinks() { - // This test verifies that create_latest_symlink properly handles - // removing broken symlinks and creating new ones + fn test_create_latest_symlink_replaces_broken_symlink() { + use crate::paths::{foc_devnet_run_dir, foc_devnet_state_latest, TestHome}; use std::os::unix::fs::symlink; - use tempfile::TempDir; - let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let home = tempfile::TempDir::new().expect("Failed to create temp dir"); + let _home = TestHome::new(home.path()); - // Mock the paths by using temp directory structure - let runs_dir = temp_dir.path().join("run"); - let state_dir = temp_dir.path().join("state"); - let latest_link = state_dir.join("latest"); + let run_dir = foc_devnet_run_dir("run2"); + std::fs::create_dir_all(&run_dir).expect("Failed to create run dir"); - std::fs::create_dir_all(&runs_dir).expect("Failed to create runs dir"); - std::fs::create_dir_all(&state_dir).expect("Failed to create state dir"); + let latest_link = foc_devnet_state_latest(); + std::fs::create_dir_all(latest_link.parent().unwrap()) + .expect("Failed to create state dir"); - // Create first run directory - let run_dir1 = runs_dir.join("run1"); - std::fs::create_dir_all(&run_dir1).expect("Failed to create run1 dir"); + // Point the existing link at a directory that does not exist. + symlink(home.path().join("run/missing"), &latest_link) + .expect("Failed to create broken symlink"); + assert!(latest_link.is_symlink()); + assert!(!latest_link.exists(), "broken link target must not exist"); - // Create initial symlink - symlink(&run_dir1, &latest_link).expect("Failed to create initial symlink"); - assert!(latest_link.is_symlink(), "Initial symlink should exist"); - assert_eq!( - std::fs::read_link(&latest_link).unwrap(), - run_dir1, - "Symlink should point to run1" - ); + create_latest_symlink("run2").unwrap(); - // Delete the target to create a broken symlink - std::fs::remove_dir_all(&run_dir1).expect("Failed to remove run1 dir"); - assert!( - latest_link.is_symlink(), - "Broken symlink should still be detected as symlink" - ); - assert!( - !latest_link.exists(), - "Broken symlink target should not exist" - ); + assert!(latest_link.is_symlink(), "latest should be recreated"); + assert_eq!(std::fs::read_link(&latest_link).unwrap(), run_dir); + assert!(latest_link.exists(), "latest target should exist"); + } - // Create a new run directory - let run_dir2 = runs_dir.join("run2"); - std::fs::create_dir_all(&run_dir2).expect("Failed to create run2 dir"); + #[cfg(unix)] + #[test] + fn test_create_latest_symlink_repoints_existing_link() { + use crate::paths::{foc_devnet_run_dir, foc_devnet_state_latest, TestHome}; - // Remove the broken symlink and create new one - if latest_link.is_symlink() { - std::fs::remove_file(&latest_link).expect("Failed to remove broken symlink"); - } - assert!(!latest_link.exists(), "Symlink should be removed"); + let home = tempfile::TempDir::new().expect("Failed to create temp dir"); + let _home = TestHome::new(home.path()); + + std::fs::create_dir_all(foc_devnet_run_dir("run1")).unwrap(); + std::fs::create_dir_all(foc_devnet_run_dir("run2")).unwrap(); + + create_latest_symlink("run1").unwrap(); + assert_eq!( + std::fs::read_link(foc_devnet_state_latest()).unwrap(), + foc_devnet_run_dir("run1") + ); - symlink(&run_dir2, &latest_link).expect("Failed to create new symlink"); - assert!(latest_link.is_symlink(), "New symlink should exist"); + create_latest_symlink("run2").unwrap(); assert_eq!( - std::fs::read_link(&latest_link).unwrap(), - run_dir2, - "Symlink should point to run2" + std::fs::read_link(foc_devnet_state_latest()).unwrap(), + foc_devnet_run_dir("run2") ); - assert!(latest_link.exists(), "New symlink target should exist"); } } diff --git a/src/run_id/persistence.rs b/src/run_id/persistence.rs index f847fd0a..54856ada 100644 --- a/src/run_id/persistence.rs +++ b/src/run_id/persistence.rs @@ -86,17 +86,26 @@ mod tests { #[test] fn test_save_and_load_run_id() { + // Never write to the real ~/.foc-devnet/state/current_runid.json: this + // test used to overwrite and then delete the user's active run ID. + let home = tempfile::TempDir::new().unwrap(); + let _home = crate::paths::TestHome::new(home.path()); + let test_run_id = "251203-1246-test-wolf"; // Save save_current_run_id(test_run_id).unwrap(); + let state_file = crate::paths::foc_devnet_state().join("current_runid.json"); + assert!(state_file.is_file(), "run ID should be persisted under the isolated home"); + // Load let loaded_id = load_current_run_id().unwrap(); assert_eq!(loaded_id, test_run_id); - // Clean up + // Delete delete_current_run_id().unwrap(); + assert!(!state_file.exists()); // Verify deletion assert!(load_current_run_id().is_err()); From 67c1a29e655d42ed75a7e40504c542bac025f9df Mon Sep 17 00:00:00 2001 From: OzzyHelper <346962152+OzzyHelper@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:59:37 +0000 Subject: [PATCH 2/2] test: isolate filesystem tests from the real ~/.foc-devnet --- src/run_id/mod.rs | 3 +-- src/run_id/persistence.rs | 5 ++++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/run_id/mod.rs b/src/run_id/mod.rs index 081b109a..58fb0b9d 100644 --- a/src/run_id/mod.rs +++ b/src/run_id/mod.rs @@ -152,8 +152,7 @@ mod tests { std::fs::create_dir_all(&run_dir).expect("Failed to create run dir"); let latest_link = foc_devnet_state_latest(); - std::fs::create_dir_all(latest_link.parent().unwrap()) - .expect("Failed to create state dir"); + std::fs::create_dir_all(latest_link.parent().unwrap()).expect("Failed to create state dir"); // Point the existing link at a directory that does not exist. symlink(home.path().join("run/missing"), &latest_link) diff --git a/src/run_id/persistence.rs b/src/run_id/persistence.rs index 54856ada..4c10bdeb 100644 --- a/src/run_id/persistence.rs +++ b/src/run_id/persistence.rs @@ -97,7 +97,10 @@ mod tests { save_current_run_id(test_run_id).unwrap(); let state_file = crate::paths::foc_devnet_state().join("current_runid.json"); - assert!(state_file.is_file(), "run ID should be persisted under the isolated home"); + assert!( + state_file.is_file(), + "run ID should be persisted under the isolated home" + ); // Load let loaded_id = load_current_run_id().unwrap();