laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
#![cfg(unix)]

use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use laravel::Application;
use laravel::config::Env;
use laravel::console::Signal;
use laravel::process::{self, Invocation, Output, OutputKind, Process, ProcessFailed, ProcessTimedOut};
use laravel::stream::StreamExt;
use laravel::testing::MakesHttpRequests;
use laravel::time::ToSpan;

use crate::logging::Lines;
use crate::support::TempDir;

fn app(base_path: &Path) -> Application {
    Application::configure()
        .replace_env(Env::from_iter([("APP_BASE_PATH", base_path.to_str().unwrap())]))
        .with_routing(|routing, _| {
            routing.routes(|routes| {
                routes.get("/branch", || async {
                    let result = process::run(["git", "branch", "--show-current"])
                        .await?
                        .ensure_successful()?;
                    Ok::<_, laravel::Error>(result.output().trim().to_owned())
                });
            });
        })
        .create()
}

fn chunks(outputs: &[Output]) -> Vec<(OutputKind, String)> {
    outputs
        .iter()
        .map(|output| (output.kind(), output.text().into_owned()))
        .collect()
}

fn written(outputs: &[Output], kind: OutputKind) -> String {
    outputs
        .iter()
        .filter(|output| output.kind() == kind)
        .map(|output| output.text())
        .collect()
}

#[tokio::test]
async fn running_returns_output_and_exit_codes_without_failing() {
    let root = TempDir::new("process-run");
    let app = app(&root);

    app.scope(async || {
        let result = process::run(["sh", "-c", "echo out; echo err >&2; exit 3"])
            .await
            .unwrap();

        assert_eq!(result.command(), "sh -c 'echo out; echo err >&2; exit 3'");
        assert_eq!(result.output(), "out\n");
        assert_eq!(result.error_output(), "err\n");
        assert_eq!(result.exit_code(), Some(3));
        assert!(result.failed());
        assert!(result.see_in_error_output("err"));

        let error = laravel::Error::from(result.ensure_successful().unwrap_err());
        assert!(error.is::<ProcessFailed>());
        assert!(error.to_string().contains("failed with exit code 3"));

        let shell = Process::shell("echo laravel | tr a-z A-Z").run().await.unwrap();
        assert_eq!(shell.command(), "echo laravel | tr a-z A-Z");
        assert_eq!(shell.ensure_successful().unwrap().output(), "LARAVEL\n");
    })
    .await;
}

#[tokio::test]
async fn processes_start_in_the_base_path_and_resolve_relative_paths_against_it() {
    let root = TempDir::with_files("process-paths", &[("scripts/import.sh", "echo imported")]);
    let app = app(&root);
    let root = root.canonicalize().unwrap();

    app.scope(async || {
        let base = process::run(["pwd", "-P"]).await.unwrap();
        assert_eq!(base.output().trim(), root.to_str().unwrap());

        let scripts = Process::new(["sh", "import.sh"]).path("scripts").run().await.unwrap();
        assert_eq!(scripts.output(), "imported\n");

        let absolute = Process::new(["pwd", "-P"])
            .path(root.join("scripts"))
            .run()
            .await
            .unwrap();
        assert_eq!(absolute.output().trim(), root.join("scripts").to_str().unwrap());
    })
    .await;
}

#[tokio::test]
async fn input_larger_than_a_pipe_is_written_while_output_is_read() {
    let root = TempDir::new("process-input");
    let app = app(&root);
    let input = "a line of input\n".repeat(100_000);

    app.scope(async || {
        let result = Process::new(["cat"]).input(input.clone()).run().await.unwrap();
        assert_eq!(result.output(), input);

        let ignored = Process::new(["true"]).input(input.clone()).run().await.unwrap();
        assert!(ignored.successful());
    })
    .await;
}

