Skip to main content

facett_core/
harness.rs

1//! Headless test harness — **fire up a `Facet`, inject data, render it offscreen,
2//! and capture what it drew**: its `state_json` + a vertex count (a "it drew
3//! something" proxy) + a stderr activity trail. No display, no GPU. This is the
4//! basis of facett's auto test matrix, and mirrors nornir viz's
5//! `NORNIR_VIZ_STATE` introspection — every component is observable from outside.
6
7use crate::Facet;
8
9/// What a headless render of one facet looked like.
10#[derive(Debug, Clone)]
11pub struct RenderReport {
12    pub title: String,
13    /// The component's observable state (its `Facet::state_json`).
14    pub state: serde_json::Value,
15    /// Tessellated mesh vertices — a proxy for "it actually drew something".
16    pub vertices: usize,
17}
18
19impl RenderReport {
20    pub fn drew(&self) -> bool {
21        self.vertices > 0
22    }
23}
24
25/// Render `facet` once into the given context at `size`, capturing its state +
26/// a vertex count. A panic in `ui` propagates — that's the point of the test.
27#[allow(deprecated)] // ctx.run / CentralPanel::show are the headless-render path
28fn capture(ctx: &egui::Context, facet: &mut dyn Facet, size: (f32, f32)) -> RenderReport {
29    let title = facet.title().to_string();
30    // Structured trace IN: which facet + at what size this render was handed
31    // (the typed sibling of the `trail`/`log` lines below — see `trace`).
32    crate::trace::emit_in(
33        "facet.render",
34        &serde_json::json!({ "title": title, "size": [size.0, size.1] }),
35    );
36    let input = egui::RawInput {
37        screen_rect: Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(size.0, size.1))),
38        ..Default::default()
39    };
40    let output = ctx.run(input, |ctx| {
41        egui::CentralPanel::default().show(ctx, |ui| facet.ui(ui));
42    });
43    let prims = ctx.tessellate(output.shapes, output.pixels_per_point);
44    let vertices = prims
45        .iter()
46        .map(|p| match &p.primitive {
47            egui::epaint::Primitive::Mesh(m) => m.vertices.len(),
48            _ => 0,
49        })
50        .sum();
51    let report = RenderReport { title, state: facet.state_json(), vertices };
52    log(&report);
53    trail(Kind::Render, format!("{} size={}x{} → {} verts", report.title, size.0 as i32, size.1 as i32, vertices));
54    dump_state(&report);
55    // Structured trace OUT: the real data the facet rendered — its full
56    // observable state + the vertex proof — so an agent reads back exactly what
57    // was drawn, no screenshot. (`state` is the same Value `dump_state` prints.)
58    crate::trace::emit_out(
59        "facet.render",
60        &serde_json::json!({
61            "title": report.title,
62            "vertices": report.vertices,
63            "drew": report.drew(),
64            "state": report.state,
65        }),
66    );
67    report
68}
69
70/// Headless render at `size` (default theme).
71pub fn render_sized(facet: &mut dyn Facet, size: (f32, f32)) -> RenderReport {
72    capture(&egui::Context::default(), facet, size)
73}
74
75/// `render_sized` at a default 800×600.
76pub fn headless_render(facet: &mut dyn Facet) -> RenderReport {
77    render_sized(facet, (800.0, 600.0))
78}
79
80/// Headless render with a theme applied (asserts the themed paint path works).
81pub fn render_themed(facet: &mut dyn Facet, theme: crate::Theme) -> RenderReport {
82    let ctx = egui::Context::default();
83    crate::set_theme(&ctx, theme);
84    capture(&ctx, facet, (800.0, 600.0))
85}
86
87/// Stderr activity trail (one line per render), like nornir viz's. The state is
88/// capped so a large component can't flood the log.
89pub fn log(r: &RenderReport) {
90    let full = r.state.to_string();
91    let shown: String = if full.chars().count() > 160 {
92        full.chars().take(159).chain(std::iter::once('…')).collect()
93    } else {
94        full
95    };
96    eprintln!("facett: {:<14} {:>7} verts · {}", r.title, r.vertices, shown);
97}
98
99// ── action-log-style trail (mirrors nornir viz `action_log`) ─────────────────
100//
101// Nornir's viz emits a timestamped, kinded, sequenced trail
102// (`HH:MM:SS.mmm  <seq> [KIND] detail`) on stderr + a greppable file so a human
103// can follow "what the headless run did". These give facett's matrices the same
104// observability. Dep-free: the stamp is derived from `SystemTime` and the seq
105// from a process-global atomic — no chrono, no extra crate.
106
107/// Coarse, greppable category for a trail entry — facett's analogue of nornir's
108/// `action_log::Kind`.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum Kind {
111    /// A facet was rendered headlessly.
112    Render,
113    /// A facet's full observable state was captured.
114    State,
115    /// A per-case matrix summary (component × theme × size).
116    Case,
117}
118
119impl Kind {
120    pub fn tag(self) -> &'static str {
121        match self {
122            Kind::Render => "RENDER",
123            Kind::State => "STATE",
124            Kind::Case => "CASE",
125        }
126    }
127}
128
129/// Process-global monotonic sequence — stable ordering even within one ms.
130fn next_seq() -> u64 {
131    use std::sync::atomic::{AtomicU64, Ordering};
132    static SEQ: AtomicU64 = AtomicU64::new(0);
133    SEQ.fetch_add(1, Ordering::Relaxed) + 1
134}
135
136/// `HH:MM:SS.mmm` local-ish wall stamp from `SystemTime` (UTC, no tz dep). Only
137/// the time-of-day matters for following a trail, so this is intentionally
138/// dependency-free rather than chrono-accurate.
139fn now_stamp() -> String {
140    let now = std::time::SystemTime::now()
141        .duration_since(std::time::UNIX_EPOCH)
142        .unwrap_or_default();
143    let total_ms = now.as_millis();
144    let ms = (total_ms % 1000) as u64;
145    let secs = (total_ms / 1000) as u64;
146    let h = (secs / 3600) % 24;
147    let m = (secs / 60) % 60;
148    let s = secs % 60;
149    format!("{h:02}:{m:02}:{s:02}.{ms:03}")
150}
151
152/// Emit one greppable, timestamped, kinded trail line — facett's analogue of
153/// nornir viz's `action_log` stderr sink:
154///   `facett ACTION HH:MM:SS.mmm  <seq> [KIND] detail`
155/// If `$FACETT_TRAIL` is set, the same line is appended to that file (greppable,
156/// externally observable — mirrors how nornir mirrors `$NORNIR_VIZ_ACTIONLOG`).
157pub fn trail(kind: Kind, detail: impl AsRef<str>) {
158    let stamp = now_stamp();
159    let seq = next_seq();
160    let detail = detail.as_ref();
161    let line = format!("facett ACTION {stamp} {seq:>5} [{}] {detail}", kind.tag());
162    eprintln!("{line}");
163    if let Ok(path) = std::env::var("FACETT_TRAIL") {
164        use std::io::Write;
165        if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
166            let _ = writeln!(f, "{line}");
167        }
168    }
169}
170
171/// Dump a facet's FULL observable `state_json` as a single greppable line
172/// (`facett STATE <title> = {…}`), the per-component analogue of viz_matrix's
173/// `eprintln!("state_json = {pretty}")`. Untruncated so a Facet's rendered
174/// contents are greppable in test output the way viz's are.
175pub fn dump_state(r: &RenderReport) {
176    eprintln!("facett STATE {} = {}", r.title, r.state);
177    trail(Kind::State, format!("{} state={}", r.title, r.state));
178}
179
180/// Emit a uniform per-case matrix summary line + trail entry for one
181/// component × axis case (e.g. a theme or a size), mirroring viz_matrix's
182/// `[ws] releases=… tables=…` per-workspace summary. `axis` is a free-form
183/// label like `theme=sci_fi` or `size=10000`.
184pub fn case_summary(component: &str, axis: &str, r: &RenderReport) {
185    eprintln!(
186        "facett CASE  {:<14} {:<16} → {:>8} verts  drew={}  state={}",
187        component,
188        axis,
189        r.vertices,
190        r.drew(),
191        r.state,
192    );
193    trail(Kind::Case, format!("{component} {axis} verts={} drew={}", r.vertices, r.drew()));
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::{Scene, hash_color};
200
201    struct Tiny(Scene);
202    impl Facet for Tiny {
203        fn title(&self) -> &str {
204            "tiny"
205        }
206        fn ui(&mut self, ui: &mut egui::Ui) {
207            crate::draw(ui, &self.0, crate::Layout::Circular, "empty");
208        }
209        fn state_json(&self) -> serde_json::Value {
210            serde_json::json!({ "nodes": self.0.nodes.len() })
211        }
212    }
213
214    #[test]
215    fn now_stamp_is_hms_millis_shaped() {
216        let s = now_stamp();
217        // HH:MM:SS.mmm — 12 chars, two ':' and one '.'.
218        assert_eq!(s.len(), 12, "stamp `{s}` should be HH:MM:SS.mmm");
219        assert_eq!(s.matches(':').count(), 2, "stamp `{s}` needs two colons");
220        assert_eq!(s.matches('.').count(), 1, "stamp `{s}` needs one dot");
221    }
222
223    #[test]
224    fn seq_is_monotonic() {
225        let a = next_seq();
226        let b = next_seq();
227        assert!(b > a, "seq must strictly increase: {a} then {b}");
228    }
229
230    #[test]
231    fn kind_tags_are_distinct() {
232        let tags = [Kind::Render.tag(), Kind::State.tag(), Kind::Case.tag()];
233        for (i, t) in tags.iter().enumerate() {
234            assert!(!t.is_empty());
235            assert!(!tags[..i].contains(t), "duplicate tag {t}");
236        }
237    }
238
239    #[test]
240    fn headless_render_captures_state_and_draws() {
241        let mut scene = Scene::new();
242        let a = scene.node("a", hash_color("a"));
243        let b = scene.node("b", hash_color("b"));
244        scene.edge(a, b);
245        let mut t = Tiny(scene);
246        let r = headless_render(&mut t);
247        assert_eq!(r.title, "tiny");
248        assert_eq!(r.state["nodes"], 2);
249        assert!(r.drew(), "a 2-node graph should tessellate to vertices");
250    }
251}