envision 0.15.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
use super::*;
use crate::app::Command;
use crate::app::command::BoxedError;
use std::time::Duration;

// =========================================================================
// Async Command and Message Channel Tests
// =========================================================================

#[tokio::test]
async fn test_runtime_async_command() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Create an async command
    let cmd = Command::perform_async(async { Some(CounterMsg::IncrementBy(5)) });

    // Execute the command
    runtime.commands.execute(cmd);
    runtime.spawn_pending_commands();

    // Wait for the message
    tokio::time::sleep(Duration::from_millis(10)).await;
    runtime.process_pending();

    assert_eq!(runtime.state().count, 5);
}

#[tokio::test]
async fn test_runtime_message_channel() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let sender = runtime.message_sender();

    // Send a message via the channel
    sender.send(CounterMsg::Increment).await.unwrap();
    sender.send(CounterMsg::Increment).await.unwrap();

    // Process the messages
    runtime.process_pending();
    assert_eq!(runtime.state().count, 2);
}

// =========================================================================
// Error Handling Tests
// =========================================================================

#[tokio::test]
async fn test_runtime_take_errors() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let error_tx = runtime.error_sender();

    // No errors initially
    let errors = runtime.take_errors();
    assert!(errors.is_empty());

    // Send an error
    let err: BoxedError = Box::new(std::io::Error::other("test error"));
    error_tx.send(err).await.unwrap();

    // Should have one error
    let errors = runtime.take_errors();
    assert_eq!(errors.len(), 1);
    assert!(errors[0].to_string().contains("test error"));

    // Errors are consumed
    let errors = runtime.take_errors();
    assert!(errors.is_empty());
}

#[tokio::test]
async fn test_runtime_has_errors() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let error_tx = runtime.error_sender();

    // No errors initially
    assert!(!runtime.has_errors());

    // Send an error
    let err: BoxedError = Box::new(std::io::Error::other("test error"));
    error_tx.send(err).await.unwrap();

    // Give the channel a moment to process
    tokio::time::sleep(Duration::from_millis(1)).await;

    // Should have errors now
    assert!(runtime.has_errors());

    // Consume the errors
    let _ = runtime.take_errors();

    // No more errors
    assert!(!runtime.has_errors());
}

#[tokio::test]
async fn test_runtime_error_from_spawned_task() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let error_tx = runtime.error_sender();

    // Spawn a task that reports an error
    tokio::spawn(async move {
        let err: BoxedError = Box::new(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "resource not found",
        ));
        let _ = error_tx.send(err).await;
    });

    // Wait for the task to complete
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Should have the error
    let errors = runtime.take_errors();
    assert_eq!(errors.len(), 1);
    assert!(errors[0].to_string().contains("resource not found"));
}

#[tokio::test]
async fn test_runtime_multiple_errors() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();
    let error_tx = runtime.error_sender();

    // Send multiple errors
    for i in 0..3 {
        let err: BoxedError = Box::new(std::io::Error::other(format!("error {}", i)));
        error_tx.send(err).await.unwrap();
    }

    // Should have all three errors
    let errors = runtime.take_errors();
    assert_eq!(errors.len(), 3);
}

// =========================================================================
// Fallible Async Command Tests
// =========================================================================

struct FallibleApp;

#[derive(Clone, Default)]
struct FallibleState {
    value: Option<i32>,
}

#[derive(Clone, Debug)]
enum FallibleMsg {
    FetchSuccess,
    FetchFailure,
    Loaded(i32),
}

impl App for FallibleApp {
    type State = FallibleState;
    type Message = FallibleMsg;

    fn init() -> (Self::State, Command<Self::Message>) {
        (FallibleState::default(), Command::none())
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
        match msg {
            FallibleMsg::FetchSuccess => {
                Command::try_perform_async(async { Ok::<_, std::io::Error>(42) }, |n| {
                    Some(FallibleMsg::Loaded(n))
                })
            }
            FallibleMsg::FetchFailure => Command::try_perform_async(
                async {
                    Err::<i32, _>(std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "data not found",
                    ))
                },
                |n| Some(FallibleMsg::Loaded(n)),
            ),
            FallibleMsg::Loaded(n) => {
                state.value = Some(n);
                Command::none()
            }
        }
    }

    fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}
}

#[tokio::test]
async fn test_runtime_try_perform_async_success() {
    let mut runtime: Runtime<FallibleApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Dispatch a message that triggers a successful async operation
    runtime.dispatch(FallibleMsg::FetchSuccess);

    // Wait for the async task to complete
    tokio::time::sleep(Duration::from_millis(20)).await;

    // Process pending messages from the spawned task
    runtime.process_pending();

    // State should be updated with the loaded value
    assert_eq!(runtime.state().value, Some(42));

    // No errors should be in the channel
    assert!(!runtime.has_errors());
}

#[tokio::test]
async fn test_runtime_try_perform_async_failure() {
    let mut runtime: Runtime<FallibleApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Dispatch a message that triggers a failing async operation
    runtime.dispatch(FallibleMsg::FetchFailure);

    // Wait for the async task to complete
    tokio::time::sleep(Duration::from_millis(20)).await;

    // Process pending (there shouldn't be any messages, just the error)
    runtime.process_pending();

    // State should NOT be updated (error occurred)
    assert_eq!(runtime.state().value, None);

    // Error should be in the channel
    let errors = runtime.take_errors();
    assert_eq!(errors.len(), 1);
    assert!(errors[0].to_string().contains("data not found"));
}

