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
use std::any::type_name;
use std::sync::{Arc, Mutex};

use anyhow::Context;

use laravel::Application;
use laravel::config::{Config, Env};
use laravel::errors::Errors;
use laravel::foundation::ServiceProvider;
use laravel::http::{File, Request, StatusCode, header};
use laravel::routing::{Params, Router};
use laravel::testing::MakesHttpRequests;
use laravel::validation::InvalidInput;
use serde::Deserialize;
use serde_json::json;

use crate::support::{TempDir, WithDir};

use self::refunds::Refund;

#[derive(Debug, thiserror::Error)]
#[error("The card was declined")]
struct PaymentFailed;

#[derive(Debug, Deserialize)]
#[expect(dead_code, reason = "only deserialized")]
struct NewUser {
    name: String,
    email: String,
}

fn charge() -> Result<(), PaymentFailed> {
    Err(PaymentFailed)
}

async fn checkout() -> laravel::Result<&'static str> {
    charge()?;
    Ok("paid")
}

async fn invite() -> laravel::Result<&'static str> {
    Err(InvalidInput::new().with("email", "That email is already invited."))?
}

async fn disk() -> laravel::Result<&'static str> {
    Err(std::io::Error::other("the disk is full"))?
}

async fn checkout_with_context() -> laravel::Result<&'static str> {
    charge().context("The order can't be paid for")?;
    Ok("paid")
}

async fn checkout_with_error_context() -> laravel::Result<&'static str> {
    charge().map_err(|error| laravel::Error::from(error).context("charging order 7"))?;
    Ok("paid")
}

async fn send_invoice() -> laravel::Result<&'static str> {
    Err(laravel::abort(404).context("loading invoice 42 for tenant acme"))
}

async fn upload() -> laravel::Result<&'static str> {
    Err(std::io::Error::other("the disk is full")).context("The upload can't be saved")?
}

fn queue() -> anyhow::Result<()> {
    anyhow::bail!("the queue is down")
}

async fn dispatch() -> laravel::Result<&'static str> {
    queue()?;
    Ok("dispatched")
}

fn app(debug: bool, reported: &Arc<Mutex<Vec<String>>>) -> Application {
    let reported = Arc::clone(reported);

    Application::configure()
        .replace_env(Env::from_iter([("APP_DEBUG", if debug { "true" } else { "false" })]))
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.post("/checkout", checkout);
                route.get("/limited-with-invalid-header", || async {
                    Err::<(), _>(
                        laravel::abort(429)
                            .with_header("x-reason", "line\nbreak")
                            .with_header(header::RETRY_AFTER, "60"),
                    )
                });
                route.get("/gzipped-failure", || async {
                    ([(header::CONTENT_ENCODING, "gzip")], laravel::abort(404))
                });
                route.get("/moved", || async {
                    Err::<(), _>(laravel::abort(303).with_header(header::LOCATION, "/login"))
                });
                route.get("/limited-by-handler", || async {
                    ([(header::RETRY_AFTER, "60")], laravel::abort(429))
                });
                route
                    .get("/tagged", || async { Err::<(), _>(laravel::abort(404)) })
                    .middleware(TagResponses);
                route
                    .get("/invoice", || async {
                        Err::<(), _>(laravel::Error::new(404, MissingInvoice))
                    })
                    .middleware(IdentifyTenant);
                route.post("/users", |request: Request| async move {
                    request.parse::<NewUser>()?;
                    Ok::<_, laravel::Error>("created")
                });
                route.post("/invite", invite);
                route.get("/disk", disk);
                route.post("/imports", || async {
                    Err::<&str, _>(laravel::Error::msg("the import file has no header row"))
                });
                route.post("/checkout-with-context", checkout_with_context);
                route.post("/checkout-with-error-context", checkout_with_error_context);
                route.post("/invoices/42/send", send_invoice);
                route.post("/upload", upload);
                route.post("/dispatch", dispatch);
                route.get("/recommendations", || async {
                    std::fs::read("/no/such/recommendations").unwrap_or_else(|error| {
                        laravel::report(error);
                        Vec::new()
                    });
                    "no recommendations today"
                });
                route.get("/upgrading", || async {
                    Err::<(), _>(laravel::abort_with(503, "We're upgrading. Back in a minute."))
                });
                route.get("/names/{name}", |Params(name): Params<String>| async move {
                    Err::<(), _>(laravel::abort_with(403, format!("The name {name} is taken.")))
                });
                route.get("/report-missing", || async {
                    laravel::report(laravel::abort(404));
                    "carried on"
                });
                route.get("/posts/deleted", || async {
                    Err::<(), _>(laravel::abort_with(404, "That post was deleted."))
                });
                #[cfg(feature = "database")]
                route.get("/posts/abc", || async {
                    Err::<(), _>(laravel::Error::from(laravel::model::ModelNotFound {
                        model: "Post",
                        key: Some("abc".to_owned()),
                    }))
                });
                #[cfg(feature = "database")]
                route.get("/posts/sole", || async {
                    Err::<(), _>(laravel::Error::from(laravel::db::RecordNotFound))
                });
            });
        })
        .with_errors(move |errors, _| {
            let every = Arc::clone(&reported);

            errors
                .render(|_: &MissingInvoice, request, status| {
                    let tenant = request.extension::<Tenant>().map_or("missing", |tenant| tenant.0);
                    Some((status, format!("No such invoice for {tenant}")))
                })
                .status::<PaymentFailed>(402)
                .report(move |error: &std::io::Error| {
                    reported.lock().unwrap().push(error.to_string());
                })
                .report_all(move |error| {
                    every.lock().unwrap().push(format!("every: {}", error.type_name()));
                });
        })
        .create()
}

struct TagResponses;

