Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/commands/init/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,15 @@ pub fn load_keys() -> Result<Vec<KeyInfo>, Box<dyn std::error::Error>> {

#[cfg(test)]
mod tests {
use crate::paths::TestHome;

use super::*;

#[test]
fn test_generate_keys_includes_bls_keys() {
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
Expand Down
5 changes: 5 additions & 0 deletions src/commands/status/build_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,15 @@ fn get_binary_version(binary_path: &std::path::Path) -> String {

#[cfg(test)]
mod tests {
use crate::paths::TestHome;

use super::*;

#[test]
fn test_print_build_status() {
let home = tempfile::TempDir::new().unwrap();
let _home = TestHome::new(home.path());

// 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
Expand Down
5 changes: 5 additions & 0 deletions src/commands/status/disk_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,15 @@ pub fn print_disk_usage() -> Result<(), Box<dyn std::error::Error>> {

#[cfg(test)]
mod tests {
use crate::paths::TestHome;

use super::*;

#[test]
fn test_print_disk_usage() {
let home = tempfile::TempDir::new().unwrap();
let _home = TestHome::new(home.path());

// This test verifies that the function doesn't panic
let result = print_disk_usage();
// We expect this to work even if directories don't exist
Expand Down
10 changes: 0 additions & 10 deletions src/commands/status/running.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,6 @@ fn format_container_ports(container_name: &str) -> Result<String, Box<dyn std::e
mod tests {
use super::*;

#[test]
fn test_print_running_status() {
// This test verifies that the function doesn't panic
// In a real environment with Docker, it would check actual containers
let result = print_running_status();
// We expect this to work even if Docker is not available
// (it will just show empty results)
assert!(result.is_ok());
}

#[test]
fn test_extract_base_image_name() {
assert_eq!(
Expand Down
98 changes: 86 additions & 12 deletions src/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@ use std::path::PathBuf;
use tracing::warn;

/// Returns the path to the foc-devnet home directory.
/// First checks for $FOC_DEVNET_BASEDIR environment variable.
/// In test builds, a [`TestHome`] override takes precedence over everything else.
/// Otherwise 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_home::current() {
return test_home;
}

let default_path = || {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("/tmp"))
Expand Down Expand Up @@ -257,15 +263,83 @@ pub fn project_root() -> Result<PathBuf, std::io::Error> {
/// Container path where Filecoin proof parameters are mounted
pub const CONTAINER_FILECOIN_PROOF_PARAMS_PATH: &str = "/var/tmp/filecoin-proof-parameters";

/// Test-only redirect for [`foc_devnet_home`].
///
/// Unit tests must never touch the real `~/.foc-devnet`: tests run in parallel
/// and writing shared user state makes them order-dependent and destructive.
/// The override and the `FOC_DEVNET_BASEDIR` tests share one process-wide lock,
/// because both mutate how paths resolve globally.
#[cfg(test)]
mod test_home {
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};

static HOME_OVERRIDE: Mutex<Option<PathBuf>> = Mutex::new(None);
static HOME_MUTEX: Mutex<()> = Mutex::new(());

fn lock() -> MutexGuard<'static, ()> {
// A panicking test poisons the lock; recovering keeps it serializing
// rather than turning every later test into a failure.
HOME_MUTEX.lock().unwrap_or_else(|error| error.into_inner())
}

pub(super) fn current() -> Option<PathBuf> {
HOME_OVERRIDE
.lock()
.unwrap_or_else(|error| error.into_inner())
.clone()
}

/// Holds the process-wide path lock for the duration of a test and points
/// `foc_devnet_home()` at `path`.
#[must_use = "the override is cleared when the guard drops; bind it to a local"]
pub struct TestHome {
_lock: MutexGuard<'static, ()>,
installed_override: bool,
}

impl TestHome {
pub fn new(path: &Path) -> Self {
let lock = lock();
*HOME_OVERRIDE
.lock()
.unwrap_or_else(|error| error.into_inner()) = Some(path.to_path_buf());
TestHome {
_lock: lock,
installed_override: true,
}
}

/// Takes the shared path lock without changing the home directory.
///
/// Use this for tests that set `FOC_DEVNET_BASEDIR` so they cannot run
/// concurrently with a `TestHome` override.
pub fn lock_only() -> Self {
TestHome {
_lock: lock(),
installed_override: false,
}
}
}

impl Drop for TestHome {
fn drop(&mut self) {
if self.installed_override {
*HOME_OVERRIDE
.lock()
.unwrap_or_else(|error| error.into_inner()) = None;
}
}
}
}

#[cfg(test)]
pub use test_home::TestHome;

#[cfg(test)]
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
struct EnvGuard {
Expand Down Expand Up @@ -295,15 +369,15 @@ mod tests {

#[test]
fn test_foc_devnet_home_with_custom_basedir() {
let _lock = ENV_MUTEX.lock().unwrap();
let _lock = TestHome::lock_only();
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"));
}

#[test]
fn test_foc_devnet_home_with_tilde_expansion() {
let _lock = ENV_MUTEX.lock().unwrap();
let _lock = TestHome::lock_only();
let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some("~/my-foc-devnet"));
let path = foc_devnet_home();

Expand All @@ -315,7 +389,7 @@ mod tests {

#[test]
fn test_foc_devnet_home_with_empty_basedir() {
let _lock = ENV_MUTEX.lock().unwrap();
let _lock = TestHome::lock_only();
let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some(""));
let path = foc_devnet_home();

Expand All @@ -328,7 +402,7 @@ mod tests {

#[test]
fn test_foc_devnet_home_with_whitespace_basedir() {
let _lock = ENV_MUTEX.lock().unwrap();
let _lock = TestHome::lock_only();
let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some(" "));
let path = foc_devnet_home();

Expand All @@ -341,7 +415,7 @@ mod tests {

#[test]
fn test_foc_devnet_home_no_env_var() {
let _lock = ENV_MUTEX.lock().unwrap();
let _lock = TestHome::lock_only();
let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", None);

let path = foc_devnet_home();
Expand All @@ -355,7 +429,7 @@ mod tests {

#[test]
fn test_dependent_paths_use_foc_devnet_home() {
let _lock = ENV_MUTEX.lock().unwrap();
let _lock = TestHome::lock_only();
let _guard = EnvGuard::new("FOC_DEVNET_BASEDIR", Some("/tmp/test-foc"));

// All dependent paths should use the custom base directory
Expand Down
55 changes: 24 additions & 31 deletions src/run_id/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,11 @@ pub fn create_latest_symlink(run_id: &str) -> Result<(), Box<dyn std::error::Err

#[cfg(test)]
mod tests {
use super::*;
use crate::paths::TestHome;
use regex::Regex;

use super::*;

#[test]
fn test_run_id_format() {
let run_id = generate_candidate();
Expand All @@ -141,35 +143,24 @@ mod tests {

#[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
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 latest_link = crate::paths::foc_devnet_state_latest();

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");

// Create first run directory
let run_dir1 = runs_dir.join("run1");
// First run creates the state directory and the symlink.
let run_dir1 = crate::paths::foc_devnet_run_dir("run1");
std::fs::create_dir_all(&run_dir1).expect("Failed to create run1 dir");

// Create initial symlink
symlink(&run_dir1, &latest_link).expect("Failed to create initial symlink");
create_latest_symlink("run1").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"
);

// Delete the target to create a broken symlink
// Deleting the target leaves a broken symlink; recreating the latest
// link must remove it rather than fail.
std::fs::remove_dir_all(&run_dir1).expect("Failed to remove run1 dir");
assert!(
latest_link.is_symlink(),
Expand All @@ -180,23 +171,25 @@ mod tests {
"Broken symlink target should not exist"
);

// Create a new run directory
let run_dir2 = runs_dir.join("run2");
let run_dir2 = crate::paths::foc_devnet_run_dir("run2");
std::fs::create_dir_all(&run_dir2).expect("Failed to create run2 dir");

// 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");

symlink(&run_dir2, &latest_link).expect("Failed to create new symlink");
assert!(latest_link.is_symlink(), "New symlink should exist");
create_latest_symlink("run2").expect("Failed to replace broken symlink");
assert_eq!(
std::fs::read_link(&latest_link).unwrap(),
run_dir2,
"Symlink should point to run2"
);
assert!(latest_link.exists(), "New symlink target should exist");

// A valid symlink must also be replaced by a newer run.
let run_dir3 = crate::paths::foc_devnet_run_dir("run3");
std::fs::create_dir_all(&run_dir3).expect("Failed to create run3 dir");
create_latest_symlink("run3").expect("Failed to replace valid symlink");
assert_eq!(
std::fs::read_link(&latest_link).unwrap(),
run_dir3,
"Symlink should point to run3"
);
assert!(latest_link.exists(), "Replacement target should exist");
}
}
4 changes: 4 additions & 0 deletions src/run_id/persistence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,15 @@ pub fn delete_current_run_id() -> Result<(), Box<dyn Error>> {

#[cfg(test)]
mod tests {
use crate::paths::TestHome;

use super::*;

#[test]
fn test_save_and_load_run_id() {
let test_run_id = "251203-1246-test-wolf";
let home = tempfile::TempDir::new().unwrap();
let _home = TestHome::new(home.path());

// Save
save_current_run_id(test_run_id).unwrap();
Expand Down