footing 0.1.0

Feature-gated foundations for Rust backend services
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
1545
1546
1547
1548
1549
1550
1551
1552
1553
//! Test builders for `footing` types.
//!
//! The builders keep tests concise while still exercising the same public
//! constructors used by production code.
//!
use std::{error::Error as StdError, fmt, sync::Arc};

use serde::de::DeserializeOwned;

use crate::{
    auth::{Principal, PrincipalKind},
    clock::ManualClock,
    http::{ApiProblem, ProblemDetails, RequestContext, RequestId, TraceParent},
    observability::{MetricLabels, MetricRecorder, MetricRegistry, MetricsError, MetricsSnapshot},
    result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};

#[derive(Debug)]
#[non_exhaustive]
/// Errors that can occur while handling testkit.
pub enum TestkitError {
    /// Indicates request build.
    RequestBuild(axum::http::Error),
    /// Indicates response body.
    ResponseBody(axum::Error),
    /// Indicates response UTF-8.
    ResponseUtf8(std::string::FromUtf8Error),
    /// Indicates response JSON.
    ResponseJson(serde_json::Error),
}

impl fmt::Display for TestkitError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RequestBuild(source) => write!(formatter, "test request build failed: {source}"),
            Self::ResponseBody(source) => write!(formatter, "response body read failed: {source}"),
            Self::ResponseUtf8(source) => write!(formatter, "response body is not UTF-8: {source}"),
            Self::ResponseJson(source) => write!(formatter, "response body is not JSON: {source}"),
        }
    }
}

impl StdError for TestkitError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::RequestBuild(source) => Some(source),
            Self::ResponseBody(source) => Some(source),
            Self::ResponseUtf8(source) => Some(source),
            Self::ResponseJson(source) => Some(source),
        }
    }
}

#[must_use]
/// Creates a manual monotonic clock starting at the current instant.
pub fn manual_clock() -> ManualClock {
    ManualClock::new()
}

#[must_use]
/// Creates a conventional administrator principal for tests.
pub fn admin_principal() -> Principal {
    Principal::user("test-admin")
        .expect("static test principal id is valid")
        .with_roles(["admin"])
        .expect("static test role is valid")
        .with_scopes(["*"])
        .expect("static test scope is valid")
}

#[must_use]
/// Creates a request context with stable test identifiers.
pub fn request_context() -> RequestContext {
    RequestContext::new(test_request_id("req_test"), None).with_principal(admin_principal())
}

#[must_use]
/// Creates a valid W3C `traceparent` value for tests.
pub fn traceparent() -> TraceParent {
    TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
        .expect("static test traceparent is valid")
}

#[derive(Debug, Clone)]
/// Builder for constructing test principal.
pub struct TestPrincipalBuilder {
    principal: Principal,
}

impl TestPrincipalBuilder {
    #[must_use]
    /// Creates user.
    pub fn user(id: impl Into<String>) -> Self {
        Self {
            principal: Principal::new(id, PrincipalKind::User)
                .expect("test principal id must be valid"),
        }
    }

    #[must_use]
    /// Creates client.
    pub fn client(id: impl Into<String>) -> Self {
        Self {
            principal: Principal::new(id, PrincipalKind::Client)
                .expect("test principal id must be valid"),
        }
    }

    #[must_use]
    /// Creates service account.
    pub fn service_account(id: impl Into<String>) -> Self {
        Self {
            principal: Principal::new(id, PrincipalKind::ServiceAccount)
                .expect("test principal id must be valid"),
        }
    }

    #[must_use]
    /// Returns the tenant.
    pub fn tenant(mut self, tenant_id: impl Into<String>) -> Self {
        self.principal = self
            .principal
            .with_tenant_id(tenant_id)
            .expect("test tenant id must be valid");
        self
    }

    #[must_use]
    /// Returns the role.
    pub fn role(mut self, role: impl Into<String>) -> Self {
        self.principal
            .add_role(role)
            .expect("test role must be valid");
        self
    }

    #[must_use]
    /// Returns the scope.
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.principal
            .add_scope(scope)
            .expect("test scope must be valid");
        self
    }

    #[must_use]
    /// Builds the configured value.
    pub fn build(self) -> Principal {
        self.principal
    }
}

#[derive(Debug, Clone)]
/// Builder for constructing test request context.
pub struct TestRequestContextBuilder {
    request_id: RequestId,
    traceparent: Option<String>,
    principal: Option<Principal>,
}

impl TestRequestContextBuilder {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self {
            request_id: test_request_id("req_test"),
            traceparent: None,
            principal: None,
        }
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = test_request_id(&request_id.into());
        self
    }

    #[must_use]
    /// Returns the traceparent.
    pub fn traceparent(mut self, traceparent: impl Into<String>) -> Self {
        self.traceparent = Some(traceparent.into());
        self
    }

    #[must_use]
    /// Returns the standard traceparent.
    pub fn standard_traceparent(mut self) -> Self {
        self.traceparent = Some(traceparent().into_string());
        self
    }

    #[must_use]
    /// Returns the principal.
    pub fn principal(mut self, principal: Principal) -> Self {
        self.principal = Some(principal);
        self
    }

    #[must_use]
    /// Builds the configured value.
    pub fn build(self) -> RequestContext {
        let context = RequestContext::new(self.request_id, self.traceparent);
        if let Some(principal) = self.principal {
            context.with_principal(principal)
        } else {
            context
        }
    }
}

