haz-exec 0.1.0

Async task execution engine for haz.
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
//! Test-double [`ProcessSpawner`]: a script-and-record mock.
//!
//! The mock pairs an outbound FIFO of [`MockSpec`] values (canned
//! stdout/stderr/exit/pid) with an inbound log of [`SpawnRecord`]
//! captures. Every [`ProcessSpawner::spawn`] call pops the front
//! spec, records the [`SpawnPlan`], and returns a [`MockProcess`]
//! whose stream readers serve the canned bytes and whose
//! [`Process::wait`] yields the canned exit code.
//!
//! The mock is intentionally NOT an in-memory simulator (there is
//! no shared "process state" the way [`MemFilesystem`] simulates a
//! filesystem): processes are transient, so the test double is a
//! scriptable stub rather than a full model.
//!
//! [`MemFilesystem`]: haz_vfs::MemFilesystem

use std::collections::VecDeque;
use std::io::Cursor;
use std::sync::{Arc, Mutex, PoisonError};

use tokio::sync::Notify;

use crate::process::{
    ExitStatus, Process, ProcessError, ProcessId, ProcessSpawner, Signal, SpawnPlan, Spawned,
};

/// Wait-vs-signal behaviour of a scripted [`MockProcess`].
///
/// Lets cancellation tests script the three useful response
/// patterns of a child to the executor's signals:
///
/// - [`Self::Immediate`] (default): [`Process::wait`] returns
///   the spec's `exit_code` right away. Signals are recorded but
///   do not affect timing. This preserves the no-delay
///   behaviour used by tests written before scheduled
///   cancellation landed.
/// - [`Self::OnTerminate`]: [`Process::wait`] blocks until a
///   `SIGTERM` (or `SIGKILL`) is delivered, then returns. Models a
///   well-behaved child that exits cleanly on a polite termination
///   request. Picks `graceful_exit_code` on SIGTERM and the spec's
///   `exit_code` on SIGKILL.
/// - [`Self::OnKillOnly`]: [`Process::wait`] blocks indefinitely
///   on SIGTERM (`signals` are recorded but ignored) and returns
///   only on SIGKILL. Models a stubborn child that ignores polite
///   termination requests; exercises the grace-period escalation
///   path of `EXEC-014`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum MockBehaviour {
    /// `wait` returns the spec's `exit_code` immediately.
    #[default]
    Immediate,
    /// `wait` blocks until SIGTERM or SIGKILL arrives. SIGTERM
    /// yields `graceful_exit_code`; SIGKILL yields the spec's
    /// `exit_code`.
    OnTerminate {
        /// Exit code reported when SIGTERM completes the wait.
        graceful_exit_code: i32,
    },
    /// `wait` blocks until SIGKILL arrives. SIGTERM is recorded but
    /// does not unblock the wait.
    OnKillOnly,
}

/// One canned response the mock returns from a single spawn.
///
/// Test code constructs a `MockSpec` per expected spawn and pushes
/// it via [`MockProcessSpawner::push_spec`]. When the FIFO empties,
/// subsequent spawns receive [`MockSpec::default`].
#[derive(Debug, Clone)]
pub struct MockSpec {
    /// Bytes the spawned child's stdout reader yields, in order.
    pub stdout: Vec<u8>,
    /// Bytes the spawned child's stderr reader yields, in order.
    pub stderr: Vec<u8>,
    /// Exit code [`Process::wait`] reports. Defaults to `0` (success).
    pub exit_code: i32,
    /// [`Process::id`] return value before [`Process::wait`] is called.
    /// Defaults to `Some(ProcessId(1))`.
    pub pid: Option<ProcessId>,
    /// Wait-vs-signal behaviour of the produced [`MockProcess`].
    /// Defaults to [`MockBehaviour::Immediate`] so tests written
    /// before scheduled cancellation landed behave unchanged.
    pub behaviour: MockBehaviour,
}

impl Default for MockSpec {
    fn default() -> Self {
        Self {
            stdout: Vec::new(),
            stderr: Vec::new(),
            exit_code: 0,
            pid: Some(ProcessId(1)),
            behaviour: MockBehaviour::default(),
        }
    }
}

