agplatform 0.4.1

Platform providing env, fs, request and process infrastructure for production and testing
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
use std::collections::VecDeque;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;

use crate::CommandOptions;
use crate::CommandOutput;
use crate::CommandRun;
use crate::OutputStream;
use crate::Process;
use crate::ProcessObserver;
use crate::Result;
use crate::env::SharedEnv;
use crate::env::record_change;
use crate::process::OutputSink;
use crate::process::Outputs;
use crate::process::StdObserver;
use crate::process::check;
use crate::process::io_error;
use crate::process::run_attempts;
#[cfg(feature = "tokio")]
use crate::process::{AsyncAttempts, SinkAttempts, run_attempts_async};
use crate::test_platform::ROOT;
use crate::test_platform::gate::Gate;
use crate::test_platform::gate::HeldGate;
use crate::utils::ObserverCell;

/// Enabled by the `testing` feature flag.
///
/// A memory-only [`crate::Process`] implementation for tests. No real
/// process is ever spawned. Commands are matched by their command line
/// (the program and the arguments separated by spaces) against the
/// patterns set with [`TestProcess::set_output`] and
/// [`TestProcess::set_io_error`].
///
/// # Examples
///
/// ```rust
/// use agplatform::{CommandExt, CommandOutput, TestProcess};
/// use std::process::Command;
///
/// let process = TestProcess::new();
/// process.set_output("git status", CommandOutput { status: Some(0), stdout: b"clean".to_vec(), ..Default::default() });
///
/// let output = Command::new("git").arg("status").run(&process).unwrap();
///
/// assert_eq!(output.stdout_str().unwrap(), "clean");
/// assert_eq!(process.calls(), ["git status"]);
/// ```
pub struct TestProcess {
    env: SharedEnv,
    data: Mutex<TestProcessData>,
    observer: ObserverCell<dyn ProcessObserver>,
}

/// Enabled by the `testing` feature flag.
///
/// A command run by [`TestProcess`], see [`TestProcess::call_details`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TestCall {
    /// The program and the arguments separated by spaces.
    pub command_line: String,

    /// The directory the command ran in, i.e. its own resolved against the
    /// current directory.
    pub current_dir: PathBuf,

    /// The environment variables the command got set (`Some`) or removed
    /// (`None`) on top of the inherited environment, which is cleared
    /// before with [`CommandOptions::clear_env`]: those changed on the
    /// platform followed by those of the command.
    pub vars: Vec<(String, Option<String>)>,

    /// The options of the run.
    pub options: CommandOptions,
}

#[derive(Default)]
struct TestProcessData {
    responses: Vec<(String, VecDeque<TestResponse>)>,
    calls: Vec<TestCall>,
}

#[derive(Clone)]
struct TestResponse {
    result: std::result::Result<CommandOutput, std::io::ErrorKind>,
    gate: Option<Gate<std::convert::Infallible>>,
}

/// Enabled by the `testing` and `process` feature flags.
///
/// Holds the runs answered by [`TestProcess::set_pending`] until it is
/// released, e.g. to check what happens while a command is running or
/// when its run is cancelled. Clones share the gate, so it can be released
/// from another thread or task.
///
/// Dropping all clones releases it, so that a test failing before it
/// releases the gate does not hang waiting for the held runs, e.g. at the
/// end of [`std::thread::scope`] if it is created in the scope.
#[derive(Clone)]
pub struct TestProcessGate(HeldGate<std::convert::Infallible>);

