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
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
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
use std::future::IntoFuture;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use laravel::Application;
use laravel::config::{Config, Env};
use laravel::console::{Console, clap};
use laravel::container::{Inject, Registrar};
use laravel::foundation::ServiceProvider;
use laravel::testing::MakesConsoleRequests;

use crate::support::failure;

struct Mailer {
    from: String,
}

struct Sequence(AtomicUsize);

#[derive(clap::Args)]
struct QueueOptions {
    #[arg(long, default_value = "default")]
    queue: String,
}

/// Send marketing emails to a user.
#[derive(clap::Parser)]
#[command(name = "mail:send", alias = "email:send")]
struct SendEmails {
    /// The user to send to.
    user: u64,
    #[command(flatten)]
    options: QueueOptions,
}

type MailerDependency = Inject<Mailer>;

#[laravel::console::command]
impl SendEmails {
    async fn handle(
        self,
        mailer: MailerDependency,
        app: &Application,
        console: &mut Console,
        sequence: Inject<Sequence>,
    ) -> laravel::Result<()> {
        let number = next_number().await;
        assert_eq!(number, next_number().await);
        console.info(format!(
            "{}: user={} queue={} from={} app={}",
            number,
            self.user,
            self.options.queue,
            mailer.from,
            laravel::config().app.name,
        ));
        let resolved = laravel::resolve::<Sequence>().await?;
        assert!(std::ptr::eq(&*sequence, &*resolved));
        let resolved = app.resolve::<Mailer>().await;
        assert!(std::ptr::eq(&*mailer, &*resolved));
        assert!(std::ptr::eq(app.config(), &*laravel::config()));
        Ok(())
    }
}

#[derive(clap::Parser)]
#[command(name = "inspect:commands")]
struct InspectCommands;

#[laravel::console::command]
impl InspectCommands {
    async fn handle(self, console: &mut Console, app: &laravel::Application) -> laravel::Result<()> {
        let mut definition = laravel::console::commands();
        console.line(&app.config().app.name);
        for command in definition.get_subcommands() {
            console.line(command.get_name());
        }
        let mail = definition.find_subcommand("email:send").expect("the alias resolves");
        assert_eq!(mail.get_about().unwrap().to_string(), "Send marketing emails to a user");
        assert!(
            mail.get_arguments()
                .any(|argument| argument.get_id() == "no-interaction")
        );
        assert!(mail.get_arguments().any(|argument| argument.get_id() == "queue"));
        definition = definition.subcommand(clap::Command::new("local:only"));
        assert!(definition.find_subcommand("local:only").is_some());
        assert!(laravel::console::commands().find_subcommand("local:only").is_none());
        let context = laravel::context::Context::current().unwrap();
        tokio::spawn(context.scope(async {
            assert!(
                laravel::console::commands()
                    .find_subcommand("inspect:commands")
                    .is_some()
            );
        }))
        .await?;
        Ok(())
    }
}

#[tokio::test]
async fn command_introspection_is_scoped_and_returns_detached_complete_metadata() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<InspectCommands>();
        })
        .create();
    app.command("inspect:commands")
        .await
        .assert_successful()
        .assert_output_contains("mail:send")
        .assert_output_contains("route:list")
        .assert_output_contains("inspect:commands");
    app.scope(async || {
        let definition = laravel::console::commands();
        assert_eq!(definition.get_name(), "app");
        assert!(definition.find_subcommand("email:send").is_some());
    })
    .await;
}

#[tokio::test]
async fn concurrent_applications_have_separate_command_definitions() {
    let first = configure()
        .with_commands(|commands, _| {
            commands.add::<InspectCommands>();
        })
        .create();
    let second = Application::configure().replace_env(Env::default()).create();
    tokio::join!(
        first.scope(async || {
            tokio::task::yield_now().await;
            assert!(
                laravel::console::commands()
                    .find_subcommand("inspect:commands")
                    .is_some()
            );
            first.command("inspect:commands").await.assert_successful();
        }),
        second.scope(async || {
            tokio::task::yield_now().await;
            assert!(
                laravel::console::commands()
                    .find_subcommand("inspect:commands")
                    .is_none()
            );
            second.command("list").await.assert_successful();
        }),
    );
}

#[tokio::test]
async fn http_handlers_can_inspect_their_applications_commands() {
    use laravel::testing::MakesHttpRequests;

    async fn inspect() -> String {
        laravel::console::commands()
            .get_subcommands()
            .map(clap::Command::get_name)
            .collect::<Vec<_>>()
            .join(",")
    }

    configure()
        .with_routing(|routing, _| {
            routing.api(|route| {
                route.get("/commands", inspect);
            });
        })
        .create()
        .get("/api/commands")
        .await
        .assert_ok()
        .assert_see("mail:send")
        .assert_see("route:list");
}

#[test]
#[should_panic(expected = "laravel::console::commands()")]
fn command_introspection_requires_application_context() {
    let _ = laravel::console::commands();
}

async fn next_number() -> usize {
    laravel::once(|| async {
        laravel::resolve::<Sequence>()
            .await
            .unwrap()
            .0
            .fetch_add(1, Ordering::SeqCst)
            + 1
    })
    .await
}