impl Default for TestRequestContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for constructing test HTTP request.
pub struct TestHttpRequestBuilder {
    method: axum::http::Method,
    uri: String,
    headers: Vec<(axum::http::HeaderName, axum::http::HeaderValue)>,
    body: axum::body::Body,
}

impl TestHttpRequestBuilder {
    #[must_use]
    /// Creates get.
    pub fn get(uri: impl Into<String>) -> Self {
        Self::new(axum::http::Method::GET, uri)
    }

    #[must_use]
    /// Creates post.
    pub fn post(uri: impl Into<String>) -> Self {
        Self::new(axum::http::Method::POST, uri)
    }

    #[must_use]
    /// Creates a new instance.
    pub fn new(method: axum::http::Method, uri: impl Into<String>) -> Self {
        Self {
            method,
            uri: uri.into(),
            headers: Vec::new(),
            body: axum::body::Body::empty(),
        }
    }

    #[must_use]
    /// Returns the header.
    pub fn header(mut self, name: axum::http::HeaderName, value: axum::http::HeaderValue) -> Self {
        self.headers.push((name, value));
        self
    }

    #[must_use]
    /// Returns the header str.
    pub fn header_str(mut self, name: axum::http::HeaderName, value: impl AsRef<str>) -> Self {
        if let Ok(value) = axum::http::HeaderValue::from_str(value.as_ref()) {
            self.headers.push((name, value));
        }
        self
    }

    #[must_use]
    /// Returns the bearer.
    pub fn bearer(self, token: impl AsRef<str>) -> Self {
        self.header_str(
            axum::http::header::AUTHORIZATION,
            format!("Bearer {}", token.as_ref()),
        )
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(self, request_id: impl AsRef<str>) -> Self {
        self.header_str(
            axum::http::HeaderName::from_static("x-request-id"),
            request_id,
        )
    }

    #[must_use]
    /// Returns the traceparent.
    pub fn traceparent(self, traceparent: impl AsRef<str>) -> Self {
        self.header_str(
            axum::http::HeaderName::from_static("traceparent"),
            traceparent,
        )
    }

    #[must_use]
    /// Returns the JSON body.
    pub fn json_body(mut self, value: &serde_json::Value) -> Self {
        self.headers.push((
            axum::http::header::CONTENT_TYPE,
            axum::http::HeaderValue::from_static("application/json"),
        ));
        self.body = axum::body::Body::from(value.to_string());
        self
    }

    #[must_use]
    /// Returns the body.
    pub fn body(mut self, body: impl Into<axum::body::Body>) -> Self {
        self.body = body.into();
        self
    }

    /// Attempts to build the configured HTTP request.
    pub fn try_build(self) -> Result<axum::http::Request<axum::body::Body>, TestkitError> {
        let mut builder = axum::http::Request::builder()
            .method(self.method)
            .uri(self.uri);
        for (name, value) in self.headers {
            builder = builder.header(name, value);
        }
        builder.body(self.body).map_err(TestkitError::RequestBuild)
    }

    /// Builds the configured value.
    pub fn build(self) -> axum::http::Request<axum::body::Body> {
        self.try_build()
            .unwrap_or_else(|error| panic!("test request should build: {error}"))
    }
}

/// Asserts response status.
pub fn assert_response_status(
    response: &axum::response::Response,
    expected: axum::http::StatusCode,
) {
    assert_eq!(response.status(), expected);
}

/// Attempts to read a response body as UTF-8 text.
pub async fn try_response_body_text(
    response: axum::response::Response,
) -> Result<String, TestkitError> {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .map_err(TestkitError::ResponseBody)?;
    String::from_utf8(bytes.to_vec()).map_err(TestkitError::ResponseUtf8)
}

/// Reads a response body as UTF-8 text or panics with test context.
pub async fn response_body_text(response: axum::response::Response) -> String {
    try_response_body_text(response)
        .await
        .unwrap_or_else(|error| panic!("response body should be text: {error}"))
}

/// Attempts to deserialize a JSON response.
pub async fn try_response_json<T>(response: axum::response::Response) -> Result<T, TestkitError>
where
    T: DeserializeOwned,
{
    let body = try_response_body_text(response).await?;
    serde_json::from_str(&body).map_err(TestkitError::ResponseJson)
}

/// Deserializes a JSON response or panics with test context.
pub async fn response_json<T>(response: axum::response::Response) -> T
where
    T: DeserializeOwned,
{
    try_response_json(response)
        .await
        .unwrap_or_else(|error| panic!("response body should be JSON: {error}"))
}

/// Asserts response JSON.
pub async fn assert_response_json<T>(
    response: axum::response::Response,
    expected_status: axum::http::StatusCode,
) -> T
where
    T: DeserializeOwned,
{
    assert_response_status(&response, expected_status);
    response_json(response).await
}

/// Attempts to deserialize an RFC 7807 response.
pub async fn try_response_problem(
    response: axum::response::Response,
) -> Result<ProblemDetails, TestkitError> {
    let status = response.status();
    let body = try_response_body_text(response).await?;
    let problem: ProblemDetails =
        serde_json::from_str(&body).map_err(TestkitError::ResponseJson)?;
    assert_eq!(
        problem.status,
        status.as_u16(),
        "problem status should match HTTP status"
    );
    Ok(problem)
}

/// Deserializes an RFC 7807 response or panics with test context.
pub async fn response_problem(response: axum::response::Response) -> ProblemDetails {
    try_response_problem(response)
        .await
        .unwrap_or_else(|error| panic!("response body should be problem+json: {error}"))
}

/// Asserts response problem.
pub async fn assert_response_problem(
    response: axum::response::Response,
    expected_status: axum::http::StatusCode,
    expected_code: &str,
) -> ProblemDetails {
    assert_eq!(response.status(), expected_status);
    let problem = response_problem(response).await;
    assert_eq!(problem.code, expected_code);
    problem
}

/// Asserts problem.
pub async fn assert_problem(
    response: axum::response::Response,
    expected_status: axum::http::StatusCode,
    expected_code: &str,
) -> ProblemAssert {
    ProblemAssert::new(assert_response_problem(response, expected_status, expected_code).await)
}

#[derive(Debug, Clone)]
/// Represents problem assert.
pub struct ProblemAssert {
    problem: ProblemDetails,
}

impl ProblemAssert {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(problem: ProblemDetails) -> Self {
        Self { problem }
    }