impl laravel::http::Middleware for TagResponses {
    async fn handle(&self, request: Request, next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
        let mut response = next.run(request).await;
        let seen = response
            .headers()
            .get(header::CONTENT_TYPE)
            .cloned()
            .unwrap_or_else(|| laravel::http::HeaderValue::from_static("none"));
        response.headers_mut().insert("x-route-saw", seen);
        Ok(response)
    }
}

#[derive(Clone)]
struct Tenant(&'static str);

struct IdentifyTenant;

impl laravel::http::Middleware for IdentifyTenant {
    async fn handle(
        &self,
        mut request: Request,
        next: laravel::http::Next,
    ) -> laravel::Result<laravel::http::Response> {
        request.extensions_mut().insert(Tenant("acme"));
        Ok(next.run(request).await)
    }
}

#[derive(Debug, thiserror::Error)]
#[error("There's no such invoice")]
struct MissingInvoice;

fn quiet_app() -> Application {
    app(false, &Arc::default())
}

#[tokio::test]
async fn error_types_respond_with_their_status() {
    let response = quiet_app().post("/checkout").header("accept", "application/json").await;

    response
        .assert_status(402)
        .assert_json(json!({ "message": "The card was declined" }))
        .assert_nothing_reported();
    assert!(response.error().is_some_and(|error| error.is::<PaymentFailed>()));
}

#[tokio::test]
async fn errors_skip_invalid_headers_and_keep_their_status() {
    let response = quiet_app().get("/limited-with-invalid-header").await;

    response
        .assert_status(StatusCode::TOO_MANY_REQUESTS)
        .assert_header("retry-after", "60");
    assert!(response.headers().get("x-reason").is_none());
}

#[tokio::test]
async fn errors_keep_the_headers_their_handler_and_route_gave_them() {
    let app = quiet_app();

    app.get("/limited-by-handler")
        .await
        .assert_status(StatusCode::TOO_MANY_REQUESTS)
        .assert_header("retry-after", "60");
}

#[tokio::test]
async fn failures_details_stay_out_of_json_outside_debug_mode() {
    let response = quiet_app().get("/disk").header("accept", "application/json").await;

    response
        .assert_internal_server_error()
        .assert_json(json!({ "message": "Server Error" }));
    assert!(response.json().get("error").is_none());
    assert!(response.json().get("causes").is_none());

    let debug = app(true, &Arc::default());
    let expected = debug.post("/invite").header("accept", "application/json").await;
    assert!(expected.json().get("error").is_none(), "{}", expected.text());
}

#[tokio::test]
async fn an_error_from_a_message_is_a_failure_that_points_to_its_caller() {
    let reported = Arc::new(Mutex::new(Vec::new()));
    let response = app(false, &reported)
        .post("/imports")
        .header("accept", "application/json")
        .await;

    response
        .assert_internal_server_error()
        .assert_exact_json(json!({ "message": "Server Error" }));
    assert_eq!(reported.lock().unwrap().len(), 1);

    let debug = app(true, &Arc::default())
        .post("/imports")
        .header("accept", "application/json")
        .await;
    let json = debug.json();
    assert_eq!(json["message"], "the import file has no header row");
    assert_eq!(json["file"], "tests/errors.rs");
}

#[tokio::test]
async fn headers_about_the_body_arent_kept_on_a_rendered_error() {
    quiet_app()
        .get("/gzipped-failure")
        .await
        .assert_not_found()
        .assert_header_missing("content-encoding");
}

#[tokio::test]
async fn errors_of_ignored_types_arent_reported() {
    let reported = Arc::new(Mutex::new(Vec::new()));
    let every = Arc::clone(&reported);
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.get("/disk", disk);
            });
        })
        .with_errors(move |errors, _| {
            errors
                .report_all(move |error| every.lock().unwrap().push(error.to_string()))
                .dont_report::<std::io::Error>();
        })
        .create();

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

    assert!(reported.lock().unwrap().is_empty());
}

#[tokio::test]
async fn responders_adjust_every_rendered_error() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.get("/missing", || async { Err::<(), _>(laravel::abort(404)) });
            });
        })
        .with_errors(|errors, _| {
            errors.respond(|mut response, error, _request| {
                response.headers_mut().insert(
                    "x-error-status",
                    laravel::http::HeaderValue::from(error.status().as_u16()),
                );
                response
            });
        })
        .create();

    app.get("/missing").await.assert_header("x-error-status", "404");
}

#[tokio::test]
async fn route_middleware_see_the_rendered_error() {
    quiet_app()
        .get("/tagged")
        .await
        .assert_not_found()
        .assert_header("x-route-saw", "text/html; charset=utf-8");
}

#[tokio::test]
async fn errors_are_rendered_with_what_route_middleware_added_to_the_request() {
    quiet_app()
        .get("/invoice")
        .await
        .assert_not_found()
        .assert_see("No such invoice for acme");
}

#[tokio::test]
async fn invalid_input_names_the_field_in_laravels_shape() {
    quiet_app()
        .post("/users")
        .json(json!({ "name": "Taylor" }))
        .await
        .assert_unprocessable()
        .assert_json(json!({
            "message": "The email field is required.",
            "errors": { "email": ["The email field is required."] },
        }));
}

#[tokio::test]
async fn invalid_input_of_your_own_is_unprocessable_too() {
    quiet_app()
        .post("/invite")
        .json(json!({}))
        .await
        .assert_unprocessable()
        .assert_json_path("errors.email.0", "That email is already invited.");
}

#[tokio::test]
async fn failures_are_reported() {
    let reported = Arc::default();

    app(false, &reported)
        .get("/disk")
        .await
        .assert_internal_server_error()
        .assert_reported::<std::io::Error>();

    assert_eq!(
        *reported.lock().unwrap(),
        [
            "the disk is full".to_owned(),
            format!("every: {}", type_name::<std::io::Error>())
        ]
    );
}

