Skip to main content

slt/
test_utils.rs

1//! Headless testing utilities.
2//!
3//! [`TestBackend`] renders a UI closure to an in-memory buffer without a real
4//! terminal. [`EventBuilder`] constructs event sequences for simulating user
5//! input. Together they enable snapshot and assertion-based UI testing.
6
7use crate::buffer::Buffer;
8use crate::context::Context;
9use crate::event::{
10    Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, ModifierKey, MouseButton, MouseEvent,
11    MouseKind,
12};
13use crate::rect::Rect;
14use crate::style::Style;
15use crate::{run_frame_kernel, FrameState, RunConfig};
16
17/// Builder for constructing a sequence of input [`Event`]s.
18///
19/// Chain calls to [`key`](EventBuilder::key), [`click`](EventBuilder::click),
20/// [`scroll_up`](EventBuilder::scroll_up), etc., then call
21/// [`build`](EventBuilder::build) to get the final `Vec<Event>`.
22///
23/// # Example
24///
25/// ```
26/// use slt::EventBuilder;
27/// use slt::KeyCode;
28///
29/// let events = EventBuilder::new()
30///     .key('a')
31///     .key_code(KeyCode::Enter)
32///     .build();
33/// assert_eq!(events.len(), 2);
34/// ```
35pub struct EventBuilder {
36    events: Vec<Event>,
37}
38
39impl EventBuilder {
40    /// Create an empty event builder.
41    pub fn new() -> Self {
42        Self { events: Vec::new() }
43    }
44
45    /// Append a character key-press event.
46    pub fn key(mut self, c: char) -> Self {
47        self.events.push(Event::Key(KeyEvent {
48            code: KeyCode::Char(c),
49            modifiers: KeyModifiers::NONE,
50            kind: KeyEventKind::Press,
51        }));
52        self
53    }
54
55    /// Append a special key-press event (arrows, Enter, Esc, etc.).
56    pub fn key_code(mut self, code: KeyCode) -> Self {
57        self.events.push(Event::Key(KeyEvent {
58            code,
59            modifiers: KeyModifiers::NONE,
60            kind: KeyEventKind::Press,
61        }));
62        self
63    }
64
65    /// Append a key-press event with modifier keys (Ctrl, Shift, Alt).
66    pub fn key_with(mut self, code: KeyCode, modifiers: KeyModifiers) -> Self {
67        self.events.push(Event::Key(KeyEvent {
68            code,
69            modifiers,
70            kind: KeyEventKind::Press,
71        }));
72        self
73    }
74
75    /// Append a modifier-only key-press event (a bare Ctrl/Shift/Alt/Super
76    /// press with no accompanying character).
77    ///
78    /// Mirrors what the Kitty keyboard protocol delivers when
79    /// [`RunConfig::report_all_keys(true)`](crate::RunConfig::report_all_keys)
80    /// is enabled, so widget tests can simulate modifier-only presses without
81    /// poking crossterm. The event carries [`KeyCode::Modifier`] with
82    /// [`KeyModifiers::NONE`].
83    ///
84    /// Since 0.21.0.
85    ///
86    /// # Example
87    ///
88    /// ```
89    /// use slt::{EventBuilder, KeyCode, ModifierKey};
90    ///
91    /// let events = EventBuilder::new()
92    ///     .key_modifier(ModifierKey::LeftCtrl)
93    ///     .build();
94    /// assert_eq!(events.len(), 1);
95    /// ```
96    pub fn key_modifier(mut self, m: ModifierKey) -> Self {
97        self.events.push(Event::Key(KeyEvent {
98            code: KeyCode::Modifier(m),
99            modifiers: KeyModifiers::NONE,
100            kind: KeyEventKind::Press,
101        }));
102        self
103    }
104
105    /// Append a left mouse click at terminal position `(x, y)`.
106    pub fn click(mut self, x: u32, y: u32) -> Self {
107        self.events.push(Event::Mouse(MouseEvent {
108            kind: MouseKind::Down(MouseButton::Left),
109            x,
110            y,
111            modifiers: KeyModifiers::NONE,
112            pixel_x: None,
113            pixel_y: None,
114        }));
115        self
116    }
117
118    /// Append a left-button press at `(x, y)` carrying the given modifiers.
119    ///
120    /// Use this to simulate `Shift`+click (e.g. range extension in the
121    /// calendar widget). The plain [`click`](EventBuilder::click) helper
122    /// always sends `KeyModifiers::NONE`.
123    pub fn click_with(mut self, x: u32, y: u32, modifiers: KeyModifiers) -> Self {
124        self.events.push(Event::Mouse(MouseEvent {
125            kind: MouseKind::Down(MouseButton::Left),
126            x,
127            y,
128            modifiers,
129            pixel_x: None,
130            pixel_y: None,
131        }));
132        self
133    }
134
135    /// Append a left mouse button release at terminal position `(x, y)`.
136    pub fn mouse_up(mut self, x: u32, y: u32) -> Self {
137        self.events.push(Event::mouse_up(x, y));
138        self
139    }
140
141    /// Append a mouse drag (movement with the left button held) at `(x, y)`.
142    pub fn drag(mut self, x: u32, y: u32) -> Self {
143        self.events.push(Event::mouse_drag(x, y));
144        self
145    }
146
147    /// Append a key-release event for character `c`.
148    ///
149    /// Only meaningful on terminals that emit release events
150    /// (e.g. with the Kitty keyboard protocol enabled).
151    pub fn key_release(mut self, c: char) -> Self {
152        self.events.push(Event::key_release(c));
153        self
154    }
155
156    /// Append a terminal focus-gained event.
157    pub fn focus_gained(mut self) -> Self {
158        self.events.push(Event::FocusGained);
159        self
160    }
161
162    /// Append a terminal focus-lost event.
163    pub fn focus_lost(mut self) -> Self {
164        self.events.push(Event::FocusLost);
165        self
166    }
167
168    /// Append a scroll-up event at `(x, y)`.
169    pub fn scroll_up(mut self, x: u32, y: u32) -> Self {
170        self.events.push(Event::Mouse(MouseEvent {
171            kind: MouseKind::ScrollUp,
172            x,
173            y,
174            modifiers: KeyModifiers::NONE,
175            pixel_x: None,
176            pixel_y: None,
177        }));
178        self
179    }
180
181    /// Append a scroll-down event at `(x, y)`.
182    pub fn scroll_down(mut self, x: u32, y: u32) -> Self {
183        self.events.push(Event::Mouse(MouseEvent {
184            kind: MouseKind::ScrollDown,
185            x,
186            y,
187            modifiers: KeyModifiers::NONE,
188            pixel_x: None,
189            pixel_y: None,
190        }));
191        self
192    }
193
194    /// Append a bracketed-paste event.
195    pub fn paste(mut self, text: impl Into<String>) -> Self {
196        self.events.push(Event::Paste(text.into()));
197        self
198    }
199
200    /// Append a terminal resize event.
201    pub fn resize(mut self, width: u32, height: u32) -> Self {
202        self.events.push(Event::Resize(width, height));
203        self
204    }
205
206    /// Consume the builder and return the event sequence.
207    pub fn build(self) -> Vec<Event> {
208        self.events
209    }
210}
211
212impl Default for EventBuilder {
213    fn default() -> Self {
214        Self::new()
215    }
216}
217
218/// Headless rendering backend for tests.
219///
220/// Renders a UI closure to an in-memory [`Buffer`] without a real terminal.
221/// Use [`render`](TestBackend::render) to run one frame, then inspect the
222/// output with [`line`](TestBackend::line), [`assert_contains`](TestBackend::assert_contains),
223/// or [`to_string_trimmed`](TestBackend::to_string_trimmed).
224/// Session state persists across renders, so multi-frame tests can exercise
225/// hooks, focus, and previous-frame hit testing.
226///
227/// # Example
228///
229/// ```
230/// use slt::TestBackend;
231///
232/// let mut backend = TestBackend::new(40, 10);
233/// backend.render(|ui| {
234///     ui.text("hello");
235/// });
236/// backend.assert_contains("hello");
237/// ```
238pub struct TestBackend {
239    buffer: Buffer,
240    width: u32,
241    height: u32,
242    frame_state: FrameState,
243    /// Frame history. `None` = recording disabled (zero overhead).
244    /// `Some(_)` = recording enabled — every [`render`](TestBackend::render)
245    /// call appends a [`FrameRecord`].
246    frames: Option<Vec<FrameRecord>>,
247}
248
249/// Snapshot of a single rendered frame, captured by
250/// [`TestBackend::record_frames`].
251///
252/// Stores the styled snapshot string (via [`Buffer::snapshot_format`]) plus a
253/// per-row trimmed text view for ergonomic substring assertions. Both are
254/// produced from the same buffer and are guaranteed to refer to the same
255/// frame.
256///
257/// Cheap to clone; useful for replaying a failing test by inspecting
258/// intermediate frames.
259#[derive(Clone, Debug, PartialEq, Eq)]
260pub struct FrameRecord {
261    /// Styled snapshot of the buffer at this frame, in the stable
262    /// [`Buffer::snapshot_format`] vocabulary.
263    pub snapshot: String,
264    /// Plain-text view of each buffer row, trailing spaces trimmed.
265    /// Mirrors [`TestBackend::line`] for every row.
266    pub lines: Vec<String>,
267}
268
269impl FrameRecord {
270    /// Return the frame as a multi-line string (rows joined with `\n`,
271    /// trailing empty rows preserved). Mirrors [`TestBackend::to_string_trimmed`]
272    /// on the originating buffer.
273    pub fn to_string_trimmed(&self) -> String {
274        let mut lines = self.lines.clone();
275        while lines.last().is_some_and(|l| l.is_empty()) {
276            lines.pop();
277        }
278        lines.join("\n")
279    }
280
281    /// Return the trimmed text of row `y` from this frame, or empty if `y`
282    /// is past the buffer height.
283    pub fn line(&self, y: u32) -> &str {
284        self.lines
285            .get(y as usize)
286            .map(|s| s.as_str())
287            .unwrap_or_default()
288    }
289
290    /// Assert any row in this frame contains `expected`. Panics with a
291    /// row-by-row dump on failure.
292    pub fn assert_contains(&self, expected: &str) {
293        for line in &self.lines {
294            if line.contains(expected) {
295                return;
296            }
297        }
298        let mut detail = String::new();
299        for (y, line) in self.lines.iter().enumerate() {
300            detail.push_str(&format!("  {y}: {line}\n"));
301        }
302        panic!("FrameRecord does not contain {expected:?}.\nFrame:\n{detail}");
303    }
304}
305
306impl TestBackend {
307    /// Create a test backend with the given terminal dimensions.
308    pub fn new(width: u32, height: u32) -> Self {
309        let area = Rect::new(0, 0, width, height);
310        Self {
311            buffer: Buffer::empty(area),
312            width,
313            height,
314            frame_state: FrameState::default(),
315            frames: None,
316        }
317    }
318
319    /// Enable frame recording.
320    ///
321    /// After this call, every subsequent [`render`](TestBackend::render),
322    /// [`render_with_events`](TestBackend::render_with_events), and
323    /// [`run_with_events`](TestBackend::run_with_events) call appends a
324    /// [`FrameRecord`] to the internal history. Disabled by default so tests
325    /// that don't need history pay zero memory overhead.
326    ///
327    /// Returns `self` for chaining.
328    ///
329    /// # Example
330    ///
331    /// ```
332    /// use slt::TestBackend;
333    ///
334    /// let mut tb = TestBackend::new(20, 3).record_frames();
335    /// for n in 0..3 {
336    ///     tb.render(|ui| {
337    ///         ui.text(format!("frame {n}"));
338    ///     });
339    /// }
340    /// assert_eq!(tb.frames().len(), 3);
341    /// tb.frames()[0].assert_contains("frame 0");
342    /// tb.frames()[2].assert_contains("frame 2");
343    /// ```
344    pub fn record_frames(mut self) -> Self {
345        if self.frames.is_none() {
346            self.frames = Some(Vec::new());
347        }
348        self
349    }
350
351    /// Return all captured frame snapshots in chronological order.
352    ///
353    /// Returns an empty slice if [`record_frames`](TestBackend::record_frames)
354    /// was never called on this backend.
355    pub fn frames(&self) -> &[FrameRecord] {
356        self.frames.as_deref().unwrap_or(&[])
357    }
358
359    /// Capture the current buffer state into the recording, if enabled.
360    ///
361    /// No-op when recording is off — keeps the hot path allocation-free
362    /// for the common case.
363    fn capture_frame(&mut self) {
364        if let Some(frames) = self.frames.as_mut() {
365            let snapshot = self.buffer.snapshot_format();
366            let mut lines = Vec::with_capacity(self.height as usize);
367            for y in 0..self.height {
368                let mut s = String::new();
369                for x in 0..self.width {
370                    s.push_str(&self.buffer.get(x, y).symbol);
371                }
372                lines.push(s.trim_end().to_string());
373            }
374            frames.push(FrameRecord { snapshot, lines });
375        }
376    }
377
378    fn render_frame(
379        &mut self,
380        events: Vec<Event>,
381        setup_state: impl FnOnce(&mut FrameState),
382        f: impl FnOnce(&mut Context),
383    ) {
384        setup_state(&mut self.frame_state);
385
386        self.buffer.reset();
387        let mut once = Some(f);
388        let mut render = |ui: &mut Context| {
389            if let Some(f) = once.take() {
390                f(ui);
391            } else {
392                panic!("render closure called twice");
393            }
394        };
395        let _ = run_frame_kernel(
396            &mut self.buffer,
397            &mut self.frame_state,
398            &RunConfig::default(),
399            (self.width, self.height),
400            events,
401            false,
402            &mut render,
403        );
404        self.capture_frame();
405    }
406
407    /// Run a UI closure for one frame and render to the internal buffer.
408    pub fn render(&mut self, f: impl FnOnce(&mut Context)) {
409        self.render_frame(Vec::new(), |_| {}, f);
410    }
411
412    /// Render with injected events and focus state for interaction testing.
413    pub fn render_with_events(
414        &mut self,
415        events: Vec<Event>,
416        focus_index: usize,
417        prev_focus_count: usize,
418        f: impl FnOnce(&mut Context),
419    ) {
420        self.render_frame(
421            events,
422            |state| {
423                state.focus.focus_index = focus_index;
424                state.focus.prev_focus_count = prev_focus_count;
425            },
426            f,
427        );
428    }
429
430    /// Convenience wrapper: render with events using default focus state.
431    pub fn run_with_events(&mut self, events: Vec<Event>, f: impl FnOnce(&mut crate::Context)) {
432        self.render_with_events(events, 0, 0, f);
433    }
434
435    /// Number of live frame-clock scheduler timer slots persisted after the
436    /// most recent render (issue #248). Test-only — used to assert that
437    /// abandoned timers are garbage-collected and `SchedulerState` does not
438    /// grow without bound.
439    #[cfg(test)]
440    pub(crate) fn scheduler_slot_count(&self) -> usize {
441        self.frame_state.scheduler.slot_count()
442    }
443
444    /// Inject the ambient Tokio runtime handle so `Context::spawn` works inside
445    /// rendered frames (issue #234). Mirrors what `run_async_loop` does once
446    /// before its loop; test-only — real async runs go through `run_async`.
447    #[cfg(all(test, feature = "async"))]
448    pub(crate) fn set_async_runtime(&mut self, handle: tokio::runtime::Handle) {
449        self.frame_state.async_tasks.set_runtime(handle);
450    }
451
452    /// Get the rendered text content of row y (trimmed trailing spaces)
453    pub fn line(&self, y: u32) -> String {
454        let mut s = String::new();
455        for x in 0..self.width {
456            s.push_str(&self.buffer.get(x, y).symbol);
457        }
458        s.trim_end().to_string()
459    }
460
461    /// Assert that row y contains `expected` as a substring
462    pub fn assert_line(&self, y: u32, expected: &str) {
463        let line = self.line(y);
464        assert_eq!(
465            line, expected,
466            "Line {y}: expected {expected:?}, got {line:?}"
467        );
468    }
469
470    /// Assert that row y contains `expected` as a substring
471    pub fn assert_line_contains(&self, y: u32, expected: &str) {
472        let line = self.line(y);
473        assert!(
474            line.contains(expected),
475            "Line {y}: expected to contain {expected:?}, got {line:?}"
476        );
477    }
478
479    /// Assert that any line in the buffer contains `expected`
480    pub fn assert_contains(&self, expected: &str) {
481        for y in 0..self.height {
482            if self.line(y).contains(expected) {
483                return;
484            }
485        }
486        let mut all_lines = String::new();
487        for y in 0..self.height {
488            all_lines.push_str(&format!("{}: {}\n", y, self.line(y)));
489        }
490        panic!("Buffer does not contain {expected:?}.\nBuffer:\n{all_lines}");
491    }
492
493    /// Access the underlying render buffer.
494    pub fn buffer(&self) -> &Buffer {
495        &self.buffer
496    }
497
498    /// Terminal width used for this backend.
499    pub fn width(&self) -> u32 {
500        self.width
501    }
502
503    /// Terminal height used for this backend.
504    pub fn height(&self) -> u32 {
505        self.height
506    }
507
508    /// Return the full rendered buffer as a multi-line string.
509    ///
510    /// Each row is trimmed of trailing spaces and joined with newlines.
511    /// Useful for snapshot testing with `insta::assert_snapshot!`.
512    pub fn to_string_trimmed(&self) -> String {
513        let mut lines = Vec::with_capacity(self.height as usize);
514        for y in 0..self.height {
515            lines.push(self.line(y));
516        }
517        while lines.last().is_some_and(|l| l.is_empty()) {
518            lines.pop();
519        }
520        lines.join("\n")
521    }
522
523    // ---- Negative assertions (#232) ---------------------------------------
524
525    /// Assert that no row in the buffer contains `expected` as a substring.
526    ///
527    /// Panics with the offending row indices and contents on failure.
528    pub fn assert_not_contains(&self, expected: &str) {
529        let mut offending: Vec<(u32, String)> = Vec::new();
530        for y in 0..self.height {
531            let line = self.line(y);
532            if line.contains(expected) {
533                offending.push((y, line));
534            }
535        }
536        if !offending.is_empty() {
537            let detail = offending
538                .iter()
539                .map(|(y, l)| format!("  row {y}: {l:?}"))
540                .collect::<Vec<_>>()
541                .join("\n");
542            panic!("Buffer unexpectedly contains {expected:?}:\n{detail}");
543        }
544    }
545
546    /// Assert that row `y` does NOT contain `expected` as a substring.
547    pub fn assert_line_not_contains(&self, y: u32, expected: &str) {
548        let line = self.line(y);
549        assert!(
550            !line.contains(expected),
551            "Line {y}: expected NOT to contain {expected:?}, but got {line:?}"
552        );
553    }
554
555    /// Assert that row `y` is entirely blank (contains no non-space content).
556    ///
557    /// Useful for verifying that cleared, padded, or overflow-suppressed rows
558    /// render as empty.
559    pub fn assert_empty_line(&self, y: u32) {
560        let line = self.line(y);
561        assert!(line.is_empty(), "Line {y}: expected empty, got {line:?}");
562    }
563
564    /// Assert that the cell at `(x, y)` carries exactly the `expected` style.
565    ///
566    /// Useful for focused color/modifier regression checks without committing
567    /// to a full-buffer snapshot. Panics with `(x, y)`, the actual style, and
568    /// the expected style on mismatch.
569    pub fn assert_style_at(&self, x: u32, y: u32, expected: Style) {
570        let actual = self.buffer.get(x, y).style;
571        assert_eq!(
572            actual, expected,
573            "Style mismatch at ({x}, {y}): expected {expected:?}, got {actual:?}"
574        );
575    }
576
577    // ---- Multi-step sequences + type_string (#230) ------------------------
578
579    /// Begin building a multi-step interaction sequence.
580    ///
581    /// Each [`tick`](TestSequence::tick) (or [`key`](TestSequence::key))
582    /// appends an event batch + render closure pair.
583    /// [`run`](TestSequence::run) executes them in order, advancing
584    /// `FrameState` naturally between steps so callers don't need to thread
585    /// `focus_index` / `prev_focus_count` manually.
586    ///
587    /// # Example
588    ///
589    /// ```
590    /// use slt::{KeyCode, TestBackend};
591    ///
592    /// let mut tb = TestBackend::new(20, 3);
593    /// tb.sequence()
594    ///     .tick(|ui| { ui.text("ready"); })
595    ///     .key(KeyCode::Esc, |ui| { ui.text("after esc"); })
596    ///     .run();
597    /// tb.assert_contains("after esc");
598    /// ```
599    pub fn sequence(&mut self) -> TestSequence<'_> {
600        TestSequence {
601            backend: self,
602            steps: Vec::new(),
603        }
604    }
605
606    /// Simulate typing `s` one character at a time, rendering with `render`
607    /// between each character.
608    ///
609    /// Each character produces a [`KeyCode::Char`] event with no modifiers.
610    /// Focus state is preserved across characters.
611    ///
612    /// # Example
613    ///
614    /// ```
615    /// use slt::TestBackend;
616    ///
617    /// let mut tb = TestBackend::new(20, 3);
618    /// let mut typed = String::new();
619    /// tb.type_string("hi", |ui| {
620    ///     ui.text(&typed);
621    /// });
622    /// // 2 characters → 2 frames rendered.
623    /// drop(typed);
624    /// ```
625    pub fn type_string(&mut self, s: &str, mut render: impl FnMut(&mut Context)) {
626        for ch in s.chars() {
627            let events = vec![Event::Key(KeyEvent {
628                code: KeyCode::Char(ch),
629                modifiers: KeyModifiers::NONE,
630                kind: KeyEventKind::Press,
631            })];
632            // Use render_frame directly so frame recording is preserved and
633            // FrameState advances naturally between characters.
634            self.render_frame(events, |_| {}, &mut render);
635        }
636    }
637}
638
639/// A single step in a [`TestSequence`].
640///
641/// Holds the event batch to inject, plus a render closure to execute. Created
642/// internally by [`TestSequence::tick`], [`TestSequence::key`],
643/// [`TestSequence::events`], etc.
644struct TestStep<'a> {
645    events: Vec<Event>,
646    render: Box<dyn FnOnce(&mut Context) + 'a>,
647}
648
649/// Builder returned by [`TestBackend::sequence`].
650///
651/// Chain step builders (`tick`, `key`, `type_string`, `events`) and finalize
652/// with [`run`](TestSequence::run). Steps execute sequentially, advancing
653/// `FrameState` between them so focus and hooks evolve naturally without the
654/// caller having to thread state.
655pub struct TestSequence<'a> {
656    backend: &'a mut TestBackend,
657    steps: Vec<TestStep<'a>>,
658}
659
660impl<'a> TestSequence<'a> {
661    /// Append a step that renders without injecting any events.
662    ///
663    /// Equivalent to a single frame tick — useful for letting hooks /
664    /// animations advance between input steps.
665    pub fn tick(mut self, f: impl FnOnce(&mut Context) + 'a) -> Self {
666        self.steps.push(TestStep {
667            events: Vec::new(),
668            render: Box::new(f),
669        });
670        self
671    }
672
673    /// Append a step that fires a single key-press event with no modifiers.
674    pub fn key(mut self, code: KeyCode, f: impl FnOnce(&mut Context) + 'a) -> Self {
675        let events = vec![Event::Key(KeyEvent {
676            code,
677            modifiers: KeyModifiers::NONE,
678            kind: KeyEventKind::Press,
679        })];
680        self.steps.push(TestStep {
681            events,
682            render: Box::new(f),
683        });
684        self
685    }
686
687    /// Append a step that types `s` as a sequence of `KeyCode::Char` events
688    /// **before** invoking `render`.
689    ///
690    /// Unlike [`TestBackend::type_string`], this collapses every typed
691    /// character into a single render step — useful when the per-character
692    /// frame state is not the assertion target. For per-keystroke rendering,
693    /// chain individual `.key(...)` calls.
694    pub fn type_string(mut self, s: &str, f: impl FnOnce(&mut Context) + 'a) -> Self {
695        let events = s
696            .chars()
697            .map(|c| {
698                Event::Key(KeyEvent {
699                    code: KeyCode::Char(c),
700                    modifiers: KeyModifiers::NONE,
701                    kind: KeyEventKind::Press,
702                })
703            })
704            .collect();
705        self.steps.push(TestStep {
706            events,
707            render: Box::new(f),
708        });
709        self
710    }
711
712    /// Append a step with an arbitrary event batch.
713    ///
714    /// Useful for mouse interactions, paste events, or sequences built
715    /// with [`EventBuilder`].
716    pub fn events(mut self, events: Vec<Event>, f: impl FnOnce(&mut Context) + 'a) -> Self {
717        self.steps.push(TestStep {
718            events,
719            render: Box::new(f),
720        });
721        self
722    }
723
724    /// Execute every queued step in order. Returns control to the caller
725    /// (the [`TestBackend`] is borrowed mutably for the lifetime of the
726    /// sequence builder). Use [`TestBackend::buffer`] / `.frames()` /
727    /// `.assert_*` after `run()` returns.
728    pub fn run(self) {
729        let backend = self.backend;
730        for step in self.steps {
731            let TestStep { events, render } = step;
732            // Adapt FnOnce(&mut Context) into the &mut FnMut(&mut Context)
733            // shape that render_frame's internal trampoline already expects.
734            let mut once = Some(render);
735            let f = move |ui: &mut Context| {
736                if let Some(f) = once.take() {
737                    f(ui);
738                }
739            };
740            backend.render_frame(events, |_| {}, f);
741        }
742    }
743}
744
745impl std::fmt::Display for TestBackend {
746    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
747        write!(f, "{}", self.to_string_trimmed())
748    }
749}
750
751// ---------------------------------------------------------------------------
752// PtyBackend — end-to-end escape-byte / image-protocol capture (#274)
753// ---------------------------------------------------------------------------
754
755/// Raw bytes emitted for a single rendered frame by [`PtyBackend`].
756///
757/// Unlike [`FrameRecord`] (a glyph/snapshot view of the in-memory
758/// [`Buffer`]), `PtyFrame` holds the *actual* escape-code byte stream the
759/// production flush pipeline produced for the frame: SGR runs, OSC 8
760/// hyperlinks, Sixel (`\x1bPq`), and Kitty graphics (`\x1b_Ga=`).
761///
762/// Since 0.21.0.
763#[cfg(feature = "pty-test")]
764#[derive(Clone, Debug)]
765pub struct PtyFrame {
766    /// Raw bytes emitted for this frame (SGR runs, OSC 8, Sixel, Kitty).
767    pub raw: Vec<u8>,
768}
769
770/// Drives the *real* [`crate::run`] flush pipeline into an in-process byte
771/// sink, so escape-code / color-depth / image-protocol output is asserted
772/// end-to-end — the byte/protocol tier that [`TestBackend`]'s buffer-only
773/// model deliberately cannot reach (see `tests/visual_snapshots.rs`).
774///
775/// Each [`render`](PtyBackend::render) constructs a fresh fullscreen
776/// `Terminal` whose sink is a captured `Vec<u8>` (no real TTY, no raw mode),
777/// runs one frame through the same [`crate::frame_owned`] entry point the
778/// production loop uses, and captures the emitted bytes. Because the previous
779/// frame buffer starts empty, every frame emits a complete first-paint diff —
780/// fully deterministic and reproducible on a headless CI runner.
781///
782/// This type is gated behind the dev-only `pty-test` feature and is **not**
783/// present in a default build.
784///
785/// Since 0.21.0.
786///
787/// # Example
788///
789/// ```no_run
790/// # #[cfg(feature = "pty-test")]
791/// # {
792/// use slt::{Color, PtyBackend};
793///
794/// let mut pb = PtyBackend::new(10, 1);
795/// pb.render(|ui| {
796///     ui.text("x").fg(Color::Red).bold();
797/// });
798/// // The real flush pipeline emitted an SGR sequence for the styled glyph.
799/// pb.assert_emits("\u{1b}[");
800/// # }
801/// ```
802#[cfg(feature = "pty-test")]
803pub struct PtyBackend {
804    width: u32,
805    height: u32,
806    color_depth: crate::style::ColorDepth,
807    state: crate::AppState,
808    config: RunConfig,
809    frames: Vec<PtyFrame>,
810}
811
812#[cfg(feature = "pty-test")]
813impl PtyBackend {
814    /// Create a PTY capture backend with the given terminal dimensions.
815    ///
816    /// Defaults to [`ColorDepth::TrueColor`](crate::ColorDepth::TrueColor);
817    /// override with [`with_color_depth`](PtyBackend::with_color_depth).
818    pub fn new(width: u32, height: u32) -> Self {
819        Self {
820            width,
821            height,
822            color_depth: crate::style::ColorDepth::TrueColor,
823            state: crate::AppState::new(),
824            config: RunConfig::default(),
825            frames: Vec::new(),
826        }
827    }
828
829    /// Set the [`ColorDepth`](crate::ColorDepth) the flush pipeline encodes
830    /// SGR colors with (e.g. truecolor vs 256-color). Returns `self` for
831    /// chaining.
832    pub fn with_color_depth(mut self, depth: crate::style::ColorDepth) -> Self {
833        self.color_depth = depth;
834        self
835    }
836
837    /// Render one frame through the real `Terminal` flush pipeline, capturing
838    /// the emitted bytes. Returns the just-captured [`PtyFrame`].
839    pub fn render(&mut self, f: impl FnOnce(&mut Context)) -> &PtyFrame {
840        self.render_with_events(Vec::new(), f)
841    }
842
843    /// Render one frame with injected input `events`, capturing the emitted
844    /// bytes. Returns the just-captured [`PtyFrame`].
845    pub fn render_with_events(
846        &mut self,
847        events: Vec<Event>,
848        f: impl FnOnce(&mut Context),
849    ) -> &PtyFrame {
850        let mut term =
851            crate::terminal::Terminal::with_sink(self.width, self.height, self.color_depth);
852        let mut once = Some(f);
853        let mut render = move |ui: &mut Context| {
854            if let Some(f) = once.take() {
855                f(ui);
856            }
857        };
858        // Drive the production single-frame entry point. The captured-sink
859        // Terminal routes every byte through flush_buffer_diff /
860        // apply_style_delta / Sixel / Kitty exactly as a real terminal would.
861        let _ = crate::frame_owned(
862            &mut term,
863            &mut self.state,
864            &self.config,
865            events,
866            &mut render,
867        );
868        let raw = term.take_sink_bytes();
869        self.frames.push(PtyFrame { raw });
870        self.frames.last().expect("frame just pushed")
871    }
872
873    /// Iterate the raw byte stream of every captured frame, oldest first.
874    pub fn frames_raw(&self) -> impl Iterator<Item = &[u8]> {
875        self.frames.iter().map(|f| f.raw.as_slice())
876    }
877
878    /// Raw bytes of the most recently rendered frame.
879    ///
880    /// Panics if no frame has been rendered yet.
881    pub fn last_raw(&self) -> &[u8] {
882        &self.frames.last().expect("no frame rendered").raw
883    }
884
885    /// Assert the last frame's byte stream contains `needle`.
886    ///
887    /// Panics with an escaped + hex dump of the emitted bytes on a miss.
888    pub fn assert_emits(&self, needle: &str) {
889        let raw = self.last_raw();
890        if find_subslice(raw, needle.as_bytes()).is_none() {
891            panic!(
892                "PtyBackend frame does not emit {:?}.\nEmitted ({} bytes):\n  escaped: {}\n  hex: {}",
893                needle,
894                raw.len(),
895                escape_bytes(raw),
896                hex_bytes(raw),
897            );
898        }
899    }
900
901    /// Assert the last frame's byte stream does **not** contain `needle`.
902    ///
903    /// Panics with an escaped + hex dump on an unexpected hit.
904    pub fn assert_not_emits(&self, needle: &str) {
905        let raw = self.last_raw();
906        if find_subslice(raw, needle.as_bytes()).is_some() {
907            panic!(
908                "PtyBackend frame unexpectedly emits {:?}.\nEmitted ({} bytes):\n  escaped: {}\n  hex: {}",
909                needle,
910                raw.len(),
911                escape_bytes(raw),
912                hex_bytes(raw),
913            );
914        }
915    }
916}
917
918/// Byte-substring search (no UTF-8 assumption — escape streams are not valid
919/// UTF-8 in general).
920#[cfg(feature = "pty-test")]
921fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
922    if needle.is_empty() {
923        return Some(0);
924    }
925    haystack.windows(needle.len()).position(|w| w == needle)
926}
927
928/// Render a byte slice with non-printable bytes shown as `\xNN` escapes.
929#[cfg(feature = "pty-test")]
930fn escape_bytes(bytes: &[u8]) -> String {
931    let mut s = String::with_capacity(bytes.len());
932    for &b in bytes {
933        match b {
934            0x1b => s.push_str("\\x1b"),
935            0x20..=0x7e => s.push(b as char),
936            b'\n' => s.push_str("\\n"),
937            b'\r' => s.push_str("\\r"),
938            b'\t' => s.push_str("\\t"),
939            _ => s.push_str(&format!("\\x{b:02x}")),
940        }
941    }
942    s
943}
944
945/// Render a byte slice as space-separated two-digit hex.
946#[cfg(feature = "pty-test")]
947fn hex_bytes(bytes: &[u8]) -> String {
948    bytes
949        .iter()
950        .map(|b| format!("{b:02x}"))
951        .collect::<Vec<_>>()
952        .join(" ")
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958    use crate::event::{KeyEventKind, MouseKind};
959
960    /// Regression test for issue #131: `mouse_up` produces `MouseKind::Up(Left)`.
961    #[test]
962    fn event_builder_mouse_up_produces_up_event() {
963        let events = EventBuilder::new().mouse_up(5, 3).build();
964        assert_eq!(events.len(), 1);
965        match &events[0] {
966            Event::Mouse(m) => {
967                assert!(matches!(m.kind, MouseKind::Up(MouseButton::Left)));
968                assert_eq!(m.x, 5);
969                assert_eq!(m.y, 3);
970            }
971            _ => panic!("expected mouse event"),
972        }
973    }
974
975    /// Regression test for issue #131: `drag` produces a drag mouse event.
976    #[test]
977    fn event_builder_drag_produces_drag_event() {
978        let events = EventBuilder::new().drag(10, 5).build();
979        assert_eq!(events.len(), 1);
980        match &events[0] {
981            Event::Mouse(m) => {
982                assert!(matches!(m.kind, MouseKind::Drag(MouseButton::Left)));
983                assert_eq!(m.x, 10);
984                assert_eq!(m.y, 5);
985            }
986            _ => panic!("expected mouse event"),
987        }
988    }
989
990    /// Regression test for issue #131: `key_release` produces a release key event.
991    #[test]
992    fn event_builder_key_release_produces_release_event() {
993        let events = EventBuilder::new().key_release('a').build();
994        assert_eq!(events.len(), 1);
995        match &events[0] {
996            Event::Key(k) => {
997                assert_eq!(k.code, KeyCode::Char('a'));
998                assert!(matches!(k.kind, KeyEventKind::Release));
999            }
1000            _ => panic!("expected key event"),
1001        }
1002    }
1003
1004    /// Regression test for issue #131: focus_gained / focus_lost chain through builder.
1005    #[test]
1006    fn event_builder_focus_events_chaining() {
1007        let events = EventBuilder::new().focus_lost().focus_gained().build();
1008        assert_eq!(events, vec![Event::FocusLost, Event::FocusGained]);
1009    }
1010
1011    /// Issue #261: `key_modifier` builds a single modifier-only key-press event.
1012    #[test]
1013    fn event_builder_key_modifier_produces_modifier_event() {
1014        let events = EventBuilder::new()
1015            .key_modifier(ModifierKey::LeftSuper)
1016            .build();
1017        assert_eq!(events.len(), 1);
1018        match &events[0] {
1019            Event::Key(k) => {
1020                assert_eq!(k.code, KeyCode::Modifier(ModifierKey::LeftSuper));
1021                assert_eq!(k.modifiers, KeyModifiers::NONE);
1022                assert!(matches!(k.kind, KeyEventKind::Press));
1023            }
1024            _ => panic!("expected key event"),
1025        }
1026    }
1027
1028    /// Issue #261: a modifier-only event reaches the frame closure end-to-end.
1029    #[test]
1030    fn modifier_key_event_reaches_frame_closure() {
1031        let mut tb = TestBackend::new(20, 2);
1032        let events = EventBuilder::new()
1033            .key_modifier(ModifierKey::LeftCtrl)
1034            .build();
1035        tb.sequence()
1036            .events(events, |ui| {
1037                if ui.key_code(KeyCode::Modifier(ModifierKey::LeftCtrl)) {
1038                    ui.text("ctrl-down");
1039                } else {
1040                    ui.text("idle");
1041                }
1042            })
1043            .run();
1044        tb.assert_contains("ctrl-down");
1045    }
1046
1047    // ---- #229 record_frames -------------------------------------------------
1048
1049    #[test]
1050    fn record_frames_disabled_returns_empty_slice() {
1051        let mut tb = TestBackend::new(10, 2);
1052        tb.render(|ui| {
1053            ui.text("hi");
1054        });
1055        assert!(tb.frames().is_empty());
1056    }
1057
1058    #[test]
1059    fn record_frames_captures_each_render() {
1060        let mut tb = TestBackend::new(20, 2).record_frames();
1061        for n in 0..3 {
1062            tb.render(|ui| {
1063                ui.text(format!("frame {n}"));
1064            });
1065        }
1066        assert_eq!(tb.frames().len(), 3);
1067        tb.frames()[0].assert_contains("frame 0");
1068        tb.frames()[1].assert_contains("frame 1");
1069        tb.frames()[2].assert_contains("frame 2");
1070    }
1071
1072    #[test]
1073    fn record_frames_stores_styled_snapshot() {
1074        let mut tb = TestBackend::new(10, 1).record_frames();
1075        tb.render(|ui| {
1076            ui.text("hi").bold();
1077        });
1078        let frame = &tb.frames()[0];
1079        // Styled snapshot should encode the bold modifier somewhere.
1080        assert!(
1081            frame.snapshot.contains("bold"),
1082            "snapshot missing bold marker: {:?}",
1083            frame.snapshot
1084        );
1085    }
1086
1087    #[test]
1088    fn record_frames_idempotent_when_called_twice() {
1089        // record_frames() called twice must not wipe prior history.
1090        let tb = TestBackend::new(10, 1).record_frames();
1091        let mut tb = tb.record_frames();
1092        tb.render(|ui| {
1093            ui.text("a");
1094        });
1095        assert_eq!(tb.frames().len(), 1);
1096    }
1097
1098    #[test]
1099    fn frame_record_to_string_trimmed_drops_trailing_blank_rows() {
1100        let mut tb = TestBackend::new(10, 4).record_frames();
1101        tb.render(|ui| {
1102            ui.text("hello");
1103        });
1104        let frame = &tb.frames()[0];
1105        // The frame should have all 4 rows recorded.
1106        assert_eq!(frame.lines.len(), 4);
1107        // to_string_trimmed drops the trailing empty rows like TestBackend.
1108        let s = frame.to_string_trimmed();
1109        assert!(!s.ends_with('\n'));
1110        assert!(s.starts_with("hello"));
1111    }
1112
1113    // ---- #230 sequence + type_string ----------------------------------------
1114
1115    #[test]
1116    fn sequence_runs_multiple_steps_in_order() {
1117        let mut tb = TestBackend::new(20, 2).record_frames();
1118        tb.sequence()
1119            .tick(|ui| {
1120                ui.text("step-1");
1121            })
1122            .tick(|ui| {
1123                ui.text("step-2");
1124            })
1125            .tick(|ui| {
1126                ui.text("step-3");
1127            })
1128            .run();
1129        assert_eq!(tb.frames().len(), 3);
1130        tb.frames()[0].assert_contains("step-1");
1131        tb.frames()[1].assert_contains("step-2");
1132        tb.frames()[2].assert_contains("step-3");
1133    }
1134
1135    #[test]
1136    fn sequence_key_step_injects_event() {
1137        // We can't easily observe the key event without a stateful widget,
1138        // but we can confirm the sequence builder ran the render closure.
1139        let mut tb = TestBackend::new(20, 2);
1140        tb.sequence()
1141            .key(KeyCode::Esc, |ui| {
1142                ui.text("after-esc");
1143            })
1144            .run();
1145        tb.assert_contains("after-esc");
1146    }
1147
1148    #[test]
1149    fn sequence_type_string_collapses_into_single_step() {
1150        let mut tb = TestBackend::new(20, 2).record_frames();
1151        tb.sequence()
1152            .type_string("abc", |ui| {
1153                ui.text("done");
1154            })
1155            .run();
1156        // Sequence's type_string is one step → one frame, not three.
1157        assert_eq!(tb.frames().len(), 1);
1158        tb.frames()[0].assert_contains("done");
1159    }
1160
1161    #[test]
1162    fn sequence_events_step_takes_arbitrary_batch() {
1163        let mut tb = TestBackend::new(20, 2);
1164        let events = EventBuilder::new()
1165            .key('a')
1166            .key_code(KeyCode::Enter)
1167            .build();
1168        tb.sequence()
1169            .events(events, |ui| {
1170                ui.text("ran");
1171            })
1172            .run();
1173        tb.assert_contains("ran");
1174    }
1175
1176    #[test]
1177    fn type_string_renders_one_frame_per_char() {
1178        let mut tb = TestBackend::new(20, 2).record_frames();
1179        tb.type_string("abc", |ui| {
1180            ui.text("char");
1181        });
1182        assert_eq!(tb.frames().len(), 3);
1183    }
1184
1185    #[test]
1186    fn type_string_handles_empty_input() {
1187        let mut tb = TestBackend::new(20, 2).record_frames();
1188        tb.type_string("", |ui| {
1189            ui.text("never-called");
1190        });
1191        assert_eq!(tb.frames().len(), 0);
1192    }
1193
1194    // ---- #232 negative assertions ------------------------------------------
1195
1196    #[test]
1197    fn assert_not_contains_passes_when_absent() {
1198        let mut tb = TestBackend::new(20, 2);
1199        tb.render(|ui| {
1200            ui.text("hello world");
1201        });
1202        tb.assert_not_contains("error");
1203    }
1204
1205    #[test]
1206    #[should_panic(expected = "Buffer unexpectedly contains")]
1207    fn assert_not_contains_panics_when_present() {
1208        let mut tb = TestBackend::new(20, 2);
1209        tb.render(|ui| {
1210            ui.text("error: fail");
1211        });
1212        tb.assert_not_contains("error");
1213    }
1214
1215    #[test]
1216    fn assert_line_not_contains_passes_when_other_row_has_substring() {
1217        let mut tb = TestBackend::new(20, 3);
1218        tb.render(|ui| {
1219            let _ = ui.col(|ui| {
1220                ui.text("first");
1221                ui.text("second");
1222            });
1223        });
1224        // Line 0 has "first" but not "second".
1225        tb.assert_line_not_contains(0, "second");
1226    }
1227
1228    #[test]
1229    #[should_panic(expected = "Line 0: expected NOT to contain")]
1230    fn assert_line_not_contains_panics_when_present() {
1231        let mut tb = TestBackend::new(20, 1);
1232        tb.render(|ui| {
1233            ui.text("hello");
1234        });
1235        tb.assert_line_not_contains(0, "ello");
1236    }
1237
1238    #[test]
1239    fn assert_empty_line_passes_for_blank_row() {
1240        let mut tb = TestBackend::new(20, 2);
1241        tb.render(|ui| {
1242            ui.text("only-row-0");
1243        });
1244        // Row 1 is untouched after rendering one text → blank.
1245        tb.assert_empty_line(1);
1246    }
1247
1248    #[test]
1249    #[should_panic(expected = "Line 0: expected empty")]
1250    fn assert_empty_line_panics_when_non_blank() {
1251        let mut tb = TestBackend::new(20, 2);
1252        tb.render(|ui| {
1253            ui.text("not-empty");
1254        });
1255        tb.assert_empty_line(0);
1256    }
1257
1258    #[test]
1259    fn assert_style_at_passes_for_matching_style() {
1260        use crate::style::{Color, Modifiers};
1261        let mut tb = TestBackend::new(10, 1);
1262        tb.render(|ui| {
1263            ui.text("x").fg(Color::Red);
1264        });
1265        let expected = Style {
1266            fg: Some(Color::Red),
1267            bg: None,
1268            modifiers: Modifiers::NONE,
1269            ..Style::new()
1270        };
1271        tb.assert_style_at(0, 0, expected);
1272    }
1273
1274    #[test]
1275    #[should_panic(expected = "Style mismatch")]
1276    fn assert_style_at_panics_on_mismatch() {
1277        use crate::style::Color;
1278        let mut tb = TestBackend::new(10, 1);
1279        tb.render(|ui| {
1280            ui.text("x").fg(Color::Red);
1281        });
1282        let expected = Style::new().fg(Color::Blue);
1283        tb.assert_style_at(0, 0, expected);
1284    }
1285}