atap 0.1.0

Threadsafe futureless async runtime for macOS
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
//! Process task tests
//!
//! Only programs a stock macOS install has are used

use atap::{Runtime, RuntimeError, TaskHandle, process::Process, signal::SignalKind};
use std::{
    fs, thread,
    time::{Duration, Instant},
};

/// How long a test waits for a child that ought to be quick
const PATIENCE: Duration = Duration::from_secs(20);

/// Waits for a spawned task, but not forever
///
/// ## Returns
/// `None` if the deadline passed with nothing settled
fn settled<T>(handle: &TaskHandle<T>, patience: Duration) -> Option<T> {
    let deadline = Instant::now() + patience;

    while Instant::now() < deadline {
        match handle.try_take() {
            Ok(value) => return Some(value),
            Err(RuntimeError::NotReady) => thread::sleep(Duration::from_millis(1)),
            Err(_) => break,
        }
    }

    None
}

/// A program that ran and failed is an answer, not an error
#[test]
fn a_run_reports_its_exit_code() {
    let _ = Runtime::init();

    println!("running /usr/bin/true");
    let ok =
        Runtime::block(Process::run("/usr/bin/true", Process::NO_ARGS)).expect("true must run");

    assert!(ok.success(), "true must succeed, got {:?}", ok);
    assert_eq!(ok.code(), Some(0), "true must exit zero");

    println!("running /usr/bin/false");
    let failed =
        Runtime::block(Process::run("/usr/bin/false", Process::NO_ARGS)).expect("false must run");

    assert!(!failed.success(), "false must not succeed");
    assert_eq!(
        failed.code(),
        Some(1),
        "false must exit one, got {:?}",
        failed.code()
    );
    assert_eq!(failed.signal(), None, "false was not killed");
}

/// Stdout and stderr each come back as themselves
#[test]
fn output_comes_back_on_the_right_stream() {
    let _ = Runtime::init();

    let handle = Runtime::task(Process::output(
        "/bin/sh",
        ["-c", "echo out; echo err 1>&2"],
    ))
    .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("a two line child must settle")
        .expect("sh must run");

    assert_eq!(
        found.stdout(),
        b"out\n",
        "stdout was {:?}",
        String::from_utf8_lossy(found.stdout())
    );
    assert_eq!(
        found.stderr(),
        b"err\n",
        "stderr was {:?}",
        String::from_utf8_lossy(found.stderr())
    );
    assert!(found.status().success(), "the shell itself must succeed");
}

/// A child that writes far more than a pipe holds to both
/// streams finishes
#[test]
fn a_child_that_floods_both_pipes_does_not_deadlock() {
    let _ = Runtime::init();

    const FLOOD: usize = 4 * 1024 * 1024;

    let script = format!("head -c {FLOOD} /dev/zero & head -c {FLOOD} /dev/zero 1>&2; wait");

    println!("flooding both streams with {FLOOD} bytes each");

    let handle = Runtime::task(Process::output("/bin/sh", ["-c", &script])).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("a flooding child must settle rather than deadlock")
        .expect("sh must run");

    assert_eq!(found.stdout().len(), FLOOD, "stdout was truncated");
    assert_eq!(found.stderr().len(), FLOOD, "stderr was truncated");
}

/// Many children spawned at once all finish
#[test]
fn many_children_at_once() {
    let _ = Runtime::init();

    const CHILDREN: usize = 16;

    let handles = (0..CHILDREN)
        .map(|index| {
            Runtime::task(Process::output("/bin/sh", ["-c", &format!("echo {index}")])).spawn()
        })
        .collect::<Vec<_>>();

    println!("waiting on {CHILDREN} children at once");

    for (index, handle) in handles.iter().enumerate() {
        let found = settled(handle, PATIENCE)
            .unwrap_or_else(|| panic!("child {index} never settled"))
            .unwrap_or_else(|error| panic!("child {index} could not run: {error}"));

        assert_eq!(
            found.stdout(),
            format!("{index}\n").as_bytes(),
            "child {index} came back with somebody else's output"
        );
    }
}