#[tokio::test]
async fn processes_inherit_the_environment_unless_told_not_to() {
    let root = TempDir::new("process-env");
    let app = app(&root);

    app.scope(async || {
        let inherited = Process::new(["env"])
            .env("GREETING", "hello")
            .envs([("FIRST", "1"), ("SECOND", "2")])
            .run()
            .await
            .unwrap();
        assert!(inherited.see_in_output("GREETING=hello\n"));
        assert!(inherited.see_in_output("SECOND=2\n"));
        let has_path = |output: &str| output.lines().any(|line| line.starts_with("PATH="));
        assert!(has_path(&inherited.output()));

        let removed = Process::new(["env"]).remove_env("PATH").run().await.unwrap();
        assert!(!has_path(&removed.output()));

        let isolated = Process::new(["env"])
            .env("GREETING", "hello")
            .without_inheriting_env()
            .run()
            .await
            .unwrap();
        assert_eq!(isolated.output(), "GREETING=hello\n");
    })
    .await;
}

#[tokio::test]
async fn timeouts_kill_the_process_and_keep_its_output() {
    let root = TempDir::new("process-timeouts");
    let app = app(&root);

    app.scope(async || {
        let started = Instant::now();
        let error = Process::new(["sh", "-c", "echo started; sleep 5"])
            .timeout(Duration::from_millis(300))
            .run()
            .await
            .unwrap_err();
        assert!(started.elapsed() < Duration::from_secs(3));
        let timed_out = error.downcast_ref::<ProcessTimedOut>().unwrap();
        assert!(!timed_out.is_idle());
        assert_eq!(timed_out.timeout(), Duration::from_millis(300));
        assert_eq!(timed_out.result().output(), "started\n");
        assert_eq!(timed_out.result().exit_code(), None);

        let error = Process::new(["sh", "-c", "echo tick; sleep 0.1; echo tick; sleep 5"])
            .idle_timeout(400.milliseconds())
            .run()
            .await
            .unwrap_err();
        let timed_out = error.downcast_ref::<ProcessTimedOut>().unwrap();
        assert!(timed_out.is_idle());
        assert_eq!(timed_out.timeout(), Duration::from_millis(400));
        assert_eq!(timed_out.result().output(), "tick\ntick\n");

        for timeout in [
            Process::new(["true"]).timeout(Duration::MAX),
            Process::new(["true"]).timeout(1_000.years()),
        ] {
            assert!(timeout.run().await.unwrap().successful());
        }

        let forever = Process::new(["sleep", "0.2"])
            .timeout(Duration::from_millis(50))
            .forever()
            .run()
            .await
            .unwrap();
        assert!(forever.successful());

        for unlimited in [
            Process::new(["sleep", "0.1"]).timeout(Duration::ZERO),
            Process::new(["sleep", "0.1"]).timeout((-5).seconds()),
            Process::new(["sleep", "0.1"]).idle_timeout(0.seconds()),
        ] {
            assert!(unlimited.run().await.unwrap().successful());
        }
    })
    .await;
}

#[tokio::test]
async fn stopping_terminates_gracefully_then_kills() {
    let root = TempDir::new("process-stop");
    let app = app(&root);

    app.scope(async || {
        let mut graceful =
            Process::shell("trap 'echo stopping; exit 0' TERM; echo ready; while true; do sleep 0.05; done")
                .start()
                .unwrap();
        assert!(graceful.wait_until(|output| output.text().contains("ready")).await);
        let started = Instant::now();
        let result = graceful.stop(5.seconds()).await.unwrap();
        assert!(started.elapsed() < Duration::from_secs(3));
        assert!(result.successful());
        assert!(result.see_in_output("stopping"));

        let mut stubborn = Process::shell("trap '' TERM; echo ready; while true; do sleep 5; done")
            .start()
            .unwrap();
        assert!(stubborn.wait_until(|output| output.text().contains("ready")).await);
        let started = Instant::now();
        let result = stubborn.stop(Duration::from_millis(300)).await.unwrap();
        assert!(started.elapsed() >= Duration::from_millis(300));
        assert!(started.elapsed() < Duration::from_secs(3));
        assert_eq!(result.exit_code(), None);

        let finished = Process::new(["echo", "done"]).start().unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert_eq!(finished.stop(5.seconds()).await.unwrap().output(), "done\n");
    })
    .await;
}

