icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Semantic and visual snapshots.
//!
//! A semantic snapshot is a node's subtree written as YAML: in full, reviewed with `insta`
//! through [`assert_semantic_snapshot!`](crate::assert_semantic_snapshot), or as a partial
//! template matched with [`Handle::to_match_semantic`](crate::Handle::to_match_semantic).
//! Semantic snapshots depend on no pixels and work under plain `cargo test`.
//!
//! A visual snapshot renders a window with tiny-skia and the bundled fonts, waits until two
//! consecutive frames are identical, hides the caret, crops to an element when asked, paints
//! masks over locators that change from run to run, and compares the result with a baseline
//! PNG under the test crate's `tests/screenshots/` with a perceptual diff. A failure writes
//! `expected.png`, `actual.png`, `diff.png` and `pending.json` under
//! `target/icedwright/snapshots-failed/` (or `ICEDWRIGHT_OUT_DIR`), which
//! [`review`] lists; `ICEDWRIGHT_UPDATE=always` writes the baseline instead.
//!
//! The font database is one per process, and a font loaded by one test can change the glyphs
//! another draws, so visual snapshots need a process per test: they run under
//! `cargo nextest run` and fail with [`SnapshotError::NeedsProcessPerTest`] under plain
//! `cargo test`.

mod baseline;
mod env;
pub mod fonts;
mod options;
mod png;
pub mod review;
mod semantic;
#[cfg(test)]
mod tests;
pub mod themes;
mod variant;
mod visual;

use std::fmt;
use std::path::PathBuf;

pub use env::{Runner, SnapshotEnv, UpdateMode};
pub use icedwright_check::snapshot::{DiffOptions, DiffResult, Rgba, diff};
pub use icedwright_check::{MatchReport, Template, TemplateError};
pub use icedwright_semantics::yaml::YamlOptions;
pub use options::{Caret, RenderOptions, Screenshot};
pub use png::{PngMetadata, decode_png, encode_png};
pub use semantic::SemanticOptions;
pub use variant::{Variant, scale_name, size_name, theme_name};

/// What the macros in this module expand to. Not a stable API.
#[doc(hidden)]
pub mod __private {
    pub use super::semantic::{Prepared, prepare, settings};
    pub use insta;
}

/// The text both process-per-test refusals end with.
const PER_TEST_REASON: &str =
    "  The font database is shared by every test in this process, and a font
  loaded by another test can change the glyphs this snapshot draws
  (cosmic-text falls back to any loaded face for missing glyphs).
  Run visual snapshot tests with `cargo nextest run`, which starts a
  process per test. Semantic snapshots and actions work under cargo test.";