/// A cancelled task's child stops running
#[test]
fn a_cancelled_child_stops_running() {
    let _ = Runtime::init();

    let scratch = std::env::temp_dir().join(format!("atap-cancel-{}.txt", std::process::id()));
    let _ = fs::remove_file(&scratch);

    let script = format!(
        "while true; do echo x >> {}; sleep 0.05; done",
        scratch.display()
    );

    let handle = Runtime::task(Process::run("/bin/sh", ["-c", &script])).spawn();

    // Long enough that the child is running and writing
    thread::sleep(Duration::from_millis(500));

    let before_cancel = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    assert!(
        before_cancel > 0,
        "the child must be writing before the cancel, or this proves nothing"
    );

    println!("cancelling a child that writes while it lives");
    handle.clone().cancel();
    let _ = handle.wait();

    // Long enough for a surviving child to write many more times
    thread::sleep(Duration::from_millis(750));
    let settled_at = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    thread::sleep(Duration::from_millis(750));
    let later = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    let _ = fs::remove_file(&scratch);

    assert_eq!(
        settled_at, later,
        "the child went on writing after its task was cancelled, \
         {settled_at} bytes then {later}"
    );

    assert!(
        handle.is_cancelled(),
        "the task must settle cancelled, was {:?}",
        handle.state()
    );
}

/// A child whose task runs out of time stops running
#[test]
fn a_timed_out_child_stops_running() {
    let _ = Runtime::init();

    let scratch = std::env::temp_dir().join(format!("atap-timeout-{}.txt", std::process::id()));
    let _ = fs::remove_file(&scratch);

    let script = format!(
        "while true; do echo x >> {}; sleep 0.05; done",
        scratch.display()
    );

    let handle = Runtime::task(Process::run("/bin/sh", ["-c", &script]))
        .timeout(Duration::from_millis(400))
        .spawn();

    assert_eq!(
        handle.take_with_timeout(PATIENCE).map(|_| ()),
        Err(RuntimeError::TimedOut)
    );

    let written = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    assert!(written > 0, "the child never wrote, so this proves nothing");

    // Long enough for a surviving child to write many more times
    thread::sleep(Duration::from_millis(750));
    let settled_at = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    thread::sleep(Duration::from_millis(750));
    let later = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    let _ = fs::remove_file(&scratch);

    assert_eq!(
        settled_at, later,
        "the child went on writing after its task timed out, {settled_at} bytes then {later}"
    );
}

/// A task collecting output that runs out of time stops reading and
/// ends its child
#[test]
fn a_timed_out_output_stops() {
    let _ = Runtime::init();

    let started = Instant::now();
    let handle = Runtime::task(Process::output(
        "/bin/sh",
        ["-c", "while true; do echo line; done"],
    ))
    .timeout(Duration::from_millis(300))
    .spawn();

    assert_eq!(
        handle.take_with_timeout(PATIENCE).map(|_| ()),
        Err(RuntimeError::TimedOut)
    );
    assert!(started.elapsed() >= Duration::from_millis(300));
}

/// A program that isn't there says so
#[test]
fn a_program_that_is_not_there_reports_it() {
    let _ = Runtime::init();

    let found = Runtime::block(Process::run("/no/such/program", Process::NO_ARGS));

    assert_eq!(
        found,
        Err(RuntimeError::CheckError(Some(libc::ENOENT))),
        "a missing program must come back as ENOENT, got {found:?}"
    );
}

/// A child's standard input is `/dev/null`, not this process's
#[test]
fn stdin_is_not_the_terminal() {
    let _ = Runtime::init();

    let handle = Runtime::task(Process::output("/bin/cat", Process::NO_ARGS)).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("cat must reach the end of its input")
        .expect("cat must run");

    assert!(found.stdout().is_empty(), "there was nothing to read");
    assert!(found.status().success(), "cat must finish happily");
}

/// A child gets the default `SIGPIPE` back
#[test]
fn sigpipe_is_reset() {
    let _ = Runtime::init();

    let handle = Runtime::task(Process::output("/bin/sh", ["-c", "yes | head -1"])).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("a closed pipe must kill the writer rather than spin")
        .expect("sh must run");

    assert_eq!(found.stdout(), b"y\n", "head takes exactly one line");
}

