Skip to content
Merged
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
19 changes: 19 additions & 0 deletions src/commands/init/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,14 @@ pub fn load_keys() -> Result<Vec<KeyInfo>, Box<dyn std::error::Error>> {
#[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
Expand All @@ -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]
Expand Down
7 changes: 4 additions & 3 deletions src/commands/status/build_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
5 changes: 4 additions & 1 deletion src/commands/status/disk_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
15 changes: 6 additions & 9 deletions src/commands/status/running.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,10 @@ 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());
}
// NOTE: print_running_status() is deliberately not unit-tested. It shells
// out to Docker and asserts nothing beyond "does not panic", so the old
// test passed without exercising any of its logic and failed whenever the
// Docker daemon was unavailable.

#[test]
fn test_extract_base_image_name() {
Expand All @@ -200,5 +195,7 @@ mod tests {
extract_base_image_name(crate::constants::LOTUS_CONTAINER),
crate::constants::LOTUS_CONTAINER
);
// Names without the foc- prefix are returned untouched.
assert_eq!(extract_base_image_name("postgres"), "postgres");
}
}
29 changes: 29 additions & 0 deletions src/crypto/mnemonic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,32 @@ pub fn load_mnemonic() -> Result<Mnemonic, Box<dyn std::error::Error>> {
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());
}
}
90 changes: 77 additions & 13 deletions src/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<PathBuf>> = 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<PathBuf>> {
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<PathBuf> {
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"))
Expand Down Expand Up @@ -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<String>,
_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,
}
}
}

Expand All @@ -295,15 +365,13 @@ 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"));
}

#[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();

Expand All @@ -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();

Expand All @@ -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();

Expand All @@ -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();
Expand All @@ -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
Expand Down
83 changes: 37 additions & 46 deletions src/run_id/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,64 +139,55 @@ 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");
}
}
Loading