fn configure() -> laravel::foundation::ApplicationBuilder {
    Application::configure()
        .replace_env(Env::default())
        .with_services(|services| {
            services.instance(Mailer {
                from: "booted@example.com".to_owned(),
            });
            services.instance(Sequence(AtomicUsize::new(0)));
        })
        .booted(|services| async move {
            assert!(!services.resolve::<Mailer>().await.unwrap().from.is_empty());
        })
        .with_commands(|commands, _| {
            commands.add::<SendEmails>();
        })
}

#[tokio::test]
async fn typed_input_and_injected_services_run_after_boot() {
    configure()
        .with_config(|config, _| {
            config.app.name = "Marketing".to_owned();
        })
        .create()
        .command("mail:send 42 --queue=high")
        .await
        .assert_successful()
        .assert_error_output_contains("1: user=42 queue=high from=booted@example.com app=Marketing");
}

#[tokio::test]
async fn defaults_aliases_and_fresh_contexts_share_the_booted_application() {
    let app = configure().create();
    app.command("email:send 1")
        .await
        .assert_successful()
        .assert_error_output_contains("1: user=1 queue=default");
    app.command("mail:send 2")
        .await
        .assert_successful()
        .assert_error_output_contains("2: user=2 queue=default");
    assert!(laravel::context::Context::current().is_none());
}

#[tokio::test]
async fn help_uses_descriptions_and_argument_docs_and_boots_without_resolving_handler_dependencies() {
    let boots = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&boots);
    let app = Application::configure()
        .replace_env(Env::default())
        .booted(move |_| async move {
            counter.fetch_add(1, Ordering::SeqCst);
        })
        .with_commands(|commands, _| {
            commands.add::<SendEmails>();
        })
        .create();
    app.command("mail:send --help")
        .await
        .assert_successful()
        .assert_output_contains("Send marketing emails to a user")
        .assert_output_contains("The user to send to");
    assert_eq!(boots.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn missing_services_are_errors_and_are_reported() {
    let reports = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&reports);
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<SendEmails>();
        })
        .with_errors(move |errors, _| {
            errors.report_all(move |_| {
                counter.fetch_add(1, Ordering::SeqCst);
            });
        })
        .create();
    let result = app.command("mail:send 42").await;
    result
        .assert_exit_code(1)
        .assert_error_output_contains("Mailer")
        .assert_error_output_contains("register it");
    assert!(result.output().is_empty());
    assert_eq!(reports.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn boot_failures_prevent_execution_and_help() {
    let boots = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&boots);
    let app = Application::configure()
        .replace_env(Env::default())
        .booted(move |_| {
            counter.fetch_add(1, Ordering::SeqCst);
            async { Err(std::io::Error::other("database unavailable").into()) }
        })
        .with_commands(|commands, _| {
            commands.add::<SendEmails>();
        })
        .create();
    for command in [
        "mail:send 42",
        "mail:send --help",
        "list",
        "help mail:send",
        "route:list --json",
        "key:generate --show",
        "serve --help",
        "--help",
        "mail:send not-a-number",
        "mail:send",
        "mail:send 42 --unknown",
        "unknown",
    ] {
        let result = app.command(command).await;
        result
            .assert_exit_code(1)
            .assert_error_output_contains("database unavailable");
        assert!(result.output().is_empty());
    }
    assert_eq!(boots.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn failing_factories_fail_only_the_commands_that_use_them() {
    let builds = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&builds);
    let app = Application::configure()
        .replace_env(Env::default())
        .with_services(move |services| {
            services.singleton(move |_| {
                counter.fetch_add(1, Ordering::SeqCst);
                async { Err::<Mailer, _>(std::io::Error::other("database unavailable").into()) }
            });
            services.instance(Sequence(AtomicUsize::new(0)));
        })
        .with_commands(|commands, _| {
            commands.add::<SendEmails>();
        })
        .create();

    for _ in 0..2 {
        app.command("mail:send 42")
            .await
            .assert_exit_code(1)
            .assert_error_output_contains("database unavailable");
    }
    app.command("list").await.assert_successful();
    assert_eq!(builds.load(Ordering::SeqCst), 2, "a failed build is tried again");
}

#[tokio::test]
async fn builtins_and_custom_commands_share_help_and_listings() {
    let app = configure().create();
    for invocation in ["list", "help", "--help", "-h"] {
        let result = app.command(invocation).await;
        result
            .assert_successful()
            .assert_output_contains("mail:send")
            .assert_output_contains("Send marketing emails to a user")
            .assert_output_contains("route:list")
            .assert_output_contains("key:generate")
            .assert_output_contains("serve");
        assert!(
            result
                .output()
                .starts_with(&format!("Laravel for Rust {}\n\n", laravel::VERSION)),
            "{invocation}"
        );
        assert_eq!(result.output().matches("mail:send").count(), 1);
        assert!(!result.output().contains('\x1b'));
        assert!(result.error_output().is_empty());
    }
    for invocation in ["--version", "-V", "-v --version"] {
        let result = app.command(invocation).await;
        result.assert_successful();
        assert_eq!(
            result.output(),
            format!("Laravel for Rust {}\n", laravel::VERSION),
            "{invocation}"
        );
    }
    for name in [
        "mail:send",
        "email:send",
        "route:list",
        "key:generate",
        "cache:clear",
        "cache:prune",
        "schedule:list",
        "schedule:run",
        "schedule:work",
        "schedule:clear-cache",
        "schedule:interrupt",
        "serve",
        "list",
        "help",
    ] {
        let help = app.command_args(["help", name]).await;
        help.assert_successful();
        let direct = app.command_args([name, "--help"]).await;
        direct.assert_successful();
        assert_eq!(help.output(), direct.output(), "{name}");
        let short = app.command_args([name, "-h"]).await;
        short.assert_successful();
        assert_eq!(help.output(), short.output(), "{name}");
    }
    app.command("help missing")
        .await
        .assert_exit_code(2)
        .assert_error_output_contains("missing");
}

mod listing_commands {
    /// Refresh cached reports.
    #[laravel::console::command("reports:cache:refresh", visible_alias = "refresh-reports")]
    pub async fn refresh() {}

    /// Build reports.
    #[laravel::console::command("reports:build")]
    pub async fn build() {}

    #[laravel::console::command("zebra")]
    pub async fn zebra() {}

    #[laravel::console::command("alpha")]
    pub async fn alpha() {}

    #[laravel::console::command("reports:private", hide = true)]
    pub async fn private() {}
}

#[tokio::test]
async fn listings_sort_commands_under_their_first_namespace_and_hide_private_commands() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<listing_commands::refresh>();
            commands.add::<listing_commands::zebra>();
            commands.add::<listing_commands::private>();
            commands.add::<listing_commands::build>();
            commands.add::<listing_commands::alpha>();
        })
        .create();

    let mut expected = vec![
        "alpha",
        "help",
        "list",
        "migrate",
        "serve",
        "zebra",
        "cache",
        "cache:clear",
        "cache:prune",
        "db",
        "db:seed",
        "feature",
        "feature:purge",
        "key",
        "key:generate",
        "mail",
        "mail:send",
        "make",
        "make:migration",
        "migrate",
        "migrate:fresh",
        "migrate:status",
        "queue",
        "queue:clear",
        "queue:continue",
        "queue:failed",
        "queue:flush",
        "queue:forget",
        "queue:pause",
        "queue:prune-batches",
        "queue:restart",
        "queue:retry",
        "queue:retry-batch",
        "queue:work",
        "reports",
        "reports:build",
        "reports:cache:refresh",
        "reverb",
        "reverb:start",
        "route",
        "route:list",
        "schedule",
        "schedule:clear-cache",
        "schedule:interrupt",
        "schedule:list",
        "schedule:run",
        "schedule:work",
        "schema",
        "schema:dump",
        "search",
        "search:delete-index",
        "search:flush",
        "search:import",
        "search:index",
        "workflow",
        "workflow:cancel",
        "workflow:list",
        "workflow:prune",
        "workflow:recover",
        "workflow:retry",
        "workflow:show",
    ];
    expected.retain(|name| {
        cfg!(feature = "database")
            || ![
                "db",
                "db:seed",
                "make",
                "make:migration",
                "migrate",
                "migrate:fresh",
                "migrate:status",
                "queue:failed",
                "queue:flush",
                "queue:forget",
                "queue:prune-batches",
                "queue:retry",
                "queue:retry-batch",
            ]
            .contains(name)
    });
    expected.retain(|name| cfg!(feature = "search") || !name.starts_with("search"));
    expected.retain(|name| cfg!(feature = "reverb") || !name.starts_with("reverb"));

    for invocation in ["list", "help", "--help", "-h"] {
        let result = app.command(invocation).await;
        result.assert_successful();
        let listing = result.output().split_once("Commands:\n").unwrap().1;
        let names: Vec<_> = listing
            .lines()
            .filter_map(|line| line.split_whitespace().next())
            .collect();
        assert_eq!(names, expected, "{invocation}");
        assert!(listing.contains("Refresh cached reports [aliases: refresh-reports]"));
        assert!(!listing.contains("reports:private"));
        assert!(!result.output().contains('\x1b'));
        assert!(result.error_output().is_empty());
    }
    app.command("reports:private").await.assert_successful();
    app.command("refresh-reports").await.assert_successful();
}