/// A zero byte is refused, and the refusal says which half was
/// wrong
#[test]
fn a_zero_byte_is_refused() {
    let _ = Runtime::init();

    let bad_argument = Runtime::block(Process::run("/bin/echo", ["a\0b"]));

    assert_eq!(
        bad_argument,
        Err(RuntimeError::BadArgument),
        "a zero byte in an argument must be refused, got {bad_argument:?}"
    );

    let bad_program = Runtime::block(Process::run("/bin/ec\0ho", ["fine"]));

    assert_eq!(
        bad_program,
        Err(RuntimeError::BadPath),
        "a zero byte in the program must be refused, got {bad_program:?}"
    );
}

/// A run child can still write to this process's stderr
#[test]
fn a_run_child_still_has_somewhere_to_write() {
    let _ = Runtime::init();

    let wrote = Runtime::block(Process::run(
        "/bin/sh",
        ["-c", "echo run-inherits-stderr 1>&2"],
    ))
    .expect("sh must run");

    assert!(
        wrote.success(),
        "a run child must inherit a usable stderr, exited {:?}",
        wrote.code()
    );

    let to_stdout = Runtime::block(Process::run("/bin/sh", ["-c", "echo run-inherits-stdout"]))
        .expect("sh must run");

    assert!(
        to_stdout.success(),
        "a run child must inherit a usable stdout, exited {:?}",
        to_stdout.code()
    );
}

// -- Input, working directory and environment --------------

/// The bytes reach the child
#[test]
fn input_reaches_the_child() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Process::output("/bin/cat", Process::NO_ARGS).input(b"hello\n".as_slice()))
            .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("cat must settle")
        .expect("cat must run");

    assert_eq!(
        found.stdout(),
        b"hello\n",
        "cat gave back {:?}",
        String::from_utf8_lossy(found.stdout())
    );
}

/// A child fed more than a pipe holds, while echoing it back,
/// finishes
#[test]
fn a_child_fed_more_than_a_pipe_holds_does_not_deadlock() {
    let _ = Runtime::init();

    const FLOOD: usize = 4 * 1024 * 1024;

    let fed = vec![b'z'; FLOOD];

    println!("feeding cat {FLOOD} bytes while reading it back");

    let handle =
        Runtime::task(Process::output("/bin/cat", Process::NO_ARGS).input(fed.as_slice())).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("a flooded child must settle rather than deadlock")
        .expect("cat must run");

    assert_eq!(
        found.stdout().len(),
        FLOOD,
        "cat gave back the wrong amount"
    );
    assert!(found.status().success(), "cat must finish happily");
}

/// The child is told when its input has ended
#[test]
fn input_ends_so_the_child_sees_its_end() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Process::output("/usr/bin/wc", ["-c"]).input(b"12345".as_slice())).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("wc must reach the end of its input")
        .expect("wc must run");

    let counted = String::from_utf8_lossy(found.stdout()).trim().to_string();

    assert_eq!(counted, "5", "wc counted {counted:?}");
}

/// A child that never reads its input still finishes
#[test]
fn a_child_that_ignores_its_input_finishes() {
    let _ = Runtime::init();

    let fed = vec![b'z'; 4 * 1024 * 1024];

    let handle =
        Runtime::task(Process::output("/bin/sh", ["-c", "echo done"]).input(fed.as_slice()))
            .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("a child that ignores its input must still finish")
        .expect("sh must run");

    assert_eq!(found.stdout(), b"done\n", "the child ran to its own end");
    assert!(found.status().success(), "and was not treated as a failure");
}

/// A child that takes only part of its input still finishes
#[test]
fn a_child_that_takes_part_of_its_input_finishes() {
    let _ = Runtime::init();

    let fed = vec![b'z'; 4 * 1024 * 1024];

    let handle =
        Runtime::task(Process::output("/usr/bin/head", ["-c", "10"]).input(fed.as_slice())).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("a child that stops reading must not hang its parent")
        .expect("head must run");

    assert_eq!(
        found.stdout().len(),
        10,
        "head takes exactly what it asked for"
    );
    assert!(
        found.status().success(),
        "a child stopping early is not a failure, exited {:?}",
        found.status().code()
    );
}

