rnk 0.15.31

A React-like declarative terminal UI framework for Rust, inspired by Ink
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
//! Integration tests for the Command system
//!
//! These tests verify the complete integration of:
//! - Cmd types (None, Batch, Perform, Sleep)
//! - CmdExecutor (async execution with Tokio)
//! - use_cmd Hook (dependency tracking)
//! - Predefined tasks (file I/O, process spawning)

use rnk::cmd::{Cmd, CmdExecutor, HttpRequest};
use rnk::hooks::{HookContext, use_cmd, with_hooks};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::mpsc;

/// Test 1: Complete command execution lifecycle
///
/// Verifies: Cmd creation → Executor execution → Render notification
#[tokio::test]
async fn test_complete_command_lifecycle() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let executed = Arc::new(AtomicBool::new(false));
    let executed_clone = Arc::clone(&executed);

    let cmd = Cmd::perform(move || async move {
        executed_clone.store(true, Ordering::SeqCst);
    });

    executor.execute(cmd);

    // Wait for render notification
    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout waiting for render notification")
        .expect("channel closed");

    // Verify execution
    assert!(executed.load(Ordering::SeqCst));

    executor.shutdown();
}

/// Test 2: Batch command execution with multiple tasks
///
/// Verifies: Multiple commands execute in parallel, single notification
#[tokio::test]
async fn test_batch_command_execution() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let counter = Arc::new(AtomicU32::new(0));
    let c1 = Arc::clone(&counter);
    let c2 = Arc::clone(&counter);
    let c3 = Arc::clone(&counter);

    let cmd = Cmd::batch(vec![
        Cmd::perform(move || async move {
            c1.fetch_add(1, Ordering::SeqCst);
        }),
        Cmd::perform(move || async move {
            tokio::time::sleep(Duration::from_millis(10)).await;
            c2.fetch_add(1, Ordering::SeqCst);
        }),
        Cmd::perform(move || async move {
            c3.fetch_add(1, Ordering::SeqCst);
        }),
    ]);

    executor.execute(cmd);

    // Wait for single notification
    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    // Give tasks time to complete
    tokio::time::sleep(Duration::from_millis(50)).await;

    // All three tasks should have executed
    assert_eq!(counter.load(Ordering::SeqCst), 3);

    // Should not receive additional notifications
    tokio::time::timeout(Duration::from_millis(100), rx.recv())
        .await
        .unwrap_err(); // Should timeout

    executor.shutdown();
}

/// Test 3: Sleep and chained commands
///
/// Verifies: Sleep timing + command chaining
#[tokio::test]
async fn test_sleep_chain_execution() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let executed = Arc::new(AtomicBool::new(false));
    let e = Arc::clone(&executed);

    let start = std::time::Instant::now();

    let cmd = Cmd::sleep(Duration::from_millis(100))
        .and_then(Cmd::sleep(Duration::from_millis(100)))
        .and_then(Cmd::perform(move || async move {
            e.store(true, Ordering::SeqCst);
        }));

    executor.execute(cmd);

    // Wait for notification
    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    let elapsed = start.elapsed();

    // Should take at least 200ms (two sleeps)
    assert!(elapsed >= Duration::from_millis(200));
    assert!(elapsed < Duration::from_millis(500)); // But not too long

    // Verify final command executed
    assert!(executed.load(Ordering::SeqCst));

    executor.shutdown();
}

