checkpointkit 0.1.2

Crash-resume checkpoint persistence with atomic writes and progress tracking
Documentation
//! unit tests for checkpointkit.
//! See TESTING.md for the Santh testing standard.

use checkpointkit::{load, save, CheckpointError, ProgressTracker};
use std::time::Duration;
use tempfile::tempdir;

#[test]
fn test_save_and_load_success() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("test_save_and_load.json");
    let state = 42;

    assert!(save(&path, &state).is_ok(), "save should succeed");

    let loaded: Option<i32> = load(&path).unwrap();
    assert_eq!(loaded, Some(42), "loaded state should match saved state");
}

#[test]
fn test_load_nonexistent_returns_none() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("missing.json");

    let loaded: Option<i32> = load(&path).unwrap();
    assert_eq!(loaded, None, "loading a missing file should return None");
}

#[test]
fn test_save_path_traversal_fails() {
    let path = std::path::Path::new("/tmp/../test.json");
    let state = 42;

    let result = save(path, &state);
    assert!(
        matches!(result, Err(CheckpointError::PathTraversal(_))),
        "Expected PathTraversal error, got {result:?}"
    );
}

#[test]
fn test_load_path_traversal_fails() {
    let path = std::path::Path::new("/tmp/../test.json");

    let result: Result<Option<i32>, _> = load(path);
    assert!(
        matches!(result, Err(CheckpointError::PathTraversal(_))),
        "Expected PathTraversal error, got {result:?}"
    );
}

#[test]
fn test_progress_tracker_initializes_with_zero() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("progress.json");
    
    let tracker = ProgressTracker::new(100, &path, Duration::from_secs(1)).unwrap();
    assert_eq!(tracker.current(), 0, "initial current should be 0");
    assert_eq!(tracker.total(), 100, "total should match configured");
    assert_eq!(tracker.resume().unwrap(), 0, "resume should return 0 if no checkpoint");
}

#[test]
fn test_progress_tracker_increments_correctly() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("progress.json");
    
    let mut tracker = ProgressTracker::new(100, &path, Duration::from_secs(1)).unwrap();
    let current = tracker.increment(10).unwrap();
    assert_eq!(current, 10, "current should be 10");
    assert_eq!(tracker.current(), 10, "current should be 10");
}

#[test]
fn test_progress_tracker_caps_at_total() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("progress.json");
    
    let mut tracker = ProgressTracker::new(10, &path, Duration::from_secs(1)).unwrap();
    tracker.increment(5).unwrap();
    tracker.increment(10).unwrap(); // Should cap at 10
    
    assert_eq!(tracker.current(), 10, "current should be capped at total");
}

#[test]
fn test_progress_tracker_auto_saves_on_completion() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("progress.json");
    
    let mut tracker = ProgressTracker::new(10, &path, Duration::from_secs(10)).unwrap();
    // Increment to completion. Should auto-save even if duration hasn't passed.
    tracker.increment(10).unwrap();
    
    assert_eq!(tracker.resume().unwrap(), 10, "resume should reflect auto-saved value");
}

#[test]
fn test_progress_tracker_resumes_saved_state() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("progress.json");
    
    // Create initial tracker and force save by using zero duration
    let mut tracker1 = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
    tracker1.increment(4).unwrap();
    drop(tracker1); // Ensure files are closed
    
    // Create new tracker, should resume from 4
    let tracker2 = ProgressTracker::new(10, &path, Duration::from_secs(1)).unwrap();
    assert_eq!(tracker2.current(), 4, "should resume with current=4");

}
#[test]
fn test_drop_does_not_persist_unchanged_progress() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("no_change.json");

    let tracker = ProgressTracker::new(10, &path, Duration::from_secs(1)).unwrap();
    drop(tracker);

    assert!(!path.exists(), "Drop should not create a checkpoint when progress has not changed");
}

#[test]
fn test_repeated_completion_does_not_rewrite() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("no_rewrite.json");

    let mut tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
    tracker.increment(10).unwrap();

    let first_mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
    std::thread::sleep(Duration::from_millis(20));

    // Further increments past the total should not trigger another write.
    tracker.increment(5).unwrap();

    let second_mtime = std::fs::metadata(&path).unwrap().modified().unwrap();
    assert_eq!(first_mtime, second_mtime, "no new write should occur when progress is unchanged");
}
mod test_depth_unit;

#[test]
fn test_temp_file_guard_deletes_on_panic() {
    use serde::Serializer;
    use std::panic::{catch_unwind, AssertUnwindSafe};

    struct PanicSerializer;

    impl serde::Serialize for PanicSerializer {
        fn serialize<S: Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
            panic!("intentional serialization panic");
        }
    }

    let dir = tempdir().unwrap();
    let path = dir.path().join("panic_state.json");

    let result = catch_unwind(AssertUnwindSafe(|| save(&path, &PanicSerializer)));
    assert!(result.is_err(), "save should propagate the serialization panic");

    let temp_files: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
        .collect();
    assert!(temp_files.is_empty(), "TempFileGuard should remove the temp file on panic");
}

#[cfg(unix)]
#[test]
fn test_symlink_escape_is_blocked() {
    use std::os::unix::fs::symlink;

    let dir = tempdir().unwrap();
    let base = dir.path().join("base");
    std::fs::create_dir(&base).unwrap();
    let outside = dir.path().join("outside.json");
    std::fs::write(&outside, b"{}").unwrap();

    let escaped = base.join("escape.json");
    symlink(std::path::Path::new("../outside.json"), &escaped).unwrap();

    let result = save(&escaped, &42);
    assert!(
        matches!(result, Err(CheckpointError::PathTraversal(_))),
        "save through a symlink escaping the parent should be rejected: {result:?}"
    );

    let result: Result<Option<i32>, _> = load(&escaped);
    assert!(
        matches!(result, Err(CheckpointError::PathTraversal(_))),
        "load through a symlink escaping the parent should be rejected: {result:?}"
    );
}