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
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
//! Application test harness for TEA applications with time control.
//!
//! This harness wraps `Runtime` and provides deterministic testing
//! capabilities using tokio's time control features.
//!
//! # Time Control
//!
//! When using `#[tokio::test(start_paused = true)]`, time is paused and
//! you can use `advance_time()` to manually advance the clock. This enables
//! deterministic testing of async operations and timers.
//!
//! # Example
//!
//! ```rust
//! # use envision::prelude::*;
//! # struct MyApp;
//! # #[derive(Default, Clone)]
//! # struct MyState;
//! # #[derive(Clone)]
//! # enum MyMsg {}
//! # impl App for MyApp {
//! #     type State = MyState;
//! #     type Message = MyMsg;
//! #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
//! #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
//! #     fn view(state: &MyState, frame: &mut Frame) {}
//! # }
//! use envision::harness::AppHarness;
//!
//! let mut harness = AppHarness::<MyApp>::new(80, 24)?;
//! harness.tick()?;
//! # Ok::<(), envision::EnvisionError>(())
//! ```

use ratatui::layout::Position;

use crate::error;
use tokio_util::sync::CancellationToken;

use crate::app::{App, BoxedSubscription, Command, Runtime, RuntimeConfig, Subscription};
use crate::backend::CaptureBackend;
use crate::input::{Event, EventQueue};

/// Application test harness for TEA applications.
///
/// This harness provides:
/// - Time control for deterministic async testing
/// - Convenient dispatch and assertion methods
/// - Access to the underlying runtime and state
pub struct AppHarness<A: App> {
    runtime: Runtime<A, CaptureBackend>,
}

