#![cfg(all(not(feature = "mini"), not(target_arch = "wasm32")))]
use rust_widgets::core::Rect;
use rust_widgets::widget::{Button, Label, Switch};
fn normalise_line_endings(text: &str) -> String {
text.replace("\r\n", "\n")
}
fn assert_widget_snapshot<W: rust_widgets::widget::Draw + rust_widgets::widget::Widget>(
name: &str,
widget: &mut W,
) {
let svg = rust_widgets::widget::svg::render_to_svg(widget);
let snapshot_path = format!("snapshots/{}.svg", name);
if std::env::var("UPDATE_SNAPSHOTS").as_deref() == Ok("1") {
std::fs::write(&snapshot_path, &svg).expect("write snapshot");
return;
}
let expected = match std::fs::read_to_string(&snapshot_path) {
Ok(svg) => svg,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let again = rust_widgets::widget::svg::render_to_svg(widget);
assert_eq!(
normalise_line_endings(&svg),
normalise_line_endings(&again),
"{name} renders differently on two consecutive calls, so no snapshot of it could ever \
be trusted; there is no committed baseline (`snapshots/{name}.svg` is absent), which \
is why this is not a comparison against one"
);
return;
}
Err(error) => {
panic!(
"could not read snapshot `{snapshot_path}`: {error}. A baseline that exists but \
cannot be read is not the same as a missing baseline."
);
}
};
assert_eq!(
normalise_line_endings(&svg),
normalise_line_endings(&expected),
"Snapshot mismatch for {}. Run with UPDATE_SNAPSHOTS=1 to update.",
name
);
}
#[test]
fn snapshot_button_default() {
let mut btn = Button::new("OK".to_string(), Rect::new(0, 0, 80, 30));
assert_widget_snapshot("button_default", &mut btn);
}
#[test]
fn snapshot_switch_default() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
assert_widget_snapshot("switch_default", &mut sw);
}
#[test]
fn snapshot_switch_checked() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.set_checked(true);
assert_widget_snapshot("switch_checked", &mut sw);
}
#[test]
fn snapshot_label_hello() {
let mut label = Label::new("Hello".to_string(), Rect::new(0, 0, 100, 20));
assert_widget_snapshot("label_hello", &mut label);
}