#[tokio::test]
async fn failures_can_be_reported_without_failing_the_request() {
    let reported = Arc::default();

    app(false, &reported)
        .get("/recommendations")
        .await
        .assert_ok()
        .assert_see("no recommendations today")
        .assert_reported::<std::io::Error>();

    let reported = reported.lock().unwrap();
    assert_eq!(reported.len(), 2, "{reported:?}");
    assert_eq!(reported[1], format!("every: {}", type_name::<std::io::Error>()));
}

#[test]
fn reporting_outside_the_application_logs_the_error() {
    laravel::report(std::io::Error::other("no application here"));
}

#[tokio::test]
async fn failures_raised_with_abort_show_their_message_only_as_json() {
    let app = quiet_app();

    app.get("/upgrading")
        .header("accept", "application/json")
        .await
        .assert_status(503)
        .assert_json(json!({ "message": "We're upgrading. Back in a minute." }));
    app.get("/upgrading")
        .await
        .assert_status(503)
        .assert_see("Service Unavailable")
        .assert_dont_see("upgrading");
}

#[tokio::test]
async fn messages_on_the_built_in_error_page_are_escaped() {
    quiet_app()
        .get("/names/%3Cscript%3Ealert(1)%3C%2Fscript%3E")
        .await
        .assert_forbidden()
        .assert_see_html("The name &lt;script&gt;alert(1)&lt;/script&gt; is taken.")
        .assert_dont_see_html("<script>alert(1)");
}

#[tokio::test]
async fn expected_outcomes_are_not_reported() {
    let reported = Arc::default();
    let app = app(false, &reported);

    app.get("/missing").await.assert_not_found().assert_nothing_reported();
    app.get("/report-missing").await.assert_ok().assert_nothing_reported();
    app.get("/moved")
        .await
        .assert_status(StatusCode::SEE_OTHER)
        .assert_header("location", "/login")
        .assert_nothing_reported();

    assert!(reported.lock().unwrap().is_empty());
}

#[tokio::test]
async fn only_failures_get_the_debug_page() {
    let app = app(true, &Arc::default());

    app.get("/disk")
        .await
        .assert_internal_server_error()
        .assert_see(type_name::<std::io::Error>())
        .assert_see("Server Error")
        .assert_dont_see("Internal Server Error");
    app.post("/users")
        .form([("name", "Taylor")])
        .await
        .assert_unprocessable()
        .assert_see("Unprocessable Content")
        .assert_dont_see("Caused by");
}

#[tokio::test]
async fn failures_say_where_they_happened_in_debug_mode() {
    let app = app(true, &Arc::default());

    let response = app.get("/disk").header("accept", "application/json").await;
    let json = response.json();
    assert_eq!(json["file"], "tests/errors.rs", "the `?` in `disk`: {json}");
    assert!(json["line"].as_u64().is_some(), "{json}");

    app.get("/disk")
        .await
        .assert_see(type_name::<std::io::Error>())
        .assert_see("tests/errors.rs:");
}

#[tokio::test]
async fn debug_pages_highlight_the_callers_source_from_the_app_base_path() {
    let line = line!() + 1;
    let error = laravel::abort_with(500, "Cannot render <script> markup");
    let root = tempfile::tempdir().unwrap();
    let file = root.path().join(file!());
    std::fs::create_dir_all(file.parent().unwrap()).unwrap();
    let mut source = vec!["// outside the excerpt"; line as usize + 20];
    source[line as usize - 2] = "// before the failure";
    source[line as usize - 1] = "return Err(\"<script>alert('source')</script>\");";
    source[line as usize] = "// after the failure";
    std::fs::write(&file, source.join("\n")).unwrap();

    let app = Application::configure()
        .replace_env(Env::from_iter([
            ("APP_BASE_PATH", root.path().to_str().unwrap()),
            ("APP_DEBUG", "true"),
        ]))
        .with_routing(move |routing, _| {
            routing.routes(move |route: &mut Router| {
                route.get("/broken", move || {
                    let error = error.clone();
                    async move { Err::<(), _>(error) }
                });
            });
        })
        .create();

    app.get("/broken")
        .header("authorization", "Bearer hidden-token")
        .header("proxy-authorization", "Basic hidden-proxy-token")
        .header("cookie", "secret=hidden-cookie")
        .header("x-note", "<b>header</b>")
        .await
        .assert_internal_server_error()
        .assert_see_html("Caller location</h2>")
        .assert_see(&format!("{}:{line}", file!()))
        .assert_see_html(&format!(
            r#"aria-current="true"><span class="line-number">{line}</span>return Err(&quot;&lt;script&gt;alert(&#039;source&#039;)&lt;/script&gt;&quot;);"#,
        ))
        .assert_see("// before the failure")
        .assert_see("// after the failure")
        .assert_see_html("Cannot render &lt;script&gt; markup")
        .assert_dont_see_html("<script>alert('source')</script>")
        .assert_see_html("&lt;b&gt;header&lt;/b&gt;")
        .assert_dont_see("hidden-token")
        .assert_dont_see("hidden-proxy-token")
        .assert_dont_see("hidden-cookie");

    std::fs::remove_file(file).unwrap();
    app.get("/broken")
        .await
        .assert_internal_server_error()
        .assert_see(&format!("{}:{line}", file!()))
        .assert_see("Source unavailable.");
}

fn find_report() -> Option<&'static str> {
    None
}

const PANIC_LINE: u32 = line!() + 2;
async fn show_report() -> &'static str {
    find_report().expect("the report exists")
}

