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};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[must_use = "an expectation error carries the failure report"]
pub enum ExpectError {
#[error("{}", failed_text(report, earlier))]
Failed {
report: String,
check: Box<CheckError>,
earlier: Vec<ExpectError>,
},
#[error("{}", soft_text(.0))]
Soft(Vec<ExpectError>),
}
impl ExpectError {
#[must_use]
pub fn check(&self) -> Option<&CheckError> {
match self {
ExpectError::Failed { check, .. } => Some(check),
ExpectError::Soft(_) => None,
}
}
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
}
#[derive(Debug, Default)]
pub(crate) struct ExpectState {
soft: Vec<ExpectError>,
count: u32,
}
impl ExpectState {
fn next(&mut self) -> u32 {
self.count += 1;
self.count
}
pub(crate) fn record_soft(&mut self, error: ExpectError) {
self.soft.push(error);
}
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)
}
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}"
)));
}
}
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,
}
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")
}
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;
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)
}