envision 0.10.1

A ratatui framework for collaborative TUI development with headless testing support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Core test harness implementation.

use ratatui::Terminal;

use crate::error;

use crate::annotation::{with_annotations, AnnotationRegistry, RegionInfo, WidgetType};
use crate::backend::CaptureBackend;
use crate::input::{Event, EventQueue};

use super::assertions::{Assertion, AssertionError, AssertionResult};
use super::snapshot::Snapshot;

/// Test harness for headless TUI testing.
///
/// The harness provides a unified interface for:
/// - Rendering UI to a capture backend
/// - Simulating user input
/// - Querying rendered content and annotations
/// - Making assertions about UI state
///
/// # Example
///
/// ```rust
/// use envision::harness::TestHarness;
/// use ratatui::widgets::Paragraph;
///
/// let mut harness = TestHarness::new(80, 24);
///
/// harness.render(|frame| {
///     frame.render_widget(Paragraph::new("Test"), frame.area());
/// }).unwrap();
///
/// assert!(harness.contains("Test"));
/// ```
pub struct TestHarness {
    terminal: Terminal<CaptureBackend>,
    events: EventQueue,
    annotations: AnnotationRegistry,
    frame_count: u64,
}

impl TestHarness {
    /// Creates a new test harness with the given dimensions.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::harness::TestHarness;
    ///
    /// let harness = TestHarness::new(80, 24);
    /// assert_eq!(harness.width(), 80);
    /// assert_eq!(harness.height(), 24);
    /// ```
    pub fn new(width: u16, height: u16) -> Self {
        let backend = CaptureBackend::new(width, height);
        let terminal = Terminal::new(backend).expect("Failed to create terminal");

        Self {
            terminal,
            events: EventQueue::new(),
            annotations: AnnotationRegistry::new(),
            frame_count: 0,
        }
    }

    /// Returns the width of the terminal.
    pub fn width(&self) -> u16 {
        self.terminal.backend().width()
    }

    /// Returns the height of the terminal.
    pub fn height(&self) -> u16 {
        self.terminal.backend().height()
    }

    /// Returns the current frame count.
    pub fn frame_count(&self) -> u64 {
        self.frame_count
    }

    // -------------------------------------------------------------------------
    // Rendering
    // -------------------------------------------------------------------------

    /// Renders a frame using the provided closure.
    ///
    /// This collects annotations during rendering and increments the frame count.
    ///
    /// # Errors
    ///
    /// This method currently always succeeds, but returns `Result`
    /// for API consistency with terminal rendering operations.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::harness::TestHarness;
    /// use ratatui::widgets::Paragraph;
    ///
    /// let mut harness = TestHarness::new(80, 24);
    /// harness.render(|frame| {
    ///     frame.render_widget(Paragraph::new("Hello!"), frame.area());
    /// })?;
    /// assert!(harness.contains("Hello!"));
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn render<F>(&mut self, f: F) -> error::Result<()>
    where
        F: FnOnce(&mut ratatui::Frame),
    {
        self.annotations = with_annotations(|| {
            self.terminal.draw(f).expect("Failed to draw");
        });
        self.frame_count += 1;
        Ok(())
    }

    /// Returns the current terminal content as plain text.
    pub fn screen(&self) -> String {
        self.terminal.backend().to_string()
    }

    /// Returns the content of a specific row.
    pub fn row(&self, y: u16) -> String {
        self.terminal.backend().row_content(y)
    }

    /// Returns a snapshot of the current frame.
    pub fn snapshot(&self) -> Snapshot {
        Snapshot::new(self.terminal.backend().snapshot(), self.annotations.clone())
    }

    /// Returns the cell at the given position, or `None` if out of bounds.
    ///
    /// Use this to assert on cell styling:
    /// ```rust
    /// use envision::harness::TestHarness;
    ///
    /// let harness = TestHarness::new(80, 24);
    /// let cell = harness.cell_at(5, 3);
    /// assert!(cell.is_some());
    /// ```
    pub fn cell_at(&self, x: u16, y: u16) -> Option<&crate::backend::EnhancedCell> {
        self.terminal.backend().cell(x, y)
    }

    /// Returns a reference to the backend.
    pub fn backend(&self) -> &CaptureBackend {
        self.terminal.backend()
    }

    /// Returns a mutable reference to the backend.
    pub fn backend_mut(&mut self) -> &mut CaptureBackend {
        self.terminal.backend_mut()
    }