#[tokio::test]
async fn debug_pages_show_where_a_handler_panicked() {
    let app = Application::configure()
        .replace_env(Env::from_iter([
            ("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
            ("APP_DEBUG", "true"),
        ]))
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.get("/report", show_report);
            });
        })
        .create();

    app.get("/report")
        .await
        .assert_internal_server_error()
        .assert_see_html("Panic location</h2>")
        .assert_see(&format!("tests/errors.rs:{PANIC_LINE}"))
        .assert_see_html(&format!(
            r#"aria-current="true"><span class="line-number">{PANIC_LINE}</span>"#
        ))
        .assert_see("the report exists");

    let json = app.get("/report").header("accept", "application/json").await.json();
    assert_eq!(
        (&json["file"], &json["line"]),
        (&json!("tests/errors.rs"), &json!(PANIC_LINE)),
        "{json}"
    );
}

struct MissingGateway;
struct FactoryGateway;

async fn injected_handler(_gateway: laravel::container::Inject<MissingGateway>) {}

#[laravel::http::middleware]
async fn pass_through(request: Request, next: laravel::http::Next) -> laravel::http::Response {
    next.run(request).await
}

const EXPLICIT_RESOLUTION_LINE: u32 = line!() + 2;
async fn explicit_resolution() -> laravel::Result<()> {
    laravel::resolve::<MissingGateway>().await?;
    Ok(())
}

const INJECTION_ROUTE_LINE: u32 = line!() + 2;
fn injection_routes(route: &mut Router) {
    route.get("/injected", injected_handler);
    route.get("/explicit", explicit_resolution);
    route.get("/factory", |_: laravel::container::Inject<FactoryGateway>| async {});
    route.get("/factory-explicit", || async {
        laravel::resolve::<FactoryGateway>().await?;
        Ok::<_, laravel::Error>(())
    });
    resource_injection_routes(route);
    fallback_injection_routes(route);
}

const RESOURCE_INJECTION_LINE: u32 = line!() + 2;
fn resource_injection_routes(route: &mut Router) {
    let resource = laravel::routing::Resource::new().index(injected_handler);
    route.resource("injected-resource", resource);
}

const FALLBACK_INJECTION_LINE: u32 = line!() + 2;
fn fallback_injection_routes(route: &mut Router) {
    route.fallback(injected_handler);
}

#[tokio::test]
async fn missing_services_point_to_the_application_call() {
    let factory_line = line!() + 1;
    let factory_error = laravel::abort_with(500, "gateway credentials are invalid");
    let app = Application::configure()
        .replace_env(Env::from_iter([
            ("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
            ("APP_DEBUG", "true"),
        ]))
        .with_middleware(|middleware, _| {
            middleware.append(pass_through);
        })
        .with_services(move |services| {
            services.singleton(move |_| {
                let error = factory_error.clone();
                async move { Err::<FactoryGateway, _>(error) }
            });
        })
        .with_routing(|routing, _| {
            routing.routes(injection_routes);
        })
        .create();

    for (path, line) in [
        ("/injected", INJECTION_ROUTE_LINE),
        ("/explicit", EXPLICIT_RESOLUTION_LINE),
        ("/injected-resource", RESOURCE_INJECTION_LINE),
        ("/fallback", FALLBACK_INJECTION_LINE),
    ] {
        let (logs, _guard) = crate::logging::Lines::capture();
        app.get(path)
            .await
            .assert_internal_server_error()
            .assert_see("MissingGateway")
            .assert_see_html(&format!(
                r#"aria-current="true"><span class="line-number">{line}</span>"#
            ));

        let log = logs.report();
        let location = log["fields"]["location"].as_str().unwrap();
        assert!(location.starts_with(&format!("tests/errors.rs:{line}:")), "{log}");

        let json = app.get(path).header("accept", "application/json").await.json();
        assert_eq!(json["file"], "tests/errors.rs");
        assert_eq!(json["line"], line);
    }

    for path in ["/factory", "/factory-explicit"] {
        let json = app.get(path).header("accept", "application/json").await.json();
        assert_eq!(json["file"], "tests/errors.rs");
        assert_eq!(json["line"], factory_line);
    }
}

const MISSING_VIEW_LINE: u32 = line!() + 2;
async fn missing_view() -> laravel::view::View {
    laravel::view("missing-diagnostic-page", ())
}

const MISSING_VIEW_ROUTE_LINE: u32 = line!() + 2;
fn missing_view_routes(route: &mut Router) {
    route.view("/view-shortcut", "missing-diagnostic-page");
    route.get("/missing-view", missing_view);
}

#[tokio::test]
async fn missing_views_point_to_where_the_view_was_created() {
    let app = Application::configure()
        .replace_env(Env::from_iter([
            ("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
            ("APP_DEBUG", "true"),
        ]))
        .with_middleware(|middleware, _| {
            middleware.append(pass_through);
        })
        .with_routing(|routing, _| {
            routing.routes(missing_view_routes);
        })
        .create();

    for (path, line) in [
        ("/missing-view", MISSING_VIEW_LINE),
        ("/view-shortcut", MISSING_VIEW_ROUTE_LINE),
    ] {
        app.get(path)
            .await
            .assert_internal_server_error()
            .assert_see("missing-diagnostic-page")
            .assert_see_html(&format!(
                r#"aria-current="true"><span class="line-number">{line}</span>"#
            ));

        let json = app.get(path).header("accept", "application/json").await.json();
        assert_eq!(json["file"], "tests/errors.rs");
        assert_eq!(json["line"], line);
    }
}

#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn undefined_database_connections_point_to_the_application_call() {
    let named_line = line!() + 2;
    async fn named() -> laravel::Result<()> {
        laravel::db::connection("missing-analytics")?;
        Ok(())
    }
    let default_line = line!() + 2;
    async fn default() -> laravel::Result<()> {
        laravel::db::default_connection()?;
        Ok(())
    }

    let app = Application::configure()
        .replace_env(Env::from_iter([
            ("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
            ("APP_DEBUG", "true"),
        ]))
        .with_config(|config, _| {
            config.database.default = "missing-default".into();
        })
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.get("/named", named);
                route.get("/default", default);
            });
        })
        .create();

    for (path, line, name) in [
        ("/named", named_line, "missing-analytics"),
        ("/default", default_line, "missing-default"),
    ] {
        let (logs, _guard) = crate::logging::Lines::capture();
        app.get(path)
            .await
            .assert_internal_server_error()
            .assert_see(&format!("database connection `{name}` isn't defined"))
            .assert_see_html(&format!(
                r#"aria-current="true"><span class="line-number">{line}</span>"#
            ));

        let log = logs.report();
        let location = log["fields"]["location"].as_str().unwrap();
        assert!(location.starts_with(&format!("tests/errors.rs:{line}:")), "{log}");

        let json = app.get(path).header("accept", "application/json").await.json();
        assert_eq!(json["file"], "tests/errors.rs");
        assert_eq!(json["line"], line);
    }
}