#[tokio::test]
async fn builtin_arguments_are_typed_and_validated() {
    let app = configure().create();
    for command in [
        "route:list --unknown",
        "route:list --path",
        "route:list --json=yes",
        "key:generate --unknown",
        "key:generate --show=yes",
        "serve --port=invalid",
        "serve --port=65536",
        "serve --host",
        "serve --unknown",
        "list --unknown",
        "help serve extra",
        "unknown",
    ] {
        let result = app.command(command).await;
        result.assert_exit_code(2);
        assert!(result.output().is_empty(), "{command}");
        assert!(!result.error_output().is_empty(), "{command}");
    }
}

async fn users() -> &'static str {
    "users"
}
async fn posts() -> &'static str {
    "posts"
}

#[tokio::test]
async fn routes_are_listed_and_filtered_through_the_command_client() {
    let app = configure()
        .with_routing(|routing, _| {
            routing.api(|route| {
                route.get("/users", users);
                route
                    .post("/posts", posts)
                    .middleware(laravel::http::middleware::LimitBody::bytes(1024));
            });
        })
        .create();
    let result = app.command("route:list --json").await;
    result.assert_successful();
    assert_eq!(result.output().lines().count(), 1);
    assert!(result.error_output().is_empty());
    let routes: Vec<serde_json::Value> = serde_json::from_str(result.output()).unwrap();
    assert_eq!(routes.len(), 3, "the app's two routes and the workflow resume route");
    let result = app.command("route:list --json --path=users --handler=users").await;
    result.assert_successful();
    let routes: Vec<serde_json::Value> = serde_json::from_str(result.output()).unwrap();
    assert_eq!(routes.len(), 1);
    assert_eq!(routes[0]["uri"], "/api/users");
    assert_eq!(routes[0]["methods"], serde_json::json!(["GET", "HEAD"]));
    let plain = app.command("route:list").await;
    plain.assert_successful();
    assert!(plain.output().contains("Method"));
    assert!(!plain.output().contains("Domain"));
    assert!(!plain.output().contains('┌'));
    assert!(!plain.output().contains('│'));
    assert!(!plain.output().contains("⇂"));
    assert!(!plain.output().contains('\x1b'));
    assert!(plain.error_output().is_empty());
    assert_eq!(plain.output().lines().count(), 4, "{}", plain.output());
    let verbose = app.command("route:list -v --path=posts").await;
    verbose.assert_successful();
    verbose
        .assert_output_contains("POST")
        .assert_output_contains("/api/posts")
        .assert_output_contains("⇂ LimitBody");
    assert!(verbose.output().ends_with("⇂ LimitBody\n"), "{}", verbose.output());
    assert!(!verbose.output().contains("laravel::http::middleware"));
    app.command("route:list -vv --path=posts")
        .await
        .assert_output_contains("laravel::http::middleware");
    for command in [
        "-vv route:list --path=posts",
        "route:list --verbose --path=posts",
        "route:list -vvv --path=posts",
    ] {
        app.command(command)
            .await
            .assert_successful()
            .assert_output_contains("⇂");
    }
    let empty = app.command("route:list --path=missing").await;
    empty.assert_successful();
    assert!(empty.output().is_empty());
    assert_eq!(empty.error_output(), "No routes found.\n");
    let quiet = app.command("route:list --path=missing -q").await;
    quiet.assert_successful();
    assert!(quiet.output().is_empty());
    assert!(quiet.error_output().is_empty());
    assert_eq!(app.command("route:list --json --path=missing").await.output(), "[]\n");
}

