Skip to main content

Module testing

Module testing 

Source
Expand description

Run a plugin under cargo test, against an in-process host.

On targets other than wasm, every SDK call goes to the thread’s MockHost instead of the WIT imports. The mock checks grants exactly as the viewer’s host does (both use standard-plugin-manifest), keeps values, records what the plugin emitted and committed, and lays out surfaces. Harness drives a UiPlugin the way a viewer does: activate, resize, frames, events.

ⓘ
//! Testing a plugin with `standard_plugin::testing`: the harness drives the
//! plugin as a viewer would, on an in-process host that checks grants like
//! the real one. This file is the `testing` module's documentation example.
// The in-process host exists on non-wasm targets only.
#![cfg(not(target_arch = "wasm32"))]

use standard_plugin::prelude::*;
use standard_plugin::surface::Model;
use standard_plugin::testing::{Harness, MockGraphic, MockHost};

/// Shows a counter the plugin keeps in a durable value.
struct Counter {
    card: Surface<Cells>,
    count: u32,
}

impl UiPlugin for Counter {
    fn activate(cx: &mut Context) -> Self {
        let count = cx.values().get("counter.count").ok().flatten().unwrap_or(0);
        Self {
            card: Surface::new("card"),
            count,
        }
    }

    fn frame(&mut self, _frame: &Frame) {
        self.card
            .text(0, 0, &format!("count {}", self.count), Style::DEFAULT);
        let _ = self.card.commit();
    }
}

#[test]
fn the_harness_lays_out_frames_and_records_commits() {
    let mut host = MockHost::new("counter").surface("card", Model::Cells);
    host.values.insert("counter.count".into(), "41".into());
    let mut harness = Harness::<Counter>::activate(host, "{}");
    harness.resize("card", Geometry::cells(12, 1, (0, 0)));
    harness.frame(0, 16, standard_plugin::Power::Mains);

    let commits = harness.commits("card");
    assert_eq!(commits.len(), 1);
    assert!(commits[0].full, "the first commit covers the whole card");
    harness.plugin(|counter| assert_eq!(counter.card.row_text(0), "count 41    "));
}

/// A long surface of charts: the cells every viewer gets, a graphic over
/// them where the viewer has graphics.
struct Charts {
    pane: Surface<Cells>,
    charts: u32,
    shift: u32,
    level: u8,
    drawn: u32,
    results: Vec<standard_plugin::Result<bool>>,
}

impl Charts {
    fn paint(&mut self) {
        if self.pane.size().1 == 0 {
            return;
        }
        self.pane.clear();
        self.drawn = 0;
        self.results.clear();
        for chart in 0..self.charts {
            let top = self.shift + chart * 2;
            self.pane.text(0, top, "chart", Style::DEFAULT);
            let level = self.level;
            let mut drawn = 0;
            let place = Rect::new(0, top, 4, 2);
            let result = self.pane.draw_graphic(chart, place, |canvas| {
                drawn += 1;
                canvas.clear(standard_plugin::Rgba::rgb(level, 0, 0));
            });
            self.drawn += drawn;
            self.results.push(result);
        }
        let _ = self.pane.commit();
    }
}

impl UiPlugin for Charts {
    fn activate(_cx: &mut Context) -> Self {
        let pane = Surface::new("pane");
        let _ = pane.set_scroll(Some(Scroll::rows(16)));
        Self {
            pane,
            charts: 2,
            shift: 0,
            level: 10,
            drawn: 0,
            results: Vec::new(),
        }
    }

    fn frame(&mut self, _frame: &Frame) {}

    fn event(&mut self, event: Event, _cx: &mut Context) {
        if let Event::Resize { .. } | Event::CapabilitiesChanged = event {
            self.paint();
        }
    }
}

fn set_graphics(harness: &mut Harness<Charts>, graphics: bool) {
    let capabilities = harness.host(|host| host.capabilities);
    harness.set_capabilities(standard_plugin::capabilities::Capabilities {
        graphics,
        ..capabilities
    });
}

