use checkpointkit::{load, save, CheckpointError, ProgressTracker};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use tempfile::tempdir;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Version1State {
value: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Version2State {
value: String,
new_field: Option<i32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct LargeScanState {
items_processed: u64,
data: Vec<u64>,
}
#[test]
fn test_break_crash_during_rename() {
let dir = tempdir().unwrap();
let path = dir.path().join("crash1.json");
save(&path, &"initial").unwrap();
let tmp_path = dir.path().join("crash1.json.tmp.123");
fs::write(&tmp_path, b"\"corrupt_tmp_data\"").unwrap();
let loaded: Option<String> = load(&path).unwrap();
assert_eq!(loaded, Some("initial".to_string()));
}
#[test]
fn test_break_crash_leaves_empty_file() {
let dir = tempdir().unwrap();
let path = dir.path().join("crash2.json");
fs::write(&path, b"").unwrap();
let loaded: Result<Option<String>, _> = load(&path);
assert!(
matches!(&loaded, Err(CheckpointError::CorruptCheckpoint(p)) if p == &path),
"expected CorruptCheckpoint for crash-truncated file, got {loaded:?}"
);
}
#[test]
fn test_break_crash_leaves_partial_json() {
let dir = tempdir().unwrap();
let path = dir.path().join("crash3.json");
fs::write(&path, b"{\"value\":").unwrap();
let loaded: Result<Option<Version1State>, _> = load(&path);
assert!(matches!(loaded, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_crash_leaves_null_bytes() {
let dir = tempdir().unwrap();
let path = dir.path().join("crash4.json");
fs::write(&path, b"\0\0\0\0").unwrap();
let loaded: Result<Option<Version1State>, _> = load(&path);
assert!(matches!(loaded, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_crash_tmp_file_cleaned_on_next_save() {
let dir = tempdir().unwrap();
let path = dir.path().join("crash5.json");
let tmp_path = dir.path().join("crash5.json.tmp.999");
fs::write(&tmp_path, b"junk").unwrap();
save(&path, &"new").unwrap();
let loaded: Option<String> = load(&path).unwrap();
assert_eq!(loaded, Some("new".to_string()));
}
#[test]
fn test_break_zero_progress_tracker() {
let dir = tempdir().unwrap();
let path = dir.path().join("zero1.json");
let mut tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
tracker.increment(0).unwrap();
let resumed = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
assert_eq!(resumed.current(), 0);
}
#[test]
fn test_break_zero_progress_resume() {
let dir = tempdir().unwrap();
let path = dir.path().join("zero2.json");
let tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
assert_eq!(tracker.resume().unwrap(), 0);
}
#[test]
fn test_break_zero_progress_file_content() {
let dir = tempdir().unwrap();
let path = dir.path().join("zero3.json");
let mut tracker = ProgressTracker::new(100, &path, Duration::ZERO).unwrap();
tracker.flush().unwrap();
let content = fs::read_to_string(&path).unwrap();
assert!(content.contains("\"progress\":0"));
}
#[test]
fn test_break_zero_total_progress() {
let dir = tempdir().unwrap();
let path = dir.path().join("zero4.json");
let mut tracker = ProgressTracker::new(0, &path, Duration::ZERO).unwrap();
tracker.increment(10).unwrap();
assert_eq!(tracker.current(), 0); }
#[test]
fn test_break_exact_completion_increment() {
let dir = tempdir().unwrap();
let path = dir.path().join("comp1.json");
let mut tracker = ProgressTracker::new(50, &path, Duration::from_secs(100)).unwrap();
tracker.increment(50).unwrap();
let resumed = ProgressTracker::new(50, &path, Duration::ZERO).unwrap();
assert_eq!(resumed.current(), 50);
}
#[test]
fn test_break_exact_completion_multiple_steps() {
let dir = tempdir().unwrap();
let path = dir.path().join("comp2.json");
let mut tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
for _ in 0..10 {
tracker.increment(1).unwrap();
}
assert_eq!(tracker.resume().unwrap(), 10);
}
#[test]
fn test_break_past_completion_capped() {
let dir = tempdir().unwrap();
let path = dir.path().join("comp3.json");
let mut tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
tracker.increment(100).unwrap();
assert_eq!(tracker.current(), 10);
assert_eq!(tracker.resume().unwrap(), 10);
}
#[test]
fn test_break_completion_resume_from_file() {
let dir = tempdir().unwrap();
let path = dir.path().join("comp4.json");
fs::write(&path, r#"{"total":10,"progress":10}"#).unwrap();
let tracker = ProgressTracker::new(10, &path, Duration::ZERO).unwrap();
assert_eq!(tracker.current(), 10);
}
#[test]
fn test_break_concurrent_writers_progress() {
let dir = tempdir().unwrap();
let path = Arc::new(dir.path().join("conc1.json"));
let mut handles = vec![];
for _ in 0..10 {
let path = Arc::clone(&path);
handles.push(thread::spawn(move || {
let mut tracker = ProgressTracker::new(1000, &*path, Duration::ZERO).unwrap();
tracker.increment(10).unwrap();
}));
}
for h in handles {
h.join().unwrap();
}
let tracker = ProgressTracker::new(1000, &*path, Duration::ZERO).unwrap();
assert!(tracker.current() >= 10);
}
#[test]
fn test_break_concurrent_readers_and_writers() {
let dir = tempdir().unwrap();
let path = Arc::new(dir.path().join("conc2.json"));
save(&*path, &0).unwrap();
let mut handles = vec![];
for i in 0..20 {
let path = Arc::clone(&path);
if i % 2 == 0 {
handles.push(thread::spawn(move || {
let _ = save(&*path, &i);
}));
} else {
handles.push(thread::spawn(move || {
let _loaded: Option<i32> = load(&*path).unwrap();
}));
}
}
for h in handles {
h.join().unwrap();
}
let final_val: Option<i32> = load(&*path).unwrap();
assert!(final_val.is_some());
}
#[test]
fn test_break_concurrent_saves_same_value() {
let dir = tempdir().unwrap();
let path = Arc::new(dir.path().join("conc3.json"));
let mut handles = vec![];
for _ in 0..10 {
let path = Arc::clone(&path);
handles.push(thread::spawn(move || {
save(&*path, &42).unwrap();
}));
}
for h in handles {
h.join().unwrap();
}
let loaded: Option<i32> = load(&*path).unwrap();
assert_eq!(loaded, Some(42));
}
#[test]
fn test_break_concurrent_rapid_updates() {
let dir = tempdir().unwrap();
let path = Arc::new(dir.path().join("conc4.json"));
let mut handles = vec![];
for i in 0..5 {
let path = Arc::clone(&path);
handles.push(thread::spawn(move || {
for j in 0..50 {
save(&*path, &(i * 100 + j)).unwrap();
}
}));
}
for h in handles {
h.join().unwrap();
}
let loaded: Option<i32> = load(&*path).unwrap();
assert!(loaded.is_some());
}
#[test]
fn test_break_corrupt_recovery_overwrite() {
let dir = tempdir().unwrap();
let path = dir.path().join("corr1.json");
fs::write(&path, b"invalid_json").unwrap();
assert!(matches!(load::<i32>(&path), Err(CheckpointError::Serialize(_))));
save(&path, &99).unwrap();
let loaded: Option<i32> = load(&path).unwrap();
assert_eq!(loaded, Some(99));
}
#[test]
fn test_break_corrupt_recovery_progress_tracker() {
let dir = tempdir().unwrap();
let path = dir.path().join("corr2.json");
fs::write(&path, b"invalid").unwrap();
let res = ProgressTracker::new(100, &path, Duration::ZERO);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_corrupt_type_mismatch() {
let dir = tempdir().unwrap();
let path = dir.path().join("corr3.json");
save(&path, &"string_value").unwrap();
let res: Result<Option<i32>, _> = load(&path);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_corrupt_array_for_object() {
let dir = tempdir().unwrap();
let path = dir.path().join("corr4.json");
fs::write(&path, b"[1, 2, 3]").unwrap();
let res: Result<Option<Version1State>, _> = load(&path);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_corrupt_whitespace_only() {
let dir = tempdir().unwrap();
let path = dir.path().join("corr5.json");
fs::write(&path, b" \n \t ").unwrap();
let res: Result<Option<i32>, _> = load(&path);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_large_scan_resume() {
let dir = tempdir().unwrap();
let path = dir.path().join("scan1.json");
let state = LargeScanState {
items_processed: 500_000,
data: vec![1, 2, 3, 4, 5],
};
save(&path, &state).unwrap();
let loaded: LargeScanState = load(&path).unwrap().unwrap();
assert_eq!(loaded.items_processed, 500_000);
assert_eq!(loaded.data, vec![1, 2, 3, 4, 5]);
}
#[test]
fn test_break_large_scan_huge_data() {
let dir = tempdir().unwrap();
let path = dir.path().join("scan2.json");
let state = LargeScanState {
items_processed: 100,
data: vec![42; 100_000],
};
save(&path, &state).unwrap();
let loaded: LargeScanState = load(&path).unwrap().unwrap();
assert_eq!(loaded.data.len(), 100_000);
}
#[test]
fn test_break_large_scan_progress_tracker() {
let dir = tempdir().unwrap();
let path = dir.path().join("scan3.json");
fs::write(&path, r#"{"total":1000000,"progress":500000}"#).unwrap();
let mut tracker = ProgressTracker::new(1_000_000, &path, Duration::ZERO).unwrap();
assert_eq!(tracker.current(), 500_000);
tracker.increment(1).unwrap();
assert_eq!(tracker.current(), 500_001);
}
#[test]
fn test_break_large_scan_progress_tracker_change_total() {
let dir = tempdir().unwrap();
let path = dir.path().join("scan4.json");
fs::write(&path, r#"{"total":1000000,"progress":500000}"#).unwrap();
let tracker = ProgressTracker::new(100_000, &path, Duration::ZERO).unwrap();
assert_eq!(tracker.current(), 100_000); }
#[test]
fn test_break_large_scan_zero_progress_resume() {
let dir = tempdir().unwrap();
let path = dir.path().join("scan5.json");
let state = LargeScanState {
items_processed: 0,
data: vec![],
};
save(&path, &state).unwrap();
let loaded: LargeScanState = load(&path).unwrap().unwrap();
assert_eq!(loaded.items_processed, 0);
}
#[test]
fn test_break_version_upgrade_forward_compatible() {
let dir = tempdir().unwrap();
let path = dir.path().join("vers1.json");
let v1 = Version1State { value: "test".to_string() };
save(&path, &v1).unwrap();
let v2: Version2State = load(&path).unwrap().unwrap();
assert_eq!(v2.value, "test");
assert_eq!(v2.new_field, None);
}
#[test]
fn test_break_version_downgrade_backward_compatible() {
let dir = tempdir().unwrap();
let path = dir.path().join("vers2.json");
let v2 = Version2State { value: "test".to_string(), new_field: Some(42) };
save(&path, &v2).unwrap();
let v1: Version1State = load(&path).unwrap().unwrap();
assert_eq!(v1.value, "test");
}
#[test]
fn test_break_version_upgrade_missing_required_field() {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Version3State {
value: String,
required_field: i32,
}
let dir = tempdir().unwrap();
let path = dir.path().join("vers3.json");
let v1 = Version1State { value: "test".to_string() };
save(&path, &v1).unwrap();
let res: Result<Option<Version3State>, _> = load(&path);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_version_type_change() {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Version4State {
value: i32, }
let dir = tempdir().unwrap();
let path = dir.path().join("vers4.json");
let v1 = Version1State { value: "123".to_string() };
save(&path, &v1).unwrap();
let res: Result<Option<Version4State>, _> = load(&path);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_version_enum_variants() {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
enum V1Enum { A, B }
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
enum V2Enum { A, B, C }
let dir = tempdir().unwrap();
let path = dir.path().join("vers5.json");
save(&path, &V1Enum::B).unwrap();
let loaded: V2Enum = load(&path).unwrap().unwrap();
assert_eq!(loaded, V2Enum::B);
save(&path, &V2Enum::C).unwrap();
let res: Result<Option<V1Enum>, _> = load(&path);
assert!(matches!(res, Err(CheckpointError::Serialize(_))));
}
#[test]
fn test_break_progress_tracker_interval_not_elapsed() {
let dir = tempdir().unwrap();
let path = dir.path().join("extra1.json");
let mut tracker = ProgressTracker::new(100, &path, Duration::from_secs(1000)).unwrap();
tracker.increment(1).unwrap();
let file_exists = path.exists();
assert!(!file_exists);
}
#[test]
fn test_break_progress_tracker_persist_error_propagation() {
let dir = tempdir().unwrap();
let _path = dir.path().join("readonly").join("extra2.json");
let path = Path::new("null\0dir/progress.json");
let res = ProgressTracker::new(100, path, Duration::ZERO);
assert!(matches!(res, Err(CheckpointError::Io { .. })));
}