#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn debug_pages_select_the_application_frame_for_async_database_errors() {
    let query_line = line!() + 2;
    async fn broken_query() -> laravel::Result<()> {
        laravel::db::query!("SELEC id FROM users").select().await?;
        Ok(())
    }

    let app = Application::configure()
        .replace_env(Env::from_iter([
            ("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
            ("APP_DEBUG", "true"),
            ("DATABASE_URL", "sqlite::memory:"),
        ]))
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.get("/broken-query", broken_query);
            });
        })
        .create();

    app.get("/broken-query")
        .await
        .assert_internal_server_error()
        .assert_see_html("Application frame</h2>")
        .assert_see(&format!("tests/errors.rs:{query_line}"))
        .assert_see_html(&format!(
            r#"aria-current="true"><span class="line-number">{query_line}</span>"#
        ))
        .assert_see("syntax error");
}

#[tokio::test]
async fn anyhow_errors_convert_with_the_question_mark() {
    let response = quiet_app().post("/dispatch").await;

    response.assert_internal_server_error();
    let error = response.error().expect("the error");
    assert_eq!(error.to_string(), "the queue is down");
    assert_eq!(error.type_name(), "anyhow::Error");
}

#[rstest::rstest]
#[case::abort("/invoices/42/send", 404, "Not Found", "loading invoice 42 for tenant acme")]
#[case::error_context("/checkout-with-error-context", 402, "The card was declined", "charging order 7")]
#[case::anyhow_context(
    "/checkout-with-context",
    402,
    "The card was declined",
    "The order can't be paid for"
)]
#[tokio::test]
async fn client_errors_show_the_message_of_the_error_that_set_their_status(
    #[case] path: &str,
    #[case] status: u16,
    #[case] message: &str,
    #[case] context: &str,
) {
    let json = app(true, &Arc::default())
        .post(path)
        .header("accept", "application/json")
        .await;

    json.assert_status(status).assert_json(json!({ "message": message }));
    assert!(json.error().is_some_and(|error| error.to_string().contains(context)));

    let production = quiet_app();
    production
        .post(path)
        .header("accept", "application/json")
        .await
        .assert_status(status)
        .assert_json(json!({ "message": message }));
    let reason = StatusCode::from_u16(status).unwrap().canonical_reason().unwrap();
    production
        .post(path)
        .await
        .assert_status(status)
        .assert_see(reason)
        .assert_dont_see(context);
}

#[cfg(feature = "database")]
#[rstest::rstest]
#[case::model("/posts/abc", "No query results for model `Post` with the key `abc`.")]
#[case::record("/posts/sole", "No query results.")]
#[tokio::test]
async fn missing_rows_give_their_message_as_json_and_a_not_found_page(#[case] path: &str, #[case] detail: &str) {
    for app in [app(true, &Arc::default()), quiet_app()] {
        app.get(path)
            .header("accept", "application/json")
            .await
            .assert_not_found()
            .assert_json(json!({ "message": detail }));
        app.get(path)
            .await
            .assert_not_found()
            .assert_see_html("<title>404 Not Found</title>")
            .assert_dont_see(detail);
    }

    let production = quiet_app();

    production
        .get("/posts/deleted")
        .header("accept", "application/json")
        .await
        .assert_not_found()
        .assert_json(json!({ "message": "That post was deleted." }));
}

#[tokio::test]
async fn context_is_reported_with_its_causes() {
    let reported = Arc::default();
    let app = app(true, &reported);

    app.post("/upload")
        .await
        .assert_internal_server_error()
        .assert_reported::<std::io::Error>()
        .assert_see_html("The upload can&#039;t be saved")
        .assert_see("Caused by")
        .assert_see("the disk is full");

    assert_eq!(reported.lock().unwrap()[0], "the disk is full");
}

fn checkout_routes(routing: &mut laravel::routing::Routing, _: &Config) {
    routing.api(|route: &mut Router| {
        route.post("/checkout", checkout);
    });
    routing.routes(|route: &mut Router| {
        route.post("/checkout", checkout);
    });
}

#[tokio::test]
async fn errors_on_api_routes_render_as_json_whatever_the_client_accepts() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(checkout_routes)
        .with_errors(|errors, _| {
            errors.status::<PaymentFailed>(402);
        })
        .create();

    app.post("/api/checkout")
        .await
        .assert_status(402)
        .assert_json(json!({ "message": "The card was declined" }));

    app.post("/checkout")
        .await
        .assert_status(402)
        .assert_header("content-type", "text/html; charset=utf-8");
}

