qubit-command 0.2.1

Command-line process running utilities for Rust
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
/*******************************************************************************
 *
 *    Copyright (c) 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
//! Tests for [`CommandRunner`](qubit_command::CommandRunner).

use std::{
    fs,
    path::PathBuf,
    time::{
        Duration,
        SystemTime,
        UNIX_EPOCH,
    },
};
#[cfg(not(windows))]
use std::{
    sync::Once,
    time::Instant,
};

#[cfg(any(not(windows), coverage))]
use qubit_command::OutputStream;
#[cfg(coverage)]
use qubit_command::coverage_support;
use qubit_command::{
    Command,
    CommandError,
    CommandRunner,
};

#[path = "command_runner/captured_output_tests.rs"]
mod captured_output_tests;
#[path = "command_runner/command_io_tests.rs"]
mod command_io_tests;
#[path = "command_runner/finished_command_tests.rs"]
mod finished_command_tests;
#[path = "command_runner/managed_child_process_tests.rs"]
mod managed_child_process_tests;
#[path = "command_runner/output_capture_error_tests.rs"]
mod output_capture_error_tests;
#[path = "command_runner/output_capture_options_tests.rs"]
mod output_capture_options_tests;
#[path = "command_runner/output_reader_tests.rs"]
mod output_reader_tests;
#[path = "command_runner/output_tee_tests.rs"]
mod output_tee_tests;
#[path = "command_runner/running_command_tests.rs"]
mod running_command_tests;
#[path = "command_runner/stdin_writer_tests.rs"]
mod stdin_writer_tests;

#[cfg(not(windows))]
mod unix {
    use super::*;

    static LOGGER_INIT: Once = Once::new();
    static TEST_LOGGER: TestLogger = TestLogger;

    struct TestLogger;

    impl log::Log for TestLogger {
        fn enabled(&self, _metadata: &log::Metadata<'_>) -> bool {
            true
        }

        fn log(&self, _record: &log::Record<'_>) {}

        fn flush(&self) {}
    }

    fn init_test_logger() {
        LOGGER_INIT.call_once(|| {
            log::set_logger(&TEST_LOGGER).expect("test logger should be installed once");
            log::set_max_level(log::LevelFilter::Trace);
        });
    }

    fn unique_temp_path(name: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time should be after Unix epoch")
            .as_nanos();
        std::env::temp_dir().join(format!(
            "qubit-command-{name}-{}-{suffix}",
            std::process::id(),
        ))
    }

    #[test]
    fn test_command_runner_default_configuration() {
        init_test_logger();
        let runner = CommandRunner::new();

        assert_eq!(runner.configured_timeout(), None);
        assert_eq!(runner.configured_success_exit_codes(), &[0]);
        assert!(runner.configured_working_directory().is_none());
        assert!(!runner.is_logging_disabled());
        assert!(!runner.is_lossy_output_enabled());
        assert_eq!(runner.configured_max_stdout_bytes(), None);
        assert_eq!(runner.configured_max_stderr_bytes(), None);
        assert!(runner.configured_stdout_file().is_none());
        assert!(runner.configured_stderr_file().is_none());
    }

    #[test]
    fn test_command_runner_run_captures_stdout() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(Command::shell("printf command-out"))
            .expect("command should run successfully");

        assert_eq!(output.exit_code(), Some(0));
        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "command-out",
        );
        assert!(output.stderr_bytes().is_empty());
    }

    #[test]
    fn test_command_runner_run_captures_stderr() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(Command::shell("printf command-error >&2"))
            .expect("command should run successfully");

        assert!(output.stdout_bytes().is_empty());
        assert_eq!(
            output.stderr().expect("stderr should be valid UTF-8"),
            "command-error",
        );
    }

    #[test]
    fn test_command_runner_run_applies_environment_override() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(
                Command::shell("printf \"$QUBIT_COMMAND_TEST\"")
                    .env("QUBIT_COMMAND_TEST", "from-env"),
            )
            .expect("command should receive environment override");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "from-env",
        );
    }

    #[test]
    fn test_command_runner_run_applies_environment_remove() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(
                Command::shell("printf \"${QUBIT_COMMAND_TEST:-missing}\"")
                    .env("QUBIT_COMMAND_TEST", "from-env")
                    .env_remove("QUBIT_COMMAND_TEST"),
            )
            .expect("command should remove configured environment variable");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "missing",
        );
    }

    #[test]
    fn test_command_runner_run_applies_environment_clear_then_set() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(
                Command::shell("printf \"$QUBIT_COMMAND_TEST\"")
                    .env_clear()
                    .env("QUBIT_COMMAND_TEST", "after-clear"),
            )
            .expect("command should run with cleared environment plus explicit set");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "after-clear",
        );
    }

    #[test]
    fn test_command_runner_run_applies_working_directory_override() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(Command::shell("pwd").working_directory("/"))
            .expect("command should run in requested working directory");

        assert_eq!(
            output
                .stdout()
                .expect("stdout should be valid UTF-8")
                .trim(),
            "/",
        );
    }

    #[test]
    fn test_command_runner_run_applies_default_working_directory() {
        init_test_logger();
        let output = CommandRunner::new()
            .working_directory("/")
            .run(Command::shell("pwd"))
            .expect("command should run in runner working directory");

        assert_eq!(
            output
                .stdout()
                .expect("stdout should be valid UTF-8")
                .trim(),
            "/",
        );
    }

    #[test]
    fn test_command_runner_run_reports_unexpected_exit() {
        init_test_logger();
        let error = CommandRunner::new()
            .run(Command::shell(
                "printf fail-out; printf fail-err >&2; exit 7",
            ))
            .expect_err("non-success exit code should be rejected");

        match error {
            CommandError::UnexpectedExit {
                exit_code,
                expected,
                output,
                ..
            } => {
                assert_eq!(exit_code, Some(7));
                assert_eq!(expected, vec![0]);
                assert_eq!(
                    output.stdout().expect("stdout should be valid UTF-8"),
                    "fail-out",
                );
                assert_eq!(
                    output.stderr().expect("stderr should be valid UTF-8"),
                    "fail-err",
                );
            }
            other => panic!("expected unexpected-exit error, got {other:?}"),
        }
    }

    #[test]
    fn test_command_runner_run_accepts_configured_success_code() {
        init_test_logger();
        let output = CommandRunner::new()
            .success_exit_code(7)
            .run(Command::shell("exit 7"))
            .expect("configured success exit code should be accepted");

        assert_eq!(output.exit_code(), Some(7));
    }

    #[test]
    fn test_command_runner_run_accepts_configured_success_codes() {
        init_test_logger();
        let output = CommandRunner::new()
            .success_exit_codes(&[3, 7])
            .run(Command::shell("exit 3"))
            .expect("configured success exit code list should be accepted");

        assert_eq!(output.exit_code(), Some(3));
    }

    #[test]
    fn test_command_runner_run_without_timeout() {
        init_test_logger();
        let output = CommandRunner::new()
            .without_timeout()
            .run(Command::shell("printf no-timeout"))
            .expect("command should run successfully without timeout");

        assert_eq!(output.exit_code(), Some(0));
        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "no-timeout",
        );
    }

    #[test]
    fn test_command_runner_run_writes_stdin_bytes() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(Command::shell("cat").stdin_bytes(b"stdin-bytes".to_vec()))
            .expect("command should receive stdin bytes");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "stdin-bytes",
        );
    }

    #[test]
    fn test_command_runner_run_ignores_stdin_broken_pipe_for_success() {
        init_test_logger();
        let input = vec![b'x'; 1024 * 1024];
        let output = CommandRunner::new()
            .run(Command::shell("true").stdin_bytes(input))
            .expect("closed stdin should not hide a successful exit");

        assert_eq!(output.exit_code(), Some(0));
    }

    #[test]
    fn test_command_runner_run_preserves_exit_status_after_stdin_broken_pipe() {
        init_test_logger();
        let input = vec![b'x'; 1024 * 1024];
        let error = CommandRunner::new()
            .run(Command::shell("exit 7").stdin_bytes(input))
            .expect_err("non-success exit should remain visible after stdin closes");

        match error {
            CommandError::UnexpectedExit {
                exit_code,
                expected,
                ..
            } => {
                assert_eq!(exit_code, Some(7));
                assert_eq!(expected, vec![0]);
            }
            other => panic!("expected unexpected-exit error, got {other:?}"),
        }
    }

    #[test]
    fn test_command_runner_run_reads_stdin_file() {
        init_test_logger();
        let path = unique_temp_path("stdin.txt");
        fs::write(&path, b"stdin-file").expect("stdin fixture should be written");

        let output = CommandRunner::new()
            .run(Command::shell("cat").stdin_file(path.clone()))
            .expect("command should receive stdin file");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "stdin-file",
        );
        let _ = fs::remove_file(path);
    }

    #[test]
    fn test_command_runner_run_accepts_stdin_inherit() {
        init_test_logger();
        let output = CommandRunner::new()
            .run(Command::shell("printf inherited").stdin_inherit())
            .expect("command should run with inherited stdin");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "inherited",
        );
    }

    #[test]
    fn test_command_runner_run_reports_missing_stdin_file() {
        init_test_logger();
        let path = unique_temp_path("missing-stdin.txt");
        let error = CommandRunner::new()
            .run(Command::shell("cat").stdin_file(path.clone()))
            .expect_err("missing stdin file should be reported");

        match error {
            CommandError::OpenInputFailed {
                path: actual_path, ..
            } => assert_eq!(actual_path, path),
            other => panic!("expected stdin open failure, got {other:?}"),
        }
    }

    #[test]
    fn test_command_runner_disable_logging_updates_configuration() {
        let runner = CommandRunner::new().disable_logging(true);

        assert!(runner.is_logging_disabled());
    }

    #[test]
    fn test_command_runner_lossy_output_updates_configuration() {
        let runner = CommandRunner::new().lossy_output(true);

        assert!(runner.is_lossy_output_enabled());
    }

    #[test]
    fn test_command_runner_output_limit_updates_configuration() {
        let runner = CommandRunner::new().max_stdout_bytes(3).max_stderr_bytes(4);

        assert_eq!(runner.configured_max_stdout_bytes(), Some(3));
        assert_eq!(runner.configured_max_stderr_bytes(), Some(4));
    }

    #[test]
    fn test_command_runner_output_file_updates_configuration() {
        let stdout_path = unique_temp_path("stdout-config.txt");
        let stderr_path = unique_temp_path("stderr-config.txt");
        let runner = CommandRunner::new()
            .tee_stdout_to_file(stdout_path.clone())
            .tee_stderr_to_file(stderr_path.clone());

        assert_eq!(runner.configured_stdout_file(), Some(stdout_path.as_path()));
        assert_eq!(runner.configured_stderr_file(), Some(stderr_path.as_path()));
    }

    #[test]
    fn test_command_runner_run_suppresses_success_logging() {
        let output = CommandRunner::new()
            .disable_logging(true)
            .run(Command::shell("printf quiet-success"))
            .expect("command should run successfully when logging is disabled");

        assert_eq!(
            output.stdout().expect("stdout should be valid UTF-8"),
            "quiet-success",
        );
    }

    #[test]
    fn test_command_runner_run_suppresses_failure_logging() {
        let error = CommandRunner::new()
            .disable_logging(true)
            .run(Command::shell("exit 8"))
            .expect_err("unexpected exit should still be reported when logging is disabled");

        assert!(matches!(error, CommandError::UnexpectedExit { .. }));
    }

    #[test]
    fn test_command_runner_run_reports_timeout() {
        init_test_logger();
        let error = CommandRunner::new()
            .timeout(Duration::from_millis(50))
            .run(Command::shell("sleep 2"))
            .expect_err("long-running command should time out");

        match error {
            CommandError::TimedOut {
                timeout, output, ..
            } => {
                assert_eq!(timeout, Duration::from_millis(50));
                assert!(output.elapsed() >= Duration::from_millis(50));
            }
            other => panic!("expected timeout error, got {other:?}"),
        }
    }

    #[test]
    fn test_command_runner_run_kills_process_group_on_timeout() {
        init_test_logger();
        let start = Instant::now();
        let error = CommandRunner::new()
            .timeout(Duration::from_millis(50))
            .run(Command::shell("sleep 2 & wait"))
            .expect_err("process group should time out");

        assert!(matches!(error, CommandError::TimedOut { .. }));
        assert!(
            start.elapsed() < Duration::from_secs(1),
            "timeout should not wait for a background child that inherited output pipes",
        );
    }

    #[test]
    fn test_command_runner_run_limits_captured_output() {
        init_test_logger();
        let output = CommandRunner::new()
            .max_stdout_bytes(3)
            .max_stderr_bytes(2)
            .run(Command::shell("printf abcdef; printf wxyz >&2"))
            .expect("command should run successfully");

        assert_eq!(output.stdout_bytes(), b"abc");
        assert_eq!(output.stderr_bytes(), b"wx");
        assert!(output.stdout_truncated());
        assert!(output.stderr_truncated());
    }

    #[test]
    fn test_command_runner_run_tees_output_to_files() {
        init_test_logger();
        let stdout_path = unique_temp_path("stdout.txt");
        let stderr_path = unique_temp_path("stderr.txt");

        let output = CommandRunner::new()
            .max_output_bytes(3)
            .tee_stdout_to_file(stdout_path.clone())
            .tee_stderr_to_file(stderr_path.clone())
            .run(Command::shell("printf abcdef; printf wxyz >&2"))
            .expect("command should run successfully");

        assert_eq!(output.stdout_bytes(), b"abc");
        assert_eq!(output.stderr_bytes(), b"wxy");
        assert_eq!(
            fs::read(&stdout_path).expect("stdout tee file should be readable"),
            b"abcdef",
        );
        assert_eq!(
            fs::read(&stderr_path).expect("stderr tee file should be readable"),
            b"wxyz",
        );

        let _ = fs::remove_file(stdout_path);
        let _ = fs::remove_file(stderr_path);
    }

    #[test]
    fn test_command_runner_run_reports_output_file_open_failure() {
        init_test_logger();
        let path = unique_temp_path("missing-dir").join("stdout.txt");
        let error = CommandRunner::new()
            .tee_stdout_to_file(path.clone())
            .run(Command::shell("printf ignored"))
            .expect_err("missing output directory should be reported");

        match error {
            CommandError::OpenOutputFailed {
                stream,
                path: actual_path,
                ..
            } => {
                assert_eq!(stream, OutputStream::Stdout);
                assert_eq!(actual_path, path);
            }
            other => panic!("expected stdout open failure, got {other:?}"),
        }
    }

    #[test]
    fn test_command_runner_run_reports_stderr_file_open_failure() {
        init_test_logger();
        let path = unique_temp_path("missing-dir").join("stderr.txt");
        let error = CommandRunner::new()
            .tee_stderr_to_file(path.clone())
            .run(Command::shell("printf ignored"))
            .expect_err("missing output directory should be reported");

        match error {
            CommandError::OpenOutputFailed {
                stream,
                path: actual_path,
                ..
            } => {
                assert_eq!(stream, OutputStream::Stderr);
                assert_eq!(actual_path, path);
            }
            other => panic!("expected stderr open failure, got {other:?}"),
        }
    }

    #[test]
    fn test_command_runner_run_reports_spawn_failure() {
        init_test_logger();
        let error = CommandRunner::new()
            .run(Command::new("__qubit_command_missing_executable__"))
            .expect_err("missing executable should fail to spawn");

        assert!(matches!(error, CommandError::SpawnFailed { .. }));
    }

    #[test]
    fn test_command_runner_error_uses_argv_style_command_text() {
        init_test_logger();
        let error = CommandRunner::new()
            .run(Command::new("__qubit_command_missing_executable__").arg("two words"))
            .expect_err("missing executable should fail to spawn");

        assert_eq!(
            error.command(),
            r#"["__qubit_command_missing_executable__", "two words"]"#,
        );
    }

    #[test]
    #[cfg(coverage)]
    fn test_command_runner_coverage_exercises_defensive_paths() {
        let diagnostics = coverage_support::exercise_defensive_paths();
        let disabled_fake = CommandRunner::new()
            .run(Command::new("__qubit_command_missing_stdout__"))
            .expect_err("synthetic child names should not be active outside the coverage guard");
        assert!(matches!(disabled_fake, CommandError::SpawnFailed { .. }));

        coverage_support::with_fake_children_enabled(|| {
            let missing_stdout = CommandRunner::new()
                .run(Command::new("__qubit_command_missing_stdout__"))
                .expect_err("missing synthetic stdout pipe should be reported");
            assert!(matches!(
                missing_stdout,
                CommandError::ReadOutputFailed {
                    stream: OutputStream::Stdout,
                    ..
                }
            ));

            let missing_stderr = CommandRunner::new()
                .run(Command::new("__qubit_command_missing_stderr__"))
                .expect_err("missing synthetic stderr pipe should be reported");
            assert!(matches!(
                missing_stderr,
                CommandError::ReadOutputFailed {
                    stream: OutputStream::Stderr,
                    ..
                }
            ));

            let missing_stdin = CommandRunner::new()
                .run(Command::new("__qubit_command_missing_stdin__").stdin_bytes(b"input".to_vec()))
                .expect_err("missing synthetic stdin pipe should be reported");
            assert!(matches!(
                missing_stdin,
                CommandError::WriteInputFailed { .. }
            ));

            let try_wait_error = CommandRunner::new()
                .run(Command::new("__qubit_command_try_wait_error__"))
                .expect_err("synthetic try-wait failure should be reported");
            assert!(matches!(try_wait_error, CommandError::WaitFailed { .. }));
            let collected = coverage_support::take_collect_output_commands();
            assert!(
                collected
                    .iter()
                    .any(|command| command.contains("__qubit_command_try_wait_error__")),
                "try-wait cleanup should drain output helpers before returning",
            );

            let pending_after_kill = CommandRunner::new()
                .run(Command::new(
                    "__qubit_command_try_wait_error_pending_after_kill__",
                ))
                .expect_err("pending synthetic child should preserve the try-wait failure");
            assert!(matches!(
                pending_after_kill,
                CommandError::WaitFailed { .. }
            ));
            let collected = coverage_support::take_collect_output_commands();
            assert!(
                !collected.iter().any(|command| command
                    .contains("__qubit_command_try_wait_error_pending_after_kill__")),
                "wait-error cleanup must not collect output without confirmed child exit",
            );

            let try_wait_cleanup_error = CommandRunner::new()
                .run(Command::new(
                    "__qubit_command_try_wait_error_kill_cleanup__",
                ))
                .expect_err("synthetic try-wait cleanup fallback should preserve wait error");
            assert!(matches!(
                try_wait_cleanup_error,
                CommandError::WaitFailed { .. }
            ));
            let collected = coverage_support::take_collect_output_commands();
            assert!(
                collected.iter().any(
                    |command| command.contains("__qubit_command_try_wait_error_kill_cleanup__")
                ),
                "try-wait cleanup fallback should drain output helpers when the child already exited",
            );

            let kill_error = CommandRunner::new()
                .timeout(Duration::ZERO)
                .run(Command::new("__qubit_command_kill_error__"))
                .expect_err("synthetic kill failure should be reported");
            assert!(matches!(kill_error, CommandError::KillFailed { .. }));
            let collected = coverage_support::take_collect_output_commands();
            assert!(
                collected
                    .iter()
                    .any(|command| command.contains("__qubit_command_kill_error__")),
                "kill-error cleanup should drain output helpers when the child already exited",
            );

            let wait_after_kill_error = CommandRunner::new()
                .timeout(Duration::ZERO)
                .run(Command::new("__qubit_command_wait_after_kill_error__"))
                .expect_err("synthetic wait-after-kill failure should be reported");
            assert!(matches!(
                wait_after_kill_error,
                CommandError::WaitFailed { .. }
            ));
            let collected = coverage_support::take_collect_output_commands();
            assert!(
                collected
                    .iter()
                    .any(|command| command.contains("__qubit_command_wait_after_kill_error__")),
                "wait-after-kill cleanup should drain output helpers when the child already exited",
            );

            let collect_output_error = CommandRunner::new()
                .run(Command::new("__qubit_command_collect_output_error__"))
                .expect_err("synthetic output collection failure should be reported");
            assert!(matches!(
                collect_output_error,
                CommandError::ReadOutputFailed {
                    stream: OutputStream::Stdout,
                    ..
                }
            ));

            let timeout_collect_output_error = CommandRunner::new()
                .timeout(Duration::ZERO)
                .run(Command::new(
                    "__qubit_command_timeout_collect_output_error__",
                ))
                .expect_err("synthetic timeout output collection failure should be reported");
            assert!(matches!(
                timeout_collect_output_error,
                CommandError::ReadOutputFailed {
                    stream: OutputStream::Stdout,
                    ..
                }
            ));
        });

        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("failed to spawn command `spawn`")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("failed to wait for command `wait`")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("failed to kill timed-out command `kill`")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("failed to read stdout for command `pipe`")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("failed to read stderr for command `pipe`")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("read failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("write failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("flush failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("stdin pipe was not created")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("collect stdout failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("collect stderr failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("collect stdin failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("reader failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("reader write failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("output reader thread panicked")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("stdin write failed")),
        );
        assert!(
            diagnostics
                .iter()
                .any(|message| message.contains("stdin writer thread panicked")),
        );
    }
}

#[cfg(windows)]
mod windows {
    use super::*;

    /// Removes trailing Windows line endings from command output.
    ///
    /// # Parameters
    ///
    /// * `text` - Captured output text.
    ///
    /// # Returns
    ///
    /// Output text without trailing CR/LF characters.
    fn trim_windows_line_endings(text: &str) -> &str {
        text.trim_end_matches(['\r', '\n'])
    }

    /// Creates a unique temporary file path for one test run.
    ///
    /// # Parameters
    ///
    /// * `name` - Human-readable filename component.
    ///
    /// # Returns
    ///
    /// Path inside the platform temporary directory.
    fn unique_windows_temp_path(name: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time should be after Unix epoch")
            .as_nanos();
        std::env::temp_dir().join(format!(
            "qubit-command-windows-{name}-{}-{suffix}",
            std::process::id(),
        ))
    }

    #[test]
    fn test_command_runner_windows_captures_stdout() {
        let output = CommandRunner::new()
            .run(Command::shell("echo command-out"))
            .expect("Windows shell command should run successfully");

        assert_eq!(
            trim_windows_line_endings(output.stdout().expect("stdout should be UTF-8")),
            "command-out",
        );
    }

    #[test]
    fn test_command_runner_windows_captures_stderr() {
        let output = CommandRunner::new()
            .run(Command::shell("echo command-error>&2"))
            .expect("Windows shell command should run successfully");

        assert_eq!(
            trim_windows_line_endings(output.stderr().expect("stderr should be UTF-8")),
            "command-error",
        );
    }

    #[test]
    fn test_command_runner_windows_reports_timeout() {
        let error = CommandRunner::new()
            .timeout(Duration::from_millis(50))
            .run(Command::shell("ping -n 3 127.0.0.1 >NUL"))
            .expect_err("long-running Windows command should time out");

        assert!(matches!(error, CommandError::TimedOut { .. }));
    }

    #[test]
    fn test_command_runner_windows_tees_output_to_file() {
        let stdout_path = unique_windows_temp_path("stdout.txt");
        let output = CommandRunner::new()
            .max_stdout_bytes(3)
            .tee_stdout_to_file(stdout_path.clone())
            .run(Command::shell("echo abcdef"))
            .expect("Windows shell command should run successfully");

        assert_eq!(output.stdout_bytes(), b"abc");
        assert!(output.stdout_truncated());
        assert_eq!(
            trim_windows_line_endings(
                std::str::from_utf8(&fs::read(&stdout_path).expect("tee file should be readable"))
                    .expect("tee file should contain UTF-8"),
            ),
            "abcdef",
        );

        let _ = fs::remove_file(stdout_path);
    }
}