icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! [`ExpectError`], the failure report built from [`FailureReport`], the failure screenshot,
//! and the soft failures a harness collects.

use std::fmt::Write as _;
use std::panic::Location;
use std::path::PathBuf;

use icedwright_check::{CheckError, FailureReport};
use icedwright_semantics::{NodePath, SemanticTree};
use icedwright_types::units::Logical;
use icedwright_types::{Frame, Rect};

use crate::effects::TaskState;
use crate::error::Error;
use crate::harness::{Harness, TestProgram};

/// An expectation that failed. Its `Display` is the whole report: what was expected and
/// received, the nearest subtree, suggestions, the call log, and the screenshot and trace.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[must_use = "an expectation error carries the failure report"]
pub enum ExpectError {
    /// One expectation failed.
    #[error("{}", failed_text(report, earlier))]
    Failed {
        /// The printed report.
        report: String,
        /// The check's own error, with the attempt log.
        check: Box<CheckError>,
        /// Soft failures recorded before this one.
        earlier: Vec<ExpectError>,
    },
    /// Soft failures, reported together by `Harness::finish`.
    #[error("{}", soft_text(.0))]
    Soft(Vec<ExpectError>),
}

impl ExpectError {
    /// The check's error, for a single failure.
    #[must_use]
    pub fn check(&self) -> Option<&CheckError> {
        match self {
            ExpectError::Failed { check, .. } => Some(check),
            ExpectError::Soft(_) => None,
        }
    }

    /// The soft failures this error carries: its bundle, or those recorded before it.
    pub fn soft_failures(&self) -> &[ExpectError] {
        match self {
            ExpectError::Failed { earlier, .. } => earlier,
            ExpectError::Soft(all) => all,
        }
    }
}

fn failed_text(report: &str, earlier: &[ExpectError]) -> String {
    let mut out = report.to_owned();
    if !earlier.is_empty() {
        let _ = write!(out, "\nSoft failures before it:\n\n{}", soft_text(earlier));
    }
    out
}

fn soft_text(all: &[ExpectError]) -> String {
    let mut out = format!("{} soft expectations failed\n", all.len());
    for (index, error) in all.iter().enumerate() {
        let _ = write!(out, "\n--- soft failure {} ---\n{error}", index + 1);
    }
    out
}

/// The soft failures and the expectation count of one harness.
#[derive(Debug, Default)]
pub(crate) struct ExpectState {
    soft: Vec<ExpectError>,
    count: u32,
}

impl ExpectState {
    /// The number of the next failing expectation, for its screenshot's name.
    fn next(&mut self) -> u32 {
        self.count += 1;
        self.count
    }

    pub(crate) fn record_soft(&mut self, error: ExpectError) {
        self.soft.push(error);
    }

    /// Every soft failure as one error, or `None` when there were none.
    pub(crate) fn take_soft(&mut self) -> Option<ExpectError> {
        if self.soft.is_empty() {
            return None;
        }
        Some(ExpectError::Soft(std::mem::take(&mut self.soft)))
    }

    fn take_earlier(&mut self) -> Vec<ExpectError> {
        std::mem::take(&mut self.soft)
    }

    /// A harness dropped with soft failures nobody reported fails the test, unless it is
    /// already failing, so a test that forgets `finish` cannot lose them. Drop cannot return
    /// an error, so the report is printed and the thread unwinds.
    pub(crate) fn report_unfinished(&mut self) {
        let Some(soft) = self.take_soft() else {
            return;
        };
        if std::thread::panicking() {
            return;
        }
        eprintln!("{soft}");
        std::panic::resume_unwind(Box::new(format!(
            "the harness was dropped with unreported soft failures; call Harness::finish\n\n{soft}"
        )));
    }
}

/// What the expectation was, for the report.
pub(crate) struct Context<'a> {
    pub(crate) subject: String,
    pub(crate) location: &'static Location<'static>,
    pub(crate) message: Option<&'a str>,
    pub(crate) tree: Option<&'a SemanticTree>,
    pub(crate) window: Option<iced_core::window::Id>,
    pub(crate) soft: bool,
}

