Skip to content

Commit

Permalink
Assert file equality
Browse files Browse the repository at this point in the history
  • Loading branch information
xandkar committed Jul 9, 2024
1 parent 2ca6381 commit 6bc03d3
Showing 1 changed file with 51 additions and 11 deletions.
62 changes: 51 additions & 11 deletions tests/integration.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use std::path::{Path, PathBuf};
use std::{
fs::{self, File},
io::{self, Read},
path::{Path, PathBuf},
};

use tempfile::tempdir;

Expand All @@ -22,22 +26,22 @@ fn from_empty_dst() {
phorg::hash::Hash::Crc32,
)
.unwrap();

let foo_before = "foo.jpg";
let foo_after = "img/2000/12/27/2000-12-27--06:47:01--crc32:383ba95e.jpg";
let bar_before = "bar.jpg";
let bar_after = "img/2010/01/31/2010-01-31--17:35:49--crc32:c653b4f3.jpg";

assert_eq!(
&file_paths_sorted(&src),
&vec![src.join("bar.jpg"), src.join("foo.jpg"), src.join("make"),]
&vec![src.join(bar_before), src.join(foo_before), src.join("make"),]
);
assert_eq!(
&file_paths_sorted(dst),
&vec![
dst.join(
"img/2000/12/27/2000-12-27--06:47:01--crc32:383ba95e.jpg"
),
dst.join(
"img/2010/01/31/2010-01-31--17:35:49--crc32:c653b4f3.jpg"
),
]
&vec![dst.join(foo_after), dst.join(bar_after),]
);
// TODO Assert file contents did not change.
assert!(files_eq(src.join(foo_before), dst.join(foo_after)).unwrap());
assert!(files_eq(src.join(bar_before), dst.join(bar_after)).unwrap());
}

fn file_paths_sorted(root: &Path) -> Vec<PathBuf> {
Expand All @@ -46,3 +50,39 @@ fn file_paths_sorted(root: &Path) -> Vec<PathBuf> {
paths.sort();
paths
}

fn files_eq<P: AsRef<Path>>(path_a: P, path_b: P) -> io::Result<bool> {
const CHUNK_SIZE: usize = 8;

let path_a = path_a.as_ref();
let path_b = path_b.as_ref();

let size_a = fs::metadata(path_a)?.len();
let size_b = fs::metadata(path_b)?.len();
if size_a != size_b {
return Ok(false);
}

let mut file_a = File::open(path_a)?;
let mut file_b = File::open(path_b)?;
let mut buff_a = [0; CHUNK_SIZE];
let mut buff_b = [0; CHUNK_SIZE];
loop {
let n_a = file_a.read(&mut buff_a)?;
let n_b = file_b.read(&mut buff_b)?;

let chunk_a = &buff_a[..n_a];
let chunk_b = &buff_b[..n_b];

if n_a != n_b {
return Ok(false);
}
if chunk_a != chunk_b {
return Ok(false);
}
if n_a == 0 {
assert_eq!(n_b, 0);
return Ok(true);
}
}
}

0 comments on commit 6bc03d3

Please sign in to comment.