#[tokio::test]
async fn fakes_can_time_out_or_fail_to_start() {
    let root = TempDir::new("process-fake-failures");
    let app = app(&root);

    app.scope(async || {
        let processes = process::fake()
            .with("ffmpeg *", process::result().output("frame=1\n").timed_out())
            .with(
                "convert *",
                process::result().failed_to_start(std::io::ErrorKind::NotFound),
            )
            .with(
                "rsync *",
                process::sequence([process::result().timed_out(), process::result().output("synced\n")]),
            );

        let error = process::run(["ffmpeg", "-i", "in.mp4"]).await.unwrap_err();
        let timed_out = error.downcast_ref::<ProcessTimedOut>().unwrap();
        assert_eq!(timed_out.result().output(), "frame=1\n");
        assert_eq!(timed_out.timeout(), 1.minutes());
        assert!(!timed_out.is_idle());
        assert!(
            timed_out
                .to_string()
                .starts_with("the command `ffmpeg -i in.mp4` exceeded its timeout of 1m and was killed")
        );

        let error = process::run(["convert", "a.png"]).await.unwrap_err();
        assert!(error.is::<std::io::Error>());
        assert!(error.to_string().starts_with("failed to start `convert a.png`"));
        assert!(Process::new(["convert", "b.png"]).start().is_err());

        let mut started = Process::new(["ffmpeg", "-i", "in.mp4"]).start().unwrap();
        let chunks: Vec<Output> = started.chunks().collect().await;
        assert_eq!(chunks.len(), 1);
        assert!(started.wait().await.unwrap_err().is::<ProcessTimedOut>());

        assert!(process::run(["rsync", "a", "b"]).await.is_err());
        assert_eq!(process::run(["rsync", "a", "b"]).await.unwrap().output(), "synced\n");

        processes.assert_ran("convert a.png").assert_ran_times("rsync a b", 2);
    })
    .await;
}

#[tokio::test]
async fn output_callbacks_receive_chunks_as_they_are_read() {
    let root = TempDir::new("process-callbacks");
    let app = app(&root);
    let received = Arc::new(Mutex::new(Vec::new()));
    let collected = Arc::clone(&received);

    app.scope(async || {
        let result = Process::new([
            "sh",
            "-c",
            "printf one; sleep 0.1; echo two >&2; sleep 0.1; printf 'three\\nfour'",
        ])
        .quietly()
        .on_output(move |output| collected.lock().unwrap().push(output.clone()))
        .run()
        .await
        .unwrap();

        assert!(result.output().is_empty());
    })
    .await;

    let received = received.lock().unwrap();
    assert_eq!(written(&received, OutputKind::Stdout), "onethree\nfour");
    assert_eq!(written(&received, OutputKind::Stderr), "two\n");
    assert!(received.len() >= 3);
}

#[tokio::test]
async fn started_processes_stream_chunks_without_waiting_for_line_endings() {
    let root = TempDir::new("process-start");
    let app = app(&root);

    app.scope(async || {
        let mut process = Process::new(["sh", "-c", "printf 'Password: '; sleep 0.5; echo done"])
            .start()
            .unwrap();
        assert!(process.id().is_some_and(|id| id > 0));

        assert!(process.wait_until(|output| output.text().contains("Password: ")).await);
        assert!(process.running());
        let rest: Vec<Output> = process.chunks().collect().await;
        assert_eq!(written(&rest, OutputKind::Stdout), "done\n");

        let result = process.wait().await.unwrap();
        assert_eq!(result.output(), "Password: done\n");

        let mut quick = Process::new(["echo", "bye"]).start().unwrap();
        assert!(!quick.wait_until(|output| output.text().contains("never")).await);
    })
    .await;
}