fn charts_at(graphics: bool, geometry: Geometry) -> Harness<Charts> {
    let host = MockHost::new("charts").surface("pane", Model::Cells);
    let mut harness = Harness::<Charts>::activate(host, "{}");
    set_graphics(&mut harness, graphics);
    harness.resize("pane", geometry);
    harness
}

fn charts(graphics: bool) -> Harness<Charts> {
    charts_at(graphics, Geometry::cells(8, 16, (2, 2)))
}

fn images_sent(harness: &Harness<Charts>) -> u32 {
    harness.host(|host| host.images_sent("pane"))
}

fn graphics(harness: &Harness<Charts>) -> std::collections::BTreeMap<u32, MockGraphic> {
    harness.host(|host| host.graphics("pane"))
}

#[test]
fn a_viewer_without_graphics_gets_the_cells_and_no_drawing_runs() {
    let harness = charts(false);
    harness.plugin(|plugin| {
        assert_eq!(plugin.drawn, 0);
        assert!(
            plugin
                .results
                .iter()
                .all(|result| matches!(result, Ok(false)))
        );
        assert!(plugin.pane.row_text(0).starts_with("chart"));
    });
    assert!(graphics(&harness).is_empty());
    assert_eq!(images_sent(&harness), 0);
}

#[test]
fn a_viewer_with_graphics_gets_the_same_cells_and_an_image_for_each_chart() {
    let harness = charts(true);
    harness.plugin(|plugin| {
        assert_eq!(plugin.drawn, 2);
        assert!(
            plugin
                .results
                .iter()
                .all(|result| matches!(result, Ok(true)))
        );
        assert!(plugin.pane.row_text(0).starts_with("chart"));
    });
    let graphics = graphics(&harness);
    assert_eq!(graphics.len(), 2);
    assert_eq!(graphics[&1].place, Rect::new(0, 2, 4, 2));
    assert_eq!(graphics[&1].size, (8, 4));
    assert_eq!(graphics[&1].rgba.len(), 8 * 4 * 4);
    assert_eq!(images_sent(&harness), 2);
}

#[test]
fn an_unchanged_image_is_never_sent_again_and_only_moves() {
    let harness = charts(true);
    // The same paint: nothing goes to the host.
    harness.plugin(Charts::paint);
    assert_eq!(images_sent(&harness), 2);

    // Rows moved: the same images at new places.
    harness.plugin(|plugin| {
        plugin.shift = 3;
        plugin.paint();
    });
    assert_eq!(images_sent(&harness), 2);
    assert_eq!(graphics(&harness)[&0].place, Rect::new(0, 3, 4, 2));

    // New data: new images.
    harness.plugin(|plugin| {
        plugin.level = 20;
        plugin.paint();
    });
    assert_eq!(images_sent(&harness), 4);
}

#[test]
fn a_graphic_not_drawn_again_goes_with_the_commit() {
    let harness = charts(true);
    harness.plugin(|plugin| {
        plugin.charts = 1;
        plugin.paint();
    });
    assert_eq!(graphics(&harness).len(), 1);
    assert_eq!(images_sent(&harness), 2);
}

#[test]
fn a_graphic_change_with_no_cell_change_publishes_with_the_commit() {
    let harness = charts(true);
    harness.plugin(|plugin| {
        plugin.pane.remove_graphic(1).unwrap();
        assert_eq!(graphics(&harness).len(), 2, "it waits for the commit");
        plugin.pane.commit().unwrap();
    });
    assert_eq!(graphics(&harness).len(), 1);
}