    #[must_use]
    /// Returns the code.
    pub fn code(self, expected: &str) -> Self {
        assert_eq!(self.problem.code, expected);
        self
    }

    #[must_use]
    /// Returns the status.
    pub fn status(self, expected: axum::http::StatusCode) -> Self {
        assert_eq!(self.problem.status, expected.as_u16());
        self
    }

    #[must_use]
    /// Returns the detail.
    pub fn detail(self, expected: &str) -> Self {
        assert_eq!(self.problem.detail, expected);
        self
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(self, expected: &str) -> Self {
        assert_eq!(self.problem.request_id.as_deref(), Some(expected));
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> ProblemDetails {
        self.problem
    }
}

#[derive(Debug, Clone)]
/// Represents error descriptor assert.
pub struct ErrorDescriptorAssert {
    descriptor: ErrorDescriptor,
}

impl ErrorDescriptorAssert {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(descriptor: ErrorDescriptor) -> Self {
        Self { descriptor }
    }

    #[must_use]
    /// Returns the kind.
    pub fn kind(self, expected: ErrorKind) -> Self {
        assert_eq!(self.descriptor.kind(), expected);
        self
    }

    #[must_use]
    /// Returns the code.
    pub fn code(self, expected: &str) -> Self {
        assert_eq!(self.descriptor.code().as_str(), expected);
        self
    }

    #[must_use]
    /// Returns the message contains.
    pub fn message_contains(self, expected: &str) -> Self {
        assert!(
            self.descriptor.message().contains(expected),
            "expected error message {:?} to contain {expected:?}",
            self.descriptor.message()
        );
        self
    }

    #[must_use]
    /// Returns the retryable.
    pub fn retryable(self, expected: bool) -> Self {
        assert_eq!(self.descriptor.retryable(), expected);
        self
    }

    #[must_use]
    /// Returns the public message.
    pub fn public_message(self, expected: &str) -> Self {
        assert_eq!(self.descriptor.public_message(), expected);
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> ErrorDescriptor {
        self.descriptor
    }
}

#[must_use]
/// Asserts error.
pub fn assert_error<E>(error: &E) -> ErrorDescriptorAssert
where
    E: ClassifyError + ?Sized,
{
    ErrorDescriptorAssert::new(error.error_descriptor())
}

#[must_use]
/// Asserts error descriptor.
pub fn assert_error_descriptor(descriptor: ErrorDescriptor) -> ErrorDescriptorAssert {
    ErrorDescriptorAssert::new(descriptor)
}

#[derive(Debug, Clone, Copy)]
/// Represents diagnostic assert.
pub struct DiagnosticAssert<'a> {
    diagnostic: &'a Diagnostic,
}

impl<'a> DiagnosticAssert<'a> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(diagnostic: &'a Diagnostic) -> Self {
        Self { diagnostic }
    }

    #[must_use]
    /// Returns the component.
    pub fn component(self, expected: &str) -> Self {
        assert_eq!(self.diagnostic.component(), expected);
        self
    }

    #[must_use]
    /// Returns the operation.
    pub fn operation(self, expected: &str) -> Self {
        assert_eq!(self.diagnostic.operation(), expected);
        self
    }

    #[must_use]
    /// Returns the resource.
    pub fn resource(self, expected: Option<&str>) -> Self {
        assert_eq!(self.diagnostic.resource(), expected);
        self
    }

    #[must_use]
    /// Returns the kind.
    pub fn kind(self, expected: DiagnosticKind) -> Self {
        assert_eq!(self.diagnostic.kind(), expected);
        self
    }

    #[must_use]
    /// Returns the message contains.
    pub fn message_contains(self, expected: &str) -> Self {
        assert!(
            self.diagnostic.message().contains(expected),
            "expected diagnostic message {:?} to contain {expected:?}",
            self.diagnostic.message()
        );
        self
    }

    #[must_use]
    /// Returns the remediation contains.
    pub fn remediation_contains(self, expected: &str) -> Self {
        let remediation = self
            .diagnostic
            .remediation()
            .expect("expected diagnostic remediation");
        assert!(
            remediation.summary().contains(expected),
            "expected diagnostic remediation {:?} to contain {expected:?}",
            remediation.summary()
        );
        self
    }

    #[must_use]
    /// Returns the retryable.
    pub fn retryable(self, expected: bool) -> Self {
        assert_eq!(self.diagnostic.retryable(), expected);
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub const fn into_inner(self) -> &'a Diagnostic {
        self.diagnostic
    }
}

#[must_use]
/// Asserts diagnostic.
pub const fn assert_diagnostic(diagnostic: &Diagnostic) -> DiagnosticAssert<'_> {
    DiagnosticAssert::new(diagnostic)
}

#[cfg(feature = "config")]
#[derive(Debug, Clone, Copy)]
/// Represents config validation assert.
pub struct ConfigValidationAssert<'a> {
    error: &'a crate::config::ConfigValidationError,
}