impl TestProcess {
    /// Creates a new test process interface whose current directory is
    /// the [`ROOT`] directory.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::TestProcess;
    ///
    /// let process = TestProcess::new();
    /// ```
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            env: SharedEnv::new(Vec::new(), PathBuf::from(ROOT)),
            data: Mutex::new(TestProcessData::default()),
            observer: ObserverCell::new(Arc::new(StdObserver)),
        }
    }

    /// Returns the command lines of all commands run so far, oldest
    /// first.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, TestProcess};
    /// use std::process::Command;
    ///
    /// let process = TestProcess::new();
    /// let _ = Command::new("git").arg("status").run(&process);
    ///
    /// assert_eq!(process.calls(), ["git status"]);
    /// ```
    pub fn calls(&self) -> Vec<String> {
        self.data()
            .calls
            .iter()
            .map(|call| call.command_line.clone())
            .collect()
    }

    /// Returns all commands run so far with their directory, environment
    /// variables and options, oldest first.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, TestProcess};
    /// use std::process::Command;
    ///
    /// let process = TestProcess::new();
    /// let _ = Command::new("kubectl")
    ///     .current_dir("repo")
    ///     .env("KUBECONFIG", "config")
    ///     .input("manifest")
    ///     .run(&process);
    ///
    /// let call = &process.call_details()[0];
    /// assert_eq!(call.command_line, "kubectl");
    /// assert!(call.current_dir.ends_with("repo"));
    /// assert_eq!(call.vars, [("KUBECONFIG".to_string(), Some("config".to_string()))]);
    /// assert_eq!(call.options.input.as_deref(), Some(b"manifest".as_slice()));
    /// ```
    pub fn call_details(&self) -> Vec<TestCall> {
        self.data().calls.clone()
    }

    /// Forgets the commands run so far.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, TestProcess};
    /// use std::process::Command;
    ///
    /// let process = TestProcess::new();
    /// let _ = Command::new("git").arg("status").run(&process);
    /// process.clear_calls();
    ///
    /// assert!(process.calls().is_empty());
    /// ```
    pub fn clear_calls(&self) {
        self.data().calls.clear();
    }

    /// Sets the `output` of the commands whose command line starts with
    /// `pattern`. When more patterns match, the most recently set one
    /// (including by [`Self::set_io_error`]) wins, so an empty pattern
    /// set first acts as a default.
    ///
    /// A [`CommandOutput::duration`] longer than the
    /// [`CommandOptions::timeout`] of a command makes it time out, without
    /// waiting. The output with non-zero status will return an error with
    /// the output attached to it that can be retrieved via [`Error::command_output`](crate::Error::command_output).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, CommandOutput, TestProcess};
    /// use std::process::Command;
    ///
    /// let process = TestProcess::new();
    /// process.set_output("", CommandOutput { status: Some(0), ..Default::default() });
    /// process.set_output("git push", CommandOutput { status: Some(1), ..Default::default() });
    ///
    /// assert!(Command::new("git").arg("pull").run(&process).is_ok());
    /// assert!(Command::new("git").arg("push").run(&process).is_err());
    /// ```
    pub fn set_output<T: Into<String>>(&self, pattern: T, output: CommandOutput) {
        self.data().responses.push((
            pattern.into(),
            VecDeque::from([TestResponse::new(Ok(output))]),
        ));
    }

    /// Sets the `outputs` of the commands whose command line starts with
    /// `pattern`, returned one per run in order with the last one repeated,
    /// e.g. to make a command fail before it succeeds on a retry. Patterns
    /// match as in [`Self::set_output`]. No `outputs` set nothing.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, CommandOutput, TestProcess};
    /// use std::process::Command;
    /// use std::time::Duration;
    ///
    /// let process = TestProcess::new();
    /// let failure = CommandOutput { status: Some(1), ..Default::default() };
    /// let success = CommandOutput { status: Some(0), ..Default::default() };
    /// process.set_outputs("curl", [failure, success]);
    ///
    /// let output = Command::new("curl").retry(3, Duration::from_secs(1)).run(&process).unwrap();
    ///
    /// assert_eq!(output.status, Some(0));
    /// assert_eq!(process.calls(), ["curl", "curl"]);
    /// ```
    pub fn set_outputs<T: Into<String>, I: IntoIterator<Item = CommandOutput>>(
        &self,
        pattern: T,
        outputs: I,
    ) {
        let outputs: VecDeque<_> = outputs
            .into_iter()
            .map(|output| TestResponse::new(Ok(output)))
            .collect();

        if !outputs.is_empty() {
            self.data().responses.push((pattern.into(), outputs));
        }
    }

    /// Makes the commands whose command line starts with `pattern` fail to
    /// start with an [`std::io::Error`] of `kind`, e.g.
    /// [`NotFound`](std::io::ErrorKind::NotFound) for a program that is not
    /// installed. Patterns match as in [`Self::set_output`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, TestProcess};
    /// use std::io::ErrorKind;
    /// use std::process::Command;
    ///
    /// let process = TestProcess::new();
    /// process.set_io_error("docker", ErrorKind::NotFound);
    ///
    /// let error = Command::new("docker").run(&process).unwrap_err();
    ///
    /// assert_eq!(error.source_as::<std::io::Error>().unwrap().kind(), ErrorKind::NotFound);
    /// assert!(error.command_output().is_none());
    /// ```
    pub fn set_io_error<T: Into<String>>(&self, pattern: T, kind: std::io::ErrorKind) {
        self.data().responses.push((
            pattern.into(),
            VecDeque::from([TestResponse::new(Err(kind))]),
        ));
    }

    /// Makes the commands whose command line starts with `pattern` return
    /// `output` like [`Self::set_output`], held until the returned gate is
    /// released. The runs are recorded when they start, before being held.
    /// A [`CommandOptions::timeout`] does not end the hold.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use agplatform::{CommandExt, CommandOutput, TestProcess};
    /// use std::process::Command;
    ///
    /// let process = TestProcess::new();
    ///
    /// std::thread::scope(|scope| {
    ///     let gate = process.set_pending("cargo build", CommandOutput { status: Some(0), ..Default::default() });
    ///     let building = scope.spawn(|| Command::new("cargo").arg("build").run(&process));
    ///
    ///     while process.calls().is_empty() {
    ///         std::thread::yield_now();
    ///     }
    ///
    ///     assert!(!building.is_finished());
    ///     gate.release();
    ///     assert!(building.join().unwrap().is_ok());
    /// });
    /// ```
    pub fn set_pending<T: Into<String>>(
        &self,
        pattern: T,
        output: CommandOutput,
    ) -> TestProcessGate {
        let gate = TestProcessGate(HeldGate::new());
        self.data().responses.push((
            pattern.into(),
            VecDeque::from([TestResponse {
                gate: Some(gate.0.gate().clone()),
                ..TestResponse::new(Ok(output))
            }]),
        ));
        gate
    }

    /// [internal]
    ///
    /// Takes the current directory and the variable changes from `env`,
    /// e.g. of a [`TestPlatform`](crate::test_platform::TestPlatform).
    pub(crate) fn set_env(&mut self, env: SharedEnv) {
        self.env = env;
    }

    /// [internal]
    ///
    /// Returns the current directory the commands run in.
    #[cfg(test)]
    pub(crate) fn current_dir(&self) -> PathBuf {
        self.env.current_dir().to_path_buf()
    }

    fn respond(
        &self,
        observer: &dyn ProcessObserver,
        run: &CommandRun,
        sink: Option<&mut OutputSink>,
    ) -> Result<CommandOutput> {
        let response = self.select(run)?;

        if let Some(gate) = &response.gate {
            gate.wait();
        }

        self.deliver(observer, run, response.result, sink)
    }

    #[cfg(feature = "tokio")]
    async fn respond_async(
        &self,
        observer: &dyn ProcessObserver,
        run: &CommandRun<'_>,
        sink: Option<&mut OutputSink<'_>>,
    ) -> Result<CommandOutput> {
        let response = self.select(run)?;

        if let Some(gate) = &response.gate {
            gate.wait_async().await;
        }

        self.deliver(observer, run, response.result, sink)
    }

    /// Records the call of `run` and returns the response set for it, the
    /// most recent one matching.
    fn select(&self, run: &CommandRun) -> Result<TestResponse> {
        let (command, options) = (run.command(), run.options());
        let command_line = run.command_line();
        let mut vars = if options.clear_env {
            Vec::new()
        } else {
            run.var_changes().to_vec()
        };

        for (key, value) in command.get_envs() {
            record_change(
                &mut vars,
                key.to_string_lossy().into_owned(),
                value.map(|value| value.to_string_lossy().into_owned()),
            );
        }

        let mut data = self.data();
        data.calls.push(TestCall {
            command_line: command_line.clone(),
            // WHY: only runs resolved against the env are run.
            current_dir: run.current_dir().unwrap_or(Path::new("")).to_path_buf(),
            vars,
            options: options.clone(),
        });
        let response = data
            .responses
            .iter_mut()
            .rev()
            .find(|(pattern, _)| command_line.starts_with(pattern.as_str()))
            .and_then(|(_, responses)| {
                if responses.len() > 1 {
                    responses.pop_front()
                } else {
                    responses.front().cloned()
                }
            })
            .ok_or_else(|| process_error!("'{command_line}': no output set"));
        drop(data);
        response
    }

    /// Returns the output of `run` from the `result` set for it, applying
    /// its options.
    fn deliver(
        &self,
        observer: &dyn ProcessObserver,
        run: &CommandRun,
        result: std::result::Result<CommandOutput, std::io::ErrorKind>,
        sink: Option<&mut OutputSink>,
    ) -> Result<CommandOutput> {
        let options = run.options();
        let program = run.program();
        let output = result.map_err(|kind| io_error(&program, kind.into()))?;
        let output = CommandOutput {
            display_lines: options.display_lines,
            ..output
        };
        let output = if options.silent || options.interactive {
            CommandOutput {
                stdout: Vec::new(),
                stderr: Vec::new(),
                ..output
            }
        } else {
            output
        };

        let mut outputs = Outputs::new(observer, run, sink);

        if !output.stdout.is_empty() {
            outputs.push(OutputStream::Stdout, &output.stdout);
        }

        if !outputs.failed() && !output.stderr.is_empty() {
            outputs.push(OutputStream::Stderr, &output.stderr);
        }

        let (stdout, stderr) = outputs.finish()?;
        let output = CommandOutput {
            stdout,
            stderr,
            ..output
        };

        match options.timeout {
            Some(timeout) if output.duration > timeout => check(
                run,
                CommandOutput {
                    status: None,
                    duration: timeout,
                    timed_out: true,
                    ..output
                },
            ),
            _ => check(run, output),
        }
    }

    fn data(&self) -> std::sync::MutexGuard<'_, TestProcessData> {
        self.data.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl TestResponse {
    fn new(result: std::result::Result<CommandOutput, std::io::ErrorKind>) -> Self {
        Self { result, gate: None }
    }
}