mod listing_handlers {
    pub mod alpha {
        pub mod users {
            pub async fn show() -> &'static str {
                "alpha"
            }
        }
    }
    pub mod beta {
        pub mod users {
            pub async fn show() -> &'static str {
                "beta"
            }
        }
    }
}

#[tokio::test]
async fn route_listings_keep_domains_and_distinguish_shortened_handlers() {
    let app = configure()
        .with_routing(|routing, _| {
            routing.api(|route| {
                route.domain("admin.example.com").group(|route| {
                    route.get("/alpha", listing_handlers::alpha::users::show);
                });
                route.get("/beta", listing_handlers::beta::users::show);
                route.get("/closure", || async { "closure" });
            });
        })
        .create();
    let listing = app.command("route:list").await;
    listing.assert_successful();
    listing
        .assert_output_contains("Domain")
        .assert_output_contains("admin.example.com")
        .assert_output_contains("integration::alpha::users::show")
        .assert_output_contains("integration::beta::users::show")
        .assert_output_contains("Closure");
    assert!(!listing.output().contains("listing_handlers"));
    let full = app.command("route:list -vv").await;
    full.assert_successful()
        .assert_output_contains("integration::console::listing_handlers::alpha::users::show");
    let filtered = app.command("route:list --path=beta").await;
    filtered.assert_successful();
    assert!(!filtered.output().contains("Domain"));
    let json = app.command("route:list --json").await;
    json.assert_successful()
        .assert_output_contains("integration::console::listing_handlers::alpha::users::show");
    assert!(!json.output().contains("Closure"));
    let quiet = app.command("route:list -q").await;
    quiet.assert_successful();
    assert!(quiet.output().is_empty());
    assert!(quiet.error_output().is_empty());
}

#[tokio::test]
async fn keys_can_be_generated_with_captured_output() {
    use laravel::crypt::{Cipher, Encrypter};
    for key in [None, Some(""), Some("short"), Some("base64:%%%")] {
        let app = configure()
            .with_config(move |config, _| {
                config.app.cipher = Cipher::Aes128Cbc;
                config.app.key = key.map(str::to_owned);
            })
            .create();
        assert!(app.encrypter().is_err());
        let result = app.command("key:generate --show").await;
        result.assert_successful();
        assert!(result.error_output().is_empty());
        let mut config = app.config().app.clone();
        config.key = Some(result.output().trim().to_owned());
        Encrypter::from_config(&config).unwrap();
    }
}

#[derive(clap::Parser)]
#[command(name = "serve", about = "Application serve replacement")]
struct ServeReplacement;

#[laravel::console::command]
impl ServeReplacement {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        console.line("Application serve replacement");
        Ok(())
    }
}

#[tokio::test]
async fn application_commands_replace_builtins_in_dispatch_and_help() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<ServeReplacement>();
        })
        .create();
    for command in ["", "serve", "help serve", "serve --help"] {
        app.command(command)
            .await
            .assert_successful()
            .assert_output_contains("Application serve replacement");
    }
    let result = app.command("list").await;
    result
        .assert_successful()
        .assert_output_contains("Application serve replacement");
    assert_eq!(result.output().matches("Application serve replacement").count(), 1);
}

