// Integration tests for compressed archive functionality use json_archive::archive_open::open_archive; use json_archive::write_observation; use json_archive::{read_archive, ReadMode}; use serde_json::{json, Value}; use std::fs::File; use std::io::{BufWriter, Write}; use tempfile::NamedTempFile; #[test] #[cfg(feature = "compression")] fn test_append_to_compressed_archive_basic() { use flate2::write::GzEncoder; use flate2::Compression; // Create initial archive with one state let initial_state = create_json_file(&json!({"count": 0})); let archive_file = NamedTempFile::with_suffix(".json.archive").unwrap(); #[allow(unused_assignments)] { let file = File::create(archive_file.path()).unwrap(); let mut writer = BufWriter::new(file); let mut current_state = Value::Null; let mut observation_count: usize = 0; current_state = write_observation( &mut writer, &mut observation_count, None, ¤t_state, &initial_state.path().to_path_buf(), Some("test".to_string()), ) .unwrap(); writer.flush().unwrap(); } dump_file(archive_file.path(), "Uncompressed archive"); // Compress it let compressed_file = NamedTempFile::with_suffix(".json.archive.gz").unwrap(); { let input = std::fs::read(archive_file.path()).unwrap(); let mut encoder = GzEncoder::new( compressed_file.as_file().try_clone().unwrap(), Compression::default(), ); encoder.write_all(&input).unwrap(); encoder.finish().unwrap(); } dump_file(compressed_file.path(), "Compressed archive"); // Verify the compressed archive can be read let opened = open_archive(compressed_file.path()).unwrap(); let result = read_archive( opened.reader, &compressed_file.path().display().to_string(), ReadMode::FullValidation, ) .unwrap(); eprintln!("=== Reader result ==="); eprintln!("final_state: {:?}", result.final_state); eprintln!("observation_count: {}", result.observation_count); eprintln!("diagnostics: {:?}", result.diagnostics); eprintln!(); assert_eq!(result.final_state, json!({"count": 0})); assert_eq!(result.observation_count, 0); } /// Helper to create a temp file with JSON content fn create_json_file(content: &Value) -> NamedTempFile { let mut file = NamedTempFile::new().expect("Failed to create temp file"); writeln!(file, "{}", serde_json::to_string(content).unwrap()).unwrap(); file } /// Debug helper: print file contents as both hex and text fn dump_file(path: &std::path::Path, label: &str) { let bytes = std::fs::read(path).unwrap(); eprintln!("=== {} ({} bytes) ===", label, bytes.len()); eprintln!("Hex: {:02x?}", &bytes[..bytes.len().min(100)]); if let Ok(text) = std::str::from_utf8(&bytes) { eprintln!("Text:\n{}", &text[..text.len().min(500)]); } else { eprintln!("(not valid UTF-8)"); } eprintln!(); }