#[cfg(feature = "config")]
impl<'a> ConfigValidationAssert<'a> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(error: &'a crate::config::ConfigValidationError) -> Self {
        Self { error }
    }

    #[must_use]
    /// Returns the issue count.
    pub fn issue_count(self, expected: usize) -> Self {
        assert_eq!(self.error.issues().len(), expected);
        self
    }

    #[must_use]
    /// Returns whether this value has path.
    pub fn has_path(self, expected_path: &str) -> Self {
        assert!(
            self.error
                .issues()
                .iter()
                .any(|issue| issue.path() == expected_path),
            "expected config validation error to include path {expected_path:?}; got {:?}",
            self.error.issues()
        );
        self
    }

    #[must_use]
    /// Returns the path message contains.
    pub fn path_message_contains(self, expected_path: &str, expected_message: &str) -> Self {
        let issue = self
            .error
            .issues()
            .iter()
            .find(|issue| issue.path() == expected_path)
            .unwrap_or_else(|| {
                panic!(
                    "expected config validation error to include path {expected_path:?}; got {:?}",
                    self.error.issues()
                )
            });
        assert!(
            issue.message().contains(expected_message),
            "expected config issue message {:?} to contain {expected_message:?}",
            issue.message()
        );
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub const fn into_inner(self) -> &'a crate::config::ConfigValidationError {
        self.error
    }
}

#[cfg(feature = "config")]
#[must_use]
/// Asserts config error.
pub const fn assert_config_error(
    error: &crate::config::ConfigValidationError,
) -> ConfigValidationAssert<'_> {
    ConfigValidationAssert::new(error)
}

#[derive(Debug, Clone, Default)]
/// Represents test metrics.
pub struct TestMetrics {
    registry: Arc<MetricRegistry>,
}

impl TestMetrics {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    /// Returns the recorder.
    pub fn recorder(self: &Arc<Self>) -> Arc<dyn MetricRecorder> {
        Arc::clone(self) as Arc<dyn MetricRecorder>
    }

    #[must_use]
    /// Returns the registry.
    pub fn registry(&self) -> &Arc<MetricRegistry> {
        &self.registry
    }

    /// Returns an immutable snapshot.
    pub fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
        self.registry.snapshot()
    }

    /// Asserts counter.
    pub fn assert_counter(&self, name: &str, labels: MetricLabels, expected: u64) {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        assert_metric_value(&snapshot, name, labels, expected as f64);
    }

    /// Asserts counter at least.
    pub fn assert_counter_at_least(&self, name: &str, labels: MetricLabels, expected: u64) {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        assert_metric_value_at_least(&snapshot, name, labels, expected as f64);
    }

    /// Asserts no metric.
    pub fn assert_no_metric(&self, name: &str, labels: MetricLabels) {
        let snapshot = self.snapshot().expect("metrics snapshot should build");
        assert_no_metric(&snapshot, name, labels);
    }
}

impl MetricRecorder for TestMetrics {
    fn increment_counter(
        &self,
        name: &str,
        value: u64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        self.registry.increment_counter(name, value, labels)
    }

    fn set_gauge(&self, name: &str, value: f64, labels: MetricLabels) -> Result<(), MetricsError> {
        self.registry.set_gauge(name, value, labels)
    }

    fn observe_histogram(
        &self,
        name: &str,
        value: f64,
        labels: MetricLabels,
    ) -> Result<(), MetricsError> {
        self.registry.observe_histogram(name, value, labels)
    }

    fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
        self.registry.snapshot()
    }
}

#[derive(Clone)]
/// Represents test HTTP app.
pub struct TestHttpApp {
    router: axum::Router,
}

impl TestHttpApp {
    #[must_use]
    /// Creates a new instance.
    pub fn new(router: axum::Router) -> Self {
        Self { router }
    }

    /// Executes a request against the in-memory router.
    pub async fn request(
        &self,
        request: axum::http::Request<axum::body::Body>,
    ) -> axum::response::Response {
        use tower::ServiceExt;

        self.router
            .clone()
            .oneshot(request)
            .await
            .expect("test HTTP request should complete")
    }

    /// Executes a GET request against the in-memory router.
    pub async fn get(&self, uri: impl Into<String>) -> axum::response::Response {
        self.request(TestHttpRequestBuilder::get(uri).build()).await
    }

