aprender-test-lib 0.34.0

Probar: Rust-native testing framework with pixel coverage, TUI snapshots, and visual regression
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! TUI Test Backend for Frame Capture
//!
//! Provides a test backend that captures frames for assertion.
//! Uses TextGrid instead of presentar-terminal CellBuffer for zero external dependencies.
//!
//! ## EXTREME TDD: Tests written FIRST per spec

use super::buffer::TextGrid;
use crate::result::{ProbarError, ProbarResult};
use serde::{Deserialize, Serialize};
use std::fmt;

/// A captured TUI frame for testing
#[derive(Clone, Serialize, Deserialize)]
pub struct TuiFrame {
    /// The buffer content
    content: Vec<String>,
    /// Frame width
    width: u16,
    /// Frame height
    height: u16,
    /// Timestamp when captured (milliseconds from test start)
    timestamp_ms: u64,
}

impl TuiFrame {
    /// Create a new TUI frame from a TextGrid
    #[must_use]
    pub fn from_grid(grid: &TextGrid, timestamp_ms: u64) -> Self {
        Self {
            content: grid.to_lines(),
            width: grid.width(),
            height: grid.height(),
            timestamp_ms,
        }
    }

    /// Create a frame from raw text lines
    #[must_use]
    pub fn from_lines(lines: &[&str]) -> Self {
        let height = lines.len() as u16;
        // Count characters, not bytes (important for Unicode TUI content)
        let width = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0) as u16;
        let content = lines.iter().map(|s| (*s).to_string()).collect();

        Self {
            content,
            width,
            height,
            timestamp_ms: 0,
        }
    }

    /// Get the frame width
    #[must_use]
    pub fn width(&self) -> u16 {
        self.width
    }

    /// Get the frame height
    #[must_use]
    pub fn height(&self) -> u16 {
        self.height
    }

    /// Get the timestamp
    #[must_use]
    pub fn timestamp_ms(&self) -> u64 {
        self.timestamp_ms
    }

    /// Get the frame content as lines
    #[must_use]
    pub fn lines(&self) -> &[String] {
        &self.content
    }

    /// Get the full frame content as a single string
    #[must_use]
    pub fn as_text(&self) -> String {
        self.content.join("\n")
    }

    /// Check if the frame contains a substring
    #[must_use]
    pub fn contains(&self, text: &str) -> bool {
        self.content.iter().any(|line| line.contains(text))
    }

    /// Check if the frame matches a regex pattern
    #[must_use]
    pub fn matches(&self, pattern: &str) -> ProbarResult<bool> {
        let re = regex::Regex::new(pattern).map_err(|e| ProbarError::TuiError {
            message: format!("Invalid regex pattern: {e}"),
        })?;
        Ok(self.content.iter().any(|line| re.is_match(line)))
    }

    /// Find all lines matching a pattern
    #[must_use]
    pub fn find_matches(&self, pattern: &str) -> ProbarResult<Vec<&str>> {
        let re = regex::Regex::new(pattern).map_err(|e| ProbarError::TuiError {
            message: format!("Invalid regex pattern: {e}"),
        })?;
        Ok(self
            .content
            .iter()
            .filter(|line| re.is_match(line))
            .map(String::as_str)
            .collect())
    }

    /// Get a specific line by index
    #[must_use]
    pub fn line(&self, index: usize) -> Option<&str> {
        self.content.get(index).map(String::as_str)
    }

    /// Check if two frames are identical
    #[must_use]
    pub fn is_identical(&self, other: &TuiFrame) -> bool {
        self.content == other.content
    }

    /// Get the difference between two frames
    #[must_use]
    pub fn diff(&self, other: &TuiFrame) -> FrameDiff {
        let mut changed_lines = Vec::new();

        let max_lines = self.content.len().max(other.content.len());
        for i in 0..max_lines {
            let self_line = self.content.get(i).map(String::as_str).unwrap_or("");
            let other_line = other.content.get(i).map(String::as_str).unwrap_or("");

            if self_line != other_line {
                changed_lines.push(LineDiff {
                    line_number: i,
                    expected: self_line.to_string(),
                    actual: other_line.to_string(),
                });
            }
        }

        FrameDiff {
            is_identical: changed_lines.is_empty(),
            changed_lines,
        }
    }
}

impl fmt::Debug for TuiFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "TuiFrame({}x{}):", self.width, self.height)?;
        for (i, line) in self.content.iter().enumerate() {
            writeln!(f, "  {i:3}: {line}")?;
        }
        Ok(())
    }
}

/// Difference between two frames
#[derive(Debug, Clone)]
pub struct FrameDiff {
    /// Whether frames are identical
    pub is_identical: bool,
    /// Lines that differ
    pub changed_lines: Vec<LineDiff>,
}

/// A single line difference
#[derive(Debug, Clone)]
pub struct LineDiff {
    /// Line number (0-indexed)
    pub line_number: usize,
    /// Expected content
    pub expected: String,
    /// Actual content
    pub actual: String,
}