/// Input reaches a run child too
#[test]
fn input_reaches_a_run_child() {
    let _ = Runtime::init();

    let found =
        Runtime::block(Process::run("/usr/bin/grep", ["-q", "ping"]).input(b"ping\n".as_slice()))
            .expect("grep must run");

    assert!(found.success(), "grep must find what it was fed");

    let missing =
        Runtime::block(Process::run("/usr/bin/grep", ["-q", "ping"]).input(b"pong\n".as_slice()))
            .expect("grep must run");

    assert_eq!(
        missing.code(),
        Some(1),
        "grep must not find what it was not fed"
    );
}

/// An empty input is the same as none at all
#[test]
fn an_empty_input_is_the_same_as_none() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Process::output("/bin/cat", Process::NO_ARGS).input(b"".as_slice())).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("an empty input must still end")
        .expect("cat must run");

    assert!(found.stdout().is_empty(), "there was nothing to give it");
    assert!(found.status().success(), "cat must finish happily");
}

/// The child starts where it was told to
#[test]
fn in_dir_changes_where_the_child_starts() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Process::output("/bin/pwd", Process::NO_ARGS).in_dir("/usr")).spawn();

    let found = settled(&handle, PATIENCE)
        .expect("pwd must settle")
        .expect("pwd must run");

    let where_it_ran = String::from_utf8_lossy(found.stdout()).trim().to_string();

    assert_eq!(
        where_it_ran, "/usr",
        "the child started in {where_it_ran:?}"
    );
}

/// A relative program runs once, in the new directory
#[test]
fn a_relative_program_runs_once_in_the_new_directory() {
    let _ = Runtime::init();

    let scratch = std::env::temp_dir().join(format!("atap-relative-{}.txt", std::process::id()));
    let _ = fs::remove_file(&scratch);

    let script = format!("echo x >> {}", scratch.display());

    let found = Runtime::block(Process::run("./sh", ["-c", &script]).in_dir("/bin"))
        .expect("a relative program must run rather than report a phantom ENOENT");

    assert!(found.success(), "the shell itself must succeed");

    let wrote = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);
    let _ = fs::remove_file(&scratch);

    assert_eq!(
        wrote, 2,
        "the program must run exactly once, wrote {wrote} bytes"
    );
}

/// A directory that isn't there is reported
#[test]
fn a_directory_that_is_not_there_is_reported() {
    let _ = Runtime::init();

    let found = Runtime::block(Process::run("/bin/pwd", Process::NO_ARGS).in_dir("/no/such/dir"));

    assert!(
        found.is_err(),
        "a missing directory must not be silently ignored, got {found:?}"
    );
}

/// A directory that can't be used is refused before anything
/// runs
#[test]
fn a_relative_directory_is_refused() {
    let _ = Runtime::init();

    let relative = Runtime::block(Process::run("/bin/pwd", Process::NO_ARGS).in_dir("build"));

    assert_eq!(
        relative,
        Err(RuntimeError::BadDirectory),
        "a relative directory must be refused, got {relative:?}"
    );

    let holed = Runtime::block(Process::run("/bin/pwd", Process::NO_ARGS).in_dir("/a\0b"));

    assert_eq!(
        holed,
        Err(RuntimeError::BadDirectory),
        "a zero byte must be refused, got {holed:?}"
    );
}

/// A variable reaches the child
#[test]
fn env_puts_a_variable_in_the_child() {
    let _ = Runtime::init();

    let handle = Runtime::task(
        Process::output("/bin/sh", ["-c", "printf %s \"$ATAP_TEST\""]).env([("ATAP_TEST", "yes")]),
    )
    .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("sh must settle")
        .expect("sh must run");

    assert_eq!(found.stdout(), b"yes", "the variable did not arrive");
}

/// An overlay leaves the rest of the environment alone
#[test]
fn env_leaves_the_rest_of_the_environment_alone() {
    let _ = Runtime::init();

    let handle = Runtime::task(
        Process::output("/bin/sh", ["-c", "printf %s \"$PATH\""]).env([("ATAP_TEST", "yes")]),
    )
    .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("sh must settle")
        .expect("sh must run");

    assert!(
        !found.stdout().is_empty(),
        "an overlay must not replace the whole environment"
    );
}