    // -------------------------------------------------------------------------
    // Input Simulation
    // -------------------------------------------------------------------------

    /// Returns a reference to the event queue.
    pub fn events(&self) -> &EventQueue {
        &self.events
    }

    /// Returns a mutable reference to the event queue.
    pub fn events_mut(&mut self) -> &mut EventQueue {
        &mut self.events
    }

    /// Queues a single event.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::harness::TestHarness;
    /// use envision::input::{Event, KeyCode};
    ///
    /// let mut harness = TestHarness::new(80, 24);
    /// harness.push_event(Event::key(KeyCode::Enter));
    /// let event = harness.pop_event();
    /// assert!(event.is_some());
    /// ```
    pub fn push_event(&mut self, event: Event) {
        self.events.push(event);
    }

    /// Pops the next event from the queue.
    pub fn pop_event(&mut self) -> Option<Event> {
        self.events.pop()
    }

    /// Types a string as keyboard input.
    ///
    /// Each character is enqueued as a separate key event.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::harness::TestHarness;
    ///
    /// let mut harness = TestHarness::new(80, 24);
    /// harness.type_str("hello");
    /// // 5 key events are now queued
    /// ```
    pub fn type_str(&mut self, s: &str) {
        self.events.type_str(s);
    }

    /// Simulates pressing Enter.
    pub fn enter(&mut self) {
        self.events.enter();
    }

    /// Simulates pressing Escape.
    pub fn escape(&mut self) {
        self.events.escape();
    }

    /// Simulates pressing Tab.
    pub fn tab(&mut self) {
        self.events.tab();
    }

    /// Simulates `Ctrl+<key>`.
    pub fn ctrl(&mut self, c: char) {
        self.events.ctrl(c);
    }

    /// Simulates a mouse click at the given position.
    pub fn click(&mut self, x: u16, y: u16) {
        self.events.click(x, y);
    }

    /// Clears all pending events.
    pub fn clear_events(&mut self) {
        self.events.clear();
    }

    // -------------------------------------------------------------------------
    // Annotations
    // -------------------------------------------------------------------------

    /// Returns a reference to the annotation registry.
    pub fn annotations(&self) -> &AnnotationRegistry {
        &self.annotations
    }

    /// Returns the region at the given position.
    pub fn region_at(&self, x: u16, y: u16) -> Option<&RegionInfo> {
        self.annotations.region_at(x, y)
    }

    /// Finds regions by id.
    pub fn find_by_id(&self, id: &str) -> Vec<&RegionInfo> {
        self.annotations.find_by_id(id)
    }

    /// Gets the first region with the given id.
    pub fn get_by_id(&self, id: &str) -> Option<&RegionInfo> {
        self.annotations.get_by_id(id)
    }

    /// Finds regions by widget type.
    pub fn find_by_type(&self, widget_type: &WidgetType) -> Vec<&RegionInfo> {
        self.annotations.find_by_type(widget_type)
    }

    /// Returns the currently focused region.
    pub fn focused(&self) -> Option<&RegionInfo> {
        self.annotations.focused_region()
    }

    /// Returns all interactive regions.
    pub fn interactive(&self) -> Vec<&RegionInfo> {
        self.annotations.interactive_regions()
    }

    /// Clicks on a widget by id.
    ///
    /// Returns true if the widget was found and clicked.
    pub fn click_on(&mut self, id: &str) -> bool {
        if let Some(region) = self.annotations.get_by_id(id) {
            let x = region.area.x + region.area.width / 2;
            let y = region.area.y + region.area.height / 2;
            self.click(x, y);
            true
        } else {
            false
        }
    }

    // -------------------------------------------------------------------------
    // Content Queries
    // -------------------------------------------------------------------------

    /// Returns true if the screen contains the given text.
    ///
    /// # Example
    ///
    /// ```rust
    /// use envision::harness::TestHarness;
    /// use ratatui::widgets::Paragraph;
    ///
    /// let mut harness = TestHarness::new(80, 24);
    /// harness.render(|frame| {
    ///     frame.render_widget(Paragraph::new("Search"), frame.area());
    /// }).unwrap();
    /// assert!(harness.contains("Search"));
    /// assert!(!harness.contains("Missing"));
    /// ```
    pub fn contains(&self, needle: &str) -> bool {
        self.terminal.backend().contains_text(needle)
    }