#[derive(clap::Parser)]
#[command(name = "parser:probe")]
struct ParserProbe {
    #[arg(long, value_parser = ["json", "text"])]
    format: Option<String>,
    #[arg(long, require_equals = true)]
    color: Option<String>,
    #[arg(long, num_args = 2)]
    pair: Vec<String>,
    #[arg(long, num_args = 2..)]
    many: Vec<String>,
    #[arg(long, value_parser = validate_parser_probe)]
    custom: Option<String>,
    #[arg(long, value_parser = validate_raw_parser_probe)]
    raw: Option<String>,
    #[arg(long, conflicts_with = "right")]
    left: bool,
    #[arg(long)]
    right: bool,
}

fn validate_parser_probe(_: &str) -> Result<String, String> {
    Err("vendor detail?\n\nsecond paragraph without punctuation".to_owned())
}

fn validate_raw_parser_probe(_: &str) -> Result<String, clap::Error> {
    Err(clap::Error::raw(
        clap::error::ErrorKind::ValueValidation,
        "application message without punctuation",
    ))
}

#[laravel::console::command]
impl ParserProbe {
    // `inline` is rejected on impl blocks, so this fails to compile if the attribute leaks onto `impl Command`.
    #[cfg_attr(all(), inline(never))]
    async fn handle(self) -> laravel::Result<()> {
        Ok(())
    }
}

#[tokio::test]
async fn parser_errors_have_consistent_headlines_and_preserve_validation_details() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<ParserProbe>();
        })
        .create();
    for (command, expected) in [
        ("route:lis", "unknown command `route:lis`"),
        ("help route:lis", "unknown command `route:lis`"),
        ("serve --por 8000", "unexpected argument `--por`"),
        ("mail:send", "missing required argument `<USER>`"),
        ("list -q -v", "argument `--quiet` can't be used with `--verbose`"),
        (
            "serve --port 80 --port 81",
            "argument `--port` can't be used multiple times",
        ),
        (
            "parser:probe --format xml",
            "invalid value `xml` for `--format`\nValid values: json, text",
        ),
        (
            "parser:probe --format",
            "argument `--format` requires a value\nValid values: json, text",
        ),
        (
            "parser:probe --color blue",
            "argument `--color` requires a value using `=`",
        ),
        (
            "parser:probe --pair one",
            "argument `--pair` requires 2 values; received 1",
        ),
        (
            "parser:probe --many one",
            "argument `--many` requires at least 2 values; received 1",
        ),
        (
            "serve --port oops",
            "invalid value `oops` for `--port`\nexpected a whole number",
        ),
        (
            "parser:probe --custom bad",
            "invalid value `bad` for `--custom`\nvendor detail?\n\nsecond paragraph without punctuation",
        ),
        (
            "parser:probe --raw bad",
            "invalid value `bad` for `--raw`\nerror: application message without punctuation",
        ),
        (
            "parser:probe --left --right",
            "argument `--left` can't be used with `--right`",
        ),
    ] {
        let result = app.command(command).await;
        result.assert_exit_code(2);
        let (message, _) = result
            .error_output()
            .split_once("\n\nUsage:")
            .or_else(|| result.error_output().split_once("\n\nFor more information,"))
            .unwrap_or_else(|| panic!("{}", result.error_output()));
        assert_eq!(message, expected, "{command}");
        assert!(!result.error_output().contains("tip:"), "{command}");
        assert!(result.output().is_empty(), "{command}");
    }
    app.command("route:lis")
        .await
        .assert_error_output_contains("\n\nUsage:");
}

#[tokio::test]
async fn parser_errors_show_the_invoked_commands_usage_rather_than_the_arguments_used_so_far() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<ParserProbe>().add::<SendEmails>();
        })
        .create();
    for (command, usage) in [
        ("parser:probe --right --nope", "Usage: app parser:probe [OPTIONS]"),
        ("parser:probe -v --nope", "Usage: app parser:probe [OPTIONS]"),
        ("parser:probe --left --right", "Usage: app parser:probe [OPTIONS]"),
        ("mail:send 42 --nope", "Usage: app mail:send [OPTIONS] <USER>"),
        ("-v mail:send", "Usage: app mail:send [OPTIONS] <USER>"),
        ("list -q -v", "Usage: app list [OPTIONS]"),
        ("rouet:list", "Usage: app [OPTIONS] <COMMAND>"),
    ] {
        let result = app.command(command).await;
        result.assert_exit_code(2);
        let shown = result
            .error_output()
            .lines()
            .find(|line| line.starts_with("Usage:"))
            .unwrap_or_else(|| panic!("{}", result.error_output()));
        assert_eq!(shown, usage, "{command}");
    }
}

#[derive(clap::Parser)]
#[command(name = "mail:send")]
struct Replacement;

#[laravel::console::command]
impl Replacement {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        console.line("Application replacement");
        Ok(())
    }
}

struct MailProvider;

impl ServiceProvider for MailProvider {
    fn config(&self, config: &mut Config, _: &Env) {
        config.app.name = "Provider".to_owned();
    }

    fn register(&self, services: &mut Registrar) {
        services.instance(Mailer {
            from: "provider@example.com".to_owned(),
        });
        services.instance(Sequence(AtomicUsize::new(0)));

        assert_eq!(services.config().app.name, "Final configuration");
        services.commands().add::<SendEmails>();
    }
}