    /// Executes a JSON POST request against the in-memory router.
    pub async fn post_json(
        &self,
        uri: impl Into<String>,
        value: &serde_json::Value,
    ) -> axum::response::Response {
        self.request(TestHttpRequestBuilder::post(uri).json_body(value).build())
            .await
    }
}

#[cfg(feature = "config")]
#[derive(Debug, Clone)]
/// Represents test HTTP foundation.
pub struct TestHttpFoundation {
    settings: crate::http::HttpFoundationSettings,
}

#[cfg(feature = "config")]
impl Default for TestHttpFoundation {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "config")]
impl TestHttpFoundation {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self {
            settings: crate::http::HttpFoundationSettings::new(),
        }
    }

    #[must_use]
    /// Creates a value from settings.
    pub fn from_settings(settings: crate::http::HttpFoundationSettings) -> Self {
        Self { settings }
    }

    #[must_use]
    /// Configures settings and returns the updated value.
    pub fn with_settings(
        mut self,
        update: impl FnOnce(crate::http::HttpFoundationSettings) -> crate::http::HttpFoundationSettings,
    ) -> Self {
        self.settings = update(self.settings);
        self
    }

    #[must_use]
    /// Returns the settings.
    pub const fn settings(&self) -> &crate::http::HttpFoundationSettings {
        &self.settings
    }

    /// Validates this value.
    pub fn validate(&self) -> Result<(), crate::config::ConfigValidationError> {
        use crate::config::ValidateSettings;

        self.settings.validate_settings()
    }

    #[must_use]
    /// Validates the settings and panics with test context on failure.
    pub fn assert_valid(self) -> Self {
        self.validate()
            .expect("test HTTP foundation settings should be valid");
        self
    }

    #[must_use]
    /// Returns the config.
    pub fn config(&self) -> crate::http::HttpLayerConfig {
        self.settings
            .clone()
            .into_config()
            .expect("test HTTP foundation settings should adapt")
    }

    #[must_use]
    /// Returns the invalid paths.
    pub fn invalid_paths(&self, path: &str) -> Vec<String> {
        self.settings
            .validate_at(path)
            .map(|()| Vec::new())
            .unwrap_or_else(|error| {
                error
                    .issues()
                    .iter()
                    .map(|issue| issue.path().to_owned())
                    .collect()
            })
    }
}

#[cfg(feature = "postgres")]
/// Utilities for PostgreSQL.
pub mod postgres {
    use uuid::Uuid;

    #[must_use]
    /// Reads the test database URL from `DATABASE_URL`.
    pub fn database_url_from_env() -> Option<String> {
        std::env::var("DATABASE_URL")
            .ok()
            .map(|value| value.trim().to_owned())
            .filter(|value| !value.is_empty())
    }

    #[must_use]
    /// Generates a process-scoped unique database name.
    pub fn unique_database_name(prefix: &str) -> String {
        let prefix = prefix.trim().trim_matches('_');
        let prefix = if prefix.is_empty() { "test" } else { prefix };
        format!("{prefix}_{}", Uuid::now_v7().simple())
    }

    #[must_use]
    /// Replaces the database name in a PostgreSQL URL.
    pub fn database_url_with_name(base_url: &str, database_name: &str) -> String {
        match base_url.rsplit_once('/') {
            Some((prefix, _)) => format!("{prefix}/{database_name}"),
            None => base_url.to_owned(),
        }
    }
}

/// Asserts problem code.
pub fn assert_problem_code(problem: &ApiProblem, expected_code: &str) {
    assert_eq!(problem.body().code, expected_code);
}

/// Asserts problem detail.
pub fn assert_problem_detail(problem: &ApiProblem, expected_detail: &str) {
    assert_eq!(problem.body().detail, expected_detail);
}

/// Asserts problem status.
pub fn assert_problem_status(problem: &ApiProblem, expected_status: axum::http::StatusCode) {
    assert_eq!(problem.status(), expected_status);
}

/// Asserts problem request identifier.
pub fn assert_problem_request_id(problem: &ApiProblem, expected_request_id: &str) {
    assert_eq!(
        problem.body().request_id.as_deref(),
        Some(expected_request_id)
    );
}

/// Asserts metric value.
pub fn assert_metric_value(
    snapshot: &MetricsSnapshot,
    name: &str,
    labels: MetricLabels,
    expected: f64,
) {
    let labels = labels.into_vec();
    let sample = snapshot
        .samples()
        .iter()
        .find(|sample| sample.name() == name && sample.labels() == labels.as_slice())
        .unwrap_or_else(|| panic!("metric sample {name} with expected labels was not found"));
    assert_eq!(sample.value(), expected);
}

/// Asserts metric value at least.
pub fn assert_metric_value_at_least(
    snapshot: &MetricsSnapshot,
    name: &str,
    labels: MetricLabels,
    expected_minimum: f64,
) {
    let labels = labels.into_vec();
    let sample = snapshot
        .samples()
        .iter()
        .find(|sample| sample.name() == name && sample.labels() == labels.as_slice())
        .unwrap_or_else(|| panic!("metric {name} with labels {labels:?} should exist"));
    assert!(
        sample.value() >= expected_minimum,
        "metric {name} with labels {labels:?} value {} should be at least {expected_minimum}",
        sample.value()
    );
}