/// One captured spawn against [`MockProcessSpawner`].
///
/// Returned in chronological order by [`MockProcessSpawner::spawns`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpawnRecord {
    /// The plan as it was passed to [`ProcessSpawner::spawn`].
    pub plan: SpawnPlan,
}

#[derive(Debug, Default)]
struct SharedState {
    specs: VecDeque<MockSpec>,
    spawns: Vec<SpawnRecord>,
    /// Parallel to [`Self::spawns`]: each entry is the shared
    /// signal log for the corresponding spawn. The
    /// [`MockProcess`] holds a clone of the same [`Arc`] and
    /// appends to it on every [`Process::send_signal`] call, so
    /// tests can inspect the delivered signals after the
    /// [`MockProcess`] has been consumed by the spawn-step
    /// future.
    signal_logs: Vec<Arc<Mutex<Vec<Signal>>>>,
}

/// Test-double [`ProcessSpawner`]. Cheap to clone (state is shared).
#[derive(Debug, Default, Clone)]
pub struct MockProcessSpawner {
    state: Arc<Mutex<SharedState>>,
}

impl MockProcessSpawner {
    /// Construct a new mock with no scripted specs.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Append `spec` to the mock's FIFO. The next spawn pops `spec`
    /// from the front and shapes its [`Spawned`] value accordingly.
    ///
    /// Lock poisoning is recovered from rather than panicked on:
    /// the test-double state is well-typed and safe to mutate
    /// even after a prior holder panicked.
    pub fn push_spec(&self, spec: MockSpec) {
        self.state
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .specs
            .push_back(spec);
    }

    /// Snapshot of every spawn that has happened against this mock,
    /// in chronological order. Lock poisoning is recovered from
    /// rather than panicked on; see [`Self::push_spec`].
    #[must_use]
    pub fn spawns(&self) -> Vec<SpawnRecord> {
        self.state
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .spawns
            .clone()
    }

    /// Snapshot of every [`Signal`] delivered to the
    /// `index`-th spawn (0-based, chronological), in the order
    /// they were delivered. Returns `None` when `index` is out
    /// of range so callers can distinguish "no signals yet"
    /// (`Some(vec![])`) from "no such spawn"
    /// (`None`).
    ///
    /// Lets tests inspect the cancellation flow's signal trace
    /// after the [`MockProcess`] has been consumed by the
    /// spawn-step future. Lock poisoning is recovered from
    /// rather than panicked on: the test-double state is
    /// well-typed and safe to read even after a prior holder
    /// panicked.
    #[must_use]
    pub fn signals_for(&self, index: usize) -> Option<Vec<Signal>> {
        let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
        let log = state.signal_logs.get(index)?;
        let snapshot = log.lock().unwrap_or_else(PoisonError::into_inner).clone();
        Some(snapshot)
    }
}

impl ProcessSpawner for MockProcessSpawner {
    type Process = MockProcess;

    async fn spawn(&self, plan: &SpawnPlan) -> Result<Spawned<Self::Process>, ProcessError> {
        if !plan.cwd.is_absolute() {
            return Err(ProcessError::NonAbsoluteCwd {
                cwd: plan.cwd.clone(),
            });
        }

        let signal_log = Arc::new(Mutex::new(Vec::new()));
        let spec = {
            let mut guard = self.state.lock().map_err(|_| ProcessError::SpawnFailed {
                program: plan.program.clone(),
                source: std::io::Error::other("mock spawner internal state lock poisoned"),
            })?;
            guard.spawns.push(SpawnRecord { plan: plan.clone() });
            guard.signal_logs.push(signal_log.clone());
            guard.specs.pop_front().unwrap_or_default()
        };

        Ok(Spawned {
            process: MockProcess {
                pid: spec.pid,
                exit_code: spec.exit_code,
                behaviour: spec.behaviour,
                signals: signal_log,
                signal_state: SignalState::Pending,
                wake: Arc::new(Notify::new()),
            },
            stdout: Cursor::new(spec.stdout),
            stderr: Cursor::new(spec.stderr),
        })
    }
}

/// Internal record of which exit-driving signal the mock has
/// observed, if any. Drives the `wait` future's exit branch for
/// the [`MockBehaviour::OnTerminate`] /
/// [`MockBehaviour::OnKillOnly`] variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SignalState {
    Pending,
    Terminated,
    Killed,
}