/// An overlay replaces a variable rather than adding it twice
#[test]
fn env_replaces_a_variable_rather_than_adding_it_twice() {
    let _ = Runtime::init();

    let handle = Runtime::task(
        Process::output("/bin/sh", ["-c", "env | grep -c '^HOME='"]).env([("HOME", "/atap")]),
    )
    .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("sh must settle")
        .expect("sh must run");

    let seen = String::from_utf8_lossy(found.stdout()).trim().to_string();

    assert_eq!(seen, "1", "HOME appeared {seen} times, not once");

    let value = Runtime::task(
        Process::output("/bin/sh", ["-c", "printf %s \"$HOME\""]).env([("HOME", "/atap")]),
    )
    .spawn();

    let found = settled(&value, PATIENCE)
        .expect("sh must settle")
        .expect("sh must run");

    assert_eq!(
        found.stdout(),
        b"/atap",
        "and the overlay's value is the one kept"
    );
}

/// A replaced environment gives the child nothing else
#[test]
fn env_only_gives_the_child_nothing_else() {
    let _ = Runtime::init();

    let handle =
        Runtime::task(Process::output("/usr/bin/env", Process::NO_ARGS).env_only([("ONLY", "1")]))
            .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("env must settle")
        .expect("env must run");

    assert_eq!(
        found.stdout(),
        b"ONLY=1\n",
        "the child kept more than it was given: {:?}",
        String::from_utf8_lossy(found.stdout())
    );
}

/// A variable that can't be passed on is refused
#[test]
fn a_bad_variable_is_refused() {
    let _ = Runtime::init();

    for (name, value, why) in [
        ("A\0B", "x", "a zero byte in the name"),
        ("A", "x\0y", "a zero byte in the value"),
        ("A=B", "x", "an equals sign in the name"),
        ("", "x", "an empty name"),
    ] {
        let found =
            Runtime::block(Process::run("/usr/bin/true", Process::NO_ARGS).env([(name, value)]));

        assert_eq!(
            found,
            Err(RuntimeError::BadVariable),
            "{why} must be refused, got {found:?}"
        );
    }
}

/// Input, directory and environment all at once
#[test]
fn all_three_at_once() {
    let _ = Runtime::init();

    let handle = Runtime::task(
        Process::output("/bin/sh", ["-c", "cat; pwd; printf %s \"$V\""])
            .input(b"fed\n".as_slice())
            .in_dir("/usr")
            .env([("V", "set")]),
    )
    .spawn();

    let found = settled(&handle, PATIENCE)
        .expect("sh must settle")
        .expect("sh must run");

    let said = String::from_utf8_lossy(found.stdout()).to_string();

    assert_eq!(
        said, "fed\n/usr\nset",
        "the three settings interfered: {said:?}"
    );
}

/// A spawned child can be written to and read from while it runs
#[test]
fn a_running_child_talks_back() {
    let _ = Runtime::init();

    let child =
        Runtime::block(Process::spawn("/bin/cat", Process::NO_ARGS)).expect("cat must start");
    let input = child.stdin().expect("a fresh child's input is open");

    for line in [b"one\n".as_slice(), b"two\n".as_slice()] {
        Runtime::block(input.send(line)).expect("the child must take its input");

        let echoed = Runtime::task(child.stdout().recv_until(b"\n", 64))
            .spawn()
            .take_with_timeout(PATIENCE)
            .expect("the echo must come back");

        assert_eq!(echoed.as_deref(), Ok(line));
    }

    child.close_stdin();
    drop(input);

    assert!(child.stdin().is_none(), "a closed input is gone");

    let status = Runtime::task(child.wait())
        .spawn()
        .take_with_timeout(PATIENCE)
        .expect("cat must end once its input does")
        .expect("cat must be reaped");

    assert!(status.success());
    assert_eq!(
        Runtime::block(child.wait()),
        Ok(status),
        "a second wait gives the same answer"
    );
}

