Merge pull request #1409 from dotCooCoo/feat/craft-testkit-image

craft-testkit: add the image feature for image comparison and golden checks
This commit is contained in:
BFlat authored and GitHub committed 2026-11-29 00:26:05 +07:00
commit 923a3dcf33
6 files changed
+1976

No files matched your search

Generated
+1
View File
@@ -4345,6 +4345,7 @@ name = "craft-testkit"
version = "0.1.0"
dependencies = [
"libc",
"png 0.18.1",
"rustix 1.1.6",
"serde_json",
"sha2 0.10.9",
+4
View File
@@ -9,6 +9,9 @@ description = "Source-level platform regression guards, test deadlines, hostile-
publish = false
[features]
default = []
# Image comparison, PNG reading and writing, and golden reference checks.
image = ["dep:png"]
# `mcp::McpChild`: an MCP stdio test client.
mcp = ["dep:serde_json"]
# Pinned-corpus manifests and the `corpus::pinned` test gate (native only).
@@ -17,6 +20,7 @@ corpus = ["dep:sha2", "dep:libc"]
font-coverage = ["dep:skrifa"]
[dependencies]
png = { version = "0.18", optional = true }
sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+42
View File
@@ -258,6 +258,30 @@ Changes from `craft-media-testkit`'s `hammer`:
- `parse` is owned and runs on a worker thread. A closure that borrows from the test needs its data
moved or shared with an `Arc`.
## `image` feature
`craft-testkit = { ..., features = ["image"] }` adds `craft_testkit::image` and `assert_similar!`. It depends on `png` 0.18.
| Item | What it does |
|---|---|
| `Rgba8`, `Gray8` | Borrowed 8-bit views. `new` returns an error when a side is 0 or the buffer is not exactly `width × height × channels` bytes. |
| `diff_rgba`, `diff_gray` | `DiffStats`: differing pixels, maximum and mean absolute sample difference, nearest-rank p99 of each pixel's largest difference, and PSNR with a peak of 255. RGBA counts alpha as a fourth sample. |
| `psnr(a, b, peak)` | PSNR of two `u8` or `u16` planes. The caller passes the peak (255, 1023, 4095, 65535). Equal planes give `f64::INFINITY`; empty or unequal planes and a peak that is not finite and positive are errors. |
| `Tolerance`, `compare_rgba`, `compare_gray` | Gates for maximum difference, p99, minimum PSNR and the share of bad pixels, each inclusive. With `neighborhood`, a pixel is bad only when nothing in the other image's 3×3 window is within `channel`, checked in both directions. |
| `diff_image` | An opaque RGBA image of each absolute sample difference times 8, with alpha differences shown in every color channel. |
| `decode_png`, `encode_png`, `encode_gray_png`, `read_png`, `write_png`, `write_gray_png` | 8-bit PNG reading and writing under `PngLimits` (default 16,384 × 16,384 pixels, 64 MiB encoded, 256 MiB decoded). Palette, low bit depths, 16-bit samples, `tRNS` and interlacing are converted to 8-bit gray or RGBA. Gamma, ICC and sRGB chunks are not applied. |
| `check_golden`, `assert_similar!` | Compare an image with a reference PNG. The reference is written only when the variable named in `GoldenOptions::bless_var` (default `CRAFT_BLESS`) is exactly `1`; otherwise a missing reference is an error. A failed check writes `<name>.actual.png` and `<name>.diff.png` into `GoldenOptions::failures_dir`, using `<name>-1`, `<name>-2` and so on rather than replacing a file. `assert_similar!` fails the calling test. |
The views, statistics, PSNR, tolerances, the difference image and the in-memory PNG functions build for `wasm32`. The file functions, the bless variable and the golden check are native only.
```rust
use craft_testkit::image::{GoldenOptions, Rgba8, Tolerance};
let options = GoldenOptions { bless_var: "FILMCRAFT_BLESS", ..GoldenOptions::new(&failures, "title_card") };
let tolerance = Tolerance { min_psnr: Some(45.0), max_abs: Some(12), max_p99: Some(2), ..Tolerance::EXACT };
craft_testkit::assert_similar!(&reference, Rgba8::new(width, height, &pixels)?, tolerance, options);
```
## fixtures
The `fixtures` module (native targets only) generates missing test fixtures and shares them between test runs and processes:
@@ -470,6 +494,14 @@ PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copie
|---|---|---|---|
| `Rng`, the edits of `mutations` and `hammer` | storytold/craft-libs | `crates/media-testkit/src/hostile.rs` | `75a654f4` |
### image
| Code | Source |
|---|---|
| Statistics, PNG reading and writing, golden check | FilmCraft `crates/testkit/src/golden.rs` at `e4ab3c6a99` |
| Per-pixel channel tolerance and bad-pixel share | AniCraft `crates/engine/tests/golden/mod.rs` at `3435e98681` |
| Gray view and 3×3 neighborhood comparison | PdfCraft `crates/oracle/src/pixels.rs` at `eead454105` |
### fixtures
| Part | Repository | Path | Commit |
@@ -559,6 +591,16 @@ An adoption keeps the variable name the app uses today.
CADCraft's and TextureCraft's loops make other edits than `mutations`. Their adoptions say which
cases change, and keep the test names.
### image
| Consumer | Today | State |
|---|---|---|
| FilmCraft | `golden.rs`, `FILMCRAFT_BLESS` | Not started |
| AniCraft | `crates/engine/tests/golden/mod.rs`, `UPDATE_GOLDENS` | Not started |
| PdfCraft | `pdfcraft-oracle` `pixels.rs` | Not started |
| VectorCraft | `crates/testkit/src/raster.rs` (comparison only) | Not started |
| DesignCraft | `crates/render/tests/it/effects.rs`, `DESIGNCRAFT_BLESS` | Not started |
### fixtures
| Consumer | Copy it replaces | State |
+997
View File
@@ -0,0 +1,997 @@
//! Image comparison for tests: checked RGBA8 and gray views, difference statistics, PSNR, a
//! tolerance with an optional 3×3 neighborhood, a difference image, PNG reading and writing with
//! size limits, and golden reference checks.
//!
//! Every function returns a [`Result`]. `assert_similar!` is the one form that fails a test, and it
//! panics in the calling test.
//!
//! Statistics compare raw 8-bit sample values. PNG decoding does not apply gamma, ICC or sRGB
//! chunks, so a reference compares as the bytes it stores.
//!
//! The views, statistics, PSNR, tolerance, difference image and in-memory PNG functions build for
//! `wasm32`. The file functions, the bless variable and the golden check are native only.
use std::fmt;
use std::io::Cursor;
use std::path::PathBuf;
#[cfg(not(target_arch = "wasm32"))]
use std::{
ffi::OsStr,
fs,
io::{Read, Write},
path::Path,
sync::atomic::{AtomicU64, Ordering},
};
/// The bless variable `GoldenOptions::new` uses.
pub const DEFAULT_BLESS_VAR: &str = "CRAFT_BLESS";
/// The most failure image pairs [`check_golden`] writes for one name in one folder.
#[cfg(not(target_arch = "wasm32"))]
const MAX_FAILURE_PAIRS: usize = 1000;
/// Why an image could not be compared, read or written.
#[derive(Debug)]
#[non_exhaustive]
pub enum ImageError {
/// A side is 0, or the stated size does not fit in memory.
InvalidDimensions { width: u32, height: u32 },
/// The pixel buffer is not exactly `width × height × channels` bytes.
InvalidBufferLength { expected: usize, actual: usize },
/// The two images have different sizes.
SizeMismatch { a: (u32, u32), b: (u32, u32) },
/// The two PSNR planes have different sample counts.
PlaneLengthMismatch { a: usize, b: usize },
/// A PSNR plane has no samples.
EmptyPlane,
/// A tolerance value is NaN or out of range.
InvalidTolerance(&'static str),
/// The PSNR peak is not finite or not greater than 0.
InvalidPeak(f64),
/// An input or output is larger than its [`PngLimits`] value.
LimitExceeded(String),
/// A failure image name or bless variable name is not allowed.
InvalidName(String),
/// The reference file does not exist and the bless variable is not `1`.
MissingReference { path: PathBuf, bless_var: String },
/// The image is outside the tolerance; the actual and difference images were written.
GoldenMismatch(Box<GoldenMismatch>),
/// The image is outside the tolerance, and the actual and difference images could not be
/// encoded or written.
GoldenMismatchUnsaved(Box<UnsavedMismatch>),
/// The PNG stream is malformed, truncated or uses an unsupported form.
Decode(String),
/// The PNG encoder failed.
Encode(String),
/// A file could not be read or written.
Io { path: PathBuf, source: std::io::Error },
}
/// The details of a failed golden check.
#[derive(Clone, Debug, PartialEq)]
pub struct GoldenMismatch {
/// The reference image.
pub reference: PathBuf,
/// The comparison that failed.
pub verdict: Verdict,
/// The actual image, written inside the failure folder.
pub actual: PathBuf,
/// The difference image, written inside the failure folder.
pub diff: PathBuf,
}
/// The details of a failed golden check whose failure images could not be saved.
#[derive(Debug)]
pub struct UnsavedMismatch {
/// The reference image.
pub reference: PathBuf,
/// The comparison that failed.
pub verdict: Verdict,
/// Why the actual or difference image could not be encoded or written.
pub error: ImageError,
}
impl fmt::Display for ImageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidDimensions { width, height } => {
write!(f, "a {width}x{height} image is not valid: each side must be at least 1 and the buffer size must fit in memory")
}
Self::InvalidBufferLength { expected, actual } => {
write!(f, "the pixel buffer holds {actual} bytes, but the stated size needs {expected}")
}
Self::SizeMismatch { a, b } => write!(f, "cannot compare a {}x{} image with a {}x{} one", a.0, a.1, b.0, b.1),
Self::PlaneLengthMismatch { a, b } => write!(f, "cannot compare a plane of {a} samples with one of {b}"),
Self::EmptyPlane => write!(f, "PSNR needs at least one sample"),
Self::InvalidTolerance(why) => write!(f, "invalid tolerance: {why}"),
Self::InvalidPeak(peak) => write!(f, "invalid PSNR peak {peak}: it must be finite and greater than 0"),
Self::LimitExceeded(what) | Self::InvalidName(what) => f.write_str(what),
Self::MissingReference { path, bless_var } => {
write!(f, "{}: no reference image; run with {bless_var}=1 to write it, and look at it before committing", path.display())
}
Self::GoldenMismatch(m) => {
write!(
f,
"{}: {}; actual image written to {}, difference image to {}",
m.reference.display(),
m.verdict,
m.actual.display(),
m.diff.display()
)
}
Self::GoldenMismatchUnsaved(m) => {
write!(f, "{}: {}; the actual and difference images could not be written: {}", m.reference.display(), m.verdict, m.error)
}
Self::Decode(e) => write!(f, "PNG decoding failed: {e}"),
Self::Encode(e) => write!(f, "PNG encoding failed: {e}"),
Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
}
}
}
impl std::error::Error for ImageError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } => Some(source),
Self::GoldenMismatchUnsaved(m) => Some(&m.error),
_ => None,
}
}
}
/// Checks a view's size and returns its pixel count.
fn checked_len(width: u32, height: u32, channels: usize, actual: usize) -> Result<usize, ImageError> {
if width == 0 || height == 0 {
return Err(ImageError::InvalidDimensions { width, height });
}
let pixels = usize::try_from(width).ok().zip(usize::try_from(height).ok()).and_then(|(w, h)| w.checked_mul(h));
let expected = pixels.and_then(|n| n.checked_mul(channels)).ok_or(ImageError::InvalidDimensions { width, height })?;
if expected != actual {
return Err(ImageError::InvalidBufferLength { expected, actual });
}
Ok(expected / channels)
}
/// A borrowed 8-bit RGBA image, row-major, straight alpha, no row padding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rgba8<'a> {
width: u32,
height: u32,
pixels: &'a [u8],
}
impl<'a> Rgba8<'a> {
/// Borrows `pixels` as a `width` × `height` image. Returns an error when a side is 0 or the
/// buffer is not exactly `width × height × 4` bytes.
pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self, ImageError> {
checked_len(width, height, 4, pixels.len())?;
Ok(Self { width, height, pixels })
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
/// The pixel bytes, four per pixel.
pub fn pixels(&self) -> &'a [u8] {
self.pixels
}
fn plane(self) -> Plane<'a> {
Plane { width: self.width, height: self.height, channels: 4, pixels: self.pixels }
}
}
/// A borrowed 8-bit grayscale image, row-major, no row padding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Gray8<'a> {
width: u32,
height: u32,
pixels: &'a [u8],
}
impl<'a> Gray8<'a> {
/// Borrows `pixels` as a `width` × `height` image. Returns an error when a side is 0 or the
/// buffer is not exactly `width × height` bytes.
pub fn new(width: u32, height: u32, pixels: &'a [u8]) -> Result<Self, ImageError> {
checked_len(width, height, 1, pixels.len())?;
Ok(Self { width, height, pixels })
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
/// The pixel bytes, one per pixel.
pub fn pixels(&self) -> &'a [u8] {
self.pixels
}
fn plane(self) -> Plane<'a> {
Plane { width: self.width, height: self.height, channels: 1, pixels: self.pixels }
}
}
/// A checked view with its channel count.
#[derive(Clone, Copy)]
struct Plane<'a> {
width: u32,
height: u32,
channels: usize,
pixels: &'a [u8],
}
fn same_size(a: Plane<'_>, b: Plane<'_>) -> Result<(), ImageError> {
if (a.width, a.height) != (b.width, b.height) {
return Err(ImageError::SizeMismatch { a: (a.width, a.height), b: (b.width, b.height) });
}
Ok(())
}
/// Difference statistics over raw 8-bit samples. RGBA counts alpha as a fourth sample.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DiffStats {
/// Pixels with any sample different.
pub differing_pixels: usize,
/// Largest absolute sample difference.
pub max_abs: u8,
/// Mean absolute sample difference over every sample.
pub mean_abs: f64,
/// The nearest-rank 99th percentile of each pixel's largest sample difference: the value at
/// one-based position `ceil(0.99 × pixels)` in ascending order.
pub p99: u8,
/// PSNR in dB with a peak of 255 over every sample; `f64::INFINITY` when the images are equal.
pub psnr: f64,
/// Pixels in each image.
pub total_pixels: usize,
}
impl fmt::Display for DiffStats {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"PSNR {:.2} dB, max {}, p99 {}, mean {:.3}, {} of {} pixels differ",
self.psnr, self.max_abs, self.p99, self.mean_abs, self.differing_pixels, self.total_pixels
)
}
}
fn max_delta(p: &[u8], q: &[u8]) -> u8 {
p.iter().zip(q).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0)
}
/// The value at one-based position `ceil(count × percent / 100)` of the histogram's samples.
fn nearest_rank(histogram: &[usize; 256], count: usize, percent: u128) -> u8 {
let rank = (count as u128 * percent).div_ceil(100).max(1);
let mut seen = 0u128;
for (value, &n) in histogram.iter().enumerate() {
seen += n as u128;
if seen >= rank {
return u8::try_from(value).unwrap_or(u8::MAX);
}
}
u8::MAX
}
fn psnr_from(squares: u128, samples: usize, peak: f64) -> f64 {
if squares == 0 {
return f64::INFINITY;
}
let mse = squares as f64 / samples as f64;
20.0 * peak.log10() - 10.0 * mse.log10()
}
fn stats(a: Plane<'_>, b: Plane<'_>) -> Result<DiffStats, ImageError> {
same_size(a, b)?;
let mut histogram = [0usize; 256];
let (mut sum, mut squares) = (0u128, 0u128);
let (mut max_abs, mut differing_pixels, mut total_pixels) = (0u8, 0usize, 0usize);
for (p, q) in a.pixels.chunks_exact(a.channels).zip(b.pixels.chunks_exact(b.channels)) {
let mut largest = 0u8;
for (x, y) in p.iter().zip(q) {
let d = x.abs_diff(*y);
sum += u128::from(d);
squares += u128::from(d) * u128::from(d);
largest = largest.max(d);
}
if let Some(n) = histogram.get_mut(usize::from(largest)) {
*n += 1;
}
max_abs = max_abs.max(largest);
differing_pixels += usize::from(largest > 0);
total_pixels += 1;
}
let samples = a.pixels.len();
Ok(DiffStats {
differing_pixels,
max_abs,
mean_abs: sum as f64 / samples as f64,
p99: nearest_rank(&histogram, total_pixels, 99),
psnr: psnr_from(squares, samples, 255.0),
total_pixels,
})
}
/// Statistics for two RGBA images of the same size.
pub fn diff_rgba(a: Rgba8<'_>, b: Rgba8<'_>) -> Result<DiffStats, ImageError> {
stats(a.plane(), b.plane())
}
/// Statistics for two gray images of the same size.
pub fn diff_gray(a: Gray8<'_>, b: Gray8<'_>) -> Result<DiffStats, ImageError> {
stats(a.plane(), b.plane())
}
mod sealed {
pub trait Sealed {}
impl Sealed for u8 {}
impl Sealed for u16 {}
}
/// A sample type [`psnr`] accepts: `u8` or `u16`.
pub trait Sample: Copy + sealed::Sealed {
/// The sample as an unsigned value.
fn value(self) -> u32;
}
impl Sample for u8 {
fn value(self) -> u32 {
u32::from(self)
}
}
impl Sample for u16 {
fn value(self) -> u32 {
u32::from(self)
}
}
/// PSNR in dB of two planes: `10 log10(peak² / MSE)`, with `MSE = Σ(a − b)² / samples`.
///
/// The caller supplies `peak`, for example 255 for 8-bit samples, 1023 for 10-bit, 4095 for
/// 12-bit or 65535 for 16-bit. Equal planes return `f64::INFINITY`. Returns an error for planes
/// of different lengths, empty planes, and a peak that is not finite or not greater than 0.
pub fn psnr<T: Sample>(a: &[T], b: &[T], peak: f64) -> Result<f64, ImageError> {
if !(peak.is_finite() && peak > 0.0) {
return Err(ImageError::InvalidPeak(peak));
}
if a.len() != b.len() {
return Err(ImageError::PlaneLengthMismatch { a: a.len(), b: b.len() });
}
if a.is_empty() {
return Err(ImageError::EmptyPlane);
}
let squares: u128 = a
.iter()
.zip(b)
.map(|(x, y)| {
let d = u128::from(x.value().abs_diff(y.value()));
d * d
})
.sum();
Ok(psnr_from(squares, a.len(), peak))
}
/// Acceptance gates for a comparison. Each gate that is set must hold, and every bound is
/// inclusive.
///
/// A pixel is bad when its largest sample difference is greater than `channel`. With
/// `neighborhood`, a pixel is bad only when no pixel in the other image's 3×3 window around it
/// (clipped at the edges) is within `channel`; the check runs in both directions and the larger
/// count is used. `max_abs`, `max_p99` and `min_psnr` always read the aligned statistics.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tolerance {
/// Largest allowed sample difference.
pub max_abs: Option<u8>,
/// Largest allowed [`DiffStats::p99`].
pub max_p99: Option<u8>,
/// Smallest allowed PSNR in dB.
pub min_psnr: Option<f64>,
/// The sample difference a pixel may have and still not count as bad.
pub channel: u8,
/// Largest allowed share of bad pixels, in `0.0..=1.0`; the allowed count is the largest
/// count whose share of the pixels is at most this value.
pub max_bad_fraction: Option<f64>,
/// Match each pixel against the other image's 3×3 window instead of the aligned pixel.
pub neighborhood: bool,
}
impl Tolerance {
/// Every sample must be equal.
pub const EXACT: Tolerance =
Tolerance { max_abs: Some(0), max_p99: None, min_psnr: None, channel: 0, max_bad_fraction: None, neighborhood: false };
/// Returns an error when `min_psnr` is NaN or `max_bad_fraction` is NaN or outside
/// `0.0..=1.0`.
pub fn validate(&self) -> Result<(), ImageError> {
if self.min_psnr.is_some_and(f64::is_nan) {
return Err(ImageError::InvalidTolerance("min_psnr is NaN"));
}
if self.max_bad_fraction.is_some_and(|f| !(0.0..=1.0).contains(&f)) {
return Err(ImageError::InvalidTolerance("max_bad_fraction must be in 0.0..=1.0"));
}
Ok(())
}
}
/// The result of comparing two images under a [`Tolerance`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Verdict {
/// Aligned statistics.
pub stats: DiffStats,
/// Bad pixels under the tolerance's `channel` and `neighborhood` rules.
pub bad_pixels: usize,
/// The bad pixels allowed, when the tolerance sets `max_bad_fraction`.
pub allowed_bad_pixels: Option<usize>,
/// The tolerance the comparison used.
pub tolerance: Tolerance,
}
impl Verdict {
/// Whether every gate of the tolerance holds.
pub fn passed(&self) -> bool {
let t = &self.tolerance;
t.max_abs.is_none_or(|m| self.stats.max_abs <= m)
&& t.max_p99.is_none_or(|m| self.stats.p99 <= m)
&& t.min_psnr.is_none_or(|m| self.stats.psnr >= m)
&& self.allowed_bad_pixels.is_none_or(|n| self.bad_pixels <= n)
}
}
impl fmt::Display for Verdict {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let t = &self.tolerance;
write!(f, "{}, {} pixels differ by more than {}", self.stats, self.bad_pixels, t.channel)?;
if t.neighborhood {
f.write_str(" within a 3x3 neighborhood")?;
}
let mut gates = Vec::new();
if let Some(m) = t.min_psnr {
gates.push(format!("PSNR >= {m} dB"));
}
if let Some(m) = t.max_abs {
gates.push(format!("max <= {m}"));
}
if let Some(m) = t.max_p99 {
gates.push(format!("p99 <= {m}"));
}
if let Some(n) = self.allowed_bad_pixels {
gates.push(format!("at most {n} such pixels"));
}
if !gates.is_empty() {
write!(f, " (tolerance: {})", gates.join(", "))?;
}
Ok(())
}
}
/// Pixels of `a` with no pixel within `channel` in `b`'s 3×3 window around the same position.
fn unmatched(a: Plane<'_>, b: Plane<'_>, channel: u8) -> usize {
let (Ok(w), Ok(h)) = (usize::try_from(a.width), usize::try_from(a.height)) else { return 0 };
let ch = a.channels;
a.pixels
.chunks_exact(ch)
.enumerate()
.filter(|&(i, p)| {
let (x, y) = (i % w, i / w);
let mut rows = y.saturating_sub(1)..=(y + 1).min(h.saturating_sub(1));
!rows.any(|ny| {
(x.saturating_sub(1)..=(x + 1).min(w.saturating_sub(1))).any(|nx| {
let j = (ny * w + nx) * ch;
b.pixels.get(j..j + ch).is_some_and(|q| max_delta(p, q) <= channel)
})
})
})
.count()
}
/// The largest bad pixel count `n` with `n / total <= fraction`, computed as `f64` division so a
/// share that equals `fraction` is allowed.
fn allowed_bad(fraction: f64, total: usize) -> usize {
let n = total as f64;
let mut allowed = ((fraction * n).floor() as usize).min(total);
while allowed > 0 && allowed as f64 / n > fraction {
allowed -= 1;
}
while allowed < total && (allowed + 1) as f64 / n <= fraction {
allowed += 1;
}
allowed
}
fn compare(a: Plane<'_>, b: Plane<'_>, tolerance: Tolerance) -> Result<Verdict, ImageError> {
tolerance.validate()?;
let stats = stats(a, b)?;
let bad_pixels = if tolerance.neighborhood {
unmatched(a, b, tolerance.channel).max(unmatched(b, a, tolerance.channel))
} else {
a.pixels.chunks_exact(a.channels).zip(b.pixels.chunks_exact(b.channels)).filter(|(p, q)| max_delta(p, q) > tolerance.channel).count()
};
let allowed_bad_pixels = tolerance.max_bad_fraction.map(|f| allowed_bad(f, stats.total_pixels));
Ok(Verdict { stats, bad_pixels, allowed_bad_pixels, tolerance })
}
/// Compares two RGBA images of the same size under `tolerance`.
pub fn compare_rgba(a: Rgba8<'_>, b: Rgba8<'_>, tolerance: Tolerance) -> Result<Verdict, ImageError> {
compare(a.plane(), b.plane(), tolerance)
}
/// Compares two gray images of the same size under `tolerance`.
pub fn compare_gray(a: Gray8<'_>, b: Gray8<'_>, tolerance: Tolerance) -> Result<Verdict, ImageError> {
compare(a.plane(), b.plane(), tolerance)
}
/// An opaque RGBA image of the same size showing `|a − b|` × 8 per color channel (at most 255),
/// with each pixel's alpha difference raised into all three color channels.
pub fn diff_image(a: Rgba8<'_>, b: Rgba8<'_>) -> Result<Vec<u8>, ImageError> {
same_size(a.plane(), b.plane())?;
let scaled = |x: u8, y: u8| u8::try_from((u16::from(x.abs_diff(y)) * 8).min(255)).unwrap_or(u8::MAX);
Ok(a.pixels
.as_chunks::<4>()
.0
.iter()
.zip(b.pixels.as_chunks::<4>().0)
.flat_map(|(p, q)| {
let alpha = scaled(p[3], q[3]);
[scaled(p[0], q[0]).max(alpha), scaled(p[1], q[1]).max(alpha), scaled(p[2], q[2]).max(alpha), 255]
})
.collect())
}
/// Size limits for PNG reading and writing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PngLimits {
/// Largest width in pixels.
pub max_width: u32,
/// Largest height in pixels.
pub max_height: u32,
/// Largest encoded PNG, read or written, in bytes.
pub max_input_bytes: usize,
/// Largest decoded output in bytes, after conversion to 8-bit gray or RGBA. The returned pixels
/// never exceed it. The decoder also takes it as a budget for its own working memory, but
/// applies that budget on a best-effort basis: it allocates small fixed buffers, such as one for
/// chunk data, before it checks the budget.
pub max_decoded_bytes: usize,
}
impl PngLimits {
/// 16,384 × 16,384 pixels, 64 MiB encoded and 256 MiB decoded.
pub const DEFAULT: PngLimits = PngLimits { max_width: 16_384, max_height: 16_384, max_input_bytes: 64 << 20, max_decoded_bytes: 256 << 20 };
}
impl Default for PngLimits {
fn default() -> Self {
Self::DEFAULT
}
}
/// A decoded PNG with 8-bit samples.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DecodedPng {
/// Color, gray with alpha, palette, or gray with a `tRNS` chunk, as straight RGBA.
Rgba { width: u32, height: u32, pixels: Vec<u8> },
/// Gray without transparency.
Gray { width: u32, height: u32, pixels: Vec<u8> },
}
impl DecodedPng {
pub fn width(&self) -> u32 {
match self {
Self::Rgba { width, .. } | Self::Gray { width, .. } => *width,
}
}
pub fn height(&self) -> u32 {
match self {
Self::Rgba { height, .. } | Self::Gray { height, .. } => *height,
}
}
/// The pixels as RGBA; gray becomes opaque RGBA with equal color channels.
pub fn into_rgba(self) -> Vec<u8> {
match self {
Self::Rgba { pixels, .. } => pixels,
Self::Gray { pixels, .. } => pixels.iter().flat_map(|&g| [g, g, g, 255]).collect(),
}
}
}
fn limit(what: &str, value: impl Into<u128>, max: impl Into<u128>) -> Result<(), ImageError> {
let (value, max) = (value.into(), max.into());
if value > max {
return Err(ImageError::LimitExceeded(format!("{what} {value} exceeds the limit of {max}")));
}
Ok(())
}
fn decoding_error(e: png::DecodingError) -> ImageError {
match e {
png::DecodingError::LimitsExceeded => ImageError::LimitExceeded("the PNG decoder's working memory exceeds max_decoded_bytes".into()),
e => ImageError::Decode(e.to_string()),
}
}
fn to_usize(n: u32) -> Result<usize, ImageError> {
usize::try_from(n).map_err(|_| ImageError::LimitExceeded(format!("{n} does not fit in memory")))
}
/// Decodes a PNG to 8-bit gray or RGBA.
///
/// Palette images and `tRNS` chunks are expanded, samples under 8 bits are scaled to 8 bits, and
/// 16-bit samples keep their high byte. Interlaced images are returned whole. An animated PNG
/// returns its default image. The chunks after the image, through `IEND`, are read, and the CRC of
/// every chunk, ancillary chunks included, is checked. The input size, the header's width and
/// height, and the decoded size, both as the decoder returns it and after conversion to gray or
/// RGBA, are each checked against `limits` and against the largest buffer the platform can
/// allocate before the buffer for them is allocated.
pub fn decode_png(bytes: &[u8], limits: PngLimits) -> Result<DecodedPng, ImageError> {
limit("PNG input bytes", bytes.len() as u64, limits.max_input_bytes as u64)?;
let mut options = png::DecodeOptions::default();
options.set_skip_ancillary_crc_failures(false);
let mut decoder = png::Decoder::new_with_options(Cursor::new(bytes), options);
decoder.set_limits(png::Limits { bytes: limits.max_decoded_bytes });
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let (width, height) = {
let info = decoder.read_header_info().map_err(decoding_error)?;
(info.width, info.height)
};
limit("PNG width", width, limits.max_width)?;
limit("PNG height", height, limits.max_height)?;
let mut reader = decoder.read_info().map_err(decoding_error)?;
let pixels = to_usize(width)?.checked_mul(to_usize(height)?).ok_or(ImageError::InvalidDimensions { width, height })?;
let channels = match reader.output_color_type().0 {
png::ColorType::Grayscale => 1,
png::ColorType::GrayscaleAlpha => 2,
png::ColorType::Rgb => 3,
png::ColorType::Rgba => 4,
png::ColorType::Indexed => return Err(ImageError::Decode("the palette was not expanded".into())),
};
let size = reader.output_buffer_size().ok_or_else(|| ImageError::LimitExceeded("the decoded PNG does not fit in memory".into()))?;
limit("decoded PNG bytes", size as u64, limits.max_decoded_bytes as u64)?;
limit("decoded PNG buffer bytes", size as u64, isize::MAX as u64)?;
let output = if channels == 1 { pixels as u128 } else { pixels as u128 * 4 };
limit("decoded PNG bytes", output, limits.max_decoded_bytes as u64)?;
limit("decoded PNG buffer bytes", output, isize::MAX as u64)?;
let mut buf = vec![0u8; size];
let info = reader.next_frame(&mut buf).map_err(decoding_error)?;
reader.finish().map_err(decoding_error)?;
if info.bit_depth != png::BitDepth::Eight || (info.width, info.height) != (width, height) {
return Err(ImageError::Decode(format!("unexpected {:?}-bit {}x{} output", info.bit_depth, info.width, info.height)));
}
if info.color_type != reader.output_color_type().0 {
return Err(ImageError::Decode(format!("unexpected {:?} output", info.color_type)));
}
let samples = pixels.checked_mul(channels).filter(|&n| n <= buf.len());
let Some(samples) = samples else {
return Err(ImageError::Decode("the decoded frame is shorter than its size".into()));
};
if channels == 1 || channels == 4 {
// The frame is already in its final form: keep the buffer and drop any row padding.
buf.truncate(samples);
return Ok(if channels == 1 { DecodedPng::Gray { width, height, pixels: buf } } else { DecodedPng::Rgba { width, height, pixels: buf } });
}
let data = buf.get(..samples).unwrap_or_default();
Ok(match channels {
2 => DecodedPng::Rgba { width, height, pixels: data.as_chunks::<2>().0.iter().flat_map(|p| [p[0], p[0], p[0], p[1]]).collect() },
_ => DecodedPng::Rgba { width, height, pixels: data.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect() },
})
}
/// An output buffer that refuses to grow past `max` bytes.
struct BoundedSink {
out: Vec<u8>,
max: usize,
exceeded: bool,
}
impl std::io::Write for BoundedSink {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if self.out.len().saturating_add(buf.len()) > self.max {
self.exceeded = true;
return Err(std::io::Error::other("the encoded PNG exceeds max_input_bytes"));
}
self.out.extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
/// Checks the size of an image to be encoded: its sides, and its pixel bytes as the decoder
/// would return them, so that a written file can be read back under the same limits.
fn check_encode_limits(width: u32, height: u32, decoded_bytes: usize, limits: PngLimits) -> Result<(), ImageError> {
limit("PNG width", width, limits.max_width)?;
limit("PNG height", height, limits.max_height)?;
limit("decoded PNG bytes", decoded_bytes as u64, limits.max_decoded_bytes as u64)
}
fn write_stream(sink: &mut BoundedSink, width: u32, height: u32, color: png::ColorType, data: &[u8]) -> Result<(), png::EncodingError> {
let mut encoder = png::Encoder::new(sink, width, height);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_compression(png::Compression::High);
let mut writer = encoder.write_header()?;
// The stream writer hands each compressed block to the sink as it fills, so a sink that refuses
// more bytes stops compression early.
let mut stream = writer.stream_writer()?;
std::io::Write::write_all(&mut stream, data)?;
stream.finish()?;
writer.finish()
}
/// Encodes `data`, stopping as soon as the output would pass `limits.max_input_bytes`.
fn encode(width: u32, height: u32, color: png::ColorType, data: &[u8], limits: PngLimits) -> Result<Vec<u8>, ImageError> {
let mut sink = BoundedSink { out: Vec::new(), max: limits.max_input_bytes, exceeded: false };
match write_stream(&mut sink, width, height, color, data) {
Ok(()) => Ok(sink.out),
Err(_) if sink.exceeded => Err(ImageError::LimitExceeded(format!("the encoded PNG exceeds the limit of {} bytes", limits.max_input_bytes))),
Err(e) => Err(ImageError::Encode(e.to_string())),
}
}
/// Encodes an RGBA image as an 8-bit PNG: RGB when every pixel is opaque, otherwise RGBA. Returns
/// an error when the image's sides, its pixel bytes or the encoded file are over `limits`.
pub fn encode_png(image: Rgba8<'_>, limits: PngLimits) -> Result<Vec<u8>, ImageError> {
check_encode_limits(image.width, image.height, image.pixels.len(), limits)?;
let px = image.pixels.as_chunks::<4>().0;
if px.iter().all(|p| p[3] == 255) {
let rgb: Vec<u8> = px.iter().flat_map(|p| [p[0], p[1], p[2]]).collect();
encode(image.width, image.height, png::ColorType::Rgb, &rgb, limits)
} else {
encode(image.width, image.height, png::ColorType::Rgba, image.pixels, limits)
}
}
/// Encodes a gray image as an 8-bit grayscale PNG. Returns an error when the image's sides, its
/// pixel bytes or the encoded file are over `limits`.
pub fn encode_gray_png(image: Gray8<'_>, limits: PngLimits) -> Result<Vec<u8>, ImageError> {
check_encode_limits(image.width, image.height, image.pixels.len(), limits)?;
encode(image.width, image.height, png::ColorType::Grayscale, image.pixels, limits)
}
#[cfg(not(target_arch = "wasm32"))]
fn io_error(path: &Path) -> impl FnOnce(std::io::Error) -> ImageError + '_ {
move |source| ImageError::Io { path: path.to_path_buf(), source }
}
/// Reads and decodes the PNG at `path`. The file size is checked against
/// `limits.max_input_bytes` before it is read.
#[cfg(not(target_arch = "wasm32"))]
pub fn read_png(path: &Path, limits: PngLimits) -> Result<DecodedPng, ImageError> {
let file = fs::File::open(path).map_err(io_error(path))?;
let len = file.metadata().map_err(io_error(path))?.len();
limit("PNG file bytes", len, limits.max_input_bytes as u64)?;
let mut bytes = Vec::new();
file.take((limits.max_input_bytes as u64).saturating_add(1)).read_to_end(&mut bytes).map_err(io_error(path))?;
decode_png(&bytes, limits)
}
/// Writes `bytes` to a new file next to `path`, then renames it over `path`, so a failed write
/// leaves an existing file as it was.
#[cfg(not(target_arch = "wasm32"))]
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), ImageError> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
fs::create_dir_all(dir).map_err(io_error(dir))?;
let file_name = path.file_name().ok_or_else(|| ImageError::InvalidName(format!("{} does not name a file", path.display())))?;
loop {
let mut temp_name = std::ffi::OsString::from(".");
temp_name.push(file_name);
temp_name.push(format!(".{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let temp = dir.join(temp_name);
match create_new(&temp, bytes) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(source) => return Err(ImageError::Io { path: temp, source }),
}
return fs::rename(&temp, path).map_err(|source| {
let _ = fs::remove_file(&temp);
ImageError::Io { path: path.to_path_buf(), source }
});
}
}
/// Encodes `image` with [`encode_png`] and writes it to `path`, creating the parent folders.
/// Nothing is written when encoding fails.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_png(path: &Path, image: Rgba8<'_>, limits: PngLimits) -> Result<(), ImageError> {
write_file(path, &encode_png(image, limits)?)
}
/// Encodes `image` with [`encode_gray_png`] and writes it to `path`, creating the parent folders.
/// Nothing is written when encoding fails.
#[cfg(not(target_arch = "wasm32"))]
pub fn write_gray_png(path: &Path, image: Gray8<'_>, limits: PngLimits) -> Result<(), ImageError> {
write_file(path, &encode_gray_png(image, limits)?)
}
/// Settings for [`check_golden`].
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Debug)]
pub struct GoldenOptions<'a> {
/// The variable that blesses references when its value is exactly `1`.
pub bless_var: &'a str,
/// The folder that receives the actual and difference images of a failed check.
pub failures_dir: &'a Path,
/// The file stem of the failure images: 1 to 100 ASCII letters, digits, `-`, `_` or `.`,
/// starting with a letter, digit or `_`.
pub name: &'a str,
/// Limits for the reference and the written images.
pub limits: PngLimits,
}
#[cfg(not(target_arch = "wasm32"))]
impl<'a> GoldenOptions<'a> {
/// Options with [`DEFAULT_BLESS_VAR`] and [`PngLimits::DEFAULT`].
pub fn new(failures_dir: &'a Path, name: &'a str) -> Self {
Self { bless_var: DEFAULT_BLESS_VAR, failures_dir, name, limits: PngLimits::DEFAULT }
}
}
/// Whether a bless variable's value asks to write references: only the exact value `1` does.
#[cfg(not(target_arch = "wasm32"))]
pub fn is_bless_value(value: Option<&OsStr>) -> bool {
value == Some(OsStr::new("1"))
}
#[cfg(not(target_arch = "wasm32"))]
fn validate_names(options: &GoldenOptions<'_>) -> Result<(), ImageError> {
let var = options.bless_var;
if var.is_empty() || var.contains(['=', '\0']) {
return Err(ImageError::InvalidName(format!("bless variable name {var:?} must not be empty or contain '=' or NUL")));
}
let name = options.name;
let allowed = name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
let first = name.bytes().next().is_some_and(|b| b.is_ascii_alphanumeric() || b == b'_');
let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase();
let numbered =
stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes().get(3).is_some_and(|b| (b'1'..=b'9').contains(b));
let reserved = numbered || matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL");
if name.len() > 100 || !allowed || !first || reserved || name.ends_with('.') {
return Err(ImageError::InvalidName(format!(
"failure image name {name:?} must be 1 to 100 ASCII letters, digits, '-', '_' or '.', start with a letter, digit or '_', and not be a device name"
)));
}
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
fn create_new(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(path)?;
let written = file.write_all(bytes);
if written.is_err() {
drop(file);
let _ = fs::remove_file(path);
}
written
}
/// Writes the actual and difference images under new names in the failure folder. An existing
/// file is never replaced: `<name>.actual.png`, then `<name>-1.actual.png` and so on.
#[cfg(not(target_arch = "wasm32"))]
fn write_failure(options: &GoldenOptions<'_>, actual: &[u8], diff: &[u8]) -> Result<(PathBuf, PathBuf), ImageError> {
let dir = options.failures_dir;
fs::create_dir_all(dir).map_err(io_error(dir))?;
for n in 0..MAX_FAILURE_PAIRS {
let stem = if n == 0 { options.name.to_string() } else { format!("{}-{n}", options.name) };
let actual_path = dir.join(format!("{stem}.actual.png"));
match create_new(&actual_path, actual) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(source) => return Err(ImageError::Io { path: actual_path, source }),
}
let diff_path = dir.join(format!("{stem}.diff.png"));
match create_new(&diff_path, diff) {
Ok(()) => return Ok((actual_path, diff_path)),
Err(e) => {
let _ = fs::remove_file(&actual_path);
if e.kind() != std::io::ErrorKind::AlreadyExists {
return Err(ImageError::Io { path: diff_path, source: e });
}
}
}
}
Err(ImageError::LimitExceeded(format!("{} already holds {MAX_FAILURE_PAIRS} failure images named {}", dir.display(), options.name)))
}
/// Compares `actual` with the reference PNG at `reference`, or writes the reference when the
/// variable `options.bless_var` is exactly `1`.
///
/// A missing reference returns [`ImageError::MissingReference`] unless blessing. When the
/// comparison fails, the actual and difference images are written as new files inside
/// `options.failures_dir`, and [`ImageError::GoldenMismatch`] names them. When they cannot be
/// encoded or written, [`ImageError::GoldenMismatchUnsaved`] carries the verdict together with
/// that error. A reference that would
/// be larger than `options.limits.max_input_bytes` is not written.
#[cfg(not(target_arch = "wasm32"))]
pub fn check_golden(reference: &Path, actual: Rgba8<'_>, tolerance: Tolerance, options: GoldenOptions<'_>) -> Result<Verdict, ImageError> {
validate_names(&options)?;
let bless = is_bless_value(std::env::var_os(options.bless_var).as_deref());
check_golden_with(reference, actual, tolerance, options, bless)
}
#[cfg(not(target_arch = "wasm32"))]
fn check_golden_with(
reference: &Path,
actual: Rgba8<'_>,
tolerance: Tolerance,
options: GoldenOptions<'_>,
bless: bool,
) -> Result<Verdict, ImageError> {
validate_names(&options)?;
tolerance.validate()?;
if bless {
write_png(reference, actual, options.limits)?;
return compare_rgba(actual, actual, tolerance);
}
let decoded = match read_png(reference, options.limits) {
Ok(decoded) => decoded,
Err(ImageError::Io { source, .. }) if source.kind() == std::io::ErrorKind::NotFound => {
return Err(ImageError::MissingReference { path: reference.to_path_buf(), bless_var: options.bless_var.to_string() });
}
Err(e) => return Err(e),
};
let (width, height) = (decoded.width(), decoded.height());
if (width, height) != (actual.width, actual.height) {
return Err(ImageError::SizeMismatch { a: (width, height), b: (actual.width, actual.height) });
}
limit("decoded PNG bytes", actual.pixels.len() as u64, options.limits.max_decoded_bytes as u64)?;
let pixels = decoded.into_rgba();
let expected = Rgba8::new(width, height, &pixels)?;
let verdict = compare_rgba(expected, actual, tolerance)?;
if verdict.passed() {
return Ok(verdict);
}
let saved = diff_image(expected, actual).and_then(|diff| {
let actual_png = encode_png(actual, options.limits)?;
let diff_png = encode_png(Rgba8::new(width, height, &diff)?, options.limits)?;
write_failure(&options, &actual_png, &diff_png)
});
let reference = reference.to_path_buf();
Err(match saved {
Ok((actual, diff)) => ImageError::GoldenMismatch(Box::new(GoldenMismatch { reference, verdict, actual, diff })),
Err(error) => ImageError::GoldenMismatchUnsaved(Box::new(UnsavedMismatch { reference, verdict, error })),
})
}
/// Fails the test that called [`assert_similar!`](crate::assert_similar); the panic names the
/// caller's location.
#[cfg(not(target_arch = "wasm32"))]
#[doc(hidden)]
#[track_caller]
#[allow(clippy::panic)]
pub fn fail_similar(error: ImageError) -> ! {
panic!("{error}")
}
/// Runs [`check_golden`](crate::image::check_golden) and fails the calling test when it returns
/// an error. Evaluates to the [`Verdict`](crate::image::Verdict).
///
/// ```ignore
/// let options = craft_testkit::image::GoldenOptions::new(&failures, "title_card");
/// craft_testkit::assert_similar!(&reference, actual, tolerance, options);
/// ```
#[cfg(not(target_arch = "wasm32"))]
#[macro_export]
macro_rules! assert_similar {
($reference:expr, $actual:expr, $tolerance:expr, $options:expr $(,)?) => {
match $crate::image::check_golden($reference, $actual, $tolerance, $options) {
::core::result::Result::Ok(verdict) => verdict,
::core::result::Result::Err(error) => $crate::image::fail_similar(error),
}
};
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests;
+927
View File
@@ -0,0 +1,927 @@
use std::collections::HashSet;
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use super::{
BoundedSink, DecodedPng, GoldenOptions, Gray8, ImageError, PngLimits, Rgba8, Tolerance, check_golden_with, compare_gray, compare_rgba,
decode_png, diff_gray, diff_image, diff_rgba, encode_gray_png, encode_png, is_bless_value, psnr, read_png, write_gray_png, write_png,
write_stream,
};
/// The bless variable of these tests. Comparison cases call `check_golden_with` with blessing off,
/// and the `assert_similar!` cases run in a child process with the variable removed, so a value
/// inherited from the environment cannot turn a comparison into a bless.
const NO_BLESS: &str = "CRAFT_TESTKIT_SELF_TEST_BLESS";
/// Set in the child processes that `run_child` starts.
const CHILD_MARKER: &str = "CRAFT_TESTKIT_IMAGE_CHILD";
/// A golden check that compares and never blesses.
fn compare_golden(reference: &Path, actual: Rgba8<'_>, tolerance: Tolerance, options: GoldenOptions<'_>) -> Result<super::Verdict, ImageError> {
check_golden_with(reference, actual, tolerance, options, false)
}
fn ramp(w: u32, h: u32, alpha: u8) -> Vec<u8> {
(0..w * h).flat_map(|i| [(i % w * 255 / w) as u8, (i / w * 255 / h) as u8, 77, alpha]).collect()
}
fn rgba(w: u32, h: u32, px: &[u8]) -> Rgba8<'_> {
Rgba8::new(w, h, px).expect("sized")
}
fn gray(w: usize, h: usize, fill: u8) -> Vec<u8> {
vec![fill; w * h]
}
fn g(w: usize, h: usize, px: &[u8]) -> Gray8<'_> {
Gray8::new(w as u32, h as u32, px).expect("sized")
}
fn neighborhood(channel: u8) -> Tolerance {
Tolerance { max_abs: None, channel, neighborhood: true, ..Tolerance::EXACT }
}
/// FilmCraft's render tolerance.
fn render() -> Tolerance {
Tolerance { min_psnr: Some(45.0), max_abs: Some(12), max_p99: Some(2), ..Tolerance::EXACT }
}
/// AniCraft's default tolerance.
fn per_pixel() -> Tolerance {
Tolerance { max_abs: None, channel: 3, max_bad_fraction: Some(0.002), ..Tolerance::EXACT }
}
// PNG files written by hand from the W3C PNG specification, so the reader is checked against
// the format rather than against the encoder it ships with.
fn crc32(bytes: &[u8]) -> u32 {
let mut c = 0xFFFF_FFFFu32;
for &b in bytes {
c ^= u32::from(b);
for _ in 0..8 {
c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
fn adler32(bytes: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &x in bytes {
a = (a + u32::from(x)) % 65521;
b = (b + a) % 65521;
}
(b << 16) | a
}
/// A zlib stream of stored (uncompressed) deflate blocks.
fn zlib_stored(data: &[u8]) -> Vec<u8> {
let mut out = vec![0x78, 0x01];
let blocks: Vec<&[u8]> = if data.is_empty() { vec![&[]] } else { data.chunks(65_535).collect() };
for (i, block) in blocks.iter().enumerate() {
out.push(u8::from(i + 1 == blocks.len()));
let len = block.len() as u16;
out.extend(len.to_le_bytes());
out.extend((!len).to_le_bytes());
out.extend_from_slice(block);
}
out.extend(adler32(data).to_be_bytes());
out
}
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend((data.len() as u32).to_be_bytes());
let mut body = kind.to_vec();
body.extend_from_slice(data);
out.extend_from_slice(&body);
out.extend(crc32(&body).to_be_bytes());
}
const SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
/// A PNG with the given header, extra chunks before the image data, and filtered scanlines.
fn png_file(width: u32, height: u32, depth: u8, color: u8, interlace: u8, extra: &[(&[u8; 4], &[u8])], scanlines: &[u8]) -> Vec<u8> {
let mut out = SIGNATURE.to_vec();
let mut ihdr = Vec::new();
ihdr.extend(width.to_be_bytes());
ihdr.extend(height.to_be_bytes());
ihdr.extend([depth, color, 0, 0, interlace]);
chunk(&mut out, b"IHDR", &ihdr);
for (kind, data) in extra {
chunk(&mut out, kind, data);
}
chunk(&mut out, b"IDAT", &zlib_stored(scanlines));
chunk(&mut out, b"IEND", &[]);
out
}
/// Adam7 pass origins and steps: (x0, y0, dx, dy).
const ADAM7: [(usize, usize, usize, usize); 7] = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)];
/// Scanlines of an 8-bit gray image in Adam7 order, each with filter type 0.
fn adam7_gray(w: usize, h: usize, px: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
for (x0, y0, dx, dy) in ADAM7 {
let cols: Vec<usize> = (x0..w).step_by(dx).collect();
if cols.is_empty() {
continue;
}
for y in (y0..h).step_by(dy) {
out.push(0);
out.extend(cols.iter().map(|&x| px[y * w + x]));
}
}
out
}
fn decode(bytes: &[u8]) -> DecodedPng {
decode_png(bytes, PngLimits::DEFAULT).expect("decodes")
}
#[test]
fn fixture_crc_matches_the_specification() {
// Every PNG ends with this IEND chunk, whose CRC the specification's sample code yields.
assert_eq!(crc32(b"IEND"), 0xAE42_6082);
}
// Views.
#[test]
fn invalid_view_length_is_error() {
assert!(matches!(Rgba8::new(2, 2, &[0; 15]), Err(ImageError::InvalidBufferLength { expected: 16, actual: 15 })));
assert!(matches!(Rgba8::new(2, 2, &[0; 17]), Err(ImageError::InvalidBufferLength { expected: 16, actual: 17 })));
assert!(Rgba8::new(2, 2, &[0; 16]).is_ok());
}
#[test]
fn rgba_length_overflow_is_error() {
for result in [Rgba8::new(u32::MAX, u32::MAX, &[]), Rgba8::new(u32::MAX, u32::MAX, &[0; 4])] {
assert!(matches!(result, Err(ImageError::InvalidDimensions { .. } | ImageError::InvalidBufferLength { .. })), "{result:?}");
}
}
#[test]
fn a_buffer_that_is_not_the_stated_size_is_rejected() {
let buf = gray(4, 4, 0);
assert!(Gray8::new(4, 4, &buf).is_ok());
assert!(Gray8::new(5, 4, &buf).is_err());
assert!(Gray8::new(4, 5, &buf).is_err());
assert!(Gray8::new(u32::MAX, u32::MAX, &buf).is_err(), "the area must not overflow into a match");
// A zero-sized image has no samples for p99 or PSNR, and PNG does not allow one: it is an error.
assert!(matches!(Gray8::new(0, 0, &[]), Err(ImageError::InvalidDimensions { width: 0, height: 0 })));
}
/// A zero-width image of enormous height is rejected at once, without walking its rows.
#[test]
fn an_image_without_pixels_compares_at_once() {
assert!(matches!(Gray8::new(0, u32::MAX, &[]), Err(ImageError::InvalidDimensions { .. })));
assert!(matches!(Rgba8::new(u32::MAX, 0, &[]), Err(ImageError::InvalidDimensions { .. })));
}
// Statistics.
#[test]
fn diff_metrics() {
let a = ramp(10, 10, 255);
assert_eq!(diff_rgba(rgba(10, 10, &a), rgba(10, 10, &a)).unwrap().psnr, f64::INFINITY);
let mut b = a.clone();
b[0] = b[0].wrapping_add(10); // one channel of one pixel
let d = diff_rgba(rgba(10, 10, &a), rgba(10, 10, &b)).unwrap();
assert_eq!((d.max_abs, d.p99, d.differing_pixels, d.total_pixels), (10, 0, 1, 100));
assert!((d.mean_abs - 10.0 / 400.0).abs() < 1e-12);
let mse: f64 = 100.0 / 400.0;
assert!((d.psnr - 10.0 * (255.0f64 * 255.0 / mse).log10()).abs() < 1e-9);
assert!(compare_rgba(rgba(10, 10, &a), rgba(10, 10, &b), render()).unwrap().passed());
assert!(!compare_rgba(rgba(10, 10, &a), rgba(10, 10, &b), Tolerance::EXACT).unwrap().passed());
let taller = ramp(10, 11, 255);
assert!(diff_rgba(rgba(10, 10, &a), rgba(10, 11, &taller)).is_err());
}
#[test]
fn p99_nearest_rank_small_samples() {
// One pixel: rank ceil(0.99) = 1.
let (a, b) = ([0u8], [7u8]);
assert_eq!(diff_gray(g(1, 1, &a), g(1, 1, &b)).unwrap().p99, 7);
// 100 pixels: rank 99. One changed pixel sits at position 100, two reach position 99.
let base = gray(100, 1, 0);
let mut one = base.clone();
one[0] = 10;
assert_eq!(diff_gray(g(100, 1, &base), g(100, 1, &one)).unwrap().p99, 0);
let mut two = one.clone();
two[1] = 10;
assert_eq!(diff_gray(g(100, 1, &base), g(100, 1, &two)).unwrap().p99, 10);
// 101 pixels: rank ceil(99.99) = 100.
let base = gray(101, 1, 0);
let mut one = base.clone();
one[0] = 10;
assert_eq!(diff_gray(g(101, 1, &base), g(101, 1, &one)).unwrap().p99, 0);
let mut two = one.clone();
two[1] = 10;
assert_eq!(diff_gray(g(101, 1, &base), g(101, 1, &two)).unwrap().p99, 10);
}
#[test]
fn psnr_published_two_sample_value() {
// MSE = 255² / 2, so PSNR = 10 log10(2).
let value = psnr(&[0u8, 0], &[255u8, 0], 255.0).unwrap();
assert!((value - 3.010_299_956_6).abs() < 1e-9, "{value}");
}
#[test]
fn psnr_identical_is_infinite() {
assert_eq!(psnr(&[1u8, 2, 3], &[1u8, 2, 3], 255.0).unwrap(), f64::INFINITY);
assert_eq!(psnr(&[1000u16], &[1000u16], 1023.0).unwrap(), f64::INFINITY);
}
#[test]
fn psnr_rejects_unequal_empty_and_bad_peak() {
assert!(matches!(psnr(&[0u8, 1], &[0u8], 255.0), Err(ImageError::PlaneLengthMismatch { a: 2, b: 1 })));
assert!(matches!(psnr::<u8>(&[], &[], 255.0), Err(ImageError::EmptyPlane)));
for peak in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert!(matches!(psnr(&[0u8], &[1u8], peak), Err(ImageError::InvalidPeak(_))), "{peak}");
}
}
#[test]
fn psnr_u16_peak() {
let value = psnr(&[0u16, 0], &[1023u16, 0], 1023.0).unwrap();
assert!((value - 10.0 * 2f64.log10()).abs() < 1e-9, "{value}");
assert!(psnr(&[0u16], &[65535u16], 65535.0).unwrap().abs() < 1e-12);
// peak² does not fit in f64 here, but the result does: 20 × 200 dB.
let value = psnr(&[0u8], &[1u8], 1e200).unwrap();
assert!((value - 4000.0).abs() < 1e-9, "{value}");
}
#[test]
fn diff_image_rejects_size_mismatch() {
let a = [10u8, 20, 30, 255, 0, 0, 0, 255];
let b = [11u8, 20, 30, 250, 0, 100, 0, 255];
let d = diff_image(rgba(2, 1, &a), rgba(2, 1, &b)).unwrap();
// Red differs by 1 (8 after scaling), alpha by 5 (40), which shows in every color channel.
assert_eq!(d, vec![40, 40, 40, 255, 0, 255, 0, 255]);
assert!(matches!(diff_image(rgba(2, 1, &a), rgba(1, 2, &b)), Err(ImageError::SizeMismatch { .. })));
}
// Tolerances and the neighborhood.
#[test]
fn identical_images_do_not_differ() {
let buf = gray(16, 16, 128);
let v = compare_gray(g(16, 16, &buf), g(16, 16, &buf), neighborhood(0)).expect("same size");
assert_eq!(v.bad_pixels, 0);
assert_eq!(v.stats.max_abs, 0);
assert_eq!(v.stats.differing_pixels, 0);
assert_eq!(v.stats.total_pixels, 256);
}
/// A one-pixel shift of a stem is forgiven, because every moved pixel finds its match next door.
#[test]
fn a_one_pixel_shift_is_forgiven() {
let (w, h) = (9usize, 9usize);
let mut left = gray(w, h, 255);
let mut right = gray(w, h, 255);
for y in 0..h {
left[y * w + 4] = 0;
right[y * w + 5] = 0;
}
let v = compare_gray(g(w, h, &left), g(w, h, &right), neighborhood(8)).expect("same size");
assert_eq!(v.bad_pixels, 0, "a one-pixel shift must not count as a difference");
// The aligned difference still shows the shift.
assert_eq!(v.stats.max_abs, 255);
}
/// Content that is absent is not forgiven, however tolerant the neighborhood is.
#[test]
fn missing_content_is_not_forgiven() {
let (w, h) = (16usize, 16usize);
let blank = gray(w, h, 255);
let mut drawn = blank.clone();
for y in 5..11 {
for x in 5..11 {
drawn[y * w + x] = 0;
}
}
let v = compare_gray(g(w, h, &blank), g(w, h, &drawn), neighborhood(8)).expect("same size");
// Blank against drawn forgives the block's border and counts its 4x4 interior; drawn
// against blank counts all 36 black pixels. The larger count is reported.
assert_eq!(v.bad_pixels, 36, "every pixel of a missing block must be counted");
}
/// A shift of more than one pixel is beyond the 3x3 window and is reported.
#[test]
fn a_shift_wider_than_the_window_is_reported() {
let (w, h) = (16usize, 16usize);
let mut left = gray(w, h, 255);
let mut right = gray(w, h, 255);
for y in 0..h {
for x in 4..8 {
left[y * w + x] = 0;
}
for x in 11..15 {
right[y * w + x] = 0;
}
}
assert!(compare_gray(g(w, h, &left), g(w, h, &right), neighborhood(8)).expect("same size").bad_pixels > 0);
}
#[test]
fn tolerance_absorbs_small_differences_only() {
let flat = gray(8, 8, 100);
let near = gray(8, 8, 105);
let far = gray(8, 8, 200);
let a = g(8, 8, &flat);
assert_eq!(compare_gray(a, g(8, 8, &near), neighborhood(8)).expect("ok").bad_pixels, 0);
assert_eq!(compare_gray(a, g(8, 8, &far), neighborhood(8)).expect("ok").bad_pixels, 64);
// The tolerance is inclusive at the boundary.
assert_eq!(compare_gray(a, g(8, 8, &near), neighborhood(5)).expect("ok").bad_pixels, 0);
assert_eq!(compare_gray(a, g(8, 8, &near), neighborhood(4)).expect("ok").bad_pixels, 64);
}
/// Comparison is symmetric: neither argument order flatters one image.
#[test]
fn comparison_is_symmetric() {
let (w, h) = (12usize, 12usize);
let mut thin = gray(w, h, 255);
let mut thick = gray(w, h, 255);
for y in 0..h {
thin[y * w + 6] = 0;
for x in 4..9 {
thick[y * w + x] = 0;
}
}
let forward = compare_gray(g(w, h, &thin), g(w, h, &thick), neighborhood(8)).expect("ok");
let backward = compare_gray(g(w, h, &thick), g(w, h, &thin), neighborhood(8)).expect("ok");
assert_eq!(forward, backward, "argument order must not change the verdict");
assert!(forward.bad_pixels > 0, "a 1px stem against a 5px bar is a real difference");
}
#[test]
fn neighborhood_clips_at_edges() {
// Only the edge pixels differ, and their windows stop at the image border.
let (a, b) = ([0u8, 255, 255], [255u8, 255, 0]);
assert_eq!(compare_gray(g(3, 1, &a), g(3, 1, &b), neighborhood(0)).unwrap().bad_pixels, 1);
let (a, b) = ([0u8], [1u8]);
assert_eq!(compare_gray(g(1, 1, &a), g(1, 1, &b), neighborhood(0)).unwrap().bad_pixels, 1);
assert_eq!(compare_gray(g(1, 1, &a), g(1, 1, &b), neighborhood(1)).unwrap().bad_pixels, 0);
// RGBA pixels match only when every channel is within the tolerance.
let a = [0u8, 0, 0, 255, 9, 9, 9, 255];
let b = [0u8, 0, 0, 200, 9, 9, 9, 200];
assert_eq!(compare_rgba(rgba(2, 1, &a), rgba(2, 1, &b), neighborhood(54)).unwrap().bad_pixels, 2);
assert_eq!(compare_rgba(rgba(2, 1, &a), rgba(2, 1, &b), neighborhood(55)).unwrap().bad_pixels, 0);
}
#[test]
fn bad_pixel_fraction_is_inclusive() {
let base = gray(1000, 1, 0);
let mut off = base.clone();
off[0] = 9;
off[1] = 9;
let t = Tolerance { max_abs: None, channel: 3, max_bad_fraction: Some(0.002), ..Tolerance::EXACT };
let v = compare_gray(g(1000, 1, &base), g(1000, 1, &off), t).unwrap();
assert_eq!((v.bad_pixels, v.allowed_bad_pixels), (2, Some(2)));
assert!(v.passed());
off[2] = 4;
let v = compare_gray(g(1000, 1, &base), g(1000, 1, &off), t).unwrap();
assert_eq!(v.bad_pixels, 3);
assert!(!v.passed());
// 0.29 × 100 is 28.999999999999996 in f64; 29 of 100 pixels is still 29%.
let base = gray(100, 1, 0);
let mut off = base.clone();
off[..29].fill(9);
let t = Tolerance { max_bad_fraction: Some(0.29), ..t };
let v = compare_gray(g(100, 1, &base), g(100, 1, &off), t).unwrap();
assert_eq!((v.bad_pixels, v.allowed_bad_pixels), (29, Some(29)));
assert!(v.passed());
}
#[test]
fn invalid_tolerance_is_error() {
let a = [0u8];
for t in [
Tolerance { max_bad_fraction: Some(1.5), ..Tolerance::EXACT },
Tolerance { max_bad_fraction: Some(-0.1), ..Tolerance::EXACT },
Tolerance { max_bad_fraction: Some(f64::NAN), ..Tolerance::EXACT },
Tolerance { min_psnr: Some(f64::NAN), ..Tolerance::EXACT },
] {
assert!(matches!(compare_gray(g(1, 1, &a), g(1, 1, &a), t), Err(ImageError::InvalidTolerance(_))), "{t:?}");
}
}
#[test]
fn different_sizes_are_an_error_not_a_score() {
let small = gray(4, 4, 0);
let large = gray(8, 8, 0);
let err = compare_gray(g(4, 4, &small), g(8, 8, &large), Tolerance::EXACT).expect_err("mismatch");
assert!(matches!(err, ImageError::SizeMismatch { a: (4, 4), b: (8, 8) }), "{err:?}");
assert!(err.to_string().contains("4x4"), "{err}");
}
// PNG.
#[test]
fn png_round_trip_rgb_and_rgba() {
for alpha in [255, 128] {
let px = ramp(37, 21, alpha);
let png = encode_png(rgba(37, 21, &px), PngLimits::DEFAULT).unwrap();
assert_eq!(decode(&png), DecodedPng::Rgba { width: 37, height: 21, pixels: px });
}
}
#[test]
fn gray_png_round_trip() {
let px: Vec<u8> = (0..60).map(|i| (i * 4) as u8).collect();
let png = encode_gray_png(g(10, 6, &px), PngLimits::DEFAULT).unwrap();
assert_eq!(decode(&png), DecodedPng::Gray { width: 10, height: 6, pixels: px });
}
#[test]
fn encoded_header_matches_the_png_specification() {
let opaque = ramp(3, 2, 255);
let clear = ramp(3, 2, 7);
let shades = [1u8, 2, 3, 4, 5, 6];
for (png, color_type) in [
(encode_png(rgba(3, 2, &opaque), PngLimits::DEFAULT).unwrap(), 2u8),
(encode_png(rgba(3, 2, &clear), PngLimits::DEFAULT).unwrap(), 6),
(encode_gray_png(g(3, 2, &shades), PngLimits::DEFAULT).unwrap(), 0),
] {
assert_eq!(png[..8], SIGNATURE);
assert_eq!(png[8..16], [0, 0, 0, 13, b'I', b'H', b'D', b'R']);
// Width, height, bit depth, color type, compression, filter and interlace methods.
assert_eq!(png[16..29], [0, 0, 0, 3, 0, 0, 0, 2, 8, color_type, 0, 0, 0]);
assert_eq!(png[29..33], crc32(&png[12..29]).to_be_bytes());
}
}
#[test]
fn png_normalizes_supported_color_types() {
// Gray, 1 bit: 1 scales to 255.
let png = png_file(8, 1, 1, 0, 0, &[], &[0, 0b1010_0000]);
assert_eq!(decode(&png), DecodedPng::Gray { width: 8, height: 1, pixels: vec![255, 0, 255, 0, 0, 0, 0, 0] });
// Gray, 2 bits: steps of 85.
let png = png_file(4, 1, 2, 0, 0, &[], &[0, 0b00_01_10_11]);
assert_eq!(decode(&png), DecodedPng::Gray { width: 4, height: 1, pixels: vec![0, 85, 170, 255] });
// Gray with alpha.
let png = png_file(2, 1, 8, 4, 0, &[], &[0, 10, 20, 30, 40]);
assert_eq!(decode(&png), DecodedPng::Rgba { width: 2, height: 1, pixels: vec![10, 10, 10, 20, 30, 30, 30, 40] });
// RGB.
let png = png_file(1, 1, 8, 2, 0, &[], &[0, 1, 2, 3]);
assert_eq!(decode(&png), DecodedPng::Rgba { width: 1, height: 1, pixels: vec![1, 2, 3, 255] });
// RGBA.
let png = png_file(1, 1, 8, 6, 0, &[], &[0, 1, 2, 3, 4]);
assert_eq!(decode(&png), DecodedPng::Rgba { width: 1, height: 1, pixels: vec![1, 2, 3, 4] });
// Palette with a tRNS entry for its first color.
let png = png_file(2, 1, 8, 3, 0, &[(b"PLTE", &[255, 0, 0, 0, 0, 255]), (b"tRNS", &[128])], &[0, 0, 1]);
assert_eq!(decode(&png), DecodedPng::Rgba { width: 2, height: 1, pixels: vec![255, 0, 0, 128, 0, 0, 255, 255] });
// Gray with a tRNS value of 7.
let png = png_file(2, 1, 8, 0, 0, &[(b"tRNS", &[0, 7])], &[0, 7, 9]);
assert_eq!(decode(&png), DecodedPng::Rgba { width: 2, height: 1, pixels: vec![7, 7, 7, 0, 9, 9, 9, 255] });
}
#[test]
fn png_16bit_strips_to_8bit() {
let png = png_file(1, 2, 16, 0, 0, &[], &[0, 0x12, 0x34, 0, 0xAB, 0xCD]);
assert_eq!(decode(&png), DecodedPng::Gray { width: 1, height: 2, pixels: vec![0x12, 0xAB] });
let png = png_file(1, 1, 16, 6, 0, &[], &[0, 1, 2, 3, 4, 5, 6, 0xFF, 0]);
assert_eq!(decode(&png), DecodedPng::Rgba { width: 1, height: 1, pixels: vec![1, 3, 5, 255] });
}
#[test]
fn interlaced_png_decodes_complete_frame() {
let (w, h) = (5usize, 5usize);
let px: Vec<u8> = (0..w * h).map(|i| (i * 10) as u8).collect();
let png = png_file(5, 5, 8, 0, 1, &[], &adam7_gray(w, h, &px));
assert_eq!(decode(&png), DecodedPng::Gray { width: 5, height: 5, pixels: px });
}
#[test]
fn wrong_signature_and_truncated_png_are_errors() {
let px = ramp(4, 4, 255);
let png = encode_png(rgba(4, 4, &px), PngLimits::DEFAULT).unwrap();
let mut wrong = png.clone();
wrong[1] = b'Q';
assert!(matches!(decode_png(&wrong, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
assert!(matches!(decode_png(&[], PngLimits::DEFAULT), Err(ImageError::Decode(_))));
// Cut inside the header, and just after the zlib header of the image data.
let idat = png.windows(4).position(|w| w == b"IDAT").expect("an IDAT chunk");
for len in [20, idat + 6] {
assert!(matches!(decode_png(&png[..len], PngLimits::DEFAULT), Err(ImageError::Decode(_))), "{len}");
}
}
#[test]
fn png_without_a_valid_end_is_an_error() {
let png = png_file(2, 1, 8, 0, 0, &[], &[0, 1, 2]);
assert!(decode_png(&png, PngLimits::DEFAULT).is_ok());
// No IEND chunk.
let cut = &png[..png.len() - 12];
assert!(matches!(decode_png(cut, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
// An IEND chunk with a wrong CRC.
let mut bad_crc = png.clone();
if let Some(last) = bad_crc.last_mut() {
*last ^= 0xFF;
}
assert!(matches!(decode_png(&bad_crc, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
}
#[test]
fn a_bad_ancillary_crc_is_an_error() {
let text: &[u8] = b"Comment\0x";
// A tEXt chunk between the image data and IEND.
let plain = png_file(2, 1, 8, 0, 0, &[], &[0, 1, 2]);
let (body, iend) = plain.split_at(plain.len() - 12);
let mut after = body.to_vec();
chunk(&mut after, b"tEXt", text);
after.extend_from_slice(iend);
assert!(decode_png(&after, PngLimits::DEFAULT).is_ok(), "a valid tEXt chunk is accepted");
let crc = after.len() - iend.len() - 1;
after[crc] ^= 0xFF;
assert!(matches!(decode_png(&after, PngLimits::DEFAULT), Err(ImageError::Decode(_))), "after the image");
// A tEXt chunk between IHDR and the image data: signature, IHDR, then length, type and data.
let mut before = png_file(2, 1, 8, 0, 0, &[(b"tEXt", text)], &[0, 1, 2]);
assert!(decode_png(&before, PngLimits::DEFAULT).is_ok());
let crc = 8 + 25 + 8 + text.len() + 3;
before[crc] ^= 0xFF;
assert!(matches!(decode_png(&before, PngLimits::DEFAULT), Err(ImageError::Decode(_))), "before the image");
}
#[test]
fn png_limits_reject_header_before_allocation() {
// The image data is a few bytes, so only the header can trigger the error.
let wide = png_file(1_000_000, 1, 8, 0, 0, &[], &[0]);
assert!(matches!(decode_png(&wide, PngLimits::DEFAULT), Err(ImageError::LimitExceeded(_))));
let tall = png_file(1, 1_000_000, 8, 0, 0, &[], &[0]);
assert!(matches!(decode_png(&tall, PngLimits::DEFAULT), Err(ImageError::LimitExceeded(_))));
// 16,384 × 16,384 RGBA is 1 GiB decoded, over the 256 MiB default.
let big = png_file(16_384, 16_384, 8, 6, 0, &[], &[0]);
assert!(matches!(decode_png(&big, PngLimits::DEFAULT), Err(ImageError::LimitExceeded(_))));
let narrow = PngLimits { max_width: 3, ..PngLimits::DEFAULT };
let px = ramp(4, 1, 255);
assert!(matches!(encode_png(rgba(4, 1, &px), narrow), Err(ImageError::LimitExceeded(_))));
}
#[test]
fn png_input_byte_limit() {
let px = ramp(4, 4, 255);
let png = encode_png(rgba(4, 4, &px), PngLimits::DEFAULT).unwrap();
let exact = PngLimits { max_input_bytes: png.len(), ..PngLimits::DEFAULT };
assert!(decode_png(&png, exact).is_ok());
let short = PngLimits { max_input_bytes: png.len() - 1, ..PngLimits::DEFAULT };
assert!(matches!(decode_png(&png, short), Err(ImageError::LimitExceeded(_))));
assert!(matches!(encode_png(rgba(4, 4, &px), short), Err(ImageError::LimitExceeded(_))));
}
#[test]
fn png_decoded_byte_limit() {
// 4x4 RGB: the decoder's output is 48 bytes, and 64 once converted to RGBA.
let scanlines: Vec<u8> = (0..4).flat_map(|_| std::iter::once(0).chain(std::iter::repeat_n(9, 12))).collect();
let png = png_file(4, 4, 8, 2, 0, &[], &scanlines);
let with = |max_decoded_bytes| decode_png(&png, PngLimits { max_decoded_bytes, ..PngLimits::DEFAULT });
assert!(with(64).is_ok());
assert!(matches!(with(50), Err(ImageError::LimitExceeded(_))), "the converted size is checked");
assert!(matches!(with(47), Err(ImageError::LimitExceeded(_))), "checked before allocation");
}
/// The size after conversion to RGBA is checked from the header, before any image data is read,
/// so a stream whose image data is a few bytes still fails on the limit.
#[test]
fn the_converted_size_is_checked_before_decoding() {
// 4x4 RGB, 48 bytes as decoded and 64 as RGBA, with image data that would not decode.
let png = png_file(4, 4, 8, 2, 0, &[], &[0]);
let err = decode_png(&png, PngLimits { max_decoded_bytes: 50, ..PngLimits::DEFAULT }).unwrap_err();
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
assert!(matches!(decode_png(&png, PngLimits::DEFAULT), Err(ImageError::Decode(_))));
}
#[test]
fn encoding_refuses_an_image_that_would_not_read_back() {
// An image is only written when the same limits can decode it again.
let px = ramp(4, 4, 255);
let fits = PngLimits { max_decoded_bytes: 64, ..PngLimits::DEFAULT };
let png = encode_png(rgba(4, 4, &px), fits).unwrap();
assert!(decode_png(&png, fits).is_ok());
let small = PngLimits { max_decoded_bytes: 63, ..PngLimits::DEFAULT };
assert!(matches!(encode_png(rgba(4, 4, &px), small), Err(ImageError::LimitExceeded(_))));
let shades = gray(4, 4, 9);
assert!(encode_gray_png(g(4, 4, &shades), PngLimits { max_decoded_bytes: 16, ..PngLimits::DEFAULT }).is_ok());
assert!(matches!(
encode_gray_png(g(4, 4, &shades), PngLimits { max_decoded_bytes: 15, ..PngLimits::DEFAULT }),
Err(ImageError::LimitExceeded(_))
));
}
#[test]
fn encoding_stops_at_the_byte_limit() {
// Noise does not compress, so the encoder would write about 64 KiB without the bound.
let mut state = 0x2545_F491_4F6C_DD1Du64;
let px: Vec<u8> = (0..128 * 128 * 4)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 56) as u8
})
.collect();
let tiny = PngLimits { max_input_bytes: 100, ..PngLimits::DEFAULT };
let err = encode_png(rgba(128, 128, &px), tiny).unwrap_err();
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
assert!(encode_png(rgba(128, 128, &px), PngLimits::DEFAULT).unwrap().len() > 100);
let mut sink = BoundedSink { out: Vec::new(), max: 100, exceeded: false };
assert!(write_stream(&mut sink, 128, 128, png::ColorType::Rgba, &px).is_err());
assert!(sink.exceeded && sink.out.len() <= 100, "{} bytes held", sink.out.len());
}
#[test]
fn write_error_is_result() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("file");
std::fs::write(&file, b"x").unwrap();
let px = ramp(2, 2, 255);
assert!(matches!(write_png(&file.join("x.png"), rgba(2, 2, &px), PngLimits::DEFAULT), Err(ImageError::Io { .. })));
assert!(matches!(read_png(&dir.path().join("none.png"), PngLimits::DEFAULT), Err(ImageError::Io { .. })));
}
// Golden checks.
fn options<'a>(failures: &'a Path, name: &'a str) -> GoldenOptions<'a> {
GoldenOptions { bless_var: NO_BLESS, ..GoldenOptions::new(failures, name) }
}
fn mismatch(result: Result<super::Verdict, ImageError>) -> Box<super::GoldenMismatch> {
match result {
Err(ImageError::GoldenMismatch(m)) => m,
other => panic!("expected a mismatch, got {other:?}"),
}
}
#[test]
fn check_golden_accepts_within_tolerance_and_reports_failures() {
let dir = tempfile::tempdir().unwrap();
let failures = dir.path().join("failures");
let path = dir.path().join("ramp.png");
let img = ramp(32, 16, 255);
write_png(&path, rgba(32, 16, &img), PngLimits::DEFAULT).unwrap();
assert!(compare_golden(&path, rgba(32, 16, &img), Tolerance::EXACT, options(&failures, "ramp")).is_ok());
let mut near = img.clone();
near[5] += 1;
assert!(compare_golden(&path, rgba(32, 16, &near), render(), options(&failures, "ramp")).is_ok());
let mut far = img.clone();
far.iter_mut().step_by(4).for_each(|v| *v = 255 - *v);
let e = compare_golden(&path, rgba(32, 16, &far), render(), options(&failures, "ramp")).unwrap_err();
assert!(e.to_string().contains("PSNR"), "{e}");
let missing = compare_golden(&dir.path().join("missing.png"), rgba(32, 16, &img), render(), options(&failures, "ramp")).unwrap_err();
assert!(matches!(missing, ImageError::MissingReference { .. }) && missing.to_string().contains(NO_BLESS), "{missing}");
}
#[test]
fn the_check_passes_within_the_tolerance_and_fails_past_it() {
let dir = tempfile::tempdir().unwrap();
let failures = dir.path().join("failures");
let golden = dir.path().join("g.png");
let (w, h) = (20u32, 10u32);
let base: Vec<u8> = (0..w * h).flat_map(|i| [i as u8, 100, 200, 255]).collect();
write_png(&golden, rgba(w, h, &base), PngLimits::DEFAULT).unwrap();
assert!(compare_golden(&golden, rgba(w, h, &base), per_pixel(), options(&failures, "self-test-same")).is_ok());
// Small differences everywhere are within the channel tolerance.
let near: Vec<u8> = base.iter().map(|c| c.saturating_sub(2)).collect();
assert!(compare_golden(&golden, rgba(w, h, &near), per_pixel(), options(&failures, "self-test-near")).is_ok());
// A whole row changed is not.
let mut off = base.clone();
for px in off.as_chunks_mut::<4>().0.iter_mut().take(w as usize) {
px[1] = 0;
}
let m = mismatch(compare_golden(&golden, rgba(w, h, &off), per_pixel(), options(&failures, "self-test-off")));
assert_eq!(m.verdict.bad_pixels, 20);
assert!(m.actual.exists() && m.diff.exists());
assert!(m.diff.ends_with("self-test-off.diff.png"), "{}", m.diff.display());
// A missing golden fails and says how to make one.
let err = compare_golden(&dir.path().join("none.png"), rgba(w, h, &base), per_pixel(), options(&failures, "self-test-missing")).unwrap_err();
assert!(err.to_string().contains(&format!("{NO_BLESS}=1")), "{err}");
}
#[test]
fn bless_requires_exact_one() {
assert!(is_bless_value(Some(OsStr::new("1"))));
for value in ["", "0", "true", "yes", "on", " 1", "1 ", "01", "11"] {
assert!(!is_bless_value(Some(OsStr::new(value))), "{value:?}");
}
assert!(!is_bless_value(None));
}
#[test]
fn missing_reference_fails_without_bless() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("refs").join("new.png");
let px = ramp(4, 4, 255);
let err = check_golden_with(&reference, rgba(4, 4, &px), Tolerance::EXACT, options(dir.path(), "new"), false).unwrap_err();
assert!(matches!(err, ImageError::MissingReference { .. }), "{err:?}");
assert!(!reference.exists(), "a normal run must not create a reference");
}
#[test]
fn bless_creates_missing_reference() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("refs").join("new.png");
let px = ramp(4, 4, 200);
check_golden_with(&reference, rgba(4, 4, &px), Tolerance::EXACT, options(dir.path(), "new"), true).unwrap();
assert_eq!(read_png(&reference, PngLimits::DEFAULT).unwrap(), DecodedPng::Rgba { width: 4, height: 4, pixels: px });
}
#[test]
fn oversize_bless_leaves_reference_unchanged() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("r.png");
let old = ramp(8, 8, 255);
write_png(&reference, rgba(8, 8, &old), PngLimits::DEFAULT).unwrap();
let before = std::fs::read(&reference).unwrap();
let new = ramp(8, 8, 9);
let small = GoldenOptions { limits: PngLimits { max_input_bytes: 10, ..PngLimits::DEFAULT }, ..options(dir.path(), "r") };
let err = check_golden_with(&reference, rgba(8, 8, &new), Tolerance::EXACT, small, true).unwrap_err();
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
assert_eq!(std::fs::read(&reference).unwrap(), before);
}
#[test]
fn gray_reference_expansion_respects_the_decoded_limit() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("g.png");
let shades = gray(4, 4, 9);
write_gray_png(&reference, g(4, 4, &shades), PngLimits::DEFAULT).unwrap();
let px: Vec<u8> = shades.iter().flat_map(|&v| [v, v, v, 255]).collect();
assert!(compare_golden(&reference, rgba(4, 4, &px), Tolerance::EXACT, options(dir.path(), "g")).is_ok());
// The 16-byte gray reference fits, but its 64-byte RGBA form does not.
let small = GoldenOptions { limits: PngLimits { max_decoded_bytes: 16, ..PngLimits::DEFAULT }, ..options(dir.path(), "g") };
let err = compare_golden(&reference, rgba(4, 4, &px), Tolerance::EXACT, small).unwrap_err();
assert!(matches!(err, ImageError::LimitExceeded(_)), "{err:?}");
let wide = ramp(8, 2, 255);
let err = compare_golden(&reference, rgba(8, 2, &wide), Tolerance::EXACT, options(dir.path(), "g")).unwrap_err();
assert!(matches!(err, ImageError::SizeMismatch { a: (4, 4), b: (8, 2) }), "{err:?}");
}
#[test]
fn blessing_replaces_a_reference_whole() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("r.png");
let old = ramp(4, 4, 255);
write_png(&reference, rgba(4, 4, &old), PngLimits::DEFAULT).unwrap();
let new = ramp(4, 4, 99);
check_golden_with(&reference, rgba(4, 4, &new), Tolerance::EXACT, options(dir.path(), "r"), true).unwrap();
assert_eq!(read_png(&reference, PngLimits::DEFAULT).unwrap(), DecodedPng::Rgba { width: 4, height: 4, pixels: new });
let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(names, vec![std::ffi::OsString::from("r.png")], "no temporary file is left behind");
}
#[test]
fn failure_name_rejects_path_components() {
let dir = tempfile::tempdir().unwrap();
let failures = dir.path().join("failures");
let reference = dir.path().join("r.png");
let px = ramp(2, 2, 255);
write_png(&reference, rgba(2, 2, &px), PngLimits::DEFAULT).unwrap();
let other = ramp(2, 2, 0);
let long = "a".repeat(101);
for name in ["", "..", "../escape", "a/b", "a\\b", ".hidden", "C:x", "a b", "x\0", "trailing.", "CON", "nul.x", "com1", "LPT9.png", long.as_str()]
{
let err = compare_golden(&reference, rgba(2, 2, &other), Tolerance::EXACT, options(&failures, name)).unwrap_err();
assert!(matches!(err, ImageError::InvalidName(_)), "{name:?}: {err:?}");
}
assert!(!failures.exists() && !dir.path().join("escape.actual.png").exists());
for name in ["ok-name_1.v2", "_x", "com0", "console"] {
assert!(
matches!(compare_golden(&reference, rgba(2, 2, &other), Tolerance::EXACT, options(&failures, name)), Err(ImageError::GoldenMismatch(_))),
"{name:?}"
);
}
for var in ["", "A=B", "A\0B"] {
let bad = GoldenOptions { bless_var: var, ..options(&failures, "ok") };
assert!(matches!(compare_golden(&reference, rgba(2, 2, &px), Tolerance::EXACT, bad), Err(ImageError::InvalidName(_))), "{var:?}");
}
}
#[test]
fn failure_artifacts_stay_in_folder() {
let dir = tempfile::tempdir().unwrap();
let failures = dir.path().join("deep").join("failures");
let reference = dir.path().join("r.png");
let px = ramp(3, 3, 255);
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
let other = ramp(3, 3, 1);
let m = mismatch(compare_golden(&reference, rgba(3, 3, &other), Tolerance::EXACT, options(&failures, "case")));
assert_eq!(m.actual.parent(), Some(failures.as_path()));
assert_eq!(m.diff.parent(), Some(failures.as_path()));
assert_eq!(read_png(&m.actual, PngLimits::DEFAULT).unwrap(), DecodedPng::Rgba { width: 3, height: 3, pixels: other });
let diff = read_png(&m.diff, PngLimits::DEFAULT).unwrap();
assert_eq!((diff.width(), diff.height()), (3, 3));
}
#[test]
fn failure_artifacts_do_not_overwrite() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("r.png");
let px = ramp(3, 3, 255);
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
let first_img = ramp(3, 3, 1);
let second_img = ramp(3, 3, 2);
let first = mismatch(compare_golden(&reference, rgba(3, 3, &first_img), Tolerance::EXACT, options(dir.path(), "same")));
let kept = std::fs::read(&first.actual).unwrap();
let second = mismatch(compare_golden(&reference, rgba(3, 3, &second_img), Tolerance::EXACT, options(dir.path(), "same")));
assert_ne!(first.actual, second.actual);
assert_ne!(first.diff, second.diff);
assert!(second.actual.ends_with("same-1.actual.png"), "{}", second.actual.display());
assert_eq!(std::fs::read(&first.actual).unwrap(), kept);
}
#[test]
fn parallel_failures_get_distinct_paths() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("r.png");
let px = ramp(3, 3, 255);
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
let other = ramp(3, 3, 1);
let paths: Vec<PathBuf> = std::thread::scope(|s| {
let handles: Vec<_> = (0..8)
.map(|_| s.spawn(|| mismatch(compare_golden(&reference, rgba(3, 3, &other), Tolerance::EXACT, options(dir.path(), "race")))))
.collect();
handles
.into_iter()
.flat_map(|h| {
let m = h.join().expect("thread");
[m.actual, m.diff]
})
.collect()
});
let distinct: HashSet<&PathBuf> = paths.iter().collect();
assert_eq!(distinct.len(), 16);
assert!(paths.iter().all(|p| p.exists()));
}
#[test]
fn a_mismatch_keeps_its_verdict_when_the_failure_images_cannot_be_written() {
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("r.png");
let px = ramp(3, 3, 255);
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
// The failure folder is a regular file, so the failure images cannot be written.
let blocked = dir.path().join("file");
std::fs::write(&blocked, b"x").unwrap();
let other = ramp(3, 3, 1);
let err = compare_golden(&reference, rgba(3, 3, &other), Tolerance::EXACT, options(&blocked, "case")).unwrap_err();
let ImageError::GoldenMismatchUnsaved(m) = &err else { panic!("expected an unsaved mismatch, got {err:?}") };
assert_eq!(m.verdict.bad_pixels, 9);
assert!(!m.verdict.passed());
assert!(matches!(m.error, ImageError::Io { .. }), "{:?}", m.error);
assert!(err.to_string().contains("pixels differ") && err.to_string().contains("could not be written"), "{err}");
assert!(std::error::Error::source(&err).is_some());
}
/// Runs `name`, a test of this binary, in a child process with the bless variable removed and
/// `CHILD_MARKER` set, and returns whether it passed and what it printed.
fn run_child(name: &str) -> (bool, String) {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", name, "--nocapture", "--test-threads=1"])
.env_remove(NO_BLESS)
.env(CHILD_MARKER, "1")
.output()
.unwrap();
let printed = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(printed.contains("running 1 test"), "the child did not run the test:\n{printed}");
(out.status.success(), printed)
}
#[test]
fn assert_similar_returns_the_verdict() {
let (passed, printed) = run_child("image::tests::child_assert_similar_passes");
assert!(passed, "the child failed:\n{printed}");
}
#[test]
fn assert_similar_fails_the_test() {
let (passed, printed) = run_child("image::tests::child_assert_similar_fails");
assert!(!passed, "the child passed:\n{printed}");
assert!(printed.contains("no reference image"), "{printed}");
}
/// Runs in the child process of `assert_similar_returns_the_verdict`, and passes at once elsewhere.
#[test]
fn child_assert_similar_passes() {
if std::env::var_os(CHILD_MARKER).is_none() {
return;
}
let dir = tempfile::tempdir().unwrap();
let reference = dir.path().join("r.png");
let px = ramp(3, 3, 255);
write_png(&reference, rgba(3, 3, &px), PngLimits::DEFAULT).unwrap();
let verdict = crate::assert_similar!(&reference, rgba(3, 3, &px), Tolerance::EXACT, options(dir.path(), "ok"));
assert!(verdict.passed());
}
/// Runs in the child process of `assert_similar_fails_the_test`, where it must fail, and passes at
/// once elsewhere.
#[test]
fn child_assert_similar_fails() {
if std::env::var_os(CHILD_MARKER).is_none() {
return;
}
let dir = tempfile::tempdir().unwrap();
let px = ramp(3, 3, 255);
crate::assert_similar!(&dir.path().join("none.png"), rgba(3, 3, &px), Tolerance::EXACT, options(dir.path(), "none"));
}
+5
View File
@@ -13,6 +13,9 @@
//! where `std::time::Instant::now()` panics on `wasm32`.
//! * `guards::rust_sources`: directory crawler collecting `.rs` sources while excluding tests, with
//! size limits (`guards::rust_sources_with_limits`). It is not built for `wasm32`.
//! * `image` (feature `image`): RGBA8 and gray views, difference statistics, PSNR for `u8` and
//! `u16` planes, tolerances with an optional 3×3 neighborhood, a difference image, PNG reading
//! and writing with size limits, golden reference checks and `assert_similar!`.
//!
//! On native targets, the `fixtures` module locates generated test fixtures under `<workspace>/target/fixtures`,
//! generates a missing one into a claimed temporary sibling, publishes it under a per-output lock that
@@ -79,6 +82,8 @@ pub mod fixtures;
pub mod fonts;
pub mod guards;
pub mod hostile;
#[cfg(feature = "image")]
pub mod image;
#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
pub mod mcp;
pub mod rng;