use std::time::Duration;
use iced::widget::{button, column, container, row, space, text, text_input};
use iced::{Color, Element, Subscription, Theme};
use icedwright::prelude::*;
use icedwright::snapshot::{SnapshotError, VisualKind};
use icedwright::testing::matrix::{Size as WindowSize, Theme as ThemeAxis};
use icedwright::units::Ratio;
use icedwright_probe::{semantic, test_id};
#[derive(Debug, Clone)]
enum Message {
Add,
Draft(String),
Clock(String),
Tick,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Look {
swatch: Color,
trickle: bool,
flicker: bool,
}
impl Default for Look {
fn default() -> Self {
Self {
swatch: Color::from_rgb8(0x2a, 0x6f, 0xdb),
trickle: false,
flicker: false,
}
}
}
#[derive(Debug)]
struct Board {
look: Look,
items: Vec<String>,
draft: String,
clock: String,
frames: u32,
}
impl Board {
fn new(look: Look) -> Self {
Self {
look,
items: vec!["Leeks".to_owned(), "Beans".to_owned()],
draft: String::new(),
clock: "12:34".to_owned(),
frames: 0,
}
}
fn update(&mut self, message: Message) {
match message {
Message::Add => self.items.push(format!("Item {}", self.items.len() + 1)),
Message::Draft(draft) => self.draft = draft,
Message::Clock(clock) => self.clock = clock,
Message::Tick if self.look.flicker => self.frames = self.frames.wrapping_add(1),
Message::Tick if self.items.len() < 3 => self.items.push("Carrots".to_owned()),
Message::Tick => {}
}
}
fn subscription(&self) -> Subscription<Message> {
if self.look.flicker {
return iced::window::frames().map(|_| Message::Tick);
}
if self.look.trickle {
return iced::time::every(Duration::from_millis(500)).map(|_| Message::Tick);
}
Subscription::none()
}
fn view(&self) -> Element<'_, Message> {
let swatch = if self.look.flicker {
Color::from_rgb8((self.frames % 256) as u8, 0x40, 0x40)
} else {
self.look.swatch
};
let block =
container(space().width(48).height(24)).style(move |_theme: &Theme| container::Style {
background: Some(swatch.into()),
..container::Style::default()
});
let items = semantic(
column(self.items.iter().map(|item| {
semantic(text(item.as_str()))
.role(role::ListItem)
.name(item.as_str())
.into()
}))
.spacing(4),
)
.role(role::List)
.name("Items");
column![
text("Shopping").size(24),
row![
block,
semantic(button("Add").on_press(Message::Add))
.role(role::Button)
.name("Add"),
]
.spacing(12),
items,
text_input("New item", &self.draft)
.id("draft")
.on_input(Message::Draft)
.width(240),
test_id("clock", container(text(self.clock.as_str())).width(80)),
]
.spacing(12)
.padding(16)
.into()
}
}
fn program(
look: Look,
) -> iced::Application<impl iced::Program<State = Board, Message = Message, Theme = Theme>> {
iced::application(move || Board::new(look), Board::update, Board::view)
.subscription(Board::subscription)
}
fn harness(
look: Look,
) -> icedwright::Result<Harness<impl TestProgram<State = Board, Message = Message>>> {
Harness::builder(program(look))
.size(Logical(icedwright::units::Size::new(400.0, 320.0)))
.build()
}
fn harness_in(
variant: Variant,
) -> icedwright::Result<Harness<impl TestProgram<State = Board, Message = Message>>> {
Harness::builder(program(Look::default()))
.size(Logical(icedwright::units::Size::new(400.0, 320.0)))
.variant(variant)
.build()
}
fn focus_draft(ui: &mut Harness<impl TestProgram>) -> icedwright::Result {
let window = ui.focused().ok_or(icedwright::HarnessError::NoWindow)?;
let _ = ui.operate(
window,
iced::advanced::widget::operation::focusable::focus::<()>(iced::widget::Id::new("draft")),
)?;
Ok(())
}
fn visual(error: icedwright::Error) -> Option<Box<icedwright::snapshot::VisualFailure>> {
match error {
icedwright::Error::Snapshot(SnapshotError::Visual(failure)) => Some(failure),
_ => None,
}
}
#[test]
fn a_window_matches_its_baseline() -> icedwright::Result {
let mut ui = harness(Look::default())?;
ui.to_match_image("board", &Screenshot::new())
}
#[test]
fn a_scale_factor_of_two_has_its_own_baseline_at_twice_the_pixels() -> icedwright::Result {
let mut ui = harness_in(Variant::new().scale(ScaleFactor::TWO))?;
let frame = ui.capture(&Screenshot::new())?;
assert_eq!(frame.size().get().width, 800);
assert_eq!(frame.size().get().height, 640);
ui.to_match_image("board", &Screenshot::new())
}
#[test]
fn the_dark_theme_has_its_own_baseline() -> icedwright::Result {
let mut ui = harness_in(Variant::new().theme(ThemeAxis::Dark))?;
ui.to_match_image("board", &Screenshot::new())
}
#[test]
fn an_element_screenshot_is_cropped_to_the_node() -> icedwright::Result {
let mut ui = harness(Look::default())?;
let bounds = ui
.get_by_role(role::Button)
.name("Add")
.resolve()?
.node()
.map(|node| node.bounds)
.ok_or(icedwright::HarnessError::NoWindow)?;
let frame = ui
.get_by_role(role::Button)
.name("Add")
.screenshot(&Screenshot::new())?;
assert_eq!(
frame.size().get().width,
(bounds.x + bounds.width).ceil() as u32 - bounds.x.floor() as u32
);
ui.get_by_role(role::Button)
.name("Add")
.to_match_image("add", &Screenshot::new())?;
ui.get_by_role(role::Button)
.name("Add")
.to_match_image("add-in-window", &Screenshot::new().full_frame(true))
}
#[test]
fn a_mask_hides_what_changes_between_runs() -> icedwright::Result {
let mut ui = harness(Look::default())?;
let masked = Screenshot::new().mask(sel!(r#"test-id="clock""#));
let first = ui.capture(&masked)?;
ui.dispatch(Message::Clock("23:59".to_owned()))?;
let second = ui.capture(&masked)?;
assert_eq!(first, second, "the clock is under the mask");
let unmasked = ui.capture(&Screenshot::new())?;
assert_ne!(second, unmasked);
ui.to_match_image("masked", &masked)
}
#[test]
fn a_clip_crops_a_window_screenshot() -> icedwright::Result {
let mut ui = harness(Look::default())?;
let region = Logical(icedwright::units::Rect::new(
icedwright::units::Point::new(0.0, 0.0),
icedwright::units::Size::new(200.5, 60.0),
));
let frame = ui.capture(&Screenshot::new().clip(region))?;
assert_eq!(frame.size().get().width, 201, "rounded outwards");
assert_eq!(frame.size().get().height, 60);
ui.to_match_image("heading", &Screenshot::new().clip(region))
}
#[test]
fn a_focused_text_input_never_shows_its_caret() -> icedwright::Result {
let mut ui = harness(Look::default())?;
focus_draft(&mut ui)?;
let first = ui.capture(&Screenshot::new())?;
for _ in 0..10 {
assert_eq!(ui.capture(&Screenshot::new())?, first);
}
ui.to_match_image("focused", &Screenshot::new())
}
#[test]
fn showing_the_caret_of_a_real_clock_field_is_refused() -> icedwright::Result {
let mut ui = harness(Look::default())?;
focus_draft(&mut ui)?;
let refused = ui.capture(&Screenshot::new().caret(Caret::Show));
assert!(
matches!(
refused,
Err(icedwright::Error::Snapshot(
SnapshotError::CaretOnRealClock { .. }
))
),
"{refused:?}"
);
Ok(())
}
#[test]
fn a_missing_baseline_fails_and_writes_the_review_files() -> icedwright::Result {
let mut ui = harness(Look::default())?;
let Err(error) = ui.to_match_image("never-accepted", &Screenshot::new()) else {
return Err(icedwright::Error::other(std::io::Error::other(
"a snapshot with no baseline passed",
)));
};
let failure = visual(error).ok_or_else(|| std::io::Error::other("not a visual failure"))?;
assert_eq!(failure.kind, VisualKind::New);
assert!(
!failure.baseline.exists(),
"nothing is written next to the source"
);
let dir = failure
.written
.first()
.and_then(|path| path.parent())
.map(std::path::Path::to_path_buf)
.ok_or_else(|| std::io::Error::other("nothing was written"))?;
assert!(dir.ends_with("snapshots-failed/icedwright/a_missing_baseline_fails_and_writes_the_review_files/never-accepted"));
assert!(dir.join("actual.png").exists());
assert!(dir.join("pending.json").exists());
std::fs::remove_dir_all(&dir)?;
Ok(())
}
#[test]
fn a_changed_render_fails_with_expected_actual_and_diff() -> icedwright::Result {
let mut ui = harness(Look {
swatch: Color::from_rgb8(0xdb, 0x2a, 0x2a),
..Look::default()
})?;
let options = Screenshot::new().timeout(Duration::from_millis(100));
let Err(error) = ui.to_match_image("swatch", &options) else {
return Err(icedwright::Error::other(std::io::Error::other(
"a changed render matched",
)));
};
let failure = visual(error).ok_or_else(|| std::io::Error::other("not a visual failure"))?;
let VisualKind::Changed(result) = &failure.kind else {
return Err(icedwright::Error::other(std::io::Error::other(format!(
"expected a changed snapshot, got {:?}",
failure.kind
))));
};
assert_eq!(
result.changed,
48 * 24 - 48,
"the 48 by 24 swatch changed; pixelmatch reads 48 of its edge pixels as anti-aliasing"
);
let names: Vec<String> = failure
.written
.iter()
.filter_map(|path| path.file_name()?.to_str().map(str::to_owned))
.collect();
assert_eq!(
names,
["actual.png", "expected.png", "diff.png", "pending.json"]
);
let message = failure.to_string();
assert!(message.contains("snapshot swatch differs"), "{message}");
if let Some(dir) = failure.written.first().and_then(|path| path.parent()) {
std::fs::remove_dir_all(dir)?;
}
let loose = Screenshot::new()
.max_diff_pixels(48 * 24)
.max_diff_ratio(Ratio::new(0.01)?);
ui.to_match_image("swatch", &loose)
}
#[test]
fn a_frame_that_never_settles_fails() -> icedwright::Result {
let mut ui = harness(Look {
flicker: true,
..Look::default()
})?;
let result = ui.capture(&Screenshot::new());
let Err(icedwright::Error::Snapshot(SnapshotError::NeverStable { previous, last, .. })) =
result
else {
return Err(icedwright::Error::other(std::io::Error::other(format!(
"expected a frame that never settles, got {result:?}"
))));
};
assert!(previous.exists() && last.exists());
if let Some(dir) = last.parent() {
std::fs::remove_dir_all(dir)?;
}
Ok(())
}
#[test]
fn a_semantic_snapshot_of_a_subtree() -> icedwright::Result {
let mut ui = harness(Look::default())?;
assert_semantic_snapshot!(ui.get_by_role(role::List).name("Items"));
ui.dispatch(Message::Add)?;
assert_semantic_snapshot!("after-add", ui.get_by_role(role::List).name("Items"));
Ok(())
}
#[test]
fn an_inline_semantic_snapshot() -> icedwright::Result {
let mut ui = harness(Look::default())?;
assert_semantic_snapshot!(ui.get_by_role(role::List).name("Items"), @r#"
- list "Items":
- listitem "Leeks"
- listitem "Beans"
"#);
Ok(())
}
#[test]
fn the_page_snapshots_the_whole_window() -> icedwright::Result {
let mut ui = harness(Look::default())?;
expect(ui.page()).to_be_visible()?;
ui.page().get_by_role(role::Button).name("Add").click()?;
expect(ui.page().get_by_role(role::ListItem)).to_have_count(3)?;
assert_semantic_snapshot!(ui.page(), @r#"
- text: Shopping
- button "Add":
- text: Add
- list "Items":
- listitem "Leeks"
- listitem "Beans"
- listitem "Item 3"
- textbox [focused=false] [focusable]: New item
- generic:
- text: 12:34
"#);
Ok(())
}
#[test]
fn a_semantic_snapshot_names_the_window_size() -> icedwright::Result {
let mut ui = harness_in(
Variant::new()
.size(WindowSize::Phone)
.theme(ThemeAxis::Dark),
)?;
assert_semantic_snapshot!(ui.get_by_role(role::List).name("Items"));
Ok(())
}
#[test]
fn a_partial_template_waits_for_the_list_to_fill() -> icedwright::Result {
let mut ui = harness(Look {
trickle: true,
..Look::default()
})?;
ui.get_by_role(role::List).name("Items").to_match_semantic(
r#"
- /children: equal
- listitem "Leeks"
- listitem "Beans"
- listitem "Carrots"
"#,
)?;
assert_eq!(ui.state().items.len(), 3);
let missing = ui
.get_by_role(role::List)
.name("Items")
.to_match_semantic_with(
r#"- listitem "Parsnips""#,
&SemanticOptions::new().timeout(Duration::from_secs(1)),
);
let Err(icedwright::Error::Snapshot(SnapshotError::Semantic { report, .. })) = missing else {
return Err(icedwright::Error::other(std::io::Error::other(format!(
"expected a template mismatch, got {missing:?}"
))));
};
assert!(report.to_string().contains("Parsnips"), "{report}");
Ok(())
}
#[test]
fn a_screenshot_at_another_scale_draws_more_pixels_and_tells_the_app_nothing() -> icedwright::Result
{
let mut ui = harness(Look::default())?;
let window = ui.focused().ok_or(icedwright::HarnessError::NoWindow)?;
let messages = ui.messages().len();
let at_two = ui.capture(&Screenshot::new().scale(ScaleFactor::TWO))?;
assert_eq!(at_two.size().get().width, 800);
assert_eq!(at_two.scale(), ScaleFactor::TWO);
assert_eq!(ui.messages().len(), messages, "the app saw the render");
assert_eq!(ui.window_info(window)?.scale_factor, ScaleFactor::ONE);
drop(ui);
let mut doubled = Harness::builder(program(Look::default()))
.size(Logical(icedwright::units::Size::new(400.0, 320.0)))
.scale_factor(ScaleFactor::TWO)
.build()?;
let native = doubled.capture(&Screenshot::new())?;
assert!(
native == at_two,
"a 2x render of a 1x window differs from a 2x window"
);
Ok(())
}
#[test]
fn system_fonts_mark_snapshots_unreliable_and_hold_the_process_to_them() -> icedwright::Result {
let mut ui = Harness::builder(program(Look::default()))
.size(Logical(icedwright::units::Size::new(400.0, 320.0)))
.system_fonts(true)
.build()?;
assert_eq!(
icedwright::fonts::mode(),
icedwright::fonts::FontMode::System
);
let result = ui.to_match_image("system-fonts", &Screenshot::new());
let failure = result.err().and_then(visual).ok_or_else(|| {
icedwright::Error::other(std::io::Error::other("expected a new snapshot"))
})?;
assert!(
failure.notes.iter().any(|note| note.contains("unreliable")),
"{failure}"
);
if let Some(dir) = failure.written.first().and_then(|path| path.parent()) {
std::fs::remove_dir_all(dir)?;
}
drop(ui);
let second = harness(Look::default());
assert!(
matches!(
second,
Err(icedwright::Error::Snapshot(
SnapshotError::FontModeChanged { .. }
))
),
"{second:?}"
);
Ok(())
}
#[test]
fn text_no_font_covers_is_a_warning() -> icedwright::Result {
let mut ui = harness(Look::default())?;
ui.dispatch(Message::Draft("tea \u{1F375}".to_owned()))?;
let _ = ui.capture(&Screenshot::new())?;
let warned: Vec<&icedwright::Diagnostic> = ui
.diagnostics()
.iter()
.filter(|d| matches!(&d.kind, icedwright::DiagnosticKind::UncoveredGlyphs { characters, .. } if characters == "\u{1F375}"))
.collect();
assert_eq!(warned.len(), 1, "{:?}", ui.diagnostics());
let _ = ui.capture(&Screenshot::new())?;
let again = ui
.diagnostics()
.iter()
.filter(|d| matches!(d.kind, icedwright::DiagnosticKind::UncoveredGlyphs { .. }))
.count();
assert_eq!(again, 1, "the same characters are warned about once");
Ok(())
}
#[test]
fn theme_variants_of_one_semantic_snapshot_must_agree() -> icedwright::Result {
let mut light = harness_in(Variant::new().theme(ThemeAxis::Light))?;
assert_semantic_snapshot!(light.get_by_role(role::List).name("Items"), @r#"
- list "Items":
- listitem "Leeks"
- listitem "Beans"
"#);
drop(light);
let mut dark = harness_in(Variant::new().theme(ThemeAxis::Dark))?;
dark.dispatch(Message::Add)?;
let taken = (|| -> icedwright::Result {
assert_semantic_snapshot!(dark.get_by_role(role::List).name("Items"), @"");
Ok(())
})();
let Err(icedwright::Error::Snapshot(SnapshotError::ThemesDisagree { theme, other, .. })) =
taken
else {
return Err(icedwright::Error::other(std::io::Error::other(format!(
"expected the themes to disagree, got {taken:?}"
))));
};
assert_eq!((theme, other), ("dark", "light"));
let out = icedwright::snapshot::SnapshotEnv::current()?.out_dir;
let found = icedwright::snapshot::themes::disagreements(&out)?;
let ours = found
.iter()
.find(|d| {
d.snapshot
.to_string_lossy()
.contains("theme_variants_of_one_semantic_snapshot_must_agree")
})
.ok_or_else(|| icedwright::Error::other(std::io::Error::other("no record on disk")))?;
assert_eq!(ours.yaml.len(), 2);
std::fs::remove_dir_all(
out.join(icedwright::snapshot::themes::DIR)
.join(&ours.snapshot),
)?;
Ok(())
}