struct BillingProvider;

impl ServiceProvider for BillingProvider {
    fn register(&self, app: &mut laravel::container::Registrar) {
        app.errors()
            .status::<PaymentFailed>(409)
            .render(|_: &PaymentFailed, _request, status| Some((status, "The package's page")));
    }
}

fn billing_app(configure: impl FnOnce(&mut Errors, &Config) + 'static) -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_routing(checkout_routes)
        .with_errors(configure)
        .with_providers(|providers| {
            providers.add(BillingProvider);
        })
        .create()
}

#[tokio::test]
async fn providers_give_their_errors_a_status_and_a_renderer() {
    billing_app(|_, _| {})
        .post("/checkout")
        .await
        .assert_status(409)
        .assert_see("The package's page");
}

#[tokio::test]
async fn the_applications_statuses_and_renderers_replace_a_providers() {
    billing_app(|errors, _| {
        errors
            .status::<PaymentFailed>(402)
            .render(|_: &PaymentFailed, _request, status| Some((status, "The application's page")));
    })
    .post("/checkout")
    .await
    .assert_status(402)
    .assert_see("The application's page");
}

#[tokio::test]
async fn renderers_that_decline_fall_back_to_earlier_ones() {
    billing_app(|errors, _| {
        errors.render(|_: &PaymentFailed, request, _status| request.expects_json().then_some("The application's JSON"));
    })
    .post("/checkout")
    .await
    .assert_status(409)
    .assert_see("The package's page");
}

#[tokio::test]
async fn the_application_configures_errors_with_the_final_config() {
    Application::configure()
        .replace_env(Env::from_iter([("APP_NAME", "Billing")]))
        .with_routing(checkout_routes)
        .with_errors(|errors, config| {
            let name = config.app.name.clone();

            errors.render(move |_: &PaymentFailed, _request, status| {
                Some((status, format!("{name} can't take payments right now")))
            });
        })
        .create()
        .post("/checkout")
        .await
        .assert_internal_server_error()
        .assert_see("Billing can't take payments right now");
}

#[derive(Debug, thiserror::Error, laravel::errors::Status)]
#[error("This time slot is already booked")]
#[status(409)]
struct BookingConflict;

/// The refund errors beside a middleware named `error`, which is a unit struct that a parameter
/// named `error` in the derived status lookup would match.
mod refunds {
    use laravel::http::{Next, Request, Response, StatusCode};

    #[laravel::http::middleware]
    pub(super) async fn error(request: Request, next: Next) -> Response {
        next.run(request).await
    }

    #[derive(Debug, thiserror::Error, laravel::errors::Status)]
    #[status(400)]
    pub(super) enum Refund {
        #[error("The card was declined: {reason}")]
        #[status(StatusCode::PAYMENT_REQUIRED)]
        Declined { reason: &'static str },
        #[error("The amount {0} is below the minimum")]
        #[status(422)]
        BelowMinimum(u64),
        #[error("The refund window has closed")]
        Closed,
    }
}

#[derive(Debug, thiserror::Error, laravel::errors::Status)]
#[error("The booking service is unavailable")]
#[status(503)]
struct BookingsUnavailable(#[source] BookingConflict);

#[derive(Debug, thiserror::Error, laravel::errors::Status)]
enum Ledger {
    #[error("The ledger is locked")]
    #[status(423)]
    Locked,
    #[error("The ledger is unreachable")]
    Unreachable,
}

#[tokio::test]
async fn derived_statuses_respond_by_type_and_variant_unless_the_application_maps_the_type() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route| {
                route.post("/bookings", || async {
                    Err::<(), _>(BookingConflict).context("Booking failed")?;
                    Ok::<_, laravel::Error>(())
                });
                route
                    .post("/declined", || async {
                        Err::<(), _>(Refund::Declined { reason: "expired" })?;
                        Ok::<_, laravel::Error>(())
                    })
                    .middleware(refunds::error);
                route.post("/small", || async {
                    Err::<(), _>(Refund::BelowMinimum(10))?;
                    Ok::<_, laravel::Error>(())
                });
                route.post("/closed", || async {
                    Err::<(), _>(Refund::Closed)?;
                    Ok::<_, laravel::Error>(())
                });
                route.post("/locked", || async {
                    Err::<(), _>(Ledger::Locked)?;
                    Ok::<_, laravel::Error>(())
                });
                route.post("/unreachable", || async {
                    Err::<(), _>(Ledger::Unreachable)?;
                    Ok::<_, laravel::Error>(())
                });
            });
        })
        .with_errors(|errors, _| {
            errors.status::<Ledger>(503);
        })
        .create();

    for (uri, status) in [
        ("/bookings", 409),
        ("/declined", 402),
        ("/small", 422),
        ("/closed", 400),
        ("/locked", 503),
        ("/unreachable", 503),
    ] {
        app.post(uri)
            .header("accept", "application/json")
            .await
            .assert_status(status);
    }
    app.post("/bookings")
        .header("accept", "application/json")
        .await
        .assert_json(json!({ "message": "This time slot is already booked" }))
        .assert_nothing_reported();
}

#[test]
fn errors_report_their_types_derived_status_before_they_are_rendered() {
    let statuses = [
        laravel::Error::from(BookingConflict).status(),
        laravel::Error::from(Refund::BelowMinimum(10)).status(),
        laravel::Error::from(Refund::Closed).status(),
        laravel::Error::from(Ledger::Unreachable).status(),
        laravel::Error::from(InvalidInput::new().with("email", "Taken.")).status(),
        laravel::Error::new(418, BookingConflict).status(),
    ];

    assert_eq!(statuses.map(|status| status.as_u16()), [409, 422, 400, 500, 422, 418]);
}