#[tokio::test]
async fn provider_commands_see_final_config_and_application_registration_runs_last() {
    Application::configure()
        .replace_env(Env::default())
        .with_providers(|providers| {
            providers.add(MailProvider);
        })
        .with_config(|config, _| {
            config.app.name = "Final configuration".to_owned();
        })
        .create()
        .command("mail:send 42")
        .await
        .assert_successful()
        .assert_error_output_contains("from=provider@example.com app=Final configuration");

    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, config| {
            assert_eq!(config.app.name, "Final configuration");
            commands.add::<Replacement>();
        })
        .with_providers(|providers| {
            providers.add(MailProvider);
        })
        .with_config(|config, _| {
            config.app.name = "Final configuration".to_owned();
        })
        .create();
    app.command("mail:send")
        .await
        .assert_successful()
        .assert_output_contains("Application replacement");
    app.command("email:send 1").await.assert_exit_code(2);
}

#[tokio::test]
async fn concurrent_commands_share_boot_and_have_separate_contexts() {
    let builds = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&builds);
    let app = configure()
        .with_services(move |services| {
            services.singleton(move |_| {
                let counter = Arc::clone(&counter);
                async move {
                    tokio::task::yield_now().await;
                    counter.fetch_add(1, Ordering::SeqCst);
                    Ok(Mailer {
                        from: "factory@example.com".to_owned(),
                    })
                }
            });
        })
        .create();
    let (first, second) = tokio::join!(
        app.command("mail:send 1").into_future(),
        app.command("mail:send 2").into_future()
    );
    first
        .assert_successful()
        .assert_error_output_contains("user=1 queue=default from=factory@example.com");
    second
        .assert_successful()
        .assert_error_output_contains("user=2 queue=default from=factory@example.com");
    assert_ne!(
        first.error_output().split(':').next(),
        second.error_output().split(':').next()
    );
    assert_eq!(builds.load(Ordering::SeqCst), 1);
}

#[test]
fn conflicting_command_aliases_are_startup_errors() {
    #[derive(clap::Parser)]
    #[command(name = "other", alias = "email:send")]
    struct Other;

    #[laravel::console::command]
    impl Other {
        async fn handle(self) {}
    }

    let error = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<SendEmails>().add::<Other>();
        })
        .try_create()
        .unwrap_err();
    assert!(matches!(error, laravel::foundation::StartupError::Commands(_)));
    assert!(error.to_string().contains("email:send"));
}

#[test]
fn an_invalid_command_definition_is_a_startup_error_naming_the_command() {
    #[derive(clap::Parser)]
    #[command(name = "posts:publish")]
    struct Publish {
        force: bool,
    }

    #[laravel::console::command]
    impl Publish {
        async fn handle(self) {}
    }

    let error = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<SendEmails>().add::<Publish>();
        })
        .try_create()
        .unwrap_err();

    let message = error.to_string();
    assert!(
        message.starts_with("the application's console commands are invalid: command `posts:publish` is invalid: "),
        "{message}"
    );
    assert!(
        message.contains("'force`") && !message.contains("debug_asserts.rs"),
        "{message}"
    );
}

#[test]
fn an_invalid_command_definition_prints_no_panic_report() {
    let output = std::process::Command::new(std::env::current_exe().unwrap())
        .args([
            "--exact",
            "console::an_invalid_command_definition_is_a_startup_error_naming_the_command",
            "--nocapture",
        ])
        .output()
        .unwrap();

    assert!(output.status.success(), "{output:?}");
    assert_eq!(String::from_utf8(output.stderr).unwrap(), "");
}

#[derive(clap::Parser)]
#[command(name = "outcome")]
struct Outcome {
    code: u8,
    #[arg(long)]
    fail: bool,
}

#[laravel::console::command]
impl Outcome {
    async fn handle(self, console: &mut Console) -> laravel::Result<u8> {
        console.line("stdout");
        console.warn("stderr");
        if self.fail {
            std::str::from_utf8(&[self.code | 0x80])?;
        }
        Ok(self.code)
    }
}

#[tokio::test]
async fn explicit_exit_statuses_and_foreign_errors_keep_streams_separate() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Outcome>();
        })
        .create();
    let result = app.command("outcome 7").await;
    result.assert_exit_code(7).assert_failed();
    assert_eq!(result.output(), "stdout\n");
    assert_eq!(result.error_output(), "stderr\n");
    app.command("outcome 0 --fail")
        .await
        .assert_exit_code(1)
        .assert_error_output_contains("invalid utf-8");
}

#[derive(clap::Parser)]
#[command(name = "status")]
struct Status;

#[laravel::console::command]
impl Status {
    async fn handle(self) -> u8 {
        9
    }
}

#[derive(clap::Parser)]
#[command(name = "empty")]
struct Empty;

#[laravel::console::command]
impl Empty {
    async fn handle(self) {}
}

#[tokio::test]
async fn handlers_can_return_unit_or_a_status_without_console_arguments() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Status>().add::<Empty>();
        })
        .create();
    app.command("status").await.assert_exit_code(9);
    app.command("empty").await.assert_successful().assert_no_output();
}

