mod support;
use std::path::PathBuf;
use support::{Outcome, discover, run_fixture};
fn fixtures_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
}
const TOP_LEVEL_FIXTURES: usize = 49;
#[test]
fn decodes_corpus_against_oracle() {
let fixtures = discover(&fixtures_dir()).expect("read tests/fixtures");
assert_eq!(
fixtures.len(),
TOP_LEVEL_FIXTURES,
"the corpus changed size: a deleted fixture must fail, and an added one \
must update TOP_LEVEL_FIXTURES",
);
let mut failures = Vec::new();
for fixture in &fixtures {
let outcome = run_fixture(fixture);
match &outcome {
Outcome::Passed => eprintln!("conformance: {} … ok", fixture.name),
Outcome::Failed(m) => {
eprintln!("conformance: {} … FAILED: {m}", fixture.name);
failures.push(format!("{}: {m}", fixture.name));
}
Outcome::LoadError(e) => {
eprintln!("conformance: {} … LOAD ERROR: {e}", fixture.name);
failures.push(format!("{}: {e}", fixture.name));
}
}
}
assert!(
failures.is_empty(),
"{} fixture(s) failed the conformance gate:\n {}",
failures.len(),
failures.join("\n "),
);
}
mod harness {
use super::support::{
ComponentSnapshot, Expected, Fixture, Geometry, ImageGeometry, Mismatch, Outcome,
Provenance, Tolerance, classify, compare, discover, run_fixture,
};
use rust_j2k::{Component, Error, Image};
use std::path::{Path, PathBuf};
fn geometry(width: u32, height: u32) -> Geometry {
Geometry {
width,
height,
bit_depth: 16,
signed: false,
}
}
fn image(width: u32, height: u32, samples: Vec<i32>) -> Image {
Image::new(
width,
height,
vec![Component::new(width, height, 16, false, 1, 1, samples)],
)
}
fn snapshot(geometry: Geometry, tolerance: Tolerance, samples: Vec<i32>) -> Expected {
Expected {
image: ImageGeometry {
width: geometry.width,
height: geometry.height,
},
tolerance,
components: vec![ComponentSnapshot {
width: geometry.width,
height: geometry.height,
bit_depth: geometry.bit_depth,
signed: geometry.signed,
x_sampling: 1,
y_sampling: 1,
samples,
}],
provenance: Provenance {
source: "test".into(),
oracle_command: "n/a".into(),
notes: None,
},
jp2: None,
jp2_boxes: None,
}
}
#[test]
fn exact_match_passes() {
let want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 1, 2, 3]);
let got = image(2, 2, vec![0, 1, 2, 3]);
assert_eq!(compare(&got, &want), Ok(()));
}
#[test]
fn exact_reports_first_divergent_sample() {
let want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 1, 2, 3]);
let got = image(2, 2, vec![0, 1, 2, 9]);
let err = compare(&got, &want).unwrap_err();
assert_eq!(
err,
Mismatch::Sample {
component: 0,
index: 3,
x: 1,
y: 1,
expected: 3,
actual: 9,
bound: 0.0,
}
);
}
#[test]
fn absolute_within_bound_passes() {
let want = snapshot(
geometry(2, 1),
Tolerance::Absolute { max_abs_error: 1.5 },
vec![10, 20],
);
let got = image(2, 1, vec![11, 19]); assert_eq!(compare(&got, &want), Ok(()));
}
#[test]
fn absolute_outside_bound_fails() {
let want = snapshot(
geometry(2, 1),
Tolerance::Absolute { max_abs_error: 1.5 },
vec![10, 20],
);
let got = image(2, 1, vec![10, 23]); let err = compare(&got, &want).unwrap_err();
assert_eq!(
err,
Mismatch::Sample {
component: 0,
index: 1,
x: 1,
y: 0,
expected: 20,
actual: 23,
bound: 1.5,
}
);
}
#[test]
fn component_geometry_mismatch_fails_before_samples() {
let mut want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 0, 0, 0]);
want.components[0].bit_depth = 8; let got = image(2, 2, vec![0, 0, 0, 0]);
let err = compare(&got, &want).unwrap_err();
assert!(
matches!(err, Mismatch::Geometry { component: 0, .. }),
"{err}"
);
}
#[test]
fn image_area_mismatch_is_reported_before_any_component() {
let want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 0, 0, 0]);
let got = image(4, 1, vec![0, 0, 0, 0]); let err = compare(&got, &want).unwrap_err();
assert!(matches!(err, Mismatch::DecodeError(_)), "{err}");
}
#[test]
fn component_count_mismatch_is_reported() {
let mut want = snapshot(geometry(2, 2), Tolerance::Exact, vec![0, 0, 0, 0]);
want.components.push(want.components[0].clone());
let got = image(2, 2, vec![0, 0, 0, 0]);
let err = compare(&got, &want).unwrap_err();
assert!(matches!(err, Mismatch::DecodeError(_)), "{err}");
}
#[test]
fn panic_classifies_as_failed() {
let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![0]);
let decoded =
std::panic::catch_unwind(|| -> Result<Image, Error> { panic!("decoder bug") });
assert!(matches!(
classify(decoded, &want),
Outcome::Failed(Mismatch::DecodeError(_))
));
}
#[test]
fn ok_matching_classifies_as_passed() {
let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![42]);
let decoded = Ok(Ok(image(1, 1, vec![42])));
assert_eq!(classify(decoded, &want), Outcome::Passed);
}
#[test]
fn ok_mismatch_classifies_as_failed() {
let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![42]);
let decoded = Ok(Ok(image(1, 1, vec![7])));
assert!(matches!(classify(decoded, &want), Outcome::Failed(_)));
}
#[test]
fn decode_error_classifies_as_failed() {
let want = snapshot(geometry(1, 1), Tolerance::Exact, vec![42]);
let decoded = Ok(Err(rust_j2k::decode(b"nope").unwrap_err()));
assert!(matches!(
classify(decoded, &want),
Outcome::Failed(Mismatch::DecodeError(_))
));
}
fn scratch(tag: &str) -> PathBuf {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("discover-{tag}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn write(dir: &Path, name: &str, contents: &str) {
std::fs::write(dir.join(name), contents).unwrap();
}
const VALID_SNAPSHOT: &str = r#"{
"image": { "width": 1, "height": 1 },
"tolerance": { "mode": "exact" },
"components": [
{ "width": 1, "height": 1, "bit_depth": 8, "signed": false,
"x_sampling": 1, "y_sampling": 1, "samples": [0] }
],
"provenance": { "source": "s", "oracle_command": "c" }
}"#;
#[test]
fn discovers_paired_fixture() {
let dir = scratch("paired");
write(&dir, "alpha.j2k", "\x00not-a-codestream");
write(&dir, "alpha.expected.json", VALID_SNAPSHOT);
let found = discover(&dir).unwrap();
assert_eq!(found.len(), 1);
assert_eq!(found[0].name, "alpha");
assert!(found[0].expected.is_ok());
assert!(matches!(
run_fixture(&found[0]),
Outcome::Failed(Mismatch::DecodeError(_))
));
}
#[test]
fn missing_snapshot_is_a_load_error() {
let dir = scratch("orphan-codestream");
write(&dir, "lonely.j2k", "bytes");
let found = discover(&dir).unwrap();
assert_eq!(found.len(), 1);
assert!(found[0].expected.is_err());
assert!(matches!(run_fixture(&found[0]), Outcome::LoadError(_)));
}
#[test]
fn malformed_snapshot_is_a_load_error() {
let dir = scratch("malformed-snapshot");
write(&dir, "broken.j2k", "bytes");
write(&dir, "broken.expected.json", "{ not valid json");
let found = discover(&dir).unwrap();
assert_eq!(found.len(), 1);
assert!(found[0].expected.is_err());
assert!(matches!(run_fixture(&found[0]), Outcome::LoadError(_)));
}
#[test]
fn snapshot_with_wrong_sample_count_is_a_load_error() {
let dir = scratch("wrong-count");
write(&dir, "bad.j2k", "bytes");
write(
&dir,
"bad.expected.json",
r#"{
"image": { "width": 2, "height": 2 },
"tolerance": { "mode": "exact" },
"components": [
{ "width": 2, "height": 2, "bit_depth": 8, "signed": false,
"x_sampling": 1, "y_sampling": 1, "samples": [0, 1, 2] }
],
"provenance": { "source": "s", "oracle_command": "c" }
}"#,
);
let found = discover(&dir).unwrap();
assert_eq!(found.len(), 1);
let reason = found[0].expected.as_ref().expect_err("must not load");
assert!(
reason.contains("4 samples but the array has 3"),
"must fail the sample-count check, not parsing: {reason}"
);
assert!(matches!(run_fixture(&found[0]), Outcome::LoadError(_)));
}
#[test]
fn discovery_is_sorted_and_ignores_other_files() {
let dir = scratch("sorted");
write(&dir, "beta.j2k", "bytes");
write(&dir, "beta.expected.json", VALID_SNAPSHOT);
write(&dir, "alpha.j2k", "bytes");
write(&dir, "alpha.expected.json", VALID_SNAPSHOT);
write(&dir, "notes.txt", "ignore me");
let names: Vec<_> = discover(&dir)
.unwrap()
.into_iter()
.map(|f| f.name)
.collect();
assert_eq!(names, vec!["alpha", "beta"]);
}
#[test]
fn missing_directory_is_an_error() {
let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("does-not-exist-xyz");
let _ = std::fs::remove_dir_all(&dir);
assert!(discover(&dir).is_err());
}
#[test]
fn fixture_load_error_short_circuits_run() {
let fixture = Fixture {
name: "x".into(),
codestream: PathBuf::from("/nonexistent/x.j2k"),
expected: Err("synthetic load error".into()),
};
assert!(matches!(run_fixture(&fixture), Outcome::LoadError(_)));
}
}
mod expected_schema {
use super::support::{Expected, Geometry, Provenance, Tolerance};
const EXACT_JSON: &str = r#"{
"image": { "width": 2, "height": 2 },
"tolerance": { "mode": "exact" },
"components": [
{ "width": 2, "height": 2, "bit_depth": 16, "signed": false,
"x_sampling": 1, "y_sampling": 1, "samples": [0, 1, 2, 3] }
],
"provenance": {
"source": "fieldglass/jpeg2000_regular_latlon.grib2",
"oracle_command": "opj_decompress -i sample.j2k -o sample.pgx"
}
}"#;
const ABSOLUTE_JSON: &str = r#"{
"image": { "width": 2, "height": 1 },
"tolerance": { "mode": "absolute", "max_abs_error": 1.5 },
"components": [
{ "width": 2, "height": 1, "bit_depth": 12, "signed": true,
"x_sampling": 1, "y_sampling": 1, "samples": [-2, 7] }
],
"provenance": {
"source": "hrrr/sample.grib2",
"oracle_command": "grib_to_jpeg ...",
"notes": "9/7 lossy path"
}
}"#;
const SUBSAMPLED_JSON: &str = r#"{
"image": { "width": 3, "height": 3 },
"tolerance": { "mode": "exact" },
"components": [
{ "width": 3, "height": 3, "bit_depth": 8, "signed": false,
"x_sampling": 1, "y_sampling": 1, "samples": [1,2,3,4,5,6,7,8,9] },
{ "width": 2, "height": 2, "bit_depth": 8, "signed": false,
"x_sampling": 2, "y_sampling": 2, "samples": [1,2,3,4] }
],
"provenance": { "source": "s", "oracle_command": "c" }
}"#;
#[test]
fn parses_exact_reversible_snapshot() {
let expected = Expected::from_json(EXACT_JSON).expect("parse exact snapshot");
assert_eq!(expected.image.width, 2);
assert_eq!(expected.image.height, 2);
assert_eq!(expected.components.len(), 1);
let component = &expected.components[0];
assert_eq!(
component.geometry(),
Geometry {
width: 2,
height: 2,
bit_depth: 16,
signed: false,
}
);
assert_eq!(expected.tolerance, Tolerance::Exact);
assert_eq!(component.samples, vec![0, 1, 2, 3]);
assert_eq!(component.samples.len(), component.geometry().sample_count());
assert_eq!(expected.provenance.notes, None);
}
#[test]
fn parses_absolute_irreversible_snapshot() {
let expected = Expected::from_json(ABSOLUTE_JSON).expect("parse absolute snapshot");
assert_eq!(
expected.tolerance,
Tolerance::Absolute { max_abs_error: 1.5 }
);
let component = &expected.components[0];
assert_eq!(component.samples, vec![-2, 7]);
assert_eq!(component.samples.len(), component.geometry().sample_count());
assert_eq!(expected.provenance.source, "hrrr/sample.grib2");
assert_eq!(expected.provenance.notes.as_deref(), Some("9/7 lossy path"));
}
#[test]
fn parses_subsampled_multi_component_snapshot() {
let expected = Expected::from_json(SUBSAMPLED_JSON).expect("parse subsampled snapshot");
assert_eq!((expected.image.width, expected.image.height), (3, 3));
assert_eq!(expected.components.len(), 2);
let luma = &expected.components[0];
assert_eq!((luma.width, luma.height), (3, 3));
assert_eq!((luma.x_sampling, luma.y_sampling), (1, 1));
let chroma = &expected.components[1];
assert_eq!((chroma.width, chroma.height), (2, 2));
assert_eq!((chroma.x_sampling, chroma.y_sampling), (2, 2));
assert_eq!(chroma.samples.len(), chroma.geometry().sample_count());
}
#[test]
fn round_trips_through_serde() {
let parsed = Expected::from_json(EXACT_JSON).expect("parse");
let reserialized = serde_json::to_string(&parsed).expect("serialize");
let reparsed = Expected::from_json(&reserialized).expect("reparse");
assert_eq!(parsed, reparsed);
}
#[test]
fn omitted_optional_note_defaults_to_none() {
let json = r#"{
"image": { "width": 1, "height": 1 },
"tolerance": { "mode": "exact" },
"components": [
{ "width": 1, "height": 1, "bit_depth": 8, "signed": false,
"x_sampling": 1, "y_sampling": 1, "samples": [42] }
],
"provenance": { "source": "s", "oracle_command": "c" }
}"#;
let expected = Expected::from_json(json).expect("parse without notes");
assert_eq!(
expected.provenance,
Provenance {
source: "s".to_string(),
oracle_command: "c".to_string(),
notes: None,
}
);
}
#[test]
fn rejects_unknown_field() {
let json = r#"{
"image": { "width": 1, "height": 1 },
"tolerance": { "mode": "exact" },
"components": [
{ "width": 1, "height": 1, "bit_depth": 8, "signed": false,
"x_sampling": 1, "y_sampling": 1, "sample": [0] }
],
"provenance": { "source": "s", "oracle_command": "c" }
}"#;
let error = Expected::from_json(json).expect_err("a typo'd key must not parse");
assert!(
error.to_string().contains("unknown field `sample`"),
"must fail on the typo'd key: {error}"
);
}
#[test]
fn rejects_unknown_tolerance_mode() {
let json = r#"{
"image": { "width": 1, "height": 1 },
"tolerance": { "mode": "relative", "max_abs_error": 1.0 },
"components": [
{ "width": 1, "height": 1, "bit_depth": 8, "signed": false,
"x_sampling": 1, "y_sampling": 1, "samples": [0] }
],
"provenance": { "source": "s", "oracle_command": "c" }
}"#;
let error = Expected::from_json(json).expect_err("an unknown mode must not parse");
assert!(
error.to_string().contains("unknown variant `relative`"),
"must fail on the tolerance mode: {error}"
);
}
}