/// Asserts no metric.
pub fn assert_no_metric(snapshot: &MetricsSnapshot, name: &str, labels: MetricLabels) {
    let labels = labels.into_vec();
    let found = snapshot
        .samples()
        .iter()
        .any(|sample| sample.name() == name && sample.labels() == labels.as_slice());
    assert!(
        !found,
        "metric {name} with labels {labels:?} should not exist"
    );
}

/// Asserts principal has role.
pub fn assert_principal_has_role(principal: &Principal, expected_role: &str) {
    assert!(
        principal.has_role(expected_role),
        "expected principal {} to have role {expected_role}",
        principal.id()
    );
}

/// Asserts principal has scope.
pub fn assert_principal_has_scope(principal: &Principal, expected_scope: &str) {
    assert!(
        principal.has_scope(expected_scope),
        "expected principal {} to have scope {expected_scope}",
        principal.id()
    );
}

fn test_request_id(value: &str) -> RequestId {
    RequestId::new(value)
        .unwrap_or_else(|error| panic!("invalid test request id {value:?}: {error}"))
}

#[cfg(feature = "worker")]
/// Utilities for worker.
pub mod worker {
    use std::{
        collections::VecDeque,
        sync::{
            Arc, Mutex, MutexGuard,
            atomic::{AtomicU64, Ordering},
        },
        time::Duration,
    };

    use async_trait::async_trait;
    use tokio::time;

    use crate::worker::{
        BoxWorkerError, OutboxClaim, OutboxHandler, OutboxItem, OutboxItemState, OutboxStore,
        Worker, WorkerTick,
    };

    #[derive(Debug, Clone)]
    /// Represents counting worker.
    pub struct CountingWorker {
        name: &'static str,
        calls: Arc<AtomicU64>,
        processed_per_tick: u64,
    }

    impl CountingWorker {
        #[must_use]
        /// Creates a new instance.
        pub fn new(name: &'static str) -> Self {
            Self {
                name,
                calls: Arc::new(AtomicU64::new(0)),
                processed_per_tick: 1,
            }
        }

        #[must_use]
        /// Returns the calls.
        pub fn calls(&self) -> u64 {
            self.calls.load(Ordering::SeqCst)
        }

        #[must_use]
        /// Configures processed per tick and returns the updated value.
        pub const fn with_processed_per_tick(mut self, processed_per_tick: u64) -> Self {
            self.processed_per_tick = processed_per_tick;
            self
        }
    }

    #[async_trait]
    impl Worker for CountingWorker {
        fn name(&self) -> &str {
            self.name
        }