/// Test-double [`Process`] returned by [`MockProcessSpawner::spawn`].
#[derive(Debug)]
pub struct MockProcess {
    pid: Option<ProcessId>,
    exit_code: i32,
    behaviour: MockBehaviour,
    /// Shared log: each [`Process::send_signal`] call appends
    /// to this vector. The owning [`MockProcessSpawner`] holds
    /// a clone of the same [`Arc`] so tests can retrieve the
    /// signal trace after the [`MockProcess`] has been
    /// consumed by the spawn-step future.
    signals: Arc<Mutex<Vec<Signal>>>,
    signal_state: SignalState,
    wake: Arc<Notify>,
}

impl MockProcess {
    /// Snapshot of every signal delivered to this child so far.
    ///
    /// Lock poisoning is recovered from rather than panicked
    /// on: the test-double state is well-typed and safe to
    /// read even after a prior holder panicked.
    #[must_use]
    pub fn signals(&self) -> Vec<Signal> {
        self.signals
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }
}

impl Process for MockProcess {
    type Stdout = Cursor<Vec<u8>>;
    type Stderr = Cursor<Vec<u8>>;

    fn id(&self) -> Option<ProcessId> {
        self.pid
    }

    fn send_signal(&mut self, signal: Signal) -> Result<(), ProcessError> {
        self.signals
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .push(signal);
        // Update the internal signal state for the wait-coordinated
        // behaviours. SIGINT does not exit the wait by itself; only
        // SIGTERM / SIGKILL drive the mock's wait future.
        match signal {
            Signal::Terminate => {
                if self.signal_state == SignalState::Pending {
                    self.signal_state = SignalState::Terminated;
                }
            }
            Signal::Kill => {
                self.signal_state = SignalState::Killed;
            }
            Signal::Interrupt => {}
        }
        self.wake.notify_waiters();
        Ok(())
    }

    async fn wait(&mut self) -> Result<ExitStatus, ProcessError> {
        loop {
            if let Some(code) = self.poll_exit_code() {
                // Reaping clears the pid, mirroring tokio::process::Child.
                self.pid = None;
                return Ok(synthetic_exit_status(code));
            }
            // Wait for the next signal delivery and re-check.
            let waiter = self.wake.clone();
            waiter.notified().await;
        }
    }
}

impl MockProcess {
    /// If the current signal state and behaviour resolve to an
    /// exit, return the exit code [`Process::wait`] should report.
    fn poll_exit_code(&self) -> Option<i32> {
        match (self.behaviour, self.signal_state) {
            (MockBehaviour::OnTerminate { graceful_exit_code }, SignalState::Terminated) => {
                Some(graceful_exit_code)
            }
            (MockBehaviour::Immediate, _)
            | (
                MockBehaviour::OnTerminate { .. } | MockBehaviour::OnKillOnly,
                SignalState::Killed,
            ) => Some(self.exit_code),
            _ => None,
        }
    }
}

#[cfg(unix)]
fn synthetic_exit_status(code: i32) -> ExitStatus {
    use std::os::unix::process::ExitStatusExt;
    // The wait(2) status word is `(exit_code << 8) | signal_number`
    // on all the Unix platforms the codebase targets.
    ExitStatus::from_raw((code & 0xff) << 8)
}