impl TestProcessGate {
    /// Lets the held runs return their output, and the later ones at once.
    /// Does nothing if the gate was released already.
    pub fn release(&self) {
        self.0.gate().open(None);
    }
}

#[cfg(feature = "tokio")]
impl AsyncAttempts for SinkAttempts<'_, '_, TestProcess> {
    fn attempt(&mut self, run: &CommandRun) -> impl Future<Output = Result<CommandOutput>> + Send {
        self.process
            .respond_async(self.observer, run, self.sink.as_deref_mut())
    }

    /// Retries are not waited for.
    fn delay(&self, _: std::time::Duration) -> impl Future<Output = ()> + Send {
        std::future::ready(())
    }
}

impl Process for TestProcess {
    /// Records the command and returns the output set for it, without
    /// reading the input. With [`CommandOptions::stream`] the non-empty output
    /// set is reported to the observer at once. With
    /// [`CommandOptions::silent`] or [`CommandOptions::interactive`] the
    /// output set is dropped, as no output would be captured.
    ///
    /// See [`crate::Process::run`].
    ///
    /// # Errors
    ///
    /// Returns an error if no output was set for the command, an I/O error
    /// was set for it, or as [`crate::Process::run`] for the options and
    /// the output set.
    fn run<'a>(&self, run: impl Into<CommandRun<'a>>) -> Result<CommandOutput> {
        // WHY: retries are not waited for, like timeouts.
        let observer = self.observer.get();
        run_attempts(
            observer.as_ref(),
            run.into().resolve(&self.env),
            &mut |run| self.respond(observer.as_ref(), run, None),
            |_| {},
        )
    }

    /// Runs the command like [`Self::run`], passing the output set for it to
    /// `sink`, the standard output and then the standard error, each in one
    /// chunk unless empty.
    ///
    /// See [`crate::Process::run_to`].
    ///
    /// # Errors
    ///
    /// As [`Self::run`], or as [`crate::Process::run_to`].
    fn run_to<'a>(
        &self,
        run: impl Into<CommandRun<'a>>,
        sink: &mut (dyn FnMut(OutputStream, &[u8]) -> Result + Send),
    ) -> Result<CommandOutput> {
        let observer = self.observer.get();
        run_attempts(
            observer.as_ref(),
            run.into().resolve(&self.env).with_sink(),
            &mut |run| self.respond(observer.as_ref(), run, Some(&mut *sink)),
            |_| {},
        )
    }

    /// Runs the command like [`Self::run`] once awaited, holding only the
    /// task while a [`Self::set_pending`] gate is closed. Dropping the
    /// future cancels the run, which is reported to the observer.
    ///
    /// See [`crate::Process::run_async`].
    ///
    /// # Errors
    ///
    /// As [`Self::run`].
    #[cfg(feature = "tokio")]
    fn run_async<'a>(
        &self,
        run: impl Into<CommandRun<'a>>,
    ) -> impl Future<Output = Result<CommandOutput>> + Send {
        let run = run.into().resolve(&self.env);
        let observer = self.observer.get();

        async move {
            run_attempts_async(
                observer.as_ref(),
                run,
                &mut SinkAttempts {
                    process: self,
                    observer: observer.as_ref(),
                    sink: None,
                },
            )
            .await
        }
    }

    /// Runs the command like [`Self::run_async`], passing the output set for
    /// it to `sink` like [`Self::run_to`].
    ///
    /// See [`crate::Process::run_async_to`].
    ///
    /// # Errors
    ///
    /// As [`Self::run_to`].
    #[cfg(feature = "tokio")]
    fn run_async_to<'a>(
        &self,
        run: impl Into<CommandRun<'a>>,
        sink: &mut (dyn FnMut(OutputStream, &[u8]) -> Result + Send),
    ) -> impl Future<Output = Result<CommandOutput>> + Send {
        let run = run.into().resolve(&self.env).with_sink();
        let observer = self.observer.get();

        async move {
            run_attempts_async(
                observer.as_ref(),
                run,
                &mut SinkAttempts {
                    process: self,
                    observer: observer.as_ref(),
                    sink: Some(sink),
                },
            )
            .await
        }
    }

    /// Sets the observer of the runs starting afterwards, replacing the
    /// previous one.
    ///
    /// See [`crate::Process::set_observer`].
    fn set_observer(&self, observer: Arc<dyn ProcessObserver>) {
        self.observer.set(observer);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::CommandExt;
    use std::process::Command;
    use std::time::Duration;

    /// Changes of the env the process shares, like by its platform.
    impl TestProcess {
        fn set_var(&self, key: String, value: String) {
            self.env.set_var(key, value);
        }

        fn remove_var(&self, key: &str) {
            self.env.remove_var(key);
        }
    }

    fn exit(status: i32) -> CommandOutput {
        CommandOutput {
            status: Some(status),
            ..Default::default()
        }
    }

    #[cfg(feature = "tokio")]
    fn block_on<T>(future: impl Future<Output = T>) -> T {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap()
            .block_on(future)
    }

    #[derive(Default)]
    struct RecordingObserver(Mutex<Vec<String>>);

    impl ProcessObserver for RecordingObserver {
        fn started(&self, run: &CommandRun) {
            self.0.lock().unwrap().push(format!(
                "started {} in {}",
                run.command_line(),
                run.current_dir().unwrap().display()
            ));
        }

        fn stdout(&self, _run: &CommandRun, data: &[u8]) {
            self.0
                .lock()
                .unwrap()
                .push(format!("Stdout {}", String::from_utf8_lossy(data)));
        }

        fn stderr(&self, _run: &CommandRun, data: &[u8]) {
            self.0
                .lock()
                .unwrap()
                .push(format!("Stderr {}", String::from_utf8_lossy(data)));
        }

        fn finished(&self, _run: &CommandRun, result: &Result<CommandOutput>) {
            self.0
                .lock()
                .unwrap()
                .push(format!("finished {}", result.is_ok()));
        }
    }

    mod test_process {
        use super::*;

        mod calls {
            use super::*;

            #[test]
            fn calls_should_return_command_lines_in_order() {
                let process = TestProcess::new();
                process.set_output("", exit(0));

                Command::new("git").arg("pull").run(&process).unwrap();
                Command::new("git").arg("push").run(&process).unwrap();

                assert_eq!(process.calls(), ["git pull", "git push"]);
            }
        }

        mod call_details {
            use super::*;

            #[test]
            fn call_details_should_return_dir_vars_and_options() {
                // GIVEN platform variable changes
                let process = TestProcess::new();
                process.set_output("", exit(0));
                process.set_var("PLATFORM".to_string(), "1".to_string());
                process.set_var("OVERRIDDEN".to_string(), "1".to_string());
                process.remove_var("REMOVED");

                // WHEN running a command changing variables in a directory
                Command::new("sort")
                    .current_dir("repo")
                    .env("OVERRIDDEN", "2")
                    .env_remove("PLATFORM")
                    .input("b\na")
                    .run(&process)
                    .unwrap();

                // THEN the call has the resolved directory and the changes
                assert_eq!(
                    process.call_details(),
                    [TestCall {
                        command_line: "sort".to_string(),
                        current_dir: PathBuf::from(ROOT).join("repo"),
                        vars: vec![
                            ("REMOVED".to_string(), None),
                            ("OVERRIDDEN".to_string(), Some("2".to_string())),
                            ("PLATFORM".to_string(), None),
                        ],
                        options: CommandOptions {
                            input: Some(b"b\na".to_vec()),
                            ..Default::default()
                        },
                    }]
                );
            }

            #[test]
            fn call_details_clear_env_should_have_only_command_vars() {
                let process = TestProcess::new();
                process.set_output("", exit(0));
                process.set_var("PLATFORM".to_string(), "1".to_string());

                Command::new("git")
                    .env("OWN", "1")
                    .clear_env()
                    .run(&process)
                    .unwrap();

                assert_eq!(
                    process.call_details()[0].vars,
                    [("OWN".to_string(), Some("1".to_string()))]
                );
            }

            #[cfg(windows)]
            #[test]
            fn call_details_should_merge_vars_ignoring_case() {
                let process = TestProcess::new();
                process.set_output("", exit(0));
                process.set_var("Path".to_string(), "platform".to_string());

                Command::new("git")
                    .env("PATH", "own")
                    .run(&process)
                    .unwrap();

                assert_eq!(
                    process.call_details()[0].vars,
                    [("PATH".to_string(), Some("own".to_string()))]
                );
            }
        }

        mod clear_calls {
            use super::*;

            #[test]
            fn clear_calls_should_forget_calls() {
                let process = TestProcess::new();
                process.set_output("", exit(0));
                Command::new("git").run(&process).unwrap();

                process.clear_calls();

                assert!(process.calls().is_empty());
            }
        }

        mod set_output {
            use super::*;

            #[test]
            fn set_output_should_prefer_most_recent_matching_pattern() {
                // GIVEN a specific pattern followed by a more general one
                let process = TestProcess::new();
                process.set_output("git push", exit(1));
                process.set_output("git", exit(0));

                // WHEN running a command matching both
                let output = Command::new("git").arg("push").run(&process);

                // THEN the more recent one wins
                assert_eq!(output.unwrap(), exit(0));
            }
        }

        mod set_outputs {
            use super::*;

            #[test]
            fn set_outputs_should_return_outputs_in_order_repeating_last() {
                let process = TestProcess::new();
                process.set_outputs("git", vec![exit(1), exit(2), exit(0)]);

                let statuses: Vec<_> = (0..4)
                    .map(|_| match Command::new("git").run(&process) {
                        Ok(output) => output.status,
                        Err(error) => error.command_output().unwrap().status,
                    })
                    .collect();

                assert_eq!(statuses, [Some(1), Some(2), Some(0), Some(0)]);
            }

            #[test]
            fn set_outputs_empty_should_set_nothing() {
                let process = TestProcess::new();
                process.set_output("", exit(0));

                process.set_outputs("git", Vec::new());

                assert!(Command::new("git").run(&process).is_ok());
            }

            #[test]
            fn set_outputs_with_retries_should_succeed_without_waiting() {
                // GIVEN a command failing twice before it succeeds
                let process = TestProcess::new();
                process.set_outputs("curl", vec![exit(7), exit(7), exit(0)]);
                let start = std::time::Instant::now();

                // WHEN retrying it with a long delay
                let output = Command::new("curl")
                    .retry(2, Duration::from_secs(3600))
                    .run(&process)
                    .unwrap();

                // THEN the last attempt succeeds at once
                assert_eq!(output.status, Some(0));
                assert_eq!(process.calls(), ["curl", "curl", "curl"]);
                assert!(start.elapsed() < Duration::from_secs(60));
            }
        }

        mod set_io_error {
            use super::*;

            #[test]
            fn set_io_error_should_fail_run_with_io_source_naming_program() {
                let process = TestProcess::new();
                process.set_io_error("docker", std::io::ErrorKind::NotFound);

                let error = Command::new("docker")
                    .arg("version")
                    .run(&process)
                    .unwrap_err();

                assert_eq!(error.kind(), crate::ErrorKind::Process);
                assert!(error.description().starts_with("'docker': "));
                assert_eq!(
                    error
                        .source_as::<std::io::Error>()
                        .map(std::io::Error::kind),
                    Some(std::io::ErrorKind::NotFound)
                );
                assert!(error.command_output().is_none());
                assert_eq!(process.calls(), ["docker version"]);
            }

            #[test]
            fn set_io_error_should_override_earlier_matching_output() {
                // GIVEN a default output followed by an I/O error
                let process = TestProcess::new();
                process.set_output("", exit(0));
                process.set_io_error("docker", std::io::ErrorKind::PermissionDenied);

                // WHEN running a command matching both
                let result = Command::new("docker").run(&process);

                // THEN the more recent I/O error wins
                assert_eq!(
                    result
                        .unwrap_err()
                        .source_as::<std::io::Error>()
                        .map(std::io::Error::kind),
                    Some(std::io::ErrorKind::PermissionDenied)
                );
            }
        }

        mod set_pending {
            use super::*;

            #[test]
            fn set_pending_gate_dropped_should_release_run() {
                let process = TestProcess::new();
                let command = Command::new("cargo");

                std::thread::scope(|scope| {
                    let gate = process.set_pending("cargo", exit(0));
                    let running = scope.spawn(|| command.run(&process));
                    let _ = std::iter::repeat_with(std::thread::yield_now)
                        .find(|()| !process.calls().is_empty());

                    drop(gate);

                    assert_eq!(running.join().unwrap().unwrap(), exit(0));
                });
            }

            #[test]
            fn set_pending_should_hold_run_until_released() {
                // GIVEN a pending output
                let process = TestProcess::new();
                let gate = process.set_pending("cargo", exit(0));
                let command = Command::new("cargo");

                std::thread::scope(|scope| {
                    // WHEN running a command matching it
                    let running = scope.spawn(|| command.run(&process));

                    // THEN it is recorded and held until the gate is released
                    let _ = std::iter::repeat_with(std::thread::yield_now)
                        .find(|()| !process.calls().is_empty());
                    assert!(!running.is_finished());
                    gate.release();
                    assert_eq!(running.join().unwrap().unwrap(), exit(0));
                });
            }

            #[test]
            fn set_pending_released_should_not_hold_later_runs() {
                let process = TestProcess::new();
                let gate = process.set_pending("cargo", exit(0));

                gate.release();

                assert_eq!(Command::new("cargo").run(&process).unwrap(), exit(0));
            }

            #[cfg(feature = "tokio")]
            #[test]
            fn set_pending_should_hold_async_run_until_released() {
                // GIVEN an async run matching a pending output
                let process = TestProcess::new();
                let gate = process.set_pending("cargo", exit(0));
                let command = Command::new("cargo");
                let mut future = std::pin::pin!(command.run_async(&process));
                let mut context = std::task::Context::from_waker(std::task::Waker::noop());

                // WHEN polling it before and after releasing the gate
                let held = future.as_mut().poll(&mut context);
                gate.release();
                let result = block_on(future);

                // THEN it is recorded and held until released
                assert!(held.is_pending());
                assert_eq!(process.calls(), ["cargo"]);
                assert_eq!(result.unwrap(), exit(0));
            }

            #[cfg(feature = "tokio")]
            #[test]
            fn set_pending_released_should_not_hold_later_async_runs() {
                let process = TestProcess::new();
                let gate = process.set_pending("cargo", exit(0));

                gate.release();

                assert_eq!(
                    block_on(Command::new("cargo").run_async(&process)).unwrap(),
                    exit(0)
                );
            }

            #[cfg(feature = "tokio")]
            #[test]
            fn set_pending_cancelled_should_report_finished_cancelled() {
                // GIVEN an async run held by a pending output
                #[derive(Default)]
                struct Finished(Mutex<Vec<String>>);

                impl ProcessObserver for Finished {
                    fn finished(&self, _run: &CommandRun, result: &Result<CommandOutput>) {
                        let error = result.as_ref().unwrap_err();
                        assert!(error.source_as::<crate::CommandCancelled>().is_some());
                        assert_eq!(error.program(), Some("cargo"));
                        self.0.lock().unwrap().push(error.to_string());
                    }
                }

                let observer = Arc::new(Finished::default());
                let process = TestProcess::new();
                process.set_observer(observer.clone());
                let _gate = process.set_pending("cargo", exit(0));
                let command = Command::new("cargo");
                let mut future = Box::pin(command.run_async(&process));
                let mut context = std::task::Context::from_waker(std::task::Waker::noop());
                assert!(future.as_mut().poll(&mut context).is_pending());

                // WHEN cancelling it
                drop(future);

                // THEN the run is reported as finished by cancellation
                assert_eq!(*observer.0.lock().unwrap(), ["[Process] 'cargo' cancelled"]);
            }
        }

        mod process {
            use super::*;

            mod run {
                use super::*;

                #[test]
                fn run_should_return_output_and_record_call() {
                    let process = TestProcess::new();
                    let output = CommandOutput {
                        status: Some(0),
                        stdout: b"out".to_vec(),
                        ..Default::default()
                    };
                    process.set_output("git", output.clone());

                    let result = Command::new("git").arg("status").run(&process);

                    assert_eq!(result.unwrap(), output);
                    assert_eq!(process.calls(), ["git status"]);
                }

                #[test]
                fn run_env_changed_while_retrying_should_keep_env_of_run() {
                    // GIVEN an observer changing the env before each retry
                    struct Changing(SharedEnv);

                    impl ProcessObserver for Changing {
                        fn retrying(&self, _: &CommandRun, _: &Result<CommandOutput>) {
                            self.0.set_var("A".to_string(), "2".to_string());
                            self.0.replace_current_dir(PathBuf::from("/other"));
                        }
                    }

                    let process = TestProcess::new();
                    process.set_var("A".to_string(), "1".to_string());
                    process.set_observer(Arc::new(Changing(process.env.clone())));
                    process.set_outputs("curl", vec![exit(7), exit(0)]);

                    // WHEN running a command retried once
                    Command::new("curl")
                        .retry(1, Duration::ZERO)
                        .run(&process)
                        .unwrap();

                    // THEN both attempts get the env the run started with
                    let calls = process.call_details();
                    assert_eq!(calls.len(), 2);
                    for call in calls {
                        assert_eq!(call.vars, [("A".to_string(), Some("1".to_string()))]);
                        assert_eq!(call.current_dir, Path::new(ROOT));
                    }
                }

                #[test]
                fn run_unmatched_should_return_error_and_record_call() {
                    let process = TestProcess::new();
                    process.set_output("cargo", exit(0));

                    let error = Command::new("git").run(&process).unwrap_err();

                    assert_eq!(error.description(), "'git': no output set");
                    assert_eq!(process.calls(), ["git"]);
                }

                #[test]
                fn run_invalid_options_should_return_error_without_running() {
                    let process = TestProcess::new();
                    process.set_output("", exit(0));

                    let error = Command::new("git")
                        .interactive()
                        .timeout(Duration::from_secs(1))
                        .run(&process)
                        .unwrap_err();

                    assert_eq!(
                        error.description(),
                        "'git': interactive cannot be combined with timeout"
                    );
                    assert!(process.calls().is_empty());
                }

                #[test]
                fn run_failed_output_should_return_error_with_output() {
                    let process = TestProcess::new();
                    process.set_output("git", exit(1));

                    let error = Command::new("git").run(&process).unwrap_err();

                    assert_eq!(error.command_output(), Some(&exit(1)));
                }

                #[test]
                fn run_accepted_timeout_should_return_output() {
                    let process = TestProcess::new();
                    process.set_output(
                        "git",
                        CommandOutput {
                            duration: Duration::from_secs(60),
                            ..exit(0)
                        },
                    );

                    let output = Command::new("git")
                        .timeout(Duration::from_secs(1))
                        .accept_if(|_, output| output.timed_out)
                        .run(&process)
                        .unwrap();

                    assert!(output.timed_out);
                    assert_eq!(output.duration, Duration::from_secs(1));
                }

                #[test]
                fn run_duration_exceeding_timeout_should_time_out() {
                    let process = TestProcess::new();
                    process.set_output(
                        "git",
                        CommandOutput {
                            duration: Duration::from_secs(60),
                            ..exit(0)
                        },
                    );

                    let error = Command::new("git")
                        .timeout(Duration::from_secs(1))
                        .run(&process)
                        .unwrap_err();

                    assert_eq!(error.description(), "'git' timed out after 1s");
                    assert_eq!(
                        error.command_output(),
                        Some(&CommandOutput {
                            status: None,
                            duration: Duration::from_secs(1),
                            timed_out: true,
                            ..Default::default()
                        })
                    );
                }

                #[test]
                fn run_display_lines_should_return_output_equal_to_set() {
                    let process = TestProcess::new();
                    let output = CommandOutput {
                        stdout: b"out".to_vec(),
                        ..exit(0)
                    };
                    process.set_output("git", output.clone());

                    let result = Command::new("git").display_lines(3).run(&process).unwrap();

                    assert_eq!(result, output);
                    assert_eq!(result.display_lines, 3);
                }

                #[test]
                fn run_duration_within_timeout_should_return_output() {
                    let process = TestProcess::new();
                    let output = CommandOutput {
                        duration: Duration::from_secs(1),
                        ..exit(0)
                    };
                    process.set_output("git", output.clone());

                    let result = Command::new("git")
                        .timeout(Duration::from_secs(60))
                        .run(&process);

                    assert_eq!(result.unwrap(), output);
                }

                #[test]
                fn run_silent_should_drop_output_set() {
                    // GIVEN an observer and an output with both streams
                    let observer = Arc::new(RecordingObserver::default());
                    let process = TestProcess::new();
                    process.set_observer(observer.clone());
                    process.set_output(
                        "git",
                        CommandOutput {
                            stdout: b"out".to_vec(),
                            stderr: b"err".to_vec(),
                            ..exit(0)
                        },
                    );

                    // WHEN streaming a matching command silently
                    let output = Command::new("git").stream().silent().run(&process).unwrap();

                    // THEN no output is returned or streamed
                    assert!(output.stdout.is_empty());
                    assert!(output.stderr.is_empty());
                    assert_eq!(
                        *observer.0.lock().unwrap(),
                        [
                            format!("started git in {ROOT}"),
                            "finished true".to_string()
                        ]
                    );
                }

                #[test]
                fn run_streaming_should_report_output_set_to_observer() {
                    // GIVEN an observer and an output with both streams
                    let observer = Arc::new(RecordingObserver::default());
                    let process = TestProcess::new();
                    process.set_observer(observer.clone());
                    process.set_output(
                        "git",
                        CommandOutput {
                            stdout: b"out".to_vec(),
                            stderr: b"err".to_vec(),
                            ..exit(0)
                        },
                    );

                    // WHEN streaming a matching command
                    Command::new("git").stream().run(&process).unwrap();

                    // THEN the observer gets the output between start and end
                    assert_eq!(
                        *observer.0.lock().unwrap(),
                        [
                            format!("started git in {ROOT}"),
                            "Stdout out".to_string(),
                            "Stderr err".to_string(),
                            "finished true".to_string()
                        ]
                    );
                }
            }

            #[cfg(feature = "tokio")]
            mod run_async {
                use super::*;

                #[test]
                fn run_async_should_return_output_and_record_call() {
                    let process = TestProcess::new();
                    process.set_output("git", exit(0));
                    let command = Command::new("git");

                    let result = tokio::runtime::Builder::new_current_thread()
                        .build()
                        .unwrap()
                        .block_on(command.run_async(&process));

                    assert_eq!(result.unwrap(), exit(0));
                    assert_eq!(process.calls(), ["git"]);
                }

                #[test]
                fn run_async_unmatched_should_fail() {
                    let process = TestProcess::new();
                    let command = Command::new("git");

                    let error = block_on(command.run_async(&process)).unwrap_err();

                    assert_eq!(error.description(), "'git': no output set");
                }

                #[test]
                fn run_async_should_retry_without_waiting() {
                    let process = TestProcess::new();
                    process.set_outputs("git", [exit(1), exit(0)]);
                    let command = Command::new("git");

                    let result = block_on(
                        command
                            .retry(1, Duration::from_secs(3600))
                            .run_async(&process),
                    );

                    assert_eq!(result.unwrap(), exit(0));
                    assert_eq!(process.calls(), ["git", "git"]);
                }

                #[test]
                fn run_async_invalid_options_should_fail_without_running() {
                    let process = TestProcess::new();
                    let command = Command::new("vim");

                    let error = block_on(command.interactive().input("text").run_async(&process))
                        .unwrap_err();

                    assert_eq!(
                        error.description(),
                        "'vim': interactive cannot be combined with input"
                    );
                    assert!(process.calls().is_empty());
                }

                #[test]
                fn run_async_panicking_observer_should_not_report_finished() {
                    // GIVEN a command run with an observer panicking on
                    // streamed output
                    #[derive(Default)]
                    struct Panicking(Mutex<Vec<String>>);

                    impl ProcessObserver for Panicking {
                        fn stdout(&self, _run: &CommandRun, _data: &[u8]) {
                            panic!("observer");
                        }

                        fn finished(&self, _run: &CommandRun, _result: &Result<CommandOutput>) {
                            self.0.lock().unwrap().push("finished".to_string());
                        }
                    }

                    let observer = Arc::new(Panicking::default());
                    let process = TestProcess::new();
                    process.set_observer(observer.clone());
                    process.set_output(
                        "cargo",
                        CommandOutput {
                            stdout: b"output".to_vec(),
                            ..exit(0)
                        },
                    );
                    let command = Command::new("cargo");
                    block_on(command.run_async(&process)).unwrap();

                    // WHEN running it streamed
                    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        block_on(command.stream().run_async(&process))
                    }));

                    // THEN only the end of the run before is reported, like
                    // for a blocking one
                    assert!(result.is_err());
                    assert_eq!(*observer.0.lock().unwrap(), ["finished"]);
                }
            }

            mod run_to {
                use super::*;

                fn output() -> CommandOutput {
                    CommandOutput {
                        status: Some(0),
                        stdout: b"out".to_vec(),
                        stderr: b"err".to_vec(),
                        ..Default::default()
                    }
                }

                #[test]
                fn run_to_should_pass_output_set_to_sink_by_stream() {
                    let process = TestProcess::new();
                    process.set_output("git", output());
                    let mut sunk = Vec::new();

                    let result = Command::new("git").run_to(&process, &mut |stream, data| {
                        sunk.push((stream, data.to_vec()));
                        Ok(())
                    });

                    assert_eq!(
                        result.unwrap(),
                        CommandOutput {
                            stdout: Vec::new(),
                            stderr: Vec::new(),
                            ..output()
                        }
                    );
                    assert_eq!(
                        sunk,
                        [
                            (OutputStream::Stdout, b"out".to_vec()),
                            (OutputStream::Stderr, b"err".to_vec())
                        ]
                    );
                }

                #[test]
                fn run_to_failed_without_output_should_be_retried() {
                    let process = TestProcess::new();
                    process.set_outputs("git", [exit(1), output()]);
                    let mut sunk = Vec::new();

                    let result = Command::new("git")
                        .retry(1, Duration::from_secs(60))
                        .run_to(&process, &mut |_, data| {
                            sunk.extend_from_slice(data);
                            Ok(())
                        });

                    assert_eq!(result.unwrap().status, Some(0));
                    assert_eq!(sunk, b"outerr");
                    assert_eq!(process.calls(), ["git", "git"]);
                }

                #[test]
                fn run_to_failing_sink_should_return_its_error() {
                    for failing in [OutputStream::Stdout, OutputStream::Stderr] {
                        let process = TestProcess::new();
                        process.set_output("git", output());
                        let mut streams = Vec::new();

                        let error = Command::new("git")
                            .run_to(&process, &mut |stream, _| {
                                streams.push(stream);
                                if stream == failing {
                                    Err(crate::Error::process("full"))
                                } else {
                                    Ok(())
                                }
                            })
                            .unwrap_err();

                        assert_eq!(error.description(), "full", "{failing:?}");
                        assert_eq!(*streams.last().unwrap(), failing);
                    }
                }
            }

            #[cfg(feature = "tokio")]
            mod run_async_to {
                use super::*;

                #[test]
                fn run_async_to_should_pass_output_set_to_sink() {
                    let process = TestProcess::new();
                    process.set_output(
                        "git",
                        CommandOutput {
                            status: Some(0),
                            stdout: b"out".to_vec(),
                            ..Default::default()
                        },
                    );
                    let mut sunk = Vec::new();

                    let output =
                        block_on(Command::new("git").run_async_to(&process, &mut |_, data| {
                            sunk.extend_from_slice(data);
                            Ok(())
                        }))
                        .unwrap();

                    assert!(output.stdout.is_empty());
                    assert_eq!(sunk, b"out");
                }
            }

            mod set_observer {
                use super::*;

                #[test]
                fn set_observer_should_report_runs_in_resolved_dir() {
                    let observer = Arc::new(RecordingObserver::default());
                    let process = TestProcess::new();
                    process.set_observer(observer.clone());

                    let _ = Command::new("git").current_dir("repo").run(&process);

                    assert_eq!(
                        *observer.0.lock().unwrap(),
                        [
                            format!(
                                "started git in {}",
                                PathBuf::from(ROOT).join("repo").display()
                            ),
                            "finished false".to_string()
                        ]
                    );
                }
            }
        }
    }
}