impl<A: App> AppHarness<A> {
    /// Creates a new async test harness with the given dimensions.
    ///
    /// Note: For time control, use `#[tokio::test(start_paused = true)]`.
    ///
    /// # Errors
    ///
    /// Returns an error if creating the virtual terminal fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// use envision::harness::AppHarness;
    ///
    /// let harness = AppHarness::<MyApp>::new(80, 24)?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn new(width: u16, height: u16) -> error::Result<Self> {
        let runtime = Runtime::virtual_terminal(width, height)?;
        Ok(Self { runtime })
    }

    /// Creates a new async test harness with custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if creating the virtual terminal fails.
    pub fn with_config(width: u16, height: u16, config: RuntimeConfig) -> error::Result<Self> {
        let runtime = Runtime::virtual_terminal_with_config(width, height, config)?;
        Ok(Self { runtime })
    }

    /// Creates a test harness with a pre-built state, bypassing [`App::init()`].
    ///
    /// This is useful for testing specific application states without
    /// constructing them through the normal initialization path.
    ///
    /// # Errors
    ///
    /// Returns an error if creating the virtual terminal fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # use envision::harness::AppHarness;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState { count: i32 }
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState::default(), Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// let state = MyState { count: 42 };
    /// let harness = AppHarness::<MyApp>::with_state(80, 24, state, Command::none())?;
    /// assert_eq!(harness.state().count, 42);
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn with_state(
        width: u16,
        height: u16,
        state: A::State,
        init_cmd: Command<A::Message>,
    ) -> error::Result<Self> {
        let runtime = Runtime::virtual_terminal_with_state(width, height, state, init_cmd)?;
        Ok(Self { runtime })
    }

    /// Creates a test harness with a pre-built state and custom configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if creating the virtual terminal fails.
    pub fn with_state_and_config(
        width: u16,
        height: u16,
        state: A::State,
        init_cmd: Command<A::Message>,
        config: RuntimeConfig,
    ) -> error::Result<Self> {
        let runtime = Runtime::virtual_terminal_with_state_and_config(
            width, height, state, init_cmd, config,
        )?;
        Ok(Self { runtime })
    }

    // -------------------------------------------------------------------------
    // State Access
    // -------------------------------------------------------------------------

    /// Returns a reference to the current state.
    pub fn state(&self) -> &A::State {
        self.runtime.state()
    }

    /// Returns a mutable reference to the state.
    pub fn state_mut(&mut self) -> &mut A::State {
        self.runtime.state_mut()
    }

    /// Returns the captured output as a string.
    pub fn screen(&self) -> String {
        self.runtime.display()
    }

    /// Returns the captured output with ANSI colors.
    pub fn screen_ansi(&self) -> String {
        self.runtime.display_ansi()
    }

    /// Returns the cell at the given position, or `None` if out of bounds.
    ///
    /// Use this to assert on cell styling:
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// use envision::harness::AppHarness;
    ///
    /// let harness = AppHarness::<MyApp>::new(80, 24)?;
    /// let cell = harness.cell_at(5, 3);
    /// assert!(cell.is_some());
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn cell_at(&self, x: u16, y: u16) -> Option<&crate::backend::EnhancedCell> {
        self.runtime.backend().cell(x, y)
    }

    /// Returns a snapshot of the current frame.
    ///
    /// The snapshot captures the current rendered state and can be used
    /// with `insta::assert_snapshot!` or the built-in snapshot comparison.
    pub fn snapshot(&self) -> super::Snapshot {
        super::Snapshot::new(self.runtime.backend().snapshot(), Default::default())
    }

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

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

    // -------------------------------------------------------------------------
    // Message Dispatch
    // -------------------------------------------------------------------------

    /// Dispatches a message and processes all resulting work.
    ///
    /// This dispatches the message, spawns any async commands, and processes
    /// any immediately available async results.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState { count: i32 }
    /// # #[derive(Clone)]
    /// # enum MyMsg { Increment }
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState::default(), Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> {
    /// #         match msg { MyMsg::Increment => state.count += 1 }
    /// #         Command::none()
    /// #     }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// use envision::harness::AppHarness;
    ///
    /// let mut harness = AppHarness::<MyApp>::new(80, 24)?;
    /// harness.dispatch(MyMsg::Increment);
    /// assert_eq!(harness.state().count, 1);
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn dispatch(&mut self, msg: A::Message) {
        self.runtime.dispatch(msg);
        self.runtime.process_pending();
    }

    /// Dispatches multiple messages.
    pub fn dispatch_all(&mut self, messages: impl IntoIterator<Item = A::Message>) {
        for msg in messages {
            self.dispatch(msg);
        }
    }

    /// Returns a sender that can be used to send messages to the runtime.
    pub fn message_sender(&self) -> tokio::sync::mpsc::Sender<A::Message> {
        self.runtime.message_sender()
    }

    // -------------------------------------------------------------------------
    // Subscriptions
    // -------------------------------------------------------------------------

    /// Adds a subscription to the runtime.
    pub fn subscribe(&mut self, subscription: impl Subscription<A::Message>) {
        self.runtime.subscribe(subscription);
    }

    /// Adds multiple subscriptions to the runtime.
    pub fn subscribe_all(&mut self, subscriptions: Vec<BoxedSubscription<A::Message>>) {
        self.runtime.subscribe_all(subscriptions);
    }

    // -------------------------------------------------------------------------
    // Event Queue
    // -------------------------------------------------------------------------

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

    /// Queues a single event.
    pub fn push_event(&mut self, event: Event) {
        self.runtime.events().push(event);
    }

    /// Types a string as keyboard input.
    pub fn type_str(&mut self, s: &str) {
        self.runtime.events().type_str(s);
    }

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

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

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

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

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

    // -------------------------------------------------------------------------
    // Runtime Control
    // -------------------------------------------------------------------------

    /// Processes all pending events.
    pub fn process_events(&mut self) {
        self.runtime.process_all_events();
    }

    /// Runs a single tick of the application.
    ///
    /// # Errors
    ///
    /// Returns an error if rendering to the terminal backend fails.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use envision::prelude::*;
    /// # struct MyApp;
    /// # #[derive(Default, Clone)]
    /// # struct MyState;
    /// # #[derive(Clone)]
    /// # enum MyMsg {}
    /// # impl App for MyApp {
    /// #     type State = MyState;
    /// #     type Message = MyMsg;
    /// #     fn init() -> (MyState, Command<MyMsg>) { (MyState, Command::none()) }
    /// #     fn update(state: &mut MyState, msg: MyMsg) -> Command<MyMsg> { Command::none() }
    /// #     fn view(state: &MyState, frame: &mut Frame) {}
    /// # }
    /// use envision::harness::AppHarness;
    ///
    /// let mut harness = AppHarness::<MyApp>::new(80, 24)?;
    /// harness.push_event(Event::key(KeyCode::Enter));
    /// harness.tick()?;
    /// # Ok::<(), envision::EnvisionError>(())
    /// ```
    pub fn tick(&mut self) -> error::Result<()> {
        self.runtime.tick()
    }

    /// Runs multiple ticks.
    ///
    /// # Errors
    ///
    /// Returns an error if any individual tick fails to render.
    pub fn run_ticks(&mut self, ticks: usize) -> error::Result<()> {
        self.runtime.run_ticks(ticks)
    }

    /// Renders the current state.
    ///
    /// # Errors
    ///
    /// Returns an error if drawing to the terminal backend fails.
    pub fn render(&mut self) -> error::Result<()> {
        self.runtime.render()
    }

    /// Returns true if the runtime should quit.
    pub fn should_quit(&self) -> bool {
        self.runtime.should_quit()
    }

    /// Triggers a quit.
    pub fn quit(&mut self) {
        self.runtime.quit();
    }

    /// Returns the cancellation token.
    pub fn cancellation_token(&self) -> CancellationToken {
        self.runtime.cancellation_token()
    }

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

    /// Returns true if the screen contains the given text.
    pub fn contains_text(&self, needle: &str) -> bool {
        self.runtime.contains_text(needle)
    }

    /// Finds all positions of the given text.
    pub fn find_text(&self, needle: &str) -> Vec<Position> {
        self.runtime.find_text(needle)
    }

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

    // -------------------------------------------------------------------------
    // 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_text(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_text(needle) {
            panic!(
                "Expected screen to NOT contain '{}', but it was found.\n\nScreen:\n{}",
                needle,
                self.screen()
            );
        }
    }
}