        async fn run_once(&self) -> Result<WorkerTick, BoxWorkerError> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(WorkerTick::new(self.processed_per_tick))
        }
    }

    /// Runs once.
    pub async fn run_once<W>(worker: &W) -> Result<WorkerTick, BoxWorkerError>
    where
        W: Worker,
    {
        worker.run_once().await
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    /// Represents test outbox item.
    pub struct TestOutboxItem {
        id: String,
        attempts: u32,
        action: TestOutboxAction,
    }

    impl TestOutboxItem {
        #[must_use]
        /// Creates succeeded.
        pub fn succeeded(id: impl Into<String>) -> Self {
            Self::new(id, TestOutboxAction::Succeeded)
        }

        #[must_use]
        /// Creates retry.
        pub fn retry(id: impl Into<String>, reason: impl Into<String>, delay: Duration) -> Self {
            Self::new(
                id,
                TestOutboxAction::Retry {
                    reason: reason.into(),
                    delay,
                },
            )
        }

        #[must_use]
        /// Creates skipped.
        pub fn skipped(id: impl Into<String>, reason: impl Into<String>) -> Self {
            Self::new(
                id,
                TestOutboxAction::Skipped {
                    reason: reason.into(),
                },
            )
        }

        #[must_use]
        /// Creates failed.
        pub fn failed(id: impl Into<String>, reason: impl Into<String>) -> Self {
            Self::new(
                id,
                TestOutboxAction::Failed {
                    reason: reason.into(),
                },
            )
        }

        #[must_use]
        /// Creates handler error.
        pub fn handler_error(id: impl Into<String>, reason: impl Into<String>) -> Self {
            Self::new(
                id,
                TestOutboxAction::HandlerError {
                    reason: reason.into(),
                },
            )
        }

        #[must_use]
        /// Creates slow.
        pub fn slow(id: impl Into<String>, delay: Duration) -> Self {
            Self::new(id, TestOutboxAction::Slow { delay })
        }

        #[must_use]
        /// Creates a new instance.
        pub fn new(id: impl Into<String>, action: TestOutboxAction) -> Self {
            Self {
                id: id.into(),
                attempts: 0,
                action,
            }
        }

        #[must_use]
        /// Configures attempts and returns the updated value.
        pub const fn with_attempts(mut self, attempts: u32) -> Self {
            self.attempts = attempts;
            self
        }

        #[must_use]
        /// Returns the action.
        pub fn action(&self) -> &TestOutboxAction {
            &self.action
        }
    }

    impl OutboxItem for TestOutboxItem {
        fn outbox_id(&self) -> String {
            self.id.clone()
        }

        fn outbox_attempts(&self) -> u32 {
            self.attempts
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    #[non_exhaustive]
    /// Enumerates the supported test outbox action values.
    pub enum TestOutboxAction {
        /// Indicates succeeded.
        Succeeded,
        /// Indicates skipped.
        Skipped {
            #[doc = "The reason for this outcome."]
            reason: String,
        },
        /// Indicates retry.
        Retry {
            #[doc = "The reason for this outcome."]
            reason: String,
            #[doc = "The delay before the next action."]
            delay: Duration,
        },
        /// Indicates failed.
        Failed {
            #[doc = "The reason for this outcome."]
            reason: String,
        },
        /// Indicates handler error.
        HandlerError {
            #[doc = "The reason for this outcome."]
            reason: String,
        },
        /// Indicates slow.
        Slow {
            #[doc = "The delay before the next action."]
            delay: Duration,
        },
    }

    #[derive(Debug, Clone, Default)]
    /// Storage abstraction for test outbox.
    pub struct TestOutboxStore {
        items: Arc<Mutex<VecDeque<TestOutboxItem>>>,
        states: Arc<Mutex<Vec<(String, OutboxItemState)>>>,
        dead_letters: Arc<Mutex<Vec<(String, String)>>>,
    }

    impl TestOutboxStore {
        #[must_use]
        /// Configures items and returns the updated value.
        pub fn with_items(items: impl IntoIterator<Item = TestOutboxItem>) -> Self {
            let store = Self::default();
            store.push_items(items);
            store
        }

        /// Attempts to append items to the in-memory store.
        pub fn try_push_items(
            &self,
            items: impl IntoIterator<Item = TestOutboxItem>,
        ) -> Result<(), BoxWorkerError> {
            lock_test_outbox(&self.items, "items")?.extend(items);
            Ok(())
        }

        /// Appends items.
        pub fn push_items(&self, items: impl IntoIterator<Item = TestOutboxItem>) {
            self.try_push_items(items)
                .unwrap_or_else(|error| panic!("test outbox items should be writable: {error}"));
        }

        /// Attempts to snapshot recorded item states.
        pub fn try_states(&self) -> Result<Vec<(String, OutboxItemState)>, BoxWorkerError> {
            Ok(lock_test_outbox(&self.states, "states")?.clone())
        }

        #[must_use]
        /// Returns the states.
        pub fn states(&self) -> Vec<(String, OutboxItemState)> {
            self.try_states()
                .unwrap_or_else(|error| panic!("test outbox states should be readable: {error}"))
        }

        /// Attempts to snapshot recorded dead letters.
        pub fn try_dead_letters(&self) -> Result<Vec<(String, String)>, BoxWorkerError> {
            Ok(lock_test_outbox(&self.dead_letters, "dead_letters")?.clone())
        }

        #[must_use]
        /// Returns the dead letters.
        pub fn dead_letters(&self) -> Vec<(String, String)> {
            self.try_dead_letters().unwrap_or_else(|error| {
                panic!("test outbox dead letters should be readable: {error}")
            })
        }
    }

    #[async_trait]
    impl OutboxStore<TestOutboxItem> for TestOutboxStore {
        async fn claim_due(
            &self,
            claim: OutboxClaim,
        ) -> Result<Vec<TestOutboxItem>, BoxWorkerError> {
            let mut items = lock_test_outbox(&self.items, "items")?;
            Ok((0..claim.limit())
                .filter_map(|_| items.pop_front())
                .collect())
        }

        async fn record_state(
            &self,
            item: &TestOutboxItem,
            state: OutboxItemState,
        ) -> Result<(), BoxWorkerError> {
            lock_test_outbox(&self.states, "states")?.push((item.outbox_id(), state));
            Ok(())
        }

        async fn record_dead_letter(
            &self,
            item: &TestOutboxItem,
            reason: &str,
        ) -> Result<(), BoxWorkerError> {
            lock_test_outbox(&self.dead_letters, "dead_letters")?
                .push((item.outbox_id(), reason.to_owned()));
            Ok(())
        }
    }

    fn lock_test_outbox<'a, T>(
        mutex: &'a Mutex<T>,
        name: &'static str,
    ) -> Result<MutexGuard<'a, T>, BoxWorkerError> {
        mutex
            .lock()
            .map_err(|_| std::io::Error::other(format!("test outbox {name} lock poisoned")).into())
    }

    #[derive(Debug, Clone, Copy, Default)]
    /// Represents test outbox handler.
    pub struct TestOutboxHandler;

    #[async_trait]
    impl OutboxHandler<TestOutboxItem> for TestOutboxHandler {
        async fn handle(&self, item: &TestOutboxItem) -> Result<OutboxItemState, BoxWorkerError> {
            match item.action() {
                TestOutboxAction::Succeeded => Ok(OutboxItemState::Succeeded),
                TestOutboxAction::Skipped { reason } => Ok(OutboxItemState::skipped(reason)),
                TestOutboxAction::Retry { reason, delay } => {
                    Ok(OutboxItemState::retry(reason, *delay))
                }
                TestOutboxAction::Failed { reason } => Ok(OutboxItemState::failed(reason)),
                TestOutboxAction::HandlerError { reason } => Err(reason.clone().into()),
                TestOutboxAction::Slow { delay } => {
                    time::sleep(*delay).await;
                    Ok(OutboxItemState::Succeeded)
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use axum::{
        Json, Router,
        http::StatusCode,
        routing::{get, post},
    };
    use serde_json::json;

    use super::*;

    #[test]
    fn test_metrics_records_samples() {
        let metrics = TestMetrics::new();
        metrics
            .increment_counter("jobs_total", 1, MetricLabels::default())
            .expect("metric should record");

        let snapshot = metrics.snapshot().expect("snapshot should build");
        assert_eq!(snapshot.samples().len(), 1);
        assert_eq!(snapshot.samples()[0].name(), "jobs_total");
        metrics.assert_counter("jobs_total", MetricLabels::default(), 1);
        metrics.assert_counter_at_least("jobs_total", MetricLabels::default(), 1);
        metrics.assert_no_metric("missing_total", MetricLabels::default());
    }

    #[tokio::test]
    async fn test_http_app_runs_requests() {
        let app = TestHttpApp::new(Router::new().route("/health", get(|| async { "ok" })));

        let response = app.get("/health").await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[test]
    fn test_http_request_builder_sets_standard_headers() {
        let request = TestHttpRequestBuilder::get("/secure")
            .bearer("token")
            .request_id("req_test")
            .traceparent(traceparent().into_string())
            .build();

        assert_eq!(
            request
                .headers()
                .get(axum::http::header::AUTHORIZATION)
                .and_then(|value| value.to_str().ok()),
            Some("Bearer token")
        );
        assert_eq!(
            request
                .headers()
                .get("x-request-id")
                .and_then(|value| value.to_str().ok()),
            Some("req_test")
        );
        assert!(request.headers().get("traceparent").is_some());
    }

    #[tokio::test]
    async fn test_http_app_decodes_json_responses() {
        let app = TestHttpApp::new(Router::new().route(
            "/echo",
            post(|Json(value): Json<serde_json::Value>| async move { Json(value) }),
        ));

        let response = app.post_json("/echo", &json!({ "ok": true })).await;
        let body: serde_json::Value = assert_response_json(response, StatusCode::OK).await;

        assert_eq!(body, json!({ "ok": true }));
    }

    #[test]
    fn problem_assertion_is_chainable() {
        let problem = ApiProblem::bad_request(
            crate::http::ProblemCode::from_static("invalid_input"),
            "bad input",
        )
        .with_request_id(&test_request_id("req_test"))
        .into_body();

        let _problem = ProblemAssert::new(problem)
            .status(StatusCode::BAD_REQUEST)
            .code("invalid_input")
            .detail("bad input")
            .request_id("req_test")
            .into_inner();
    }

    #[test]
    fn diagnostic_and_error_assertions_are_chainable() {
        let diagnostic = Diagnostic::dependency(
            "postgres",
            "connect",
            DiagnosticKind::Unavailable,
            "connection refused",
        )
        .with_resource("postgres://localhost/app")
        .with_remediation("start PostgreSQL")
        .with_retryable(true);

        let _diagnostic = assert_diagnostic(&diagnostic)
            .component("postgres")
            .operation("connect")
            .resource(Some("postgres://localhost/app"))
            .kind(DiagnosticKind::Unavailable)
            .message_contains("refused")
            .remediation_contains("PostgreSQL")
            .retryable(true)
            .into_inner();

        let descriptor = ErrorDescriptor::new(
            ErrorKind::Validation,
            crate::result::ErrorCode::new("invalid_test_input")
                .expect("static error code should be valid"),
            "test input is invalid",
        );
        let _descriptor = assert_error_descriptor(descriptor)
            .kind(ErrorKind::Validation)
            .code("invalid_test_input")
            .message_contains("invalid")
            .retryable(false)
            .public_message("test input is invalid")
            .into_inner();
    }

    #[cfg(feature = "config")]
    #[test]
    fn config_validation_assertion_checks_issue_paths() {
        let error = crate::config::ConfigValidationError::single(
            "server.http.timeout",
            "must be greater than zero",
        );

        let _error = assert_config_error(&error)
            .issue_count(1)
            .has_path("server.http.timeout")
            .path_message_contains("server.http.timeout", "greater")
            .into_inner();
    }

    #[cfg(feature = "config")]
    #[test]
    fn http_foundation_test_harness_validates_and_adapts_settings() {
        let harness = TestHttpFoundation::default().assert_valid();

        assert!(harness.config().request_context_enabled());
        assert!(harness.invalid_paths("server.http").is_empty());
    }

    #[cfg(feature = "worker")]
    #[tokio::test]
    async fn testkit_outbox_records_dead_letters() {
        use crate::worker::BatchWorkerJob;

        let store = worker::TestOutboxStore::with_items([worker::TestOutboxItem::failed(
            "one",
            "terminal failure",
        )
        .with_attempts(100)]);
        let job = crate::worker::OutboxJob::new(
            "test outbox",
            store.clone(),
            worker::TestOutboxHandler,
            crate::worker::OutboxWorkerConfig::default().with_batch_size(10),
        );

        let summary = job.run_batch().await.expect("outbox should run");

        assert_eq!(summary.failed(), 1);
        assert_eq!(summary.dead_lettered(), 1);
        assert_eq!(
            store.dead_letters(),
            vec![("one".to_owned(), "terminal failure".to_owned())]
        );
    }
}