fn bookings() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route| {
                route.post("/bookings", || async {
                    Err::<(), _>(BookingConflict).context("Booking failed")?;
                    Ok::<_, laravel::Error>(())
                });
                route.post("/refunds", || async {
                    Err::<(), _>(Refund::Declined { reason: "expired" })?;
                    Ok::<_, laravel::Error>(())
                });
                route.post("/paid", || async { "paid" });
                route.post("/unavailable", || async {
                    Err::<(), _>(BookingsUnavailable(BookingConflict))?;
                    Ok::<_, laravel::Error>(())
                });
            });
        })
        .create()
}

#[tokio::test]
async fn tests_assert_the_type_and_fields_of_a_response_error() {
    let app = bookings();

    app.post("/bookings")
        .await
        .assert_status(409)
        .assert_error::<BookingConflict>();
    app.post("/refunds")
        .await
        .assert_error_where(|error: &Refund| matches!(error, Refund::Declined { reason: "expired" }));
    app.post("/unavailable")
        .await
        .assert_status(503)
        .assert_error::<BookingsUnavailable>()
        .assert_error::<BookingConflict>();
}

#[tokio::test]
#[should_panic(expected = "Ledger`\n\n409 Conflict")]
async fn error_assertions_fail_for_another_type() {
    bookings().post("/bookings").await.assert_error::<Ledger>();
}

#[tokio::test]
#[should_panic(expected = "Refund` to pass the check, but it was Declined { reason: \"expired\" }")]
async fn error_assertions_fail_when_the_check_does() {
    bookings()
        .post("/refunds")
        .await
        .assert_error_where(|error: &Refund| matches!(error, Refund::Closed));
}

#[tokio::test]
#[should_panic(expected = "BookingConflict`, but it has no error\n\n200 OK")]
async fn error_assertions_fail_without_an_error() {
    bookings().post("/paid").await.assert_error::<BookingConflict>();
}

#[derive(Debug, thiserror::Error)]
#[error("There's no such page")]
struct NoSuchPage;

fn no_such_page_routes(route: &mut Router) {
    route.get("/missing", || async {
        Err::<(), _>(laravel::Error::new(404, NoSuchPage))
    });
    route.get("/also-missing", || async {
        Err::<(), _>(laravel::Error::new(404, NoSuchPage))
    });
}

#[tokio::test]
async fn a_renderer_that_fails_is_rendered_and_reported_in_its_place() {
    let reported = Arc::new(Mutex::new(Vec::new()));
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_DEBUG", "false")]))
        .with_routing(|routing, _| {
            routing.routes(no_such_page_routes);
        })
        .with_errors({
            let reported = Arc::clone(&reported);
            move |errors, _| {
                errors
                    .render(|_: &NoSuchPage, _request, _status| Some(laravel::view("errors.no-such-view", ())))
                    .report_all(move |error| reported.lock().unwrap().push(error.to_string()));
            }
        })
        .create();

    for uri in ["/missing", "/also-missing"] {
        let response = app.get(uri).await;
        response.assert_internal_server_error();
        assert!(!response.text().is_empty(), "{uri} rendered an empty page");
    }
    let reported = reported.lock().unwrap();
    assert_eq!(reported.len(), 2, "{reported:?}");
    assert!(
        reported.iter().all(|error| error.contains("errors.no-such-view")),
        "{reported:?}"
    );
}

struct PanicsBeforeRouting;

impl laravel::http::Middleware for PanicsBeforeRouting {
    async fn handle(&self, _request: Request, _next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
        panic!("the middleware failed");
    }
}

#[tokio::test]
async fn panics_in_global_middleware_are_rendered() {
    Application::configure()
        .replace_env(Env::from_iter([("APP_DEBUG", "true")]))
        .with_middleware(|middleware, _| {
            middleware.append(PanicsBeforeRouting);
        })
        .create()
        .get("/")
        .await
        .assert_internal_server_error()
        .assert_see("the middleware failed");
}

#[tokio::test]
async fn renderers_can_render_errors_with_a_file() {
    let pages = TempDir::with_files("error-pages", &[("404.html", "<h1>No such page</h1>")]);
    let page = pages.join("404.html");
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_DEBUG", "false")]))
        .with_routing(|routing, _| {
            routing.routes(no_such_page_routes);
        })
        .with_errors(move |errors, _| {
            errors.render(move |_: &NoSuchPage, _request, status| Some((status, File::new(page.clone()))));
        })
        .create();
    let app = WithDir::new(app, pages);

    for uri in ["/missing", "/also-missing"] {
        app.get(uri)
            .await
            .assert_not_found()
            .assert_header("content-type", "text/html")
            .assert_see("<h1>No such page</h1>");
    }
}

#[tokio::test]
async fn a_renderer_that_panics_gets_the_built_in_page() {
    let reported = Arc::new(Mutex::new(Vec::new()));
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_DEBUG", "false")]))
        .with_routing(|routing, _| {
            routing.routes(no_such_page_routes);
        })
        .with_errors({
            let reported = Arc::clone(&reported);
            move |errors, _| {
                errors
                    .render(|_: &NoSuchPage, _request, _status| -> Option<&str> { panic!("the renderer failed") })
                    .report_all(move |error| reported.lock().unwrap().push(error.to_string()));
            }
        })
        .create();

    app.get("/missing")
        .await
        .assert_internal_server_error()
        .assert_see("Server Error");
    app.get("/missing")
        .header("accept", "application/json")
        .await
        .assert_internal_server_error()
        .assert_exact_json(json!({ "message": "Server Error" }));
    let reported = reported.lock().unwrap();
    assert_eq!(reported.len(), 2, "{reported:?}");
    assert!(
        reported.iter().all(|error| error.contains("the renderer failed")),
        "{reported:?}"
    );
}

