icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Message and node coverage files: written under the output directory when
//! `ICEDWRIGHT_COVERAGE` is set, with every variant `#[derive(Messages)]` lists. The checks run
//! this binary again as a child process with the variables set.

use std::path::Path;
use std::process::Command;

use iced::widget::{button, column, text};
use iced::{Element, Theme};
use icedwright::prelude::*;
use icedwright::testing::CoverageFile;
use icedwright_probe::semantic;

#[derive(Debug, Clone, PartialEq, icedwright_probe::Messages)]
enum Message {
    Increment,
    Reset,
    Set(i64),
}

#[derive(Debug, Default)]
struct Counter {
    value: i64,
}

impl Counter {
    fn update(&mut self, message: Message) {
        match message {
            Message::Increment => self.value += 1,
            Message::Reset => self.value = 0,
            Message::Set(value) => self.value = value,
        }
    }

    fn view(&self) -> Element<'_, Message> {
        column![
            text(self.value.to_string()),
            semantic(button(text("+")).on_press(Message::Increment))
                .role(role::Button)
                .name("Increment"),
        ]
        .into()
    }
}

fn counter()
-> iced::Application<impl iced::Program<State = Counter, Message = Message, Theme = Theme>> {
    iced::application(Counter::default, Counter::update, Counter::view)
}

/// A message without the derive, whose variants coverage cannot list.
#[derive(Debug, Clone)]
enum Plain {
    Tick,
}

#[derive(Debug, Default)]
struct Quiet;

impl Quiet {
    fn update(&mut self, _: Plain) {}

    fn view(&self) -> Element<'_, Plain> {
        text("plain").into()
    }
}

fn plain() -> iced::Application<impl iced::Program<State = Quiet, Message = Plain, Theme = Theme>> {
    iced::application(Quiet::default, Quiet::update, Quiet::view)
}

#[icedwright::test(app = counter)]
fn produces_coverage(
    ui: &mut Harness<impl TestProgram<State = Counter, Message = Message>>,
) -> icedwright::Result {
    ui.dispatch(Message::Increment)?;
    ui.dispatch(Message::Increment)?;
    ui.dispatch(Message::Set(5))?;
    Ok(())
}

#[icedwright::test(app = plain)]
fn produces_coverage_without_variants(
    ui: &mut Harness<impl TestProgram<State = Quiet, Message = Plain>>,
) -> icedwright::Result {
    ui.dispatch(Plain::Tick)
}

/// Runs one test of this binary in a child process with coverage on, writing under `out`.
fn run_child(test: &str, out: &Path) -> icedwright::Result {
    let status = Command::new(std::env::current_exe()?)
        .args(["--exact", test, "--test-threads", "1"])
        .env("ICEDWRIGHT_COVERAGE", "1")
        .env("ICEDWRIGHT_OUT_DIR", out)
        .status()?;
    assert!(status.success(), "{test} failed in the child");
    Ok(())
}

fn read(out: &Path, test: &str) -> icedwright::Result<CoverageFile> {
    let path = CoverageFile::path_in(&out.join("coverage"), "icedwright", test);
    CoverageFile::from_json(&std::fs::read_to_string(&path)?)
}

#[icedwright::test]
fn the_file_lists_every_variant_and_counts_the_seen(dir: &TempDir) -> icedwright::Result {
    run_child("produces_coverage", dir.path())?;
    let file = read(dir.path(), "produces_coverage")?;
    assert_eq!(file.version, 1);
    assert_eq!(file.test, "produces_coverage");
    let messages = file.messages.expect("the message derives Messages");
    assert_eq!(messages.known, vec!["Increment", "Reset", "Set"]);
    let seen: Vec<(&str, u64)> = messages
        .seen
        .iter()
        .map(|(k, v)| (k.as_str(), *v))
        .collect();
    assert_eq!(seen, vec![("Increment", 2), ("Set", 1)]);
    assert!(
        file.nodes
            .iter()
            .any(|node| node.seen && node.path.contains("Increment")),
        "{:#?}",
        file.nodes
    );
    let paths: Vec<&String> = file.nodes.iter().map(|node| &node.path).collect();
    let mut sorted = paths.clone();
    sorted.sort();
    assert_eq!(paths, sorted);
    Ok(())
}

#[icedwright::test]
fn a_message_without_the_derive_has_no_variant_list(dir: &TempDir) -> icedwright::Result {
    run_child("produces_coverage_without_variants", dir.path())?;
    let file = read(dir.path(), "produces_coverage_without_variants")?;
    assert_eq!(file.messages, None);
    assert!(!file.nodes.is_empty());
    Ok(())
}

#[icedwright::test]
fn two_runs_write_the_same_bytes(dir: &TempDir) -> icedwright::Result {
    let path = CoverageFile::path_in(
        &dir.path().join("coverage"),
        "icedwright",
        "produces_coverage",
    );
    run_child("produces_coverage", dir.path())?;
    let first = std::fs::read(&path)?;
    run_child("produces_coverage", dir.path())?;
    assert_eq!(std::fs::read(&path)?, first);
    Ok(())
}

#[test]
fn a_hand_written_test_collects_coverage_itself() -> icedwright::Result {
    let mut ui = Harness::new(counter())?;
    ui.dispatch(Message::Reset)?;
    let file = CoverageFile::of("by_hand", &mut ui);
    let messages = file.messages.expect("the derive's list");
    assert_eq!(messages.seen.get("Reset"), Some(&1));
    Ok(())
}