/// Test 4: File I/O operations
///
/// Verifies: File write + read operations
#[tokio::test]
async fn test_file_io_integration() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let temp_file = std::env::temp_dir().join("rnk_integration_test.txt");
    let write_result = Arc::new(Mutex::new(None));
    let read_result = Arc::new(Mutex::new(None));

    let wr = Arc::clone(&write_result);
    let temp_file_clone = temp_file.clone();

    // Step 1: Write file
    let write_cmd = Cmd::write_file(temp_file.clone(), "integration test content", move |res| {
        *wr.lock().unwrap() = Some(res);
    });

    executor.execute(write_cmd);

    // Wait for write completion
    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    // Verify write succeeded
    assert!(write_result.lock().unwrap().as_ref().unwrap().is_ok());

    // Step 2: Read file
    let rr = Arc::clone(&read_result);
    let read_cmd = Cmd::read_file(temp_file_clone, move |res| {
        *rr.lock().unwrap() = Some(res);
    });

    executor.execute(read_cmd);

    // Wait for read completion
    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    // Verify read succeeded and content matches
    let read_res = read_result.lock().unwrap().take().unwrap();
    assert!(read_res.is_ok());
    assert_eq!(read_res.unwrap(), "integration test content");

    // Cleanup
    let _ = std::fs::remove_file(temp_file);

    executor.shutdown();
}

/// Test 5: Process spawning
///
/// Verifies: Process execution with output capture
#[tokio::test]
async fn test_process_spawn_integration() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let result = Arc::new(Mutex::new(None));
    let r = Arc::clone(&result);

    let cmd = Cmd::spawn(
        "echo",
        vec!["integration".to_string(), "test".to_string()],
        move |res| {
            *r.lock().unwrap() = Some(res);
        },
    );

    executor.execute(cmd);

    // Wait for completion
    tokio::time::timeout(Duration::from_secs(2), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    // Verify result
    let output = result.lock().unwrap().take().unwrap();
    assert!(output.is_ok());

    let output = output.unwrap();
    assert!(output.success);
    assert_eq!(output.exit_code, 0);
    assert!(output.stdout.contains("integration"));
    assert!(output.stdout.contains("test"));

    executor.shutdown();
}

/// Test 6: use_cmd Hook integration
///
/// Verifies: Hook dependency tracking + command queueing
#[test]
fn test_use_cmd_hook_integration() {
    use std::sync::RwLock;
    let ctx = Arc::new(RwLock::new(HookContext::new()));
    let execution_count = Arc::new(AtomicU32::new(0));

    // First render - should execute
    {
        let count = Arc::clone(&execution_count);
        with_hooks(ctx.clone(), move || {
            use_cmd(42, move |val| {
                assert_eq!(val, 42);
                count.fetch_add(1, Ordering::SeqCst);
                Cmd::none()
            });
        });
    }

    assert_eq!(execution_count.load(Ordering::SeqCst), 1);
    let cmds = ctx.write().unwrap().take_cmds();
    assert_eq!(cmds.len(), 1);

    // Second render - same deps, should not execute
    {
        let count = Arc::clone(&execution_count);
        with_hooks(ctx.clone(), move || {
            use_cmd(42, move |_| {
                count.fetch_add(1, Ordering::SeqCst);
                Cmd::none()
            });
        });
    }

    assert_eq!(execution_count.load(Ordering::SeqCst), 1); // Still 1
    let cmds = ctx.write().unwrap().take_cmds();
    assert_eq!(cmds.len(), 0); // No new commands

    // Third render - different deps, should execute
    {
        let count = Arc::clone(&execution_count);
        with_hooks(ctx.clone(), move || {
            use_cmd(99, move |val| {
                assert_eq!(val, 99);
                count.fetch_add(1, Ordering::SeqCst);
                Cmd::none()
            });
        });
    }

    assert_eq!(execution_count.load(Ordering::SeqCst), 2);
    let cmds = ctx.write().unwrap().take_cmds();
    assert_eq!(cmds.len(), 1);
}

/// Test 7: Concurrent command execution
///
/// Verifies: Multiple concurrent commands execute correctly
#[tokio::test]
async fn test_concurrent_command_execution() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let counter = Arc::new(AtomicU32::new(0));

    // Execute 20 commands concurrently
    for _ in 0..20 {
        let c = Arc::clone(&counter);
        executor.execute(Cmd::perform(move || async move {
            tokio::time::sleep(Duration::from_millis(10)).await;
            c.fetch_add(1, Ordering::SeqCst);
        }));
    }

    // Wait for all 20 notifications
    for _ in 0..20 {
        tokio::time::timeout(Duration::from_secs(2), rx.recv())
            .await
            .expect("timeout")
            .expect("channel closed");
    }

    // Give tasks time to complete
    tokio::time::sleep(Duration::from_millis(100)).await;

    // All 20 should have executed
    assert_eq!(counter.load(Ordering::SeqCst), 20);

    executor.shutdown();
}