/// Turns a failed retry into the reported error. A `CheckError` becomes an [`ExpectError`]
/// with the full report; every other error is returned as it is.
pub(crate) fn fail<P: TestProgram>(
    h: &mut Harness<P>,
    error: Error,
    context: &Context<'_>,
) -> Error {
    let Error::Check(check) = error else {
        return error;
    };
    let number = h.expectations.next();
    let resolved = resolved_bounds(&check, context.tree);
    let screenshot = context
        .window
        .or_else(|| h.focused())
        .and_then(|window| screenshot(h, window, number, resolved));
    let held_tasks = h
        .task_infos()
        .into_iter()
        .filter(|info| info.state() == TaskState::Held)
        .map(|info| {
            info.name()
                .map_or_else(|| info.id().to_string(), str::to_owned)
        })
        .collect();
    let trace = h.trace.as_ref().map(|trace| trace.path().to_path_buf());
    let location = format!(
        "{}:{}:{}",
        context.location.file(),
        context.location.line(),
        context.location.column()
    );
    let report = FailureReport {
        subject: context.subject.clone(),
        location: Some(location),
        context: context.message.map(str::to_owned),
        clock: "virtual time",
        error: &check,
        tree: context.tree,
        held_tasks,
        screenshot,
        trace,
    }
    .to_string();
    let earlier = if context.soft {
        Vec::new()
    } else {
        h.expectations.take_earlier()
    };
    ExpectError::Failed {
        report,
        check: Box::new(check),
        earlier,
    }
    .into()
}

fn resolved_bounds(check: &CheckError, tree: Option<&SemanticTree>) -> Option<Rect> {
    let CheckError::Failed { failure, .. } = check else {
        return None;
    };
    let path: &NodePath = failure.last.resolved.as_ref()?;
    tree?.node_at(path).map(|node| node.bounds)
}

fn screenshots_on() -> bool {
    std::env::var("ICEDWRIGHT_SCREENSHOTS").map_or(true, |value| value != "off")
}

/// Renders the window with the resolved node outlined and writes it next to the trace, as
/// `<test>.expect-N.png`. A screenshot that cannot be made is left out of the report.
fn screenshot<P: TestProgram>(
    h: &mut Harness<P>,
    window: iced_core::window::Id,
    number: u32,
    outline: Option<Rect>,
) -> Option<PathBuf> {
    if !screenshots_on() {
        return None;
    }
    let trace = h.trace.as_ref()?.path().to_path_buf();
    let stem = trace.file_stem()?.to_string_lossy().into_owned();
    let path = trace.with_file_name(format!("{stem}.expect-{number}.png"));
    let frame = h.render(window).ok()?;
    let frame = match outline {
        Some(bounds) => outlined(frame, Logical(bounds)).ok()?,
        None => frame,
    };
    let png = icedwright_trace::Png::encode(&frame).ok()?;
    std::fs::create_dir_all(path.parent()?).ok()?;
    std::fs::write(&path, png.as_bytes()).ok()?;
    Some(path)
}

const OUTLINE: [u8; 4] = [230, 20, 60, 255];
const OUTLINE_WIDTH: u32 = 2;

/// The frame with a rectangle drawn around `bounds`.
pub(crate) fn outlined(
    frame: Frame,
    bounds: Logical<Rect>,
) -> Result<Frame, icedwright_types::FrameError> {
    let scale = frame.scale();
    let physical = frame.size();
    let size = physical.get();
    let Logical(rect) = bounds;
    let factor = f32::from(scale);
    let clamp = |v: f32, max: u32| (v * factor).round().clamp(0.0, max as f32) as u32;
    let (left, top) = (clamp(rect.x, size.width), clamp(rect.y, size.height));
    let (right, bottom) = (
        clamp(rect.x + rect.width, size.width),
        clamp(rect.y + rect.height, size.height),
    );
    let mut rgba = frame.into_rgba();
    for y in top..bottom {
        for x in left..right {
            let edge = x < left + OUTLINE_WIDTH
                || x + OUTLINE_WIDTH >= right
                || y < top + OUTLINE_WIDTH
                || y + OUTLINE_WIDTH >= bottom;
            if !edge {
                continue;
            }
            let index = (y as usize * size.width as usize + x as usize) * 4;
            if let Some(pixel) = rgba.get_mut(index..index + 4) {
                pixel.copy_from_slice(&OUTLINE);
            }
        }
    }
    Frame::new(rgba, physical, scale)
}