impl fmt::Display for FrameDiff {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_identical {
            write!(f, "Frames are identical")
        } else {
            writeln!(f, "Frame differences:")?;
            for diff in &self.changed_lines {
                writeln!(f, "  Line {}: ", diff.line_number)?;
                writeln!(f, "    Expected: {:?}", diff.expected)?;
                writeln!(f, "    Actual:   {:?}", diff.actual)?;
            }
            Ok(())
        }
    }
}

/// TUI Test Backend for capturing frames
///
/// Provides a text grid and frame capture functionality for testing terminal UIs.
/// Uses TextGrid instead of presentar-terminal CellBuffer for zero external dependencies.
#[derive(Debug)]
pub struct TuiTestBackend {
    grid: TextGrid,
    frames: Vec<TuiFrame>,
    start_time: std::time::Instant,
}

impl TuiTestBackend {
    /// Create a new test backend with the given dimensions
    #[must_use]
    pub fn new(width: u16, height: u16) -> Self {
        Self {
            grid: TextGrid::new(width, height),
            frames: Vec::new(),
            start_time: std::time::Instant::now(),
        }
    }

    /// Get the backend dimensions
    #[must_use]
    pub fn size(&self) -> (u16, u16) {
        (self.grid.width(), self.grid.height())
    }

    /// Get a reference to the underlying grid
    #[must_use]
    pub fn grid(&self) -> &TextGrid {
        &self.grid
    }

    /// Get a mutable reference to the underlying grid
    #[must_use]
    pub fn grid_mut(&mut self) -> &mut TextGrid {
        &mut self.grid
    }

    /// Capture the current frame
    pub fn capture_frame(&mut self) -> TuiFrame {
        let timestamp = self.start_time.elapsed().as_millis() as u64;
        let frame = TuiFrame::from_grid(&self.grid, timestamp);
        self.frames.push(frame.clone());
        frame
    }

    /// Get the current frame without storing it
    #[must_use]
    pub fn current_frame(&self) -> TuiFrame {
        let timestamp = self.start_time.elapsed().as_millis() as u64;
        TuiFrame::from_grid(&self.grid, timestamp)
    }

    /// Get all captured frames
    #[must_use]
    pub fn frames(&self) -> &[TuiFrame] {
        &self.frames
    }

    /// Get the number of captured frames
    #[must_use]
    pub fn frame_count(&self) -> usize {
        self.frames.len()
    }

    /// Clear the grid
    pub fn clear(&mut self) {
        self.grid.clear();
    }

    /// Reset the backend (clear grid and frames)
    pub fn reset(&mut self) {
        self.grid.clear();
        self.frames.clear();
        self.start_time = std::time::Instant::now();
    }

    /// Resize the backend
    pub fn resize(&mut self, width: u16, height: u16) {
        self.grid.resize(width, height);
    }

    /// Write text at a position (for testing)
    pub fn write_text(&mut self, x: u16, y: u16, text: &str) {
        self.grid.write_str(x, y, text);
    }

    /// Write multiple lines starting at a position
    pub fn write_lines(&mut self, x: u16, y: u16, lines: &[&str]) {
        for (i, line) in lines.iter().enumerate() {
            self.grid.write_str(x, y + i as u16, line);
        }
    }
}