    /// Finds the first position of text on screen.
    pub fn find_text(&self, needle: &str) -> Option<(u16, u16)> {
        self.terminal
            .backend()
            .find_text(needle)
            .first()
            .map(|p| (p.x, p.y))
    }

    /// Finds all positions of text on screen.
    pub fn find_all_text(&self, needle: &str) -> Vec<(u16, u16)> {
        self.terminal
            .backend()
            .find_text(needle)
            .iter()
            .map(|p| (p.x, p.y))
            .collect()
    }

    /// Returns the content within a rectangular region.
    pub fn region_content(&self, x: u16, y: u16, width: u16, height: u16) -> String {
        let mut lines = Vec::new();
        for row in y..y.saturating_add(height) {
            let row_content = self.row(row);
            let start = x as usize;
            let end = (x + width) as usize;
            if start < row_content.len() {
                let end = end.min(row_content.len());
                lines.push(row_content[start..end].to_string());
            }
        }
        lines.join("\n")
    }

    // -------------------------------------------------------------------------
    // Assertions
    // -------------------------------------------------------------------------

    /// Asserts that the screen contains the given text.
    ///
    /// # Panics
    ///
    /// Panics if the text is not found.
    pub fn assert_contains(&self, needle: &str) {
        if !self.contains(needle) {
            panic!(
                "Expected screen to contain '{}', but it was not found.\n\nScreen:\n{}",
                needle,
                self.screen()
            );
        }
    }

    /// Asserts that the screen does not contain the given text.
    ///
    /// # Panics
    ///
    /// Panics if the text is found.
    pub fn assert_not_contains(&self, needle: &str) {
        if self.contains(needle) {
            panic!(
                "Expected screen to NOT contain '{}', but it was found.\n\nScreen:\n{}",
                needle,
                self.screen()
            );
        }
    }

    /// Asserts that a widget with the given id exists.
    ///
    /// # Panics
    ///
    /// Panics if the widget is not found.
    pub fn assert_widget_exists(&self, id: &str) {
        if self.get_by_id(id).is_none() {
            panic!(
                "Expected widget with id '{}' to exist, but it was not found.\n\nAnnotations:\n{}",
                id,
                self.annotations.format_tree()
            );
        }
    }

    /// Asserts that a widget with the given id does not exist.
    ///
    /// # Panics
    ///
    /// Panics if the widget is found.
    pub fn assert_widget_not_exists(&self, id: &str) {
        if self.get_by_id(id).is_some() {
            panic!(
                "Expected widget with id '{}' to NOT exist, but it was found.\n\nAnnotations:\n{}",
                id,
                self.annotations.format_tree()
            );
        }
    }

    /// Asserts that a widget with the given id is focused.
    ///
    /// # Panics
    ///
    /// Panics if the widget is not focused or doesn't exist.
    pub fn assert_focused(&self, id: &str) {
        match self.get_by_id(id) {
            Some(region) if region.annotation.focused => {}
            Some(_) => panic!(
                "Expected widget '{}' to be focused, but it is not.\n\nAnnotations:\n{}",
                id,
                self.annotations.format_tree()
            ),
            None => panic!(
                "Expected widget '{}' to be focused, but it doesn't exist.\n\nAnnotations:\n{}",
                id,
                self.annotations.format_tree()
            ),
        }
    }

    /// Runs an assertion and returns the result.
    ///
    /// # Errors
    ///
    /// Returns an [`AssertionError`] if the assertion condition is not met.
    pub fn assert(&self, assertion: Assertion) -> AssertionResult {
        assertion.check(self)
    }

    /// Runs multiple assertions and returns all results.
    pub fn assert_all(&self, assertions: Vec<Assertion>) -> Vec<AssertionResult> {
        assertions.into_iter().map(|a| self.assert(a)).collect()
    }

    /// Runs multiple assertions, returning the first failure if any.
    ///
    /// # Errors
    ///
    /// Returns an [`AssertionError`] from the first assertion that fails.
    pub fn assert_all_ok(&self, assertions: Vec<Assertion>) -> Result<(), AssertionError> {
        for assertion in assertions {
            self.assert(assertion)?;
        }
        Ok(())
    }
}

impl Default for TestHarness {
    fn default() -> Self {
        Self::new(80, 24)
    }
}

#[cfg(test)]
mod tests;