/// Why a snapshot could not be taken, or did not match.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum SnapshotError {
    /// A visual snapshot outside nextest's process-per-test mode.
    #[error("{what} needs a process per test\n\n{}", PER_TEST_REASON)]
    NeedsProcessPerTest {
        /// The call that was refused.
        what: String,
    },
    /// A program font outside the bundled set, in a process several tests share.
    #[error(
        "the program loads a font of {bytes} bytes that is not one of icedwright's bundled fonts, in a process several tests share\n\n{}\n  An app with its own fonts runs its harness tests under nextest.",
        PER_TEST_REASON
    )]
    FontsNeedProcessPerTest {
        /// The font's size.
        bytes: usize,
    },
    /// A second harness in one test asked for a different set of program fonts.
    #[error(
        "this harness loads {now} program fonts that differ from the {before} an earlier harness in this test loaded; a font loaded once stays loaded for the whole process, so give every harness in one test the same fonts"
    )]
    FontSetChanged {
        /// How many program fonts the first harness loaded.
        before: usize,
        /// How many this one asked for.
        now: usize,
    },
    /// `system_fonts(true)` in a process several tests share.
    #[error(
        "system_fonts(true) keeps the machine's fonts, in a process several tests share\n\n{}",
        PER_TEST_REASON
    )]
    SystemFontsNeedProcessPerTest,
    /// A second harness in one test asked for the other font mode.
    #[error(
        "this harness asks for {now:?} fonts but an earlier harness in this test loaded {before:?} fonts, which stay loaded for the whole process; give every harness in one test the same system_fonts setting"
    )]
    FontModeChanged {
        /// The mode the process loaded.
        before: fonts::FontMode,
        /// The mode this harness asked for.
        now: fonts::FontMode,
    },
    /// Two theme variants of one semantic snapshot gave different YAML.
    #[error(
        "the semantic snapshot {name} differs between the {theme} and {other} themes, but its name leaves the theme out; pass SemanticOptions::new().per_theme(true) to keep one snapshot per theme\n\n{theme}:\n{yaml}\n\n{other}:\n{other_yaml}"
    )]
    ThemesDisagree {
        /// The snapshot's name.
        name: String,
        /// This variant's theme.
        theme: &'static str,
        /// The YAML in this theme.
        yaml: String,
        /// The other variant's theme.
        other: &'static str,
        /// The YAML in the other theme.
        other_yaml: String,
    },
    /// `Caret::Show` with a focused field whose caret blinks on the real clock.
    #[error(
        "Caret::Show keeps the caret of {node}, which blinks on the real clock, so the snapshot would depend on when it was taken; use Caret::Hide, or a widget that declares caret-clock = \"probe\""
    )]
    CaretOnRealClock {
        /// The focused field.
        node: String,
    },
    /// Two consecutive frames never came out the same.
    #[error(
        "the frame never stopped changing after {frames} frames; the last two are {previous} and {last}"
    )]
    NeverStable {
        /// How many frames were advanced.
        frames: u32,
        /// The frame before the last.
        previous: PathBuf,
        /// The last frame.
        last: PathBuf,
    },
    /// A subtree's YAML changed on every frame.
    #[error("the semantic YAML of {subject} never stopped changing after {frames} frames")]
    NeverStableYaml {
        /// The locator.
        subject: String,
        /// How many frames were advanced.
        frames: u32,
    },
    /// A visual snapshot did not match its baseline, or had none.
    #[error("{0}")]
    Visual(Box<VisualFailure>),
    /// A partial template did not match before the timeout.
    #[error("{subject} does not match the template\n\n{report}")]
    Semantic {
        /// The locator.
        subject: String,
        /// The matcher's report.
        report: Box<MatchReport>,
    },
    /// A template that did not parse.
    #[error(transparent)]
    Template(#[from] TemplateError),
    /// An element with no visible part, or a crop that could not be cut.
    #[error(transparent)]
    Crop(#[from] icedwright_check::CropError),
    /// A PNG that could not be written or read.
    #[error("the PNG could not be {action}: {message}")]
    Png {
        /// `encoded` or `decoded`.
        action: &'static str,
        /// What went wrong.
        message: String,
    },
    /// A snapshot name that cannot be a file name.
    #[error(
        "{name:?} cannot name a snapshot: use letters, digits, `-`, `_` and `.`, and no path separators"
    )]
    InvalidName {
        /// The name given.
        name: String,
    },
    /// Where the snapshot belongs could not be worked out.
    #[error("{0}")]
    Location(String),
}

/// What kind of visual failure.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum VisualKind {
    /// There was no baseline.
    New,
    /// The baseline and the render differ.
    Changed(DiffResult),
    /// The baseline has another size or scale.
    Resized(String),
}

/// A visual snapshot that did not match, with everything the report shows.
#[derive(Debug, Clone, PartialEq)]
pub struct VisualFailure {
    /// The snapshot's file stem, `name@variant`.
    pub snapshot: String,
    /// What went wrong.
    pub kind: VisualKind,
    /// Whether the baseline was drawn with another font database.
    pub fonts_changed: bool,
    /// The baseline's path.
    pub baseline: PathBuf,
    /// The files written for review: `expected.png`, `actual.png`, `diff.png`,
    /// `pending.json`.
    pub written: Vec<PathBuf>,
    /// Masks that matched nothing, masked caret fields, a clamped crop.
    pub notes: Vec<String>,
}

impl fmt::Display for VisualFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.fonts_changed {
            writeln!(
                f,
                "the baseline was drawn with another font database, which can explain every changed glyph at once"
            )?;
        }
        match &self.kind {
            VisualKind::New => writeln!(
                f,
                "new snapshot {}, review with cargo icedwright review (or set ICEDWRIGHT_UPDATE=always)",
                self.snapshot
            )?,
            VisualKind::Changed(result) => {
                writeln!(f, "snapshot {} differs: {result}", self.snapshot)?;
            }
            VisualKind::Resized(why) => writeln!(f, "snapshot {}: {why}", self.snapshot)?,
        }
        writeln!(f, "  baseline: {}", self.baseline.display())?;
        for path in &self.written {
            writeln!(f, "  wrote: {}", path.display())?;
        }
        for note in &self.notes {
            writeln!(f, "  note: {note}")?;
        }
        Ok(())
    }
}