#[tokio::test]
async fn started_processes_can_be_signalled_with_valid_signal_numbers() {
    let root = TempDir::new("process-signals");
    let app = app(&root);

    app.scope(async || {
        let terminated = Process::new(["sleep", "5"]).start().unwrap();
        terminated.signal(Signal::Terminate).unwrap();
        let result = tokio::time::timeout(Duration::from_secs(3), terminated.wait())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(result.exit_code(), None);
        assert!(result.failed());

        let killed = Process::new(["sleep", "5"]).start().unwrap();
        let error = killed.signal(Signal::Unix(9999)).unwrap_err();
        assert!(error.to_string().contains("can't send signal 9999"), "{error}");
        killed.signal(Signal::Unix(9)).unwrap();
        let result = tokio::time::timeout(Duration::from_secs(3), killed.wait())
            .await
            .unwrap()
            .unwrap();
        assert_eq!(result.exit_code(), None);
    })
    .await;
}

#[tokio::test]
async fn signalling_a_process_that_has_exited_fails() {
    let root = TempDir::new("process-signal-exited");
    let app = app(&root);

    app.scope(async || {
        // The background `sleep` keeps the output open after the shell has exited and been reaped...
        let mut process = Process::shell("sleep 1 & echo exited").start().unwrap();
        assert!(process.wait_until(|output| output.text().contains("exited")).await);
        tokio::time::sleep(Duration::from_millis(50)).await;

        let error = process.signal(Signal::Terminate).unwrap_err();
        assert!(error.to_string().contains("has already finished"), "{error}");
    })
    .await;
}

#[tokio::test]
async fn dropping_a_process_kills_it() {
    let root = TempDir::new("process-drops");
    let app = app(&root);

    app.scope(async || {
        let running = Process::shell("touch started; sleep 1; touch finished")
            .start()
            .unwrap();
        appears(&root.join("started")).await;
        drop(running);

        let run = Process::shell("touch ran; sleep 1; touch completed").run();
        let ran = root.join("ran");
        tokio::select! {
            _ = run => panic!("the process should still be running"),
            () = appears(&ran) => {}
        }
    })
    .await;

    tokio::time::sleep(Duration::from_millis(1500)).await;
    assert!(!root.join("finished").exists());
    assert!(!root.join("completed").exists());
}

#[tokio::test]
async fn abandoning_a_wait_or_stop_kills_the_process() {
    let root = TempDir::new("process-abandoned-waits");
    let app = app(&root);

    app.scope(async || {
        let waiting = Process::shell("touch waiting; sleep 1; touch waited")
            .forever()
            .start()
            .unwrap();
        appears(&root.join("waiting")).await;
        assert!(
            tokio::time::timeout(Duration::from_millis(100), waiting.wait())
                .await
                .is_err()
        );

        let stopping = Process::shell("trap '' TERM; touch stopping; sleep 1; touch stopped")
            .forever()
            .start()
            .unwrap();
        appears(&root.join("stopping")).await;
        assert!(
            tokio::time::timeout(Duration::from_millis(100), stopping.stop(5.seconds()))
                .await
                .is_err()
        );
    })
    .await;

    tokio::time::sleep(Duration::from_millis(1500)).await;
    assert!(!root.join("waited").exists());
    assert!(!root.join("stopped").exists());
}

#[tokio::test]
async fn timeouts_drops_and_stops_end_everything_the_process_started() {
    let root = TempDir::new("process-groups");
    let app = app(&root);

    app.scope(async || {
        let error = Process::shell("touch timing; (sleep 1; touch timed) & wait")
            .timeout(Duration::from_millis(300))
            .run()
            .await
            .unwrap_err();
        assert!(error.downcast_ref::<ProcessTimedOut>().is_some());

        let dropped = Process::shell("touch dropping; (sleep 1; touch dropped) & wait")
            .start()
            .unwrap();
        appears(&root.join("dropping")).await;
        drop(dropped);

        let stopping = Process::shell("touch stopping; (sleep 1; touch stopped) & wait")
            .start()
            .unwrap();
        appears(&root.join("stopping")).await;
        assert_eq!(stopping.stop(5.seconds()).await.unwrap().exit_code(), None);
    })
    .await;

    tokio::time::sleep(Duration::from_millis(1500)).await;
    assert!(root.join("timing").exists());
    assert!(!root.join("timed").exists());
    assert!(!root.join("dropped").exists());
    assert!(!root.join("stopped").exists());
}

