icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! Headed mode against a stand-in for studio's headed socket: every step arrives with its
//! frame, step mode waits for Continue before each step, pacing comes from studio's
//! acknowledgements, and the trace is the same as a headless run's.

#![cfg(unix)]

use std::io::{Read as _, Write as _};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::time::Duration;

use iced::widget::{button, column, text};
use iced::{Element, Theme};
use icedwright::prelude::*;
use icedwright::{Headed, HeadedLink};
use icedwright_protocol::{FrameKind, HEADER_LEN, WireFrame};
use icedwright_trace::{TraceConfig, TraceMode, TraceReader};

#[derive(Debug, Clone)]
enum Message {
    Add,
}

fn update(value: &mut u32, Message::Add: Message) {
    *value += 1;
}

fn view(value: &u32) -> Element<'_, Message> {
    column![
        text(value.to_string()),
        button("Add").on_press(Message::Add)
    ]
    .into()
}

fn program() -> impl TestProgram<State = u32, Message = Message> {
    iced::application(u32::default, update, view).theme(Theme::Light)
}

fn read_frame(stream: &mut UnixStream) -> Option<WireFrame> {
    let mut header = [0; HEADER_LEN];
    stream.read_exact(&mut header).ok()?;
    let (kind, length) = WireFrame::decode_header(header).ok()?;
    let mut payload = vec![0; length];
    stream.read_exact(&mut payload).ok()?;
    Some(WireFrame { kind, payload })
}

fn reply(stream: &mut UnixStream, kind: &str) -> std::io::Result<()> {
    let json = format!("{{\"type\":\"{kind}\"}}").into_bytes();
    let bytes = WireFrame::json(json)
        .encode()
        .map_err(std::io::Error::other)?;
    stream.write_all(&bytes)
}

/// What the stand-in studio saw: each message's type, with `+png` after a step whose frame
/// followed, and the hello message itself.
#[derive(Debug, Default)]
struct Seen {
    log: Vec<String>,
    hello: Option<serde_json::Value>,
}

/// Accepts one headed test and answers it as studio does: `continue` to a pause, `ack` to a
/// step, until the test finishes.
fn stand_in_studio(listener: UnixListener) -> std::thread::JoinHandle<std::io::Result<Seen>> {
    std::thread::spawn(move || answer(&listener))
}

/// Joins the stand-in once the harness has dropped. A harness that took headed mode has been
/// accepted by now, since it waited for answers; one that never connected would leave the
/// stand-in in `accept` for ever, so an empty connection releases it and the test fails on
/// the missing hello instead.
fn seen_by(
    studio: std::thread::JoinHandle<std::io::Result<Seen>>,
    path: &std::path::Path,
) -> std::io::Result<Seen> {
    let _ = UnixStream::connect(path);
    studio
        .join()
        .map_err(|_| std::io::Error::other("the stand-in studio panicked"))?
}

fn answer(listener: &UnixListener) -> std::io::Result<Seen> {
    let mut seen = Seen::default();
    let (mut stream, _) = listener.accept()?;
    while let Some(frame) = read_frame(&mut stream) {
        if frame.kind != FrameKind::Json {
            seen.log.push("a frame with no step before it".to_owned());
            break;
        }
        let message: serde_json::Value = serde_json::from_slice(&frame.payload)?;
        let kind = message["type"].as_str().unwrap_or_default().to_owned();
        match kind.as_str() {
            "hello" => seen.hello = Some(message),
            "paused" => {
                reply(&mut stream, "continue")?;
                seen.log.push(kind);
            }
            "step" => {
                let png = if message["frame"] == true {
                    read_frame(&mut stream)
                        .filter(|png| png.kind == FrameKind::Binary)
                        .filter(|png| png.payload.starts_with(b"\x89PNG"))
                        .map(|_| "step+png")
                        .unwrap_or("step with a bad frame")
                } else {
                    "step"
                };
                seen.log.push(png.to_owned());
                reply(&mut stream, "ack")?;
            }
            "finished" => {
                seen.log.push(kind);
                break;
            }
            _ => seen.log.push(kind),
        }
    }
    Ok(seen)
}

/// A socket path under the temporary directory, or under `/tmp` when that would pass the
/// 108-byte limit on Unix socket paths.
fn socket(name: &str) -> PathBuf {
    const SUN_PATH_MAX: usize = 107;
    let file = format!("iw-headed-{}-{name}.sock", std::process::id());
    let mut path = std::env::temp_dir().join(&file);
    if path.as_os_str().len() > SUN_PATH_MAX {
        path = PathBuf::from("/tmp").join(file);
    }
    let _ = std::fs::remove_file(&path);
    path
}

// milestone: Traces and studio
#[test]
fn step_mode_pauses_before_every_step_and_streams_each_frame() -> icedwright::Result {
    let path = socket("step");
    let studio = stand_in_studio(UnixListener::bind(&path)?);
    let mut h = Harness::builder(program())
        .headed(Headed::Step)
        .headed_socket(&path)
        .trace(TraceConfig::new().mode(TraceMode::Off))
        .build()?;
    h.get_by_text("Add").click()?;
    h.get_by_text("Add").click()?;
    expect(h.get_by_text("2")).to_be_visible()?;
    drop(h);
    let seen = seen_by(studio, &path)?;
    let _ = std::fs::remove_file(&path);
    let hello = seen
        .hello
        .expect("the harness never greeted the stand-in studio");
    assert_eq!(hello["step_mode"], true);
    assert_eq!(
        seen.log,
        [
            "paused", "step+png", "paused", "step+png", "paused", "step+png", "finished"
        ]
    );
    Ok(())
}