/// A child's two output streams stay apart, and read to their ends
#[test]
fn a_running_child_keeps_its_streams_apart() {
    let _ = Runtime::init();

    let child = Runtime::block(Process::spawn("/bin/sh", ["-c", "echo out; echo err >&2"]))
        .expect("sh must start");

    assert_eq!(
        Runtime::block(child.stdout().recv_to_end()),
        Ok(b"out\n".to_vec())
    );
    assert_eq!(
        Runtime::block(child.stderr().recv_to_end()),
        Ok(b"err\n".to_vec())
    );
    assert!(Runtime::block(child.wait()).unwrap().success());
}

/// A killed child reports the kill, and can't be signalled once
/// reaped
#[test]
fn a_running_child_can_be_killed() {
    let _ = Runtime::init();

    let child = Runtime::block(Process::spawn("/bin/sleep", ["60"])).expect("sleep must start");

    assert!(child.id() > 0);

    let waiting = Runtime::task(child.wait()).spawn();

    Runtime::block(child.kill()).expect("the kill must go");

    let status = waiting
        .take_with_timeout(PATIENCE)
        .expect("the wait must see the kill")
        .expect("the child must be reaped");

    assert_eq!(status.signal(), Some(libc::SIGKILL));
    assert_eq!(Runtime::block(child.kill()), Err(RuntimeError::Finished));
}

/// A signal of the program's choosing reaches the child
#[test]
fn a_running_child_can_be_signalled() {
    let _ = Runtime::init();

    let child = Runtime::block(Process::spawn("/bin/sleep", ["60"])).expect("sleep must start");

    Runtime::block(child.signal(SignalKind::Terminate)).expect("the signal must go");

    let status = Runtime::task(child.wait())
        .spawn()
        .take_with_timeout(PATIENCE)
        .expect("the wait must see the signal")
        .expect("the child must be reaped");

    assert_eq!(status.signal(), Some(libc::SIGTERM));
}

/// A cancelled wait leaves the child running
#[test]
fn a_cancelled_wait_leaves_the_child() {
    let _ = Runtime::init();

    let child =
        Runtime::block(Process::spawn("/bin/cat", Process::NO_ARGS)).expect("cat must start");

    let waiting = Runtime::task(child.wait()).spawn();
    thread::sleep(Duration::from_millis(100));

    waiting.clone().cancel();
    assert_eq!(
        waiting.join_with_timeout(PATIENCE),
        Err(RuntimeError::Cancelled)
    );

    let input = child.stdin().unwrap();
    Runtime::block(input.send(b"still here\n".as_slice())).expect("the child must still read");

    assert_eq!(
        Runtime::block(child.stdout().recv_until(b"\n", 64)),
        Ok(b"still here\n".to_vec())
    );

    Runtime::block(child.kill()).unwrap();
    assert!(Runtime::block(child.wait()).unwrap().signal().is_some());
}

/// Dropping the last handle on a child ends it
#[test]
fn dropping_a_running_child_kills_it() {
    let _ = Runtime::init();

    let scratch = std::env::temp_dir().join(format!("atap-spawned-{}.txt", std::process::id()));
    let _ = fs::remove_file(&scratch);

    let script = format!(
        "while true; do echo x >> {}; sleep 0.05; done",
        scratch.display()
    );

    let child = Runtime::block(Process::spawn("/bin/sh", ["-c", &script])).expect("sh must start");
    let copy = child.clone();

    thread::sleep(Duration::from_millis(300));
    drop(child);

    thread::sleep(Duration::from_millis(200));
    assert!(
        fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0) > 0,
        "the child never wrote, so this proves nothing"
    );

    drop(copy);

    // Long enough for a surviving child to write many more times
    thread::sleep(Duration::from_millis(300));
    let settled_at = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    thread::sleep(Duration::from_millis(750));
    let later = fs::metadata(&scratch).map(|found| found.len()).unwrap_or(0);

    let _ = fs::remove_file(&scratch);

    assert_eq!(settled_at, later, "the child outlived its last handle");
}

/// A program that isn't there is refused before anything is handed
/// back
#[test]
fn spawning_a_missing_program_fails() {
    let _ = Runtime::init();

    assert_eq!(
        Runtime::block(Process::spawn("/no/such/program", Process::NO_ARGS)).map(|_| ()),
        Err(RuntimeError::CheckError(Some(libc::ENOENT)))
    );
}