#[tokio::test]
async fn output_assertions_check_each_stream_for_what_it_lacks() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Outcome>();
        })
        .create();
    let result = app.command("outcome 0").await;

    result
        .assert_output_missing("stderr")
        .assert_error_output_missing("stdout");
    let printed = failure(|| {
        result.assert_output_missing("stdout");
    });
    let warned = failure(|| {
        result.assert_error_output_missing("stderr");
    });
    let some_output = failure(|| {
        result.assert_no_output();
    });

    assert!(
        printed.starts_with(r#"expected stdout not to contain "stdout""#),
        "{printed}"
    );
    assert!(
        warned.starts_with(r#"expected stderr not to contain "stderr""#),
        "{warned}"
    );
    assert!(some_output.starts_with("expected no output"), "{some_output}");
}

#[derive(clap::Parser)]
#[command(name = "panic")]
struct Panicking;

#[laravel::console::command]
impl Panicking {
    async fn handle(self) {
        panic!("command panicked");
    }
}

#[laravel::console::command("feeds:watch", long_running)]
async fn watch_feeds() {}

#[derive(clap::Parser)]
#[command(name = "webhooks:work")]
struct WorkWebhooks;

#[laravel::console::command(long_running)]
impl WorkWebhooks {
    async fn handle(self) {}
}

#[tokio::test]
async fn long_running_commands_have_no_span_of_their_own() {
    let (lines, _guard) = crate::logging::Lines::capture();
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<watch_feeds>().add::<WorkWebhooks>();
        })
        .create();

    app.command("route:list").await.assert_successful();
    app.command("serve").await.assert_exit_code(1);
    app.command("schedule:work").await.assert_exit_code(1);
    app.command("queue:work sync").await.assert_exit_code(1);
    app.command("feeds:watch").await.assert_successful();
    app.command("webhooks:work").await.assert_successful();

    let spans: serde_json::Value = lines
        .json()
        .into_iter()
        .filter(|line| line["fields"]["message"] == "Command finished")
        .map(|line| line["spans"][0]["command"].clone())
        .collect();
    assert_eq!(spans, serde_json::json!(["route:list", null, null, null, null, null]));
}

#[tokio::test]
async fn panics_become_reported_command_failures() {
    let reports = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&reports);
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Panicking>();
        })
        .with_errors(move |errors, _| {
            errors.report_all(move |_| {
                counter.fetch_add(1, Ordering::SeqCst);
            });
        })
        .create();
    app.command("panic")
        .await
        .assert_exit_code(1)
        .assert_error_output_contains("command panicked");
    assert_eq!(reports.load(Ordering::SeqCst), 1);
}

#[derive(clap::Parser)]
#[command(name = "reject")]
struct Reject;

#[laravel::console::command]
impl Reject {
    async fn handle(self) -> laravel::Result<()> {
        Err(std::io::Error::other("payload \x1b]0;pwned\x07 rejected").into())
    }
}

#[tokio::test]
async fn command_failures_remove_terminal_escapes_from_the_error() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Reject>();
        })
        .create();
    let result = app.command("reject").await;
    result.assert_exit_code(1);
    assert_eq!(result.error_output(), "payload  rejected\n");
}

#[derive(clap::Parser)]
#[command(name = "echo")]
struct Echo {
    value: String,
}

#[laravel::console::command]
impl Echo {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        console.line(self.value);
        Ok(())
    }
}

#[tokio::test]
async fn command_strings_support_quoting_without_shell_expansion() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Echo>();
        })
        .create();
    app.command("echo 'hello $HOME $(whoami)'")
        .await
        .assert_successful()
        .assert_output_contains("hello $HOME $(whoami)");
}

#[cfg(unix)]
#[tokio::test]
async fn exact_arguments_preserve_non_utf8_paths() {
    use std::ffi::OsString;
    use std::os::unix::ffi::OsStringExt;

    #[derive(clap::Parser)]
    #[command(name = "path")]
    struct Path {
        value: std::path::PathBuf,
    }

    #[laravel::console::command]
    impl Path {
        async fn handle(self, console: &mut Console) -> laravel::Result<()> {
            assert_eq!(self.value.as_os_str().as_encoded_bytes(), &[b'/', 0xff]);
            console.line("path received");
            Ok(())
        }
    }

    Application::configure()
        .replace_env(Env::default())
        .with_commands(|commands, _| {
            commands.add::<Path>();
        })
        .create()
        .command_args([OsString::from("path"), OsString::from_vec(vec![b'/', 0xff])])
        .await
        .assert_successful()
        .assert_output_contains("path received");
}

#[derive(clap::Parser)]
#[command(name = "setup")]
struct Setup {
    #[arg(long)]
    defaults: bool,
}

#[laravel::console::command]
impl Setup {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        let ask = console.ask("Name?");
        let name = if self.defaults {
            ask.default("Taylor").await?
        } else {
            ask.await?
        };
        let choice = console.choice("Queue?", ["default", "high"]);
        let queue = if self.defaults {
            choice.default("default").await?
        } else {
            choice.await?
        };
        let confirm = console.confirm("Send?");
        let send = if self.defaults {
            confirm.default(false).await?
        } else {
            confirm.await?
        };
        if send {
            console.table(["Name", "Queue"], [[name.as_str(), queue.as_str()]]);
            console.info("Sent.");
        } else {
            console.warn("Not sent.");
        }
        Ok(())
    }
}

fn prompting_app() -> Application {
    configure()
        .with_commands(|commands, _| {
            commands.add::<Setup>();
        })
        .create()
}