/// Runs the same steps, headed in slow motion on `socket` when given, writing an `always`
/// trace under `dir`, and returns the trace's bytes. `ICEDWRIGHT_OUT_DIR` and
/// `ICEDWRIGHT_TRACE_DIR` move the trace elsewhere, so it is looked for there too and deleted
/// once read, which keeps the next run's trace the only one.
fn run(dir: &std::path::Path, socket: Option<&std::path::Path>) -> icedwright::Result<Vec<u8>> {
    let _ = std::fs::remove_dir_all(dir);
    let mut builder =
        Harness::builder(program()).trace(TraceConfig::new().mode(TraceMode::Always).out_dir(dir));
    if let Some(socket) = socket {
        builder = builder
            .headed(Headed::Watch)
            .slow_mo(Duration::from_millis(250))
            .headed_socket(socket);
    }
    let mut h = builder.build()?;
    h.get_by_text("Add").click()?;
    h.advance(icedwright::time::VirtualDuration::from_millis(250))?;
    expect(h.get_by_text("1")).to_be_visible()?;
    drop(h);
    let name = format!("{}.iwtrace", SLOW_MOTION_TEST);
    let mut found = Vec::new();
    let mut stack: Vec<PathBuf> = ["ICEDWRIGHT_TRACE_DIR", "ICEDWRIGHT_OUT_DIR"]
        .into_iter()
        .filter_map(std::env::var_os)
        .map(PathBuf::from)
        .chain([dir.to_path_buf()])
        .collect();
    while let Some(next) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(next) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if path.file_name().is_some_and(|file| *file == *name) {
                found.push(path);
            }
        }
    }
    found.sort();
    found.dedup();
    assert_eq!(found.len(), 1, "{found:?}");
    let bytes = std::fs::read(&found[0])?;
    std::fs::remove_file(&found[0])?;
    Ok(bytes)
}

const SLOW_MOTION_TEST: &str = "a_headed_run_in_slow_motion_traces_the_same_as_a_headless_one";

// milestone: Traces and studio
#[test]
fn a_headed_run_in_slow_motion_traces_the_same_as_a_headless_one() -> icedwright::Result {
    let root = std::env::temp_dir().join(format!("iw-headed-trace-{}", std::process::id()));
    let headless = run(&root.join("headless"), None)?;

    let path = socket("slow");
    let studio = stand_in_studio(UnixListener::bind(&path)?);
    let headed = run(&root.join("headed"), Some(&path))?;
    let seen = seen_by(studio, &path)?;
    let _ = std::fs::remove_file(&path);
    let hello = seen
        .hello
        .expect("the harness never greeted the stand-in studio");
    assert_eq!(hello["step_mode"], false);
    assert_eq!(hello["slow_mo_ms"], 250);
    assert_eq!(seen.log.first().map(String::as_str), Some("step+png"));
    assert_eq!(seen.log.last().map(String::as_str), Some("finished"));
    assert!(
        !seen.log.iter().any(|kind| kind == "paused"),
        "{:?}",
        seen.log
    );

    let a = TraceReader::from_bytes(headless)?;
    let b = TraceReader::from_bytes(headed)?;
    assert_eq!(icedwright_trace::compare(&a, &b)?, None);
    let _ = std::fs::remove_dir_all(&root);
    Ok(())
}

/// A link that is already closed.
struct Gone;

impl HeadedLink for Gone {
    fn send(&mut self, _: &[u8]) -> std::io::Result<()> {
        Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
    }

    fn receive(&mut self, _: Option<Duration>) -> std::io::Result<Vec<u8>> {
        Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
    }
}

/// A studio that stays connected and takes every frame but never answers, as a stuck studio
/// would: each wait for an answer runs out its bound.
struct Silent;

impl HeadedLink for Silent {
    fn send(&mut self, _: &[u8]) -> std::io::Result<()> {
        Ok(())
    }

    fn receive(&mut self, within: Option<Duration>) -> std::io::Result<Vec<u8>> {
        assert!(within.is_some(), "a wait for an acknowledgement is bounded");
        Err(std::io::Error::from(std::io::ErrorKind::TimedOut))
    }
}

// milestone: Traces and studio
#[test]
fn a_studio_that_stops_answering_fails_the_step_with_a_hang() -> icedwright::Result {
    let mut h = Harness::builder(program())
        .headed(Headed::Watch)
        .headed_link(Silent)
        .build()?;
    let error = h.get_by_text("Add").click().unwrap_err();
    assert!(
        matches!(
            &error,
            icedwright::Error::Harness(icedwright::HarnessError::Hung {
                cause: icedwright::HangCause::HeadedStudio,
                ..
            })
        ),
        "{error}"
    );
    assert!(error.to_string().contains("headed socket"), "{error}");
    h.get_by_text("Add").click()?;
    expect(h.get_by_text("2")).to_be_visible()
}

// milestone: Traces and studio
#[test]
fn with_no_studio_the_test_runs_headless() -> icedwright::Result {
    let mut gone = Harness::builder(program())
        .headed(Headed::Step)
        .headed_link(Gone)
        .build()?;
    gone.get_by_text("Add").click()?;
    expect(gone.get_by_text("1")).to_be_visible()?;

    let mut nobody = Harness::builder(program())
        .headed(Headed::Step)
        .headed_socket(socket("nobody"))
        .build()?;
    nobody.get_by_text("Add").click()?;
    expect(nobody.get_by_text("1")).to_be_visible()
}