// Time control methods - available during tests and with the test-utils feature
#[cfg(any(test, feature = "test-utils"))]
use std::time::Duration;

#[cfg(any(test, feature = "test-utils"))]
impl<A: App> AppHarness<A> {
    /// Advances time by the specified duration.
    ///
    /// This only works when time is paused (e.g., with `#[tokio::test(start_paused = true)]`).
    /// After advancing time, all pending async work that was waiting for timers
    /// or delays will be processed.
    pub async fn advance_time(&mut self, duration: Duration) {
        // Advance in small increments to give spawned tasks a chance to wake
        // and process their timers
        let step = Duration::from_millis(10);
        let mut remaining = duration;

        while remaining > Duration::ZERO {
            let advance_by = remaining.min(step);
            tokio::time::advance(advance_by).await;

            // Yield to let spawned tasks run
            tokio::time::sleep(Duration::ZERO).await;
            tokio::task::yield_now().await;

            remaining = remaining.saturating_sub(advance_by);
        }

        // Final processing of any messages that arrived
        self.runtime.process_pending();
    }

    /// Sleeps for the specified duration.
    ///
    /// When time is paused, this immediately advances time without waiting.
    pub async fn sleep(&mut self, duration: Duration) {
        self.advance_time(duration).await;
    }

    /// Waits for a condition to become true, with a timeout.
    ///
    /// Returns true if the condition was met, false if it timed out.
    pub async fn wait_for<F>(&mut self, condition: F, timeout: Duration) -> bool
    where
        F: Fn(&A::State) -> bool,
    {
        let step = Duration::from_millis(10);
        let mut elapsed = Duration::ZERO;

        while elapsed < timeout {
            if condition(self.runtime.state()) {
                return true;
            }

            self.advance_time(step).await;
            elapsed += step;
        }

        condition(self.runtime.state())
    }

    /// Waits for the screen to contain the specified text.
    pub async fn wait_for_text(&mut self, needle: &str, timeout: Duration) -> bool {
        let step = Duration::from_millis(10);
        let mut elapsed = Duration::ZERO;

        while elapsed < timeout {
            self.runtime.render().ok();
            if self.contains_text(needle) {
                return true;
            }

            self.advance_time(step).await;
            elapsed += step;
        }

        self.runtime.render().ok();
        self.contains_text(needle)
    }
}

#[cfg(test)]
mod tests;