#[test]
fn a_resize_keeps_images_that_still_fit_and_a_new_cell_size_sends_them_again() {
    let mut harness = charts(true);
    assert_eq!(images_sent(&harness), 2);
    // Rows opened: the same cell size, so the same images.
    harness.resize("pane", Geometry::cells(10, 16, (2, 2)));
    assert_eq!(graphics(&harness).len(), 2);
    assert_eq!(images_sent(&harness), 2);
    harness.resize("pane", Geometry::cells(10, 16, (3, 3)));
    assert_eq!(graphics(&harness).len(), 2);
    assert_eq!(images_sent(&harness), 4);
}

#[test]
fn moving_a_graphic_sends_no_image_and_a_missing_one_asks_for_a_draw() {
    let mut harness = charts(true);
    let moved = Rect::new(0, 5, 4, 2);
    harness.plugin(|plugin| {
        assert_eq!(plugin.pane.move_graphic(0, moved), Ok(true));
        assert_eq!(plugin.pane.move_graphic(9, moved), Ok(false));
        assert_eq!(
            plugin.pane.move_graphic(0, Rect::new(0, 5, 6, 2)),
            Ok(false)
        );
        let _ = plugin.pane.commit();
    });
    assert_eq!(graphics(&harness)[&0].place, moved);
    assert_eq!(images_sent(&harness), 2);
}

#[test]
fn a_viewer_losing_graphics_loses_the_images_and_keeps_the_cells() {
    let mut harness = charts(true);
    set_graphics(&mut harness, false);
    assert!(graphics(&harness).is_empty());
    harness.plugin(|plugin| assert!(plugin.pane.row_text(0).starts_with("chart")));
}

#[test]
fn past_a_surface_s_limits_a_graphic_is_refused_and_the_cells_stand() {
    // Too many graphics.
    let harness = charts(true);
    let results: Vec<standard_plugin::Result<bool>> = harness.plugin(|plugin| {
        (0..255)
            .map(|key| {
                plugin
                    .pane
                    .draw_graphic(key + 100, Rect::new(0, 0, 1, 1), |_| ())
            })
            .collect()
    });
    let (first, last) = results.split_at(254);
    assert!(first.iter().all(|result| matches!(result, Ok(true))));
    assert!(matches!(last[0], Err(Error::Invalid(_))), "{last:?}");

    // Too many image bytes: each of these takes 41 MB of the 64 MiB.
    let harness = charts_at(true, Geometry::cells(64, 32, (100, 100)));
    harness.plugin(|plugin| {
        plugin.pane.clear();
        plugin.pane.commit().unwrap();
        let top = Rect::new(0, 0, 64, 16);
        assert!(matches!(plugin.pane.draw_graphic(0, top, |_| ()), Ok(true)));
        let bottom = Rect::new(0, 16, 64, 16);
        let second = plugin.pane.draw_graphic(1, bottom, |_| ());
        assert!(matches!(second, Err(Error::Invalid(_))), "{second:?}");
        plugin.pane.commit().unwrap();
    });
    assert_eq!(graphics(&harness).len(), 1);
}

Structs§

DaemonHarness
Drives a DaemonPlugin as standardd would: activate, drive at the instants it asks for, events and calls.
Harness
Drives a UiPlugin as a viewer does, on this thread’s MockHost.
MockCall
One call as the host saw it.
MockCommit
One commit as the host saw it.
MockGraphic
A graphic a commit published (Surface::draw_graphic).
MockHost
The in-process host. Build one, install it (or hand it to a Harness), and inspect it after the plugin ran.
MockPaneLaunch
One pane the plugin opened (daemon::panes::create), as the host saw it.
MockProcess
One child the plugin spawned, as the host saw it.
MockWatch
One watch the plugin holds.
MockWebSocket
A WebSocket the plugin opened on the test host.
ProcessScript
What a scripted program does when the plugin spawns it: the output it writes (delivered as Event::ProcessOutput for a piped stream) and its exit status (Event::ProcessExited, and what wait answers).

Enums§

CallKind
How a plugin made a call.

Functions§

install
Makes host this thread’s host. A thread without one gets MockHost::new("test-plugin") on its first call.
with_host
Runs f on this thread’s host.