/// Test 8: Error handling in commands
///
/// Verifies: Errors are properly propagated to callbacks
#[tokio::test]
async fn test_error_handling_integration() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    // Test 1: Non-existent file read
    let result = Arc::new(Mutex::new(None));
    let r = Arc::clone(&result);

    let cmd = Cmd::read_file("/nonexistent/path/file.txt", move |res| {
        *r.lock().unwrap() = Some(res);
    });

    executor.execute(cmd);

    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    let res = result.lock().unwrap().take().unwrap();
    assert!(res.is_err());
    assert!(res.unwrap_err().contains("Failed to read file"));

    // Test 2: Non-existent command
    let result2 = Arc::new(Mutex::new(None));
    let r2 = Arc::clone(&result2);

    let cmd2 = Cmd::spawn("nonexistent_command_xyz_123", vec![], move |res| {
        *r2.lock().unwrap() = Some(res);
    });

    executor.execute(cmd2);

    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    let res2 = result2.lock().unwrap().take().unwrap();
    assert!(res2.is_err());

    executor.shutdown();
}

/// Test 9: Complex scenario - Timer with file write
///
/// Verifies: Real-world scenario combining multiple features
#[tokio::test]
async fn test_complex_scenario_timer_file_write() {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let executor = CmdExecutor::new(tx);

    let temp_file = std::env::temp_dir().join("rnk_timer_test.txt");
    let temp_file_for_verify = temp_file.clone();
    let result = Arc::new(Mutex::new(None));
    let r = Arc::clone(&result);

    let start = std::time::Instant::now();

    // Wait 100ms then write file
    let cmd = Cmd::delay(Duration::from_millis(100), move || {
        let temp = temp_file.clone();
        let res = r.clone();
        async move {
            match tokio::fs::write(&temp, "delayed write").await {
                Ok(_) => *res.lock().unwrap() = Some(Ok(())),
                Err(e) => *res.lock().unwrap() = Some(Err(format!("{}", e))),
            }
        }
    });

    executor.execute(cmd);

    // Wait for completion
    tokio::time::timeout(Duration::from_secs(1), rx.recv())
        .await
        .expect("timeout")
        .expect("channel closed");

    let elapsed = start.elapsed();

    // Should have waited at least 100ms
    assert!(elapsed >= Duration::from_millis(100));

    // Verify file was written
    assert!(result.lock().unwrap().is_some());
    assert!(result.lock().unwrap().as_ref().unwrap().is_ok());

    let contents = std::fs::read_to_string(&temp_file_for_verify).unwrap();
    assert_eq!(contents, "delayed write");

    // Cleanup
    let _ = std::fs::remove_file(temp_file_for_verify);

    executor.shutdown();
}

/// Test 10: HttpRequest builder integration
///
/// Verifies: HttpRequest builder creates correct structure
#[test]
fn test_http_request_builder_integration() {
    let request = HttpRequest::get("https://api.github.com/users/octocat")
        .header("Authorization", "Bearer token123")
        .header("Content-Type", "application/json");

    assert_eq!(request.url, "https://api.github.com/users/octocat");
    assert_eq!(request.method, "GET");
    assert_eq!(request.headers.len(), 2);
    assert_eq!(
        request.headers[0],
        ("Authorization".to_string(), "Bearer token123".to_string())
    );
    assert_eq!(
        request.headers[1],
        ("Content-Type".to_string(), "application/json".to_string())
    );
    assert!(request.body.is_none());

    let post_request = HttpRequest::post("https://api.example.com/data")
        .header("Content-Type", "application/json")
        .body(r#"{"key": "value"}"#);

    assert_eq!(post_request.method, "POST");
    assert!(post_request.body.is_some());
    assert_eq!(post_request.body.unwrap(), r#"{"key": "value"}"#);
}