#[tokio::test]
async fn a_renderer_that_panics_in_debug_mode_answers_json_with_the_panic() {
    let app = Application::configure()
        .replace_env(Env::from_iter([("APP_DEBUG", "true")]))
        .with_routing(|routing, _| {
            routing.routes(no_such_page_routes);
        })
        .with_errors(|errors, _| {
            errors.render(|_: &NoSuchPage, _request, _status| -> Option<&str> { panic!("the renderer failed") });
        })
        .create();

    let response = app.get("/missing").header("accept", "text/html").await;
    response
        .assert_internal_server_error()
        .assert_header("content-type", "application/json");
    let message = response.json()["message"].as_str().unwrap().to_owned();
    assert!(message.starts_with("panic at tests/errors.rs:"), "{message}");
    assert!(message.ends_with(": the renderer failed"), "{message}");
    assert_eq!(response.json().as_object().unwrap().len(), 1, "{}", response.text());
}

#[laravel::http::middleware]
async fn requires_api_key(request: Request, next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
    match request.header("x-api-key") {
        Some("explode") => panic!("the group middleware failed"),
        Some(_) => Ok(next.run(request).await),
        None => Err(laravel::abort(401)),
    }
}

#[laravel::http::middleware]
async fn requires_terms(mut request: Request, next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
    request.load_input().await?;
    #[derive(serde::Deserialize)]
    struct Terms {
        terms: Option<serde_json::Value>,
    }
    if request.parse::<Terms>()?.terms.is_none() {
        laravel::validation::invalid!(terms => "Accept the terms.");
    }

    Ok(next.run(request).await)
}

fn group_middleware_app() -> Application {
    Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.app.key = Some(laravel::crypt::Encrypter::generate_key(
                laravel::crypt::Cipher::Aes256Cbc,
            ));
            config.session.driver = laravel::config::session::Driver::Memory;
        })
        .with_routing(|routing, _| {
            routing
                .web(|route: &mut Router| {
                    route.post("/posts", || async { "stored" });
                })
                .api(|route: &mut Router| {
                    route.get("/status", || async { "ok" });
                });
        })
        .with_middleware(|middleware, _| {
            middleware.api(|api| {
                api.append(requires_api_key);
            });
            middleware.web(|web| {
                web.append(requires_terms);
            });
        })
        .create()
}

#[tokio::test]
async fn errors_from_api_group_middleware_render_as_json() {
    group_middleware_app()
        .get("/api/status")
        .await
        .assert_unauthorized()
        .assert_json(json!({ "message": "Unauthorized" }));
}

#[tokio::test]
async fn panics_in_api_group_middleware_render_as_json() {
    group_middleware_app()
        .get("/api/status")
        .header("x-api-key", "explode")
        .await
        .assert_internal_server_error()
        .assert_json(json!({ "message": "Server Error" }));
}

#[tokio::test]
async fn invalid_input_from_web_group_middleware_redirects_back_with_errors() {
    group_middleware_app()
        .post("/posts")
        .header("sec-fetch-site", "same-origin")
        .header("referer", "http://localhost/posts/create")
        .form([("title", "Hello")])
        .await
        .assert_redirect_to("http://localhost/posts/create")
        .assert_invalid(&["terms"]);
}

#[tokio::test]
async fn application_renderers_replace_the_built_in_responses_for_invalid_input_and_rate_limits() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_config(|config, _| {
            config.app.key = Some(laravel::crypt::Encrypter::generate_key(
                laravel::crypt::Cipher::Aes256Cbc,
            ));
            config.session.driver = laravel::config::session::Driver::Memory;
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.post("/invite", invite);
                route.get("/limited", || async {
                    laravel::rate_limit::attempt("pin", laravel::rate_limit::Limit::per_minute(1)).await??;
                    Ok::<_, laravel::Error>("allowed")
                });
            });
        })
        .with_errors(|errors, _| {
            errors
                .render(|_: &InvalidInput, _request, status| Some((status, "Please check the form")))
                .render(|_: &laravel::rate_limit::TooManyAttempts, _request, status| {
                    Some((status, "Please slow down"))
                });
        })
        .create();

    app.post("/invite")
        .header("sec-fetch-site", "same-origin")
        .header("referer", "http://localhost/invitations")
        .form([("email", "taylor@example.com")])
        .await
        .assert_status(422)
        .assert_see("Please check the form")
        .assert_session_missing("errors");
    app.post("/invite")
        .header("accept", "application/json")
        .await
        .assert_status(422)
        .assert_see("Please check the form");

    app.get("/limited").await.assert_ok();
    app.get("/limited")
        .await
        .assert_status(429)
        .assert_see("Please slow down")
        .assert_header("retry-after", "60")
        .assert_header("x-ratelimit-limit", "1")
        .assert_header("x-ratelimit-remaining", "0");
}

#[tokio::test]
async fn a_reporter_that_panics_doesnt_stop_the_response() {
    let app = Application::configure()
        .replace_env(Env::default())
        .with_routing(|routing, _| {
            routing.routes(|route: &mut Router| {
                route.get("/disk", disk);
                route.get("/recommendations", || async {
                    laravel::report(std::io::Error::other("no recommendations"));
                    "no recommendations today"
                });
            });
        })
        .with_errors(|errors, _| {
            errors.report_all(|_| panic!("the error tracker is down"));
        })
        .create();

    app.get("/disk")
        .header("accept", "application/json")
        .await
        .assert_internal_server_error()
        .assert_json(json!({ "message": "Server Error" }));
    app.get("/disk")
        .await
        .assert_internal_server_error()
        .assert_see("Server Error");
    app.get("/recommendations")
        .await
        .assert_ok()
        .assert_see("no recommendations today");
}