// =========================================================================
// Subscription Tests
// =========================================================================

#[tokio::test]
async fn test_runtime_subscribe() {
    use crate::app::subscription::TickSubscription;

    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Subscribe to a tick that fires every 10ms
    let sub = TickSubscription::new(Duration::from_millis(10), || CounterMsg::Increment);
    runtime.subscribe(sub);

    // Spawn a task to send quit after some ticks
    let tx = runtime.message_sender();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        let _ = tx.send(CounterMsg::Quit).await;
    });

    // Run the event loop - subscriptions are polled here
    runtime.run().await.unwrap();

    // Should have quit cleanly
    assert!(runtime.should_quit());
}

#[tokio::test]
async fn test_runtime_subscribe_all() {
    use crate::app::subscription::{BoxedSubscription, TickSubscription};

    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Create multiple subscriptions
    let sub1: BoxedSubscription<CounterMsg> =
        Box::new(TickSubscription::new(Duration::from_millis(10), || {
            CounterMsg::Increment
        }));
    let sub2: BoxedSubscription<CounterMsg> =
        Box::new(TickSubscription::new(Duration::from_millis(10), || {
            CounterMsg::Increment
        }));

    runtime.subscribe_all(vec![sub1, sub2]);

    // Wait a bit for ticks
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Clean up
    runtime.quit();
}

// =========================================================================
// Run Loop Tests
// =========================================================================

#[tokio::test]
async fn test_runtime_run() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(40, 10).build().unwrap();

    // Increment counter
    runtime.dispatch(CounterMsg::Increment);

    // Spawn task to quit after a short delay
    let tx = runtime.message_sender();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        let _ = tx.send(CounterMsg::Quit).await;
    });

    // Run the event loop
    runtime.run().await.unwrap();

    // Should have quit
    assert!(runtime.should_quit());
    assert!(runtime.contains_text("Count: 1"));
}

#[tokio::test]
async fn test_runtime_run_cancelled() {
    let mut runtime: Runtime<CounterApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    let token = runtime.cancellation_token();

    // Spawn task to cancel after a short delay
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        token.cancel();
    });

    // Run the event loop
    runtime.run().await.unwrap();

    // Should have quit due to cancellation
    assert!(runtime.should_quit());
}

// =========================================================================
// Init Command Tests
// =========================================================================

struct InitCommandApp;

#[derive(Clone, Default)]
struct InitCommandState {
    initialized: bool,
}

#[derive(Clone)]
enum InitCommandMsg {
    Initialized,
}

impl App for InitCommandApp {
    type State = InitCommandState;
    type Message = InitCommandMsg;

    fn init() -> (Self::State, Command<Self::Message>) {
        // Return a command that sends Initialized message
        (
            InitCommandState::default(),
            Command::message(InitCommandMsg::Initialized),
        )
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
        match msg {
            InitCommandMsg::Initialized => state.initialized = true,
        }
        Command::none()
    }

    fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}
}

#[test]
fn test_runtime_init_command() {
    let mut runtime: Runtime<InitCommandApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Process sync commands from init
    runtime.process_pending();

    assert!(runtime.state().initialized);
}

// =========================================================================
// Ticking App Tests
// =========================================================================

struct TickingApp;

#[derive(Clone, Default)]
struct TickingState {
    ticks: i32,
    quit: bool,
}

#[derive(Clone)]
enum TickingMsg {
    Tick,
}

impl App for TickingApp {
    type State = TickingState;
    type Message = TickingMsg;

    fn init() -> (Self::State, Command<Self::Message>) {
        (TickingState::default(), Command::none())
    }

    fn update(state: &mut Self::State, msg: Self::Message) -> Command<Self::Message> {
        match msg {
            TickingMsg::Tick => {
                state.ticks += 1;
                if state.ticks >= 3 {
                    state.quit = true;
                }
            }
        }
        Command::none()
    }

    fn view(_state: &Self::State, _frame: &mut ratatui::Frame) {}

    fn should_quit(state: &Self::State) -> bool {
        state.quit
    }

    fn on_tick(_state: &Self::State) -> Option<Self::Message> {
        Some(TickingMsg::Tick)
    }
}

#[test]
fn test_runtime_ticking_app() {
    let mut runtime: Runtime<TickingApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Each tick should increment
    runtime.tick().unwrap();
    assert_eq!(runtime.state().ticks, 1);

    runtime.tick().unwrap();
    assert_eq!(runtime.state().ticks, 2);

    // Third tick should trigger quit
    runtime.tick().unwrap();
    assert_eq!(runtime.state().ticks, 3);
    assert!(runtime.should_quit());
}

#[tokio::test]
async fn test_runtime_run_with_on_tick() {
    let mut runtime: Runtime<TickingApp, _> = Runtime::virtual_builder(80, 24).build().unwrap();

    // Run the event loop - should quit after 3 ticks
    runtime.run().await.unwrap();

    assert!(runtime.should_quit());
    assert!(runtime.state().ticks >= 3);
}