async fn appears(path: &Path) {
    tokio::time::timeout(Duration::from_secs(10), async {
        while !path.exists() {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("the process should create the file");
}

#[tokio::test]
#[should_panic(
    expected = "`laravel::process::Process::run()` can only be used inside the application: while it handles a \
                request or runs a command, in `Application::scope`, or in a task spawned with \
                `laravel::task::spawn` (called at tests/processes.rs:"
)]
async fn running_outside_the_application_panics() {
    let _ = process::run(["true"]).await;
}

#[tokio::test]
async fn missing_programs_fail_to_start() {
    let root = TempDir::new("process-missing");
    let app = app(&root);

    app.scope(async || {
        let error = process::run(["laravel-rust-no-such-program"]).await.unwrap_err();

        assert!(error.is::<std::io::Error>());
        assert!(
            error
                .to_string()
                .starts_with("failed to start `laravel-rust-no-such-program`")
        );
        assert!(process::run(Vec::<String>::new()).await.is_err());

        let joined = process::run(["laravel-rust-no-such-program --force"])
            .await
            .unwrap_err();
        assert!(joined.to_string().contains("pass its arguments as separate items"));
    })
    .await;
}

#[tokio::test]
async fn fakes_cover_requests_and_record_what_ran() {
    let root = TempDir::new("process-fake-requests");
    let app = app(&root);

    app.scope(async || {
        let processes = process::fake().with("git branch *", "main\n");

        app.get("/branch").await.assert_ok().assert_see("main");

        processes
            .assert_ran("git branch --show-current")
            .assert_ran_times("git branch --show-current", 1)
            .assert_not_ran("git status")
            .assert_ran_where(|process| process.path() == &*root && process.timeout() == Some(1.minutes().into()));

        drop(processes);
        let real = process::run(["echo", "real"]).await.unwrap();
        assert_eq!(real.output(), "real\n");
    })
    .await;
}

#[tokio::test]
async fn fakes_return_results_sequences_and_callbacks() {
    let root = TempDir::new("process-fake-results");
    let app = app(&root);
    let received = Arc::new(Mutex::new(Vec::new()));
    let collected = Arc::clone(&received);

    app.scope(async || {
        let processes = process::fake()
            .with(
                "bash import.sh",
                process::result()
                    .output("partial\ndone\n")
                    .error_output("boom\n")
                    .exit_code(1),
            )
            .with("ls *", process::sequence(["first\n", "second\n"]))
            .with("cat *", |process: &Invocation| {
                process::result().output(process.input().unwrap_or_default())
            });

        let failed = Process::new(["bash", "import.sh"])
            .on_output(move |output| collected.lock().unwrap().push(output.clone()))
            .run()
            .await
            .unwrap();
        assert_eq!(failed.exit_code(), Some(1));
        assert_eq!(failed.error_output(), "boom\n");
        assert!(failed.ensure_successful().is_err());

        assert_eq!(process::run(["ls", "a"]).await.unwrap().output(), "first\n");
        assert_eq!(process::run(["ls", "b"]).await.unwrap().output(), "second\n");
        let exhausted = process::run(["ls", "c"]).await.unwrap_err();
        assert!(exhausted.to_string().contains("no results left for `ls c`"));

        let echoed = Process::new(["cat", "-"]).input("piped").run().await.unwrap();
        assert_eq!(echoed.output(), "piped");

        let unmatched = process::run(["rm", "-rf", "storage"]).await.unwrap();
        assert!(unmatched.successful() && unmatched.output().is_empty());

        processes.assert_ran_in_order(["bash import.sh", "ls a", "ls b", "cat -", "rm -rf storage"]);
    })
    .await;

    assert_eq!(
        chunks(&received.lock().unwrap()),
        [
            (OutputKind::Stdout, "partial\n".to_owned()),
            (OutputKind::Stdout, "done\n".to_owned()),
            (OutputKind::Stderr, "boom\n".to_owned()),
        ]
    );
}

#[tokio::test]
async fn stray_processes_fail_when_prevented() {
    let root = TempDir::new("process-fake-strays");
    let app = app(&root);

    app.scope(async || {
        let processes = process::fake().prevent_stray_processes();

        app.get("/branch").await.assert_internal_server_error();

        let error = process::run(["git", "status"]).await.unwrap_err();
        assert_eq!(
            error.to_string(),
            "attempted to run `git status` without a matching process fake"
        );
        assert!(Process::new(["git", "status"]).start().is_err());
        processes.assert_nothing_ran();
    })
    .await;
}

#[tokio::test]
async fn started_fakes_stream_their_output() {
    let root = TempDir::new("process-fake-start");
    let app = app(&root);

    app.scope(async || {
        let processes = process::fake().with("node *", "booting\nListening on 13714\n");

        let mut server = Process::new(["node", "server.js"]).start().unwrap();
        assert_eq!(server.id(), None);
        assert!(!server.running());
        server.signal(Signal::Terminate).unwrap();
        let chunks = chunks(&server.chunks().collect::<Vec<_>>().await);
        assert_eq!(
            chunks,
            [
                (OutputKind::Stdout, "booting\n".to_owned()),
                (OutputKind::Stdout, "Listening on 13714\n".to_owned()),
            ]
        );
        assert_eq!(server.wait().await.unwrap().output(), "booting\nListening on 13714\n");

        let mut ready = Process::new(["node", "server.js"]).start().unwrap();
        assert!(ready.wait_until(|output| output.text().starts_with("Listening")).await);

        processes.assert_ran("node server.js");
    })
    .await;
}

#[tokio::test]
async fn nested_fakes_take_over_until_dropped() {
    let root = TempDir::new("process-fake-nesting");
    let first = app(&root);

    first
        .scope(async || {
            let outer = process::fake().with("*", "outer");
            {
                let inner = process::fake().with("*", "inner");
                assert_eq!(process::run(["anything"]).await.unwrap().output(), "inner");
                inner.assert_ran("anything");
            }
            assert_eq!(process::run(["anything"]).await.unwrap().output(), "outer");
            outer.assert_ran_times("anything", 1);
        })
        .await;

    let other = app(&root);
    other
        .scope(async || {
            assert_eq!(process::run(["echo", "real"]).await.unwrap().output(), "real\n");
        })
        .await;
}

#[tokio::test]
async fn boot_hooks_can_run_processes_in_the_base_path() {
    let root = TempDir::with_files("process-boot", &[("VERSION", "1.2.3")]);
    let version = Arc::new(Mutex::new(String::new()));
    let booted = Arc::clone(&version);
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_BASE_PATH", root.to_str().unwrap())]))
        .booted(move |_| async move {
            let result = process::run(["cat", "VERSION"]).await?.ensure_successful()?;
            *booted.lock().unwrap() = result.output().into_owned();
            Ok::<_, laravel::Error>(())
        })
        .create();

    app.boot().await.unwrap();

    assert_eq!(*version.lock().unwrap(), "1.2.3");
}

#[tokio::test]
async fn background_programs_are_not_waited_for() {
    let root = TempDir::new("process-background");
    let app = app(&root);

    app.scope(async || {
        let started = Instant::now();
        let result = Process::shell("sleep 5 & echo started").run().await.unwrap();
        assert!(started.elapsed() < Duration::from_secs(2));
        assert!(result.successful());
        assert_eq!(result.output(), "started\n");

        let result = Process::shell("(sleep 0.5; echo late) & echo early")
            .run()
            .await
            .unwrap();
        assert_eq!(result.output(), "early\n");

        let mut started = Process::shell("sleep 5 & echo started").start().unwrap();
        let chunks: Vec<Output> = started.chunks().collect().await;
        assert_eq!(written(&chunks, OutputKind::Stdout), "started\n");
        assert!(started.wait().await.unwrap().successful());

        let large = Process::shell("head -c 1000000 /dev/zero | tr '\\0' a; echo; echo done >&2")
            .run()
            .await
            .unwrap();
        assert_eq!(large.output().len(), 1_000_001);
        assert_eq!(large.error_output(), "done\n");
    })
    .await;
}

#[tokio::test]
async fn invocations_expose_the_program_and_its_exact_arguments() {
    let root = TempDir::new("process-arguments");
    let app = app(&root);

    app.scope(async || {
        let processes = process::fake();

        process::run(["convert", "my photo.png", "out.png"]).await.unwrap();
        Process::shell("cat *.log | wc -l").run().await.unwrap();

        processes
            .assert_ran("convert 'my photo.png' out.png")
            .assert_ran_where(|process| {
                process.program() == "convert" && process.arguments() == ["my photo.png", "out.png"]
            })
            .assert_ran_where(|process| {
                process.program() == "sh" && process.arguments() == ["-c", "cat *.log | wc -l"]
            });
    })
    .await;
}

#[tokio::test]
async fn debug_logs_name_the_program_but_not_its_arguments() {
    let root = TempDir::new("process-logs");
    let app = app(&root);
    let (lines, _guard) = Lines::capture();

    app.scope(async || {
        process::run(["sh", "-c", "exit 3", "--token=hunter2"]).await.unwrap();
    })
    .await;

    let line = lines.find("Process finished");
    assert_eq!(line["fields"]["program"], "sh");
    assert_eq!(line["fields"]["exit_code"], 3);
    assert!(!line.to_string().contains("hunter2"), "{line}");
}

#[tokio::test]
async fn errors_point_to_the_call_that_returned_them() {
    let root = TempDir::new("process-locations");
    let app = app(&root);
    let at = |error: &laravel::Error| error.location().map(|location| (location.file(), location.line()));

    app.scope(async || {
        let line = line!() + 1;
        let timed_out = Process::new(["sleep", "5"]).timeout(Duration::from_millis(100)).run();
        let error = timed_out.await.unwrap_err();
        assert!(error.is::<ProcessTimedOut>());
        assert_eq!(at(&error), Some((file!(), line)));

        let line = line!() + 1;
        let error = process::run(["laravel-rust-no-such-program"]).await.unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));

        let line = line!() + 1;
        let error = Process::new(["laravel-rust-no-such-program"]).start().unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));

        let started = Process::new(["sleep", "5"])
            .timeout(Duration::from_millis(100))
            .start()
            .unwrap();
        let line = line!() + 1;
        let error = started.wait().await.unwrap_err();
        assert!(error.is::<ProcessTimedOut>());
        assert_eq!(at(&error), Some((file!(), line)));

        let started = Process::new(["sleep", "5"])
            .timeout(Duration::from_millis(100))
            .start()
            .unwrap();
        tokio::time::sleep(Duration::from_millis(300)).await;
        let line = line!() + 1;
        let error = started.stop(5.seconds()).await.unwrap_err();
        assert!(error.is::<ProcessTimedOut>());
        assert_eq!(at(&error), Some((file!(), line)));

        let started = Process::new(["sleep", "5"]).start().unwrap();
        let line = line!() + 1;
        let error = started.signal(Signal::Unix(9999)).unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));

        let _processes = process::fake()
            .with("ffmpeg *", process::result().timed_out())
            .with("rsync *", process::sequence([process::result()]))
            .prevent_stray_processes();
        let line = line!() + 1;
        let error = process::run(["ffmpeg", "-i", "in.mp4"]).await.unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));

        let started = Process::new(["ffmpeg", "-i", "in.mp4"]).start().unwrap();
        let line = line!() + 1;
        let error = started.wait().await.unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));

        let line = line!() + 1;
        let error = process::run(["git", "status"]).await.unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));

        process::run(["rsync", "a", "b"]).await.unwrap();
        let line = line!() + 1;
        let error = process::run(["rsync", "a", "b"]).await.unwrap_err();
        assert_eq!(at(&error), Some((file!(), line)));
    })
    .await;
}