#[cfg(not(unix))]
#[allow(clippy::cast_sign_loss)]
fn synthetic_exit_status(code: i32) -> ExitStatus {
    use std::os::windows::process::ExitStatusExt;
    ExitStatus::from_raw(code as u32)
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::path::PathBuf;

    use tokio::io::AsyncReadExt;

    use super::*;

    fn abs(path: &str) -> PathBuf {
        // A platform-portable absolute path the mock will accept.
        let mut p = std::env::temp_dir();
        p.push(path);
        p
    }

    fn plan(program: &str) -> SpawnPlan {
        SpawnPlan {
            program: OsString::from(program),
            args: Vec::new(),
            env: Vec::new(),
            cwd: abs("haz-exec-mock-tests"),
        }
    }

    #[tokio::test]
    async fn spawn_records_plan_in_chronological_order() {
        let spawner = MockProcessSpawner::new();
        let _ = spawner.spawn(&plan("first")).await.unwrap();
        let _ = spawner.spawn(&plan("second")).await.unwrap();

        let records = spawner.spawns();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].plan.program, OsString::from("first"));
        assert_eq!(records[1].plan.program, OsString::from("second"));
    }

    #[tokio::test]
    async fn spawn_uses_default_spec_when_queue_empty() {
        let spawner = MockProcessSpawner::new();
        let mut child = spawner.spawn(&plan("noop")).await.unwrap();

        let mut stdout = Vec::new();
        child.stdout.read_to_end(&mut stdout).await.unwrap();
        let mut stderr = Vec::new();
        child.stderr.read_to_end(&mut stderr).await.unwrap();
        let status = child.process.wait().await.unwrap();

        assert!(stdout.is_empty());
        assert!(stderr.is_empty());
        assert!(status.success());
        #[cfg(unix)]
        assert_eq!(status.code(), Some(0));
    }

    #[tokio::test]
    async fn spawn_pops_specs_in_fifo_order() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            stdout: b"first-out".to_vec(),
            ..MockSpec::default()
        });
        spawner.push_spec(MockSpec {
            stdout: b"second-out".to_vec(),
            ..MockSpec::default()
        });

        let mut a = spawner.spawn(&plan("a")).await.unwrap();
        let mut b = spawner.spawn(&plan("b")).await.unwrap();

        let mut a_bytes = Vec::new();
        a.stdout.read_to_end(&mut a_bytes).await.unwrap();
        let mut b_bytes = Vec::new();
        b.stdout.read_to_end(&mut b_bytes).await.unwrap();

        assert_eq!(a_bytes, b"first-out");
        assert_eq!(b_bytes, b"second-out");
    }

    #[tokio::test]
    async fn spawn_yields_canned_streams() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            stdout: b"out-bytes".to_vec(),
            stderr: b"err-bytes".to_vec(),
            ..MockSpec::default()
        });

        let mut child = spawner.spawn(&plan("p")).await.unwrap();
        let mut stdout = Vec::new();
        child.stdout.read_to_end(&mut stdout).await.unwrap();
        let mut stderr = Vec::new();
        child.stderr.read_to_end(&mut stderr).await.unwrap();

        assert_eq!(stdout, b"out-bytes");
        assert_eq!(stderr, b"err-bytes");
    }

    #[tokio::test]
    async fn wait_yields_canned_exit_code() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            exit_code: 42,
            ..MockSpec::default()
        });

        let mut child = spawner.spawn(&plan("p")).await.unwrap();
        let status = child.process.wait().await.unwrap();

        assert!(!status.success());
        assert_eq!(status.code(), Some(42));
    }

    #[tokio::test]
    async fn wait_clears_pid() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            pid: Some(ProcessId(12_345)),
            ..MockSpec::default()
        });

        let mut child = spawner.spawn(&plan("p")).await.unwrap();
        assert_eq!(child.process.id(), Some(ProcessId(12_345)));
        let _ = child.process.wait().await.unwrap();
        assert_eq!(child.process.id(), None);
    }

    #[tokio::test]
    async fn id_propagates_explicit_none_from_spec() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            pid: None,
            ..MockSpec::default()
        });

        let child = spawner.spawn(&plan("p")).await.unwrap();
        assert_eq!(child.process.id(), None);
    }

    #[tokio::test]
    async fn send_signal_records_in_order() {
        let spawner = MockProcessSpawner::new();
        let mut child = spawner.spawn(&plan("p")).await.unwrap();

        child.process.send_signal(Signal::Terminate).unwrap();
        child.process.send_signal(Signal::Interrupt).unwrap();
        child.process.send_signal(Signal::Kill).unwrap();

        assert_eq!(
            child.process.signals(),
            &[Signal::Terminate, Signal::Interrupt, Signal::Kill]
        );
    }

    #[tokio::test]
    async fn spawn_rejects_relative_cwd() {
        let spawner = MockProcessSpawner::new();
        let p = SpawnPlan {
            program: OsString::from("p"),
            args: Vec::new(),
            env: Vec::new(),
            cwd: PathBuf::from("relative/path"),
        };
        match spawner.spawn(&p).await {
            Err(ProcessError::NonAbsoluteCwd { cwd }) => {
                assert_eq!(cwd, PathBuf::from("relative/path"));
            }
            Err(other) => panic!("expected NonAbsoluteCwd, got {other:?}"),
            Ok(_) => panic!("expected NonAbsoluteCwd, got success"),
        }
        // A rejected spawn does not get recorded.
        assert!(spawner.spawns().is_empty());
    }

    #[tokio::test]
    async fn cloned_spawner_shares_state() {
        let a = MockProcessSpawner::new();
        let b = a.clone();
        a.push_spec(MockSpec {
            stdout: b"shared".to_vec(),
            ..MockSpec::default()
        });

        let mut child = b.spawn(&plan("p")).await.unwrap();
        let mut stdout = Vec::new();
        child.stdout.read_to_end(&mut stdout).await.unwrap();
        assert_eq!(stdout, b"shared");
        assert_eq!(a.spawns().len(), 1);
        assert_eq!(b.spawns().len(), 1);
    }

    #[tokio::test]
    async fn spawn_records_full_plan_including_args_and_env() {
        let spawner = MockProcessSpawner::new();
        let p = SpawnPlan {
            program: OsString::from("p"),
            args: vec![OsString::from("a"), OsString::from("b")],
            env: vec![(OsString::from("K"), OsString::from("V"))],
            cwd: abs("captured"),
        };
        let _ = spawner.spawn(&p).await.unwrap();
        let records = spawner.spawns();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].plan, p);
    }

    #[tokio::test]
    async fn wait_with_exit_on_terminate_blocks_until_sigterm_arrives() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            behaviour: MockBehaviour::OnTerminate {
                graceful_exit_code: 5,
            },
            exit_code: 99,
            ..MockSpec::default()
        });
        let mut child = spawner.spawn(&plan("p")).await.unwrap();

        // Without a signal, wait must not resolve. Race it against
        // a short timer in its own scope so the borrow drops at the
        // end of the block.
        {
            let wait_fut = child.process.wait();
            let timeout = tokio::time::sleep(std::time::Duration::from_millis(20));
            tokio::pin!(wait_fut, timeout);
            tokio::select! {
                biased;
                () = &mut timeout => {}
                _ = &mut wait_fut => panic!("wait should not resolve before a signal"),
            }
        }
        child.process.send_signal(Signal::Terminate).unwrap();
        let status = child.process.wait().await.unwrap();
        assert!(!status.success());
        assert_eq!(status.code(), Some(5));
        assert_eq!(child.process.signals(), &[Signal::Terminate]);
    }

    #[tokio::test]
    async fn wait_with_exit_on_terminate_completes_on_sigkill_too() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            behaviour: MockBehaviour::OnTerminate {
                graceful_exit_code: 5,
            },
            exit_code: 137,
            ..MockSpec::default()
        });
        let mut child = spawner.spawn(&plan("p")).await.unwrap();

        child.process.send_signal(Signal::Kill).unwrap();
        let status = child.process.wait().await.unwrap();
        assert_eq!(status.code(), Some(137));
    }

    #[tokio::test]
    async fn wait_with_exit_on_kill_only_ignores_sigterm_until_sigkill() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            behaviour: MockBehaviour::OnKillOnly,
            exit_code: 137,
            ..MockSpec::default()
        });
        let mut child = spawner.spawn(&plan("p")).await.unwrap();

        // SIGTERM is recorded but does not unblock the wait.
        child.process.send_signal(Signal::Terminate).unwrap();
        {
            let wait_fut = child.process.wait();
            let timeout = tokio::time::sleep(std::time::Duration::from_millis(20));
            tokio::pin!(wait_fut, timeout);
            tokio::select! {
                biased;
                () = &mut timeout => {}
                _ = &mut wait_fut => panic!("wait should not resolve on SIGTERM in OnKillOnly"),
            }
        }
        child.process.send_signal(Signal::Kill).unwrap();
        let status = child.process.wait().await.unwrap();
        assert_eq!(status.code(), Some(137));
        assert_eq!(child.process.signals(), &[Signal::Terminate, Signal::Kill]);
    }

    #[tokio::test]
    async fn wait_exit_immediately_returns_without_signal() {
        let spawner = MockProcessSpawner::new();
        spawner.push_spec(MockSpec {
            behaviour: MockBehaviour::Immediate,
            exit_code: 0,
            ..MockSpec::default()
        });
        let mut child = spawner.spawn(&plan("p")).await.unwrap();
        let status = child.process.wait().await.unwrap();
        assert!(status.success());
    }
}