#[tokio::test]
async fn scripted_prompts_drive_the_real_handler_without_terminal_output() {
    let result = prompting_app()
        .command("setup")
        .expects_question("Name?", "Taylor Otwell")
        .expects_choice("Queue?", "high")
        .expects_confirmation("Send?", true)
        .await;
    result
        .assert_successful()
        .assert_asked("Queue?")
        .assert_output_contains("Taylor Otwell")
        .assert_output_contains("high")
        .assert_error_output_contains("Sent.");
    assert_eq!(result.questions(), ["Name?", "Queue?", "Send?"]);
    assert!(!result.output().contains('\x1b'));
    assert_eq!(result.error_output(), "Sent.\n");
}

#[tokio::test]
async fn noninteractive_prompts_use_explicit_defaults_or_fail_without_waiting() {
    let app = prompting_app();
    let result = app.command("setup --defaults").await;
    result.assert_successful().assert_error_output_contains("Not sent.");
    assert_eq!(result.questions(), ["Name?", "Queue?", "Send?"]);
    app.command("setup")
        .await
        .assert_exit_code(1)
        .assert_error_output_contains("can't ask \"Name?\"")
        .assert_error_output_contains("supply a default");
    for command in [
        "-n setup --defaults",
        "--no-interaction setup --defaults",
        "setup --defaults -n",
    ] {
        app.command(command)
            .await
            .assert_successful()
            .assert_error_output_contains("Not sent.");
    }
    app.command("setup --help")
        .await
        .assert_successful()
        .assert_output_contains("--no-interaction");
    app.command("-n --port=invalid")
        .await
        .assert_exit_code(2)
        .assert_error_output_contains("expected a whole number");
}

#[tokio::test]
#[should_panic(expected = "`mail:send 'Taylor` has an unmatched quote or escape")]
async fn command_lines_with_an_unmatched_quote_panic() {
    let _ = configure().create().command("mail:send 'Taylor").await;
}

#[tokio::test]
#[should_panic(expected = "exit code: 1")]
async fn failed_stdout_assertions_show_the_exit_code_and_stderr() {
    prompting_app().command("setup").await.assert_output_contains("Sent.");
}

#[tokio::test]
#[should_panic(expected = "exit code: 0")]
async fn failed_stderr_assertions_show_the_exit_code_and_stdout() {
    prompting_app()
        .command("list")
        .await
        .assert_error_output_contains("can't ask");
}

#[tokio::test]
#[should_panic(expected = "unexpected prompt")]
async fn incorrect_prompt_expectations_fail_even_when_command_errors_are_expected() {
    prompting_app()
        .command("setup")
        .expects_confirmation("Name?", true)
        .await
        .assert_failed();
}

#[tokio::test]
#[should_panic(expected = "unexpected prompt")]
async fn extra_questions_fail_after_expected_answers_are_used() {
    prompting_app()
        .command("setup")
        .expects_question("Name?", "Taylor")
        .await
        .assert_failed();
}

#[derive(clap::Parser)]
#[command(name = "invalid-choice")]
struct InvalidChoice {
    #[arg(long)]
    empty: bool,
}

#[laravel::console::command]
impl InvalidChoice {
    async fn handle(self, console: &mut Console) -> laravel::Result<()> {
        if self.empty {
            console.choice("Queue?", Vec::<String>::new()).await?;
        } else {
            console.choice("Queue?", ["default", "high"]).default("missing").await?;
        }
        Ok(())
    }
}

#[tokio::test]
async fn empty_choices_and_invalid_defaults_are_errors_in_every_mode() {
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<InvalidChoice>();
        })
        .create();
    app.command("invalid-choice")
        .await
        .assert_exit_code(1)
        .assert_error_output_contains("isn't an option");
    app.command("invalid-choice --empty -n")
        .await
        .assert_exit_code(1)
        .assert_error_output_contains("at least one option");
}

#[derive(clap::Parser)]
#[command(name = "cancel")]
struct Cancel;

#[laravel::console::command]
impl Cancel {
    async fn handle(self) -> laravel::Result<()> {
        Err(laravel::console::PromptError::Cancelled.into())
    }
}

#[tokio::test]
async fn cancelled_prompts_exit_without_reporting_an_application_failure() {
    let reports = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&reports);
    let app = configure()
        .with_commands(|commands, _| {
            commands.add::<Cancel>();
        })
        .with_errors(move |errors, _| {
            errors.report_all(move |_| {
                counter.fetch_add(1, Ordering::SeqCst);
            });
        })
        .create();
    let result = app.command("cancel").await;
    result.assert_exit_code(130);
    assert!(result.output().is_empty());
    assert!(result.error_output().is_empty());
    assert_eq!(reports.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn running_inside_an_async_runtime_fails_without_side_effects() {
    let app = Application::configure().replace_env(Env::default()).create();

    assert_eq!(app.run(), std::process::ExitCode::FAILURE);
}

#[tokio::test]
async fn awaited_command_failures_name_the_line_that_ran_the_command() {
    use futures_util::FutureExt;

    let app = prompting_app();
    let line = line!() + 1;
    let command = app.command("list").expects_question("Name?", "Taylor");
    let panic = std::panic::AssertUnwindSafe(command.into_future())
        .catch_unwind()
        .await
        .expect_err("the unasked question should fail the test");
    let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();

    assert!(message.contains(&format!("\n\nat {}:{line}:", file!())), "{message}");
}