command-stream 1.1.1

Modern shell command execution library with streaming, async iteration, and event 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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! Integration tests for built-in virtual commands
//!
//! These tests mirror the JavaScript tests in js/tests/builtin-commands.test.mjs

use command_stream::commands::{
    basename, cat, cp, dirname, echo, env, exit, ls, mkdir, mv, pwd, rm, seq, sleep, tee, test,
    touch, which, yes, CommandContext,
};
use std::fs;
use std::path::PathBuf;
use tempfile::TempDir;

/// Helper to create a command context with args
fn ctx(args: Vec<&str>) -> CommandContext {
    CommandContext {
        args: args.into_iter().map(String::from).collect(),
        stdin: None,
        cwd: None,
        env: None,
        output_tx: None,
        is_cancelled: None,
    }
}

/// Helper to create a command context with args and cwd
fn ctx_with_cwd(args: Vec<&str>, cwd: PathBuf) -> CommandContext {
    CommandContext {
        args: args.into_iter().map(String::from).collect(),
        stdin: None,
        cwd: Some(cwd),
        env: None,
        output_tx: None,
        is_cancelled: None,
    }
}

/// Helper to create a command context with stdin
fn ctx_with_stdin(args: Vec<&str>, stdin: &str) -> CommandContext {
    CommandContext {
        args: args.into_iter().map(String::from).collect(),
        stdin: Some(stdin.to_string()),
        cwd: None,
        env: None,
        output_tx: None,
        is_cancelled: None,
    }
}

// ============================================================================
// Echo Command Tests
// ============================================================================