impl Default for TuiTestBackend {
    fn default() -> Self {
        Self::new(80, 24) // Standard terminal size
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    mod tui_frame_tests {
        use super::*;

        #[test]
        fn test_from_lines() {
            let frame = TuiFrame::from_lines(&["Hello", "World"]);
            assert_eq!(frame.width(), 5);
            assert_eq!(frame.height(), 2);
            assert_eq!(frame.lines(), &["Hello", "World"]);
        }

        #[test]
        fn test_from_grid() {
            let mut grid = TextGrid::new(10, 3);
            grid.write_str(0, 0, "Hello");
            grid.write_str(0, 1, "World");

            let frame = TuiFrame::from_grid(&grid, 100);
            assert_eq!(frame.width(), 10);
            assert_eq!(frame.height(), 3);
            assert_eq!(frame.timestamp_ms(), 100);
            assert!(frame.contains("Hello"));
            assert!(frame.contains("World"));
        }

        #[test]
        fn test_as_text() {
            let frame = TuiFrame::from_lines(&["Line 1", "Line 2"]);
            assert_eq!(frame.as_text(), "Line 1\nLine 2");
        }

        #[test]
        fn test_contains() {
            let frame = TuiFrame::from_lines(&["Hello World", "Goodbye"]);
            assert!(frame.contains("World"));
            assert!(frame.contains("Goodbye"));
            assert!(!frame.contains("Missing"));
        }

        #[test]
        fn test_matches_regex() {
            let frame = TuiFrame::from_lines(&["Score: 100", "Lives: 3"]);
            assert!(frame.matches(r"Score: \d+").unwrap());
            assert!(frame.matches(r"Lives: \d").unwrap());
            assert!(!frame.matches(r"Health: \d+").unwrap());
        }

        #[test]
        fn test_find_matches() {
            let frame = TuiFrame::from_lines(&["Error: failed", "Warning: slow", "Info: ok"]);
            let errors = frame.find_matches(r"Error:.*").unwrap();
            assert_eq!(errors.len(), 1);
            assert_eq!(errors[0], "Error: failed");
        }

        #[test]
        fn test_line_access() {
            let frame = TuiFrame::from_lines(&["First", "Second", "Third"]);
            assert_eq!(frame.line(0), Some("First"));
            assert_eq!(frame.line(1), Some("Second"));
            assert_eq!(frame.line(2), Some("Third"));
            assert_eq!(frame.line(3), None);
        }

        #[test]
        fn test_is_identical() {
            let frame1 = TuiFrame::from_lines(&["Same", "Content"]);
            let frame2 = TuiFrame::from_lines(&["Same", "Content"]);
            let frame3 = TuiFrame::from_lines(&["Different", "Content"]);

            assert!(frame1.is_identical(&frame2));
            assert!(!frame1.is_identical(&frame3));
        }

        #[test]
        fn test_diff() {
            let frame1 = TuiFrame::from_lines(&["Same", "Different1"]);
            let frame2 = TuiFrame::from_lines(&["Same", "Different2"]);

            let diff = frame1.diff(&frame2);
            assert!(!diff.is_identical);
            assert_eq!(diff.changed_lines.len(), 1);
            assert_eq!(diff.changed_lines[0].line_number, 1);
            assert_eq!(diff.changed_lines[0].expected, "Different1");
            assert_eq!(diff.changed_lines[0].actual, "Different2");
        }

        #[test]
        fn test_diff_identical() {
            let frame1 = TuiFrame::from_lines(&["Same", "Same"]);
            let frame2 = TuiFrame::from_lines(&["Same", "Same"]);

            let diff = frame1.diff(&frame2);
            assert!(diff.is_identical);
            assert!(diff.changed_lines.is_empty());
        }
    }

    mod tui_test_backend_tests {
        use super::*;

        #[test]
        fn test_new() {
            let backend = TuiTestBackend::new(80, 24);
            assert_eq!(backend.size(), (80, 24));
            assert_eq!(backend.frame_count(), 0);
        }

        #[test]
        fn test_default() {
            let backend = TuiTestBackend::default();
            assert_eq!(backend.size(), (80, 24));
        }

        #[test]
        fn test_write_text() {
            let mut backend = TuiTestBackend::new(20, 5);
            backend.write_text(0, 0, "Hello");

            let frame = backend.current_frame();
            assert!(frame.contains("Hello"));
        }

        #[test]
        fn test_write_lines() {
            let mut backend = TuiTestBackend::new(20, 5);
            backend.write_lines(0, 0, &["Line 1", "Line 2"]);

            let frame = backend.current_frame();
            assert!(frame.contains("Line 1"));
            assert!(frame.contains("Line 2"));
        }

        #[test]
        fn test_capture_frame() {
            let mut backend = TuiTestBackend::new(20, 5);
            backend.write_text(0, 0, "Test");

            let frame = backend.capture_frame();
            assert!(frame.contains("Test"));
            assert_eq!(backend.frame_count(), 1);

            backend.write_text(0, 1, "More");
            let _ = backend.capture_frame();
            assert_eq!(backend.frame_count(), 2);
        }

        #[test]
        fn test_frames() {
            let mut backend = TuiTestBackend::new(20, 5);

            backend.write_text(0, 0, "Frame1");
            let _ = backend.capture_frame();

            backend.write_text(0, 1, "Frame2");
            let _ = backend.capture_frame();

            let frames = backend.frames();
            assert_eq!(frames.len(), 2);
            assert!(frames[0].contains("Frame1"));
            assert!(frames[1].contains("Frame2"));
        }

        #[test]
        fn test_clear() {
            let mut backend = TuiTestBackend::new(20, 5);
            backend.write_text(0, 0, "Hello");
            backend.clear();

            let frame = backend.current_frame();
            assert!(!frame.contains("Hello"));
        }

        #[test]
        fn test_reset() {
            let mut backend = TuiTestBackend::new(20, 5);
            backend.write_text(0, 0, "Hello");
            let _ = backend.capture_frame();

            backend.reset();
            assert_eq!(backend.frame_count(), 0);
            assert!(!backend.current_frame().contains("Hello"));
        }

        #[test]
        fn test_resize() {
            let mut backend = TuiTestBackend::new(20, 5);
            backend.resize(40, 10);
            assert_eq!(backend.size(), (40, 10));
        }

        #[test]
        fn test_grid_access() {
            let mut backend = TuiTestBackend::new(20, 5);

            // Test grid() accessor
            assert_eq!(backend.grid().width(), 20);

            // Test grid_mut() accessor
            backend.grid_mut().set(0, 0, 'X');
            assert_eq!(backend.grid().get(0, 0), Some('X'));
        }
    }
}