john-slop/src/reader/tests.rs

90 lines
2.7 KiB
Rust

use super::*;
use std::fs::{self, File};
use std::io::Write;
use tempfile::tempdir;
use zip::write::FileOptions;
/// Helper to write a file with the given content
fn write_file(path: &Path, content: &str) {
let mut f = File::create(path).expect("unable to create test file");
f.write_all(content.as_bytes())
.expect("unable to write test file");
}
/// Create a small ZIP file containing two text entries.
fn create_zip(path: &Path) -> std::io::Result<()> {
let file = File::create(path)?;
let mut zip = zip::ZipWriter::new(file);
let options: FileOptions<()> = zip::write::FileOptions::default()
.compression_method(zip::CompressionMethod::Stored)
.unix_permissions(0o644);
zip.start_file("foo.txt", options)?;
zip.write_all(b"hello foo")?;
zip.start_file("bar.txt", options)?;
zip.write_all(b"hello bar")?;
zip.finish()?;
Ok(())
}
#[test]
fn test_read_single_file() {
let dir = tempdir().expect("temp dir");
let file_path = dir.path().join("test.txt");
write_file(&file_path, "line1\nline2");
let it = universal_read(&file_path.to_path_buf()).expect("universal_read");
let mut collected = Vec::new();
for r in it {
collected.push(r.expect("file read"));
}
assert_eq!(collected.len(), 1);
assert_eq!(collected[0].path, file_path);
assert_eq!(collected[0].content, "line1\nline2");
}
#[test]
fn test_read_folder() {
let dir = tempdir().expect("temp dir");
let sub = dir.path().join("sub");
fs::create_dir(&sub).expect("mkdir");
write_file(&dir.path().join("a.txt"), "a");
write_file(&sub.join("b.txt"), "b");
let it = universal_read(&dir.path().to_path_buf()).expect("universal_read");
let mut paths: Vec<PathBuf> = it.map(|r| r.expect("file read").path).collect();
paths.sort();
assert_eq!(paths, vec![dir.path().join("a.txt"), sub.join("b.txt")]);
}
#[test]
fn test_read_zip() {
let dir = tempdir().expect("temp dir");
let zip_path = dir.path().join("archive.zip");
create_zip(&zip_path).expect("create zip");
let it = universal_read(&zip_path.to_path_buf()).expect("universal_read");
let mut entries: Vec<String> = it.map(|r| r.expect("file read").content).collect();
entries.sort();
assert_eq!(
entries,
vec!["hello bar".to_string(), "hello foo".to_string()]
);
}
#[test]
fn test_replace_in_file() {
let dir = tempdir().expect("temp dir");
let file_path = dir.path().join("sample.txt");
write_file(&file_path, "foo bar foo");
replace_in_file(&file_path, "foo", "baz").expect("replace");
let content = read_file(&file_path).expect("read");
assert_eq!(content, "baz bar baz");
}