#[tokio::test]
async fn test_echo_basic() {
    let result = echo(ctx(vec!["Hello", "World"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "Hello World\n");
}

#[tokio::test]
async fn test_echo_with_n_flag() {
    let result = echo(ctx(vec!["-n", "Hello"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "Hello");
}

#[tokio::test]
async fn test_echo_empty() {
    let result = echo(ctx(vec![])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "\n");
}

#[tokio::test]
async fn test_echo_with_e_flag() {
    let result = echo(ctx(vec!["-e", "Hello\\nWorld"])).await;
    assert!(result.is_success());
    assert!(result.stdout.contains("\n"));
}

// ============================================================================
// Pwd Command Tests
// ============================================================================

#[tokio::test]
async fn test_pwd_returns_current_directory() {
    let result = pwd(ctx(vec![])).await;
    assert!(result.is_success());
    assert!(!result.stdout.is_empty());
}

// ============================================================================
// True/False Command Tests
// ============================================================================

#[tokio::test]
async fn test_true_command() {
    let result = command_stream::commands::r#true(ctx(vec![])).await;
    assert!(result.is_success());
    assert_eq!(result.code, 0);
}

#[tokio::test]
async fn test_false_command() {
    let result = command_stream::commands::r#false(ctx(vec![])).await;
    assert!(!result.is_success());
    assert_eq!(result.code, 1);
}

// ============================================================================
// Cat Command Tests
// ============================================================================

#[tokio::test]
async fn test_cat_read_file() {
    let dir = TempDir::new().unwrap();
    let file_path = dir.path().join("test.txt");
    fs::write(&file_path, "Hello World\nLine 2\n").unwrap();

    let result = cat(ctx(vec![file_path.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "Hello World\nLine 2\n");
}

#[tokio::test]
async fn test_cat_from_stdin() {
    let result = cat(ctx_with_stdin(vec![], "stdin input")).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "stdin input");
}

#[tokio::test]
async fn test_cat_nonexistent_file() {
    let result = cat(ctx(vec!["nonexistent.txt"])).await;
    assert!(!result.is_success());
    assert!(result.stderr.contains("No such file or directory"));
}

// ============================================================================
// Ls Command Tests
// ============================================================================

#[tokio::test]
async fn test_ls_list_directory() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("file1.txt"), "content").unwrap();
    fs::write(dir.path().join("file2.txt"), "content").unwrap();
    fs::create_dir(dir.path().join("subdir")).unwrap();

    let result = ls(ctx(vec![dir.path().to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(result.stdout.contains("file1.txt"));
    assert!(result.stdout.contains("file2.txt"));
    assert!(result.stdout.contains("subdir"));
}

#[tokio::test]
async fn test_ls_with_a_flag() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join(".hidden"), "content").unwrap();
    fs::write(dir.path().join("visible.txt"), "content").unwrap();

    let result = ls(ctx(vec!["-a", dir.path().to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(result.stdout.contains(".hidden"));
    assert!(result.stdout.contains("visible.txt"));
}

#[tokio::test]
async fn test_pwd_honors_context_cwd() {
    let dir = TempDir::new().unwrap();
    let expected = fs::canonicalize(dir.path()).unwrap();

    let result = pwd(ctx_with_cwd(vec![], expected.clone())).await;
    assert!(result.is_success());
    assert_eq!(result.stdout.trim(), expected.to_string_lossy());
}

#[tokio::test]
async fn test_ls_resolves_relative_path_against_context_cwd() {
    let dir = TempDir::new().unwrap();
    fs::create_dir(dir.path().join("nested")).unwrap();
    fs::write(dir.path().join("nested/inside.txt"), "content").unwrap();

    let result = ls(ctx_with_cwd(vec!["nested"], dir.path().to_path_buf())).await;
    assert!(result.is_success());
    assert!(result.stdout.contains("inside.txt"));
}

#[tokio::test]
async fn test_ls_without_path_lists_context_cwd() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("listed.txt"), "content").unwrap();

    let result = ls(ctx_with_cwd(vec![], dir.path().to_path_buf())).await;
    assert!(result.is_success());
    assert!(result.stdout.contains("listed.txt"));
}

#[tokio::test]
async fn test_ls_with_l_flag() {
    let dir = TempDir::new().unwrap();
    fs::write(dir.path().join("test.txt"), "content").unwrap();

    let result = ls(ctx(vec!["-l", dir.path().to_str().unwrap()])).await;
    assert!(result.is_success());
    // Long format should include permissions
    assert!(result.stdout.contains("-") || result.stdout.contains("r"));
    assert!(result.stdout.contains("test.txt"));
}

// ============================================================================
// Mkdir Command Tests
// ============================================================================

#[tokio::test]
async fn test_mkdir_create_directory() {
    let dir = TempDir::new().unwrap();
    let new_dir = dir.path().join("newdir");

    let result = mkdir(ctx(vec![new_dir.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(new_dir.exists());
}

#[tokio::test]
async fn test_mkdir_with_p_flag() {
    let dir = TempDir::new().unwrap();
    let nested_dir = dir.path().join("parent").join("child");

    let result = mkdir(ctx(vec!["-p", nested_dir.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(nested_dir.exists());
}

// ============================================================================
// Touch Command Tests
// ============================================================================

#[tokio::test]
async fn test_touch_create_file() {
    let dir = TempDir::new().unwrap();
    let file_path = dir.path().join("touched.txt");

    let result = touch(ctx(vec![file_path.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(file_path.exists());
}

#[tokio::test]
async fn test_touch_update_timestamp() {
    let dir = TempDir::new().unwrap();
    let file_path = dir.path().join("existing.txt");
    fs::write(&file_path, "content").unwrap();
    let old_mtime = fs::metadata(&file_path).unwrap().modified().unwrap();

    // Wait a bit to ensure timestamp difference
    std::thread::sleep(std::time::Duration::from_millis(10));

    let result = touch(ctx(vec![file_path.to_str().unwrap()])).await;
    assert!(result.is_success());

    let new_mtime = fs::metadata(&file_path).unwrap().modified().unwrap();
    assert!(new_mtime > old_mtime);
}

// ============================================================================
// Rm Command Tests
// ============================================================================

#[tokio::test]
async fn test_rm_remove_file() {
    let dir = TempDir::new().unwrap();
    let file_path = dir.path().join("to-remove.txt");
    fs::write(&file_path, "content").unwrap();

    let result = rm(ctx(vec![file_path.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(!file_path.exists());
}

#[tokio::test]
async fn test_rm_fail_on_directory() {
    let dir = TempDir::new().unwrap();
    let sub_dir = dir.path().join("to-remove-dir");
    fs::create_dir(&sub_dir).unwrap();

    let result = rm(ctx(vec![sub_dir.to_str().unwrap()])).await;
    assert!(!result.is_success());
    assert!(result.stderr.contains("Is a directory"));
    assert!(sub_dir.exists());
}

#[tokio::test]
async fn test_rm_recursive() {
    let dir = TempDir::new().unwrap();
    let sub_dir = dir.path().join("to-remove-recursive");
    fs::create_dir(&sub_dir).unwrap();
    fs::write(sub_dir.join("file.txt"), "content").unwrap();

    let result = rm(ctx(vec!["-r", sub_dir.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(!sub_dir.exists());
}

#[tokio::test]
async fn test_rm_force() {
    let result = rm(ctx(vec!["-f", "nonexistent.txt"])).await;
    assert!(result.is_success());
}

// ============================================================================
// Cp Command Tests
// ============================================================================

#[tokio::test]
async fn test_cp_copy_file() {
    let dir = TempDir::new().unwrap();
    let source = dir.path().join("source.txt");
    let dest = dir.path().join("dest.txt");
    fs::write(&source, "test content").unwrap();

    let result = cp(ctx(vec![source.to_str().unwrap(), dest.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(dest.exists());
    assert_eq!(fs::read_to_string(&dest).unwrap(), "test content");
}

#[tokio::test]
async fn test_cp_recursive() {
    let dir = TempDir::new().unwrap();
    let source_dir = dir.path().join("source-dir");
    let dest_dir = dir.path().join("dest-dir");
    fs::create_dir(&source_dir).unwrap();
    fs::write(source_dir.join("file.txt"), "content").unwrap();

    let result = cp(ctx(vec![
        "-r",
        source_dir.to_str().unwrap(),
        dest_dir.to_str().unwrap(),
    ]))
    .await;
    assert!(result.is_success());
    assert!(dest_dir.exists());
    assert!(dest_dir.join("file.txt").exists());
}

// ============================================================================
// Mv Command Tests
// ============================================================================

#[tokio::test]
async fn test_mv_rename_file() {
    let dir = TempDir::new().unwrap();
    let source = dir.path().join("source.txt");
    let dest = dir.path().join("dest.txt");
    fs::write(&source, "test content").unwrap();

    let result = mv(ctx(vec![source.to_str().unwrap(), dest.to_str().unwrap()])).await;
    assert!(result.is_success());
    assert!(!source.exists());
    assert!(dest.exists());
    assert_eq!(fs::read_to_string(&dest).unwrap(), "test content");
}

#[tokio::test]
async fn test_mv_to_directory() {
    let dir = TempDir::new().unwrap();
    let source = dir.path().join("source.txt");
    let dest_dir = dir.path().join("dest-dir");
    fs::write(&source, "test content").unwrap();
    fs::create_dir(&dest_dir).unwrap();

    let result = mv(ctx(vec![
        source.to_str().unwrap(),
        dest_dir.to_str().unwrap(),
    ]))
    .await;
    assert!(result.is_success());
    assert!(!source.exists());
    assert!(dest_dir.join("source.txt").exists());
}

// ============================================================================
// Basename/Dirname Command Tests
// ============================================================================

#[tokio::test]
async fn test_basename() {
    let result = basename(ctx(vec!["/path/to/file.txt"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout.trim(), "file.txt");
}

#[tokio::test]
async fn test_basename_with_suffix() {
    let result = basename(ctx(vec!["/path/to/file.txt", ".txt"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout.trim(), "file");
}

#[tokio::test]
async fn test_dirname() {
    let result = dirname(ctx(vec!["/path/to/file.txt"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout.trim(), "/path/to");
}

// ============================================================================
// Which Command Tests
// ============================================================================

#[tokio::test]
async fn test_which_builtin() {
    let result = which(ctx(vec!["echo"])).await;
    assert!(result.is_success());
    assert!(result.stdout.contains("shell builtin"));
}

// ============================================================================
// Exit Command Tests
// ============================================================================

#[tokio::test]
async fn test_exit_default() {
    let result = exit(ctx(vec![])).await;
    assert!(result.is_success());
    assert_eq!(result.code, 0);
}

#[tokio::test]
async fn test_exit_with_code() {
    let result = exit(ctx(vec!["42"])).await;
    assert!(!result.is_success());
    assert_eq!(result.code, 42);
}

// ============================================================================
// Sleep Command Tests
// ============================================================================

#[tokio::test]
async fn test_sleep() {
    let start = std::time::Instant::now();
    let result = sleep(ctx(vec!["0.1"])).await;
    let elapsed = start.elapsed();

    assert!(result.is_success());
    assert!(elapsed.as_millis() >= 90);
    assert!(elapsed.as_millis() < 200);
}

// ============================================================================
// Seq Command Tests
// ============================================================================

#[tokio::test]
async fn test_seq_simple() {
    let result = seq(ctx(vec!["5"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "1\n2\n3\n4\n5\n");
}

#[tokio::test]
async fn test_seq_range() {
    let result = seq(ctx(vec!["2", "5"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "2\n3\n4\n5\n");
}

#[tokio::test]
async fn test_seq_with_increment() {
    let result = seq(ctx(vec!["1", "2", "5"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "1\n3\n5\n");
}

// ============================================================================
// Yes Command Tests
// ============================================================================

#[tokio::test]
async fn test_yes_with_cancel() {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    // Create a cancellation flag
    let cancelled = Arc::new(AtomicBool::new(false));
    let cancelled_clone = cancelled.clone();

    // Cancel after a short delay
    tokio::spawn(async move {
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        cancelled_clone.store(true, Ordering::SeqCst);
    });

    let ctx = CommandContext {
        args: vec![],
        stdin: None,
        cwd: None,
        env: None,
        output_tx: None,
        is_cancelled: Some(Box::new(move || cancelled.load(Ordering::SeqCst))),
    };

    let result = yes(ctx).await;
    // Yes command should have produced some output before being cancelled
    assert!(result.stdout.contains("y") || result.is_success());
}

// ============================================================================
// Tee Command Tests
// ============================================================================

/// Helper to create a command context with stdin and cwd
fn ctx_with_stdin_and_cwd(args: Vec<&str>, stdin: &str, cwd: PathBuf) -> CommandContext {
    CommandContext {
        args: args.into_iter().map(String::from).collect(),
        stdin: Some(stdin.to_string()),
        cwd: Some(cwd),
        env: None,
        output_tx: None,
        is_cancelled: None,
    }
}

#[tokio::test]
async fn test_tee_is_a_virtual_command() {
    let result = which(ctx(vec!["tee"])).await;
    assert!(result.is_success());
    assert_eq!(result.stdout, "tee: shell builtin\n");
}

#[tokio::test]
async fn test_tee_writes_file_and_stdout() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("tee-output.txt");

    let result = tee(ctx_with_stdin(vec![file.to_str().unwrap()], "Hello Tee!\n")).await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "Hello Tee!\n");
    assert_eq!(fs::read_to_string(&file).unwrap(), "Hello Tee!\n");
}

#[tokio::test]
async fn test_tee_multiple_output_files() {
    let dir = TempDir::new().unwrap();
    let file1 = dir.path().join("tee1.txt");
    let file2 = dir.path().join("tee2.txt");
    let file3 = dir.path().join("tee3.txt");

    let result = tee(ctx_with_stdin(
        vec![
            file1.to_str().unwrap(),
            file2.to_str().unwrap(),
            file3.to_str().unwrap(),
        ],
        "Multiple files\n",
    ))
    .await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "Multiple files\n");
    for file in [&file1, &file2, &file3] {
        assert_eq!(fs::read_to_string(file).unwrap(), "Multiple files\n");
    }
}

#[tokio::test]
async fn test_tee_append_flag() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("tee-append.txt");

    tee(ctx_with_stdin(vec![file.to_str().unwrap()], "First line\n")).await;
    let result = tee(ctx_with_stdin(
        vec!["-a", file.to_str().unwrap()],
        "Second line\n",
    ))
    .await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "Second line\n");
    assert_eq!(
        fs::read_to_string(&file).unwrap(),
        "First line\nSecond line\n"
    );
}

#[tokio::test]
async fn test_tee_truncates_without_append() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("tee-truncate.txt");
    fs::write(&file, "old content that is much longer\n").unwrap();

    let result = tee(ctx_with_stdin(vec![file.to_str().unwrap()], "new\n")).await;

    assert!(result.is_success());
    assert_eq!(fs::read_to_string(&file).unwrap(), "new\n");
}

#[tokio::test]
async fn test_tee_long_options() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("tee-long-options.txt");

    tee(ctx_with_stdin(vec![file.to_str().unwrap()], "first\n")).await;
    let result = tee(ctx_with_stdin(
        vec!["--append", "--ignore-interrupts", file.to_str().unwrap()],
        "second\n",
    ))
    .await;

    assert!(result.is_success());
    assert_eq!(fs::read_to_string(&file).unwrap(), "first\nsecond\n");
}

#[tokio::test]
async fn test_tee_clustered_short_options() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("tee-clustered.txt");

    tee(ctx_with_stdin(vec![file.to_str().unwrap()], "first\n")).await;
    let result = tee(ctx_with_stdin(
        vec!["-ai", file.to_str().unwrap()],
        "second\n",
    ))
    .await;

    assert!(result.is_success());
    assert_eq!(fs::read_to_string(&file).unwrap(), "first\nsecond\n");
}

#[tokio::test]
async fn test_tee_stops_option_parsing_at_double_dash() {
    let dir = TempDir::new().unwrap();

    let result = tee(ctx_with_stdin_and_cwd(
        vec!["--", "-a"],
        "literal\n",
        dir.path().to_path_buf(),
    ))
    .await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "literal\n");
    // `-a` after `--` is a file name, not the append flag.
    assert_eq!(
        fs::read_to_string(dir.path().join("-a")).unwrap(),
        "literal\n"
    );
    assert!(!dir.path().join("--").exists());
}

#[tokio::test]
async fn test_tee_treats_bare_dash_as_a_file_name() {
    let dir = TempDir::new().unwrap();

    // GNU tee has no special case for `-`: it is a file named `-`.
    let result = tee(ctx_with_stdin_and_cwd(
        vec!["-"],
        "dash\n",
        dir.path().to_path_buf(),
    ))
    .await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "dash\n");
    assert_eq!(fs::read_to_string(dir.path().join("-")).unwrap(), "dash\n");
}

#[tokio::test]
async fn test_tee_empty_input_creates_file() {
    let dir = TempDir::new().unwrap();
    let file = dir.path().join("tee-empty.txt");

    let result = tee(ctx_with_stdin(vec![file.to_str().unwrap()], "")).await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "");
    assert_eq!(fs::read_to_string(&file).unwrap(), "");
}

#[tokio::test]
async fn test_tee_without_file_operands_passes_stdin_through() {
    let result = tee(ctx_with_stdin(vec![], "just stdout\n")).await;

    assert!(result.is_success());
    assert_eq!(result.stdout, "just stdout\n");
    assert_eq!(result.stderr, "");
}

#[tokio::test]
async fn test_tee_reports_write_errors_and_keeps_going() {
    let dir = TempDir::new().unwrap();
    let good = dir.path().join("tee-good.txt");

    let result = tee(ctx_with_stdin(
        vec!["/invalid/path/tee-error.txt", good.to_str().unwrap()],
        "error test",
    ))
    .await;

    assert_eq!(result.code, 1);
    assert_eq!(
        result.stderr,
        "tee: /invalid/path/tee-error.txt: No such file or directory\n"
    );
    // stdout and the remaining file are still written, like GNU tee.
    assert_eq!(result.stdout, "error test");
    assert_eq!(fs::read_to_string(&good).unwrap(), "error test");
}

#[tokio::test]
async fn test_tee_rejects_unknown_long_options() {
    let result = tee(ctx_with_stdin(vec!["--unknown-option", "file.txt"], "test")).await;

    assert_eq!(result.code, 1);
    assert_eq!(
        result.stderr,
        "tee: unrecognized option '--unknown-option'\n"
    );
    assert_eq!(result.stdout, "");
    assert!(!PathBuf::from("file.txt").exists());
}

#[tokio::test]
async fn test_tee_rejects_unknown_short_options() {
    let result = tee(ctx_with_stdin(vec!["-z", "file.txt"], "test")).await;

    assert_eq!(result.code, 1);
    assert_eq!(result.stderr, "tee: invalid option -- 'z'\n");
    assert!(!PathBuf::from("file.txt").exists());
}

// ============================================================================
// Test Command Tests
// ============================================================================

#[tokio::test]
async fn test_test_file_exists() {
    let dir = TempDir::new().unwrap();
    let file_path = dir.path().join("test.txt");
    fs::write(&file_path, "content").unwrap();

    let result = test(ctx(vec!["-e", file_path.to_str().unwrap()])).await;
    assert!(result.is_success());
}

#[tokio::test]
async fn test_test_file_not_exists() {
    let result = test(ctx(vec!["-e", "nonexistent.txt"])).await;
    assert!(!result.is_success());
}

#[tokio::test]
async fn test_test_is_file() {
    let dir = TempDir::new().unwrap();
    let file_path = dir.path().join("test.txt");
    fs::write(&file_path, "content").unwrap();

    let result = test(ctx(vec!["-f", file_path.to_str().unwrap()])).await;
    assert!(result.is_success());
}

#[tokio::test]
async fn test_test_is_directory() {
    let dir = TempDir::new().unwrap();

    let result = test(ctx(vec!["-d", dir.path().to_str().unwrap()])).await;
    assert!(result.is_success());
}

#[tokio::test]
async fn test_test_string_not_empty() {
    let result = test(ctx(vec!["-n", "hello"])).await;
    assert!(result.is_success());
}

#[tokio::test]
async fn test_test_string_empty() {
    let result = test(ctx(vec!["-z", ""])).await;
    assert!(result.is_success());
}

#[tokio::test]
async fn test_test_string_equals() {
    let result = test(ctx(vec!["hello", "=", "hello"])).await;
    assert!(result.is_success());
}

#[tokio::test]
async fn test_test_string_not_equals() {
    let result = test(ctx(vec!["hello", "!=", "world"])).await;
    assert!(result.is_success());
}

// ============================================================================
// Env Command Tests
// ============================================================================

#[tokio::test]
async fn test_env_list() {
    let result = env(ctx(vec![])).await;
    assert!(result.is_success());
    // Should contain some environment variables
    assert!(!result.stdout.is_empty());
}