kynos-openapi 0.1.0

OpenAPI 3.1 and 3.2 document model, serialization and validation.
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
use super::{SpecError, Validator, Violation};
use crate::model::{
    document::{Document, SpecVersion},
    info::Info,
    parameter::{Parameter, style::Style},
    paths::{item::PathItem, method::Method, operation::Operation, template::PathTemplate},
    response::{Response, Responses},
    schema::{Schema, types::SchemaType},
    security::requirement::SecurityRequirement,
};

fn ok_responses() -> Responses {
    Responses::new().with(200, Response::new("ok"))
}

fn document_with(paths: &[(&str, PathItem)]) -> Document {
    let mut document = Document::new(SpecVersion::V3_1, Info::new("Test", "1.0.0"));
    for (raw, item) in paths {
        let template = PathTemplate::parse(*raw).expect("valid template");
        document.paths.insert(&template, item.clone());
    }
    document
}

fn errors(document: &Document) -> Vec<SpecError> {
    Validator::new(SpecVersion::V3_1)
        .validate(document)
        .into_iter()
        .filter(|v| v.severity == super::Severity::Error)
        .map(|v| v.error)
        .collect()
}

#[test]
fn a_minimal_valid_document_has_no_errors() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("health").with_responses(ok_responses()),
    );
    assert!(errors(&document_with(&[("/health", item)])).is_empty());
}

#[test]
fn duplicate_operation_ids_are_rejected() {
    let first = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getThing").with_responses(ok_responses()),
    );
    let second = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getThing").with_responses(ok_responses()),
    );

    let found = errors(&document_with(&[("/a", first), ("/b", second)]));
    assert!(matches!(
        found.as_slice(),
        [SpecError::DuplicateOperationId { operation_id, .. }] if operation_id == "getThing"
    ));
}

/// Every operation the document describes is validated, not only `paths`.
///
/// `references/3.1.2.md:979` and `references/3.2.0.md:680` say an
/// `operationId` "MUST be unique among **all operations described in the
/// API**". A webhook, a reusable path item and a callback all describe
/// operations, and `check_paths` iterated `document.paths` alone — so every
/// operation-level rule stopped at that boundary. `rules/opaque.rs` already
/// walks all four containers, so this was an oversight in one walk rather than
/// a position the crate had taken.
///
/// One case per container, and one per rule would be the wrong axis: what was
/// broken is the *route to* the operation, not any individual rule.
#[test]
fn an_operation_outside_paths_is_validated_too() {
    use crate::model::{callback::Callback, reference::RefOr};

    let duplicate = || {
        PathItem::new().with_operation(
            Method::Get,
            Operation::new("shared").with_responses(ok_responses()),
        )
    };

    // The one in `paths` is the first sighting; each case below adds a second
    // somewhere the walk did not reach.
    let with_second = |place: &dyn Fn(&mut Document)| {
        let mut document = document_with(&[("/users", duplicate())]);
        place(&mut document);
        errors(&document)
    };

    let webhooks = with_second(&|document| {
        document
            .webhooks
            .insert("orderPlaced".to_owned(), duplicate());
    });
    assert!(
        webhooks
            .iter()
            .any(|error| matches!(error, SpecError::DuplicateOperationId { .. })),
        "a webhook describes an operation; got {webhooks:?}"
    );

    let components = with_second(&|document| {
        document
            .components
            .path_items
            .insert("Shared".to_owned(), duplicate());
    });
    assert!(
        components
            .iter()
            .any(|error| matches!(error, SpecError::DuplicateOperationId { .. })),
        "a reusable path item describes an operation; got {components:?}"
    );

    let callbacks = with_second(&|document| {
        document.components.callbacks.insert(
            "onData".to_owned(),
            RefOr::Item(Callback::new().with("{$request.body#/url}", duplicate())),
        );
    });
    assert!(
        callbacks
            .iter()
            .any(|error| matches!(error, SpecError::DuplicateOperationId { .. })),
        "a callback describes an operation; got {callbacks:?}"
    );
}

/// An operation with no responses is reported wherever it is written.
///
/// The companion to the case above, and a different rule on purpose: it shows
/// the walk carries *every* operation-level rule rather than the one that
/// happens to be keyed on a document-wide map.
#[test]
fn a_responseless_operation_outside_paths_is_reported() {
    let mut document = document_with(&[(
        "/users",
        PathItem::new().with_operation(
            Method::Get,
            Operation::new("listUsers").with_responses(ok_responses()),
        ),
    )]);
    document.webhooks.insert(
        "orderPlaced".to_owned(),
        PathItem::new().with_operation(Method::Post, Operation::new("onOrderPlaced")),
    );

    let found = errors(&document);
    assert!(
        found
            .iter()
            .any(|error| matches!(error, SpecError::NoResponses)),
        "got {found:?}"
    );
}

#[test]
fn paths_differing_only_in_variable_name_are_the_same_path() {
    let make = |id: &str| {
        PathItem::new().with_operation(
            Method::Get,
            Operation::new(format!("get{id}"))
                .with_parameter(Parameter::path(id, Schema::of_type(SchemaType::String)))
                .with_responses(ok_responses()),
        )
    };

    let found = errors(&document_with(&[
        ("/pets/{petId}", make("petId")),
        ("/pets/{name}", make("name")),
    ]));
    assert!(
        found
            .iter()
            .any(|e| matches!(e, SpecError::DuplicatePathTemplate { .. })),
        "expected a duplicate path violation, got {found:?}"
    );
}

#[test]
fn a_template_variable_needs_a_matching_path_parameter() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getUser").with_responses(ok_responses()),
    );
    let found = errors(&document_with(&[("/users/{id}", item)]));
    assert!(matches!(
        found.as_slice(),
        [SpecError::UndeclaredPathVariable { name }] if name == "id"
    ));
}

#[test]
fn a_path_parameter_needs_a_matching_template_variable() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers")
            .with_parameter(Parameter::path("id", Schema::of_type(SchemaType::String)))
            .with_responses(ok_responses()),
    );
    let found = errors(&document_with(&[("/users", item)]));
    assert!(matches!(
        found.as_slice(),
        [SpecError::UnusedPathParameter { name }] if name == "id"
    ));
}

#[test]
fn path_parameters_hoisted_onto_the_path_item_satisfy_the_template() {
    let mut item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getUser").with_responses(ok_responses()),
    );
    item.parameters.push(crate::RefOr::Item(Parameter::path(
        "id",
        Schema::of_type(SchemaType::String),
    )));

    assert!(errors(&document_with(&[("/users/{id}", item)])).is_empty());
}

#[test]
fn a_path_parameter_must_be_required() {
    let mut parameter = Parameter::path("id", Schema::of_type(SchemaType::String));
    parameter.required = Some(false);

    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getUser")
            .with_parameter(parameter)
            .with_responses(ok_responses()),
    );

    let found = errors(&document_with(&[("/users/{id}", item)]));
    assert!(
        found
            .iter()
            .any(|e| matches!(e, SpecError::PathParameterNotRequired { .. })),
        "got {found:?}"
    );
}

#[test]
fn duplicate_name_and_location_pairs_are_rejected() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers")
            .with_parameter(Parameter::query(
                "page",
                Schema::of_type(SchemaType::Integer),
            ))
            .with_parameter(Parameter::query(
                "page",
                Schema::of_type(SchemaType::Integer),
            ))
            .with_responses(ok_responses()),
    );

    let found = errors(&document_with(&[("/users", item)]));
    assert!(matches!(
        found.as_slice(),
        [SpecError::DuplicateParameter { name, .. }] if name == "page"
    ));
}

#[test]
fn the_same_name_in_two_locations_is_fine() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers")
            .with_parameter(Parameter::query(
                "token",
                Schema::of_type(SchemaType::String),
            ))
            .with_parameter(Parameter::cookie(
                "token",
                Schema::of_type(SchemaType::String),
            ))
            .with_responses(ok_responses()),
    );
    assert!(errors(&document_with(&[("/users", item)])).is_empty());
}

#[test]
fn headers_the_spec_ignores_may_not_be_declared_as_parameters() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers")
            .with_parameter(Parameter::header(
                "Authorization",
                Schema::of_type(SchemaType::String),
            ))
            .with_responses(ok_responses()),
    );

    let found = errors(&document_with(&[("/users", item)]));
    assert!(matches!(
        found.as_slice(),
        [SpecError::IgnoredHeaderParameter { name }] if name == "Authorization"
    ));
}

#[test]
fn styles_are_checked_against_the_parameter_location() {
    let parameter = Parameter::header("X-Trace", Schema::of_type(SchemaType::String))
        .with_style(Style::DeepObject, false);

    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers")
            .with_parameter(parameter)
            .with_responses(ok_responses()),
    );

    let found = errors(&document_with(&[("/users", item)]));
    assert!(matches!(found.as_slice(), [SpecError::IllegalStyle { .. }]));
}

#[test]
fn a_response_header_named_content_type_is_reported() {
    use crate::model::parameter::header::Header;

    // The specification says a response header named `Content-Type` shall be
    // ignored, which makes declaring one a silent lie the same way an ignored
    // header parameter is.
    let response = Response::new("ok").with_header(
        "Content-Type",
        Header::new(Schema::of_type(SchemaType::String)),
    );

    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers").with_responses(Responses::new().with(200, response)),
    );

    let found = errors(&document_with(&[("/users", item)]));
    assert_eq!(
        found.len(),
        1,
        "a `Content-Type` response header should be reported exactly once, got {found:?}"
    );
    assert!(
        found[0].to_string().contains("Content-Type"),
        "the violation should name the header, got: {}",
        found[0]
    );
}

#[test]
fn an_encoding_header_named_content_type_is_reported() {
    use crate::model::{
        body::{RequestBody, encoding::Encoding, media_type::MediaType},
        parameter::header::Header,
    };

    // The same rule reaches an encoding's headers, and header names are
    // case-insensitive, so the spelling must not decide whether it is caught.
    let encoding = Encoding::new("text/plain").with_header(
        "content-type",
        Header::new(Schema::of_type(SchemaType::String)),
    );

    let body = RequestBody::new(
        "multipart/form-data",
        MediaType::new(Schema::of_type(SchemaType::Object)).with_encoding("part", encoding),
    );

    let item = PathItem::new().with_operation(
        Method::Post,
        Operation::new("upload")
            .with_request_body(body)
            .with_responses(ok_responses()),
    );

    let found = errors(&document_with(&[("/uploads", item)]));
    assert_eq!(
        found.len(),
        1,
        "a `content-type` encoding header should be reported exactly once, got {found:?}"
    );
    assert!(
        found[0].to_string().contains("content-type"),
        "the violation should name the header, got: {}",
        found[0]
    );
}

/// Every component section's keys are checked, not five of them.
///
/// `references/3.1.2.md:593`: "**All** the fixed fields declared above are
/// objects that MUST use keys that match `^[a-zA-Z0-9\.\-_]+$`". The check
/// covered `schemas`, `responses`, `parameters`, `requestBodies` and
/// `securitySchemes`, so a key in any of the other five — six under 3.2 —
/// passed whatever it was.
///
/// One case per section rather than one representative, because what is under
/// test is the *set* of sections consulted; a representative section is the
/// thing that was already passing.
#[test]
fn every_component_section_checks_its_keys() {
    use crate::model::{
        callback::Callback, example::Example, link::Link, parameter::header::Header,
        paths::item::PathItem, reference::RefOr, schema::Schema,
    };

    const BAD: &str = "not a name";

    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers").with_responses(ok_responses()),
    );
    let mut document = document_with(&[("/users", item)]);
    let components = &mut document.components;
    components
        .schemas
        .insert(BAD.to_owned(), Schema::of_type(SchemaType::String));
    components
        .responses
        .insert(BAD.to_owned(), RefOr::Item(Response::new("ok")));
    components.parameters.insert(
        BAD.to_owned(),
        RefOr::Item(Parameter::query("q", Schema::of_type(SchemaType::String))),
    );
    components.examples.insert(
        BAD.to_owned(),
        RefOr::Item(Example::new(serde_json::json!("x"))),
    );
    components.request_bodies.insert(
        BAD.to_owned(),
        RefOr::Item(crate::model::body::RequestBody::default()),
    );
    components.headers.insert(
        BAD.to_owned(),
        RefOr::Item(Header::new(Schema::of_type(SchemaType::String))),
    );
    components.security_schemes.insert(
        BAD.to_owned(),
        RefOr::Item(crate::model::security::SecurityScheme::basic()),
    );
    components
        .links
        .insert(BAD.to_owned(), RefOr::Item(Link::to_operation("listUsers")));
    components
        .callbacks
        .insert(BAD.to_owned(), RefOr::Item(Callback::new()));
    components
        .path_items
        .insert(BAD.to_owned(), PathItem::new());
    #[cfg(feature = "openapi32")]
    components.media_types.insert(
        BAD.to_owned(),
        RefOr::Item(crate::model::body::media_type::MediaType::new(
            Schema::of_type(SchemaType::String),
        )),
    );

    let reported: Vec<String> = violations(&document)
        .into_iter()
        .filter(|v| matches!(v.error, SpecError::InvalidComponentName { .. }))
        .map(|v| v.location)
        .collect();

    let expected = [
        "schemas",
        "responses",
        "parameters",
        "examples",
        "requestBodies",
        "headers",
        "securitySchemes",
        "links",
        "callbacks",
        "pathItems",
        #[cfg(feature = "openapi32")]
        "mediaTypes",
    ];

    for section in expected {
        assert!(
            reported
                .iter()
                .any(|location| location.starts_with(&format!("#/components/{section}/"))),
            "`components.{section}` accepted `{BAD}` as a key; reported: {reported:?}"
        );
    }
}

#[test]
fn an_operation_must_declare_a_response() {
    let item = PathItem::new().with_operation(Method::Get, Operation::new("listUsers"));
    let found = errors(&document_with(&[("/users", item)]));
    assert!(matches!(found.as_slice(), [SpecError::NoResponses]));
}

/// An extension is not a response code.
///
/// `references/3.2.0.md:2109`: "The Responses Object MUST contain at least one
/// response code". `Responses::is_empty` deliberately counts extensions, and
/// argues for it: a Responses Object holding only `x-` fields is skipped whole
/// on serialization, so ignoring them there would drop it from a round trip.
/// That is right for the *predicate* and wrong for this *rule*, which reused
/// it — so `{"x-poll-interval": 30}` as a whole Responses Object satisfied a
/// requirement it plainly does not meet.
#[test]
fn extensions_alone_do_not_satisfy_the_response_requirement() {
    let mut responses = Responses::new();
    responses.extensions.insert("x-poll-interval", 30);

    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers").with_responses(responses),
    );

    let found = errors(&document_with(&[("/users", item)]));
    assert!(
        found
            .iter()
            .any(|error| matches!(error, SpecError::NoResponses)),
        "got {found:?}"
    );
}

/// 3.1 requires a response description; 3.2 does not.
///
/// `references/3.1.2.md:2010` marks `description` **REQUIRED** and
/// `references/3.2.0.md:2161` does not. The requirement used to live in the
/// type, as `description: String`, which enforced it on 3.2 as well and made a
/// legal 3.2 document unparseable. It lives here now, where it is checked
/// against the version the document claims rather than against every version at
/// once.
#[cfg(feature = "openapi32")]
#[test]
fn a_response_without_a_description_is_a_three_one_violation() {
    let summarised = Response {
        summary: Some("The order".to_owned()),
        ..Response::default()
    };
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getOrder").with_responses(Responses::new().with(200, summarised)),
    );
    let document = document_with(&[("/orders", item)]);

    assert!(
        errors(&document)
            .iter()
            .any(|error| matches!(error, SpecError::MissingResponseDescription)),
        "3.1 requires one"
    );

    let under_three_two: Vec<SpecError> = Validator::new(SpecVersion::V3_2)
        .validate(&document)
        .into_iter()
        .filter(|v| v.severity == super::Severity::Error)
        .map(|v| v.error)
        .collect();
    assert!(
        !under_three_two
            .iter()
            .any(|error| matches!(error, SpecError::MissingResponseDescription)),
        "3.2 does not"
    );
}

#[test]
fn security_requirements_must_name_a_declared_scheme() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("listUsers")
            .with_responses(ok_responses())
            .with_security(SecurityRequirement::scheme("Bearer")),
    );

    let found = errors(&document_with(&[("/users", item)]));
    assert!(matches!(
        found.as_slice(),
        [SpecError::UnknownSecurityScheme { name }] if name == "Bearer"
    ));
}

/// 3.2 lets a requirement name a scheme by URI; 3.1 does not.
///
/// `references/3.2.0.md:4685`: the name "MUST **either** correspond to a
/// security scheme declared in the Security Schemes … **or be the URI of a
/// Security Scheme Object**". `references/3.1.2.md:4129` has only the first
/// half, and the rule was written to it and never gated — so a valid 3.2
/// document naming `./foo` is reported as an error.
///
/// A bare undeclared name stays an error under both. It is a legal relative
/// URI reference in the abstract, but 3.2 says a name matching a component
/// name is a component name and that referencing by single-segment relative
/// URI is spelled `./foo` — so the bare form is the typo the rule exists to
/// catch, and reading it as a URI would make the check vacuous.
#[cfg(feature = "openapi32")]
#[test]
fn a_three_two_requirement_may_name_a_scheme_by_uri() {
    let requiring = |name: &str| {
        let item = PathItem::new().with_operation(
            Method::Get,
            Operation::new("listUsers")
                .with_responses(ok_responses())
                .with_security(SecurityRequirement::scheme(name)),
        );
        document_with(&[("/users", item)])
    };
    let unknown_schemes = |document: &Document, version: SpecVersion| {
        Validator::new(version)
            .validate(document)
            .into_iter()
            .filter(|v| matches!(v.error, SpecError::UnknownSecurityScheme { .. }))
            .count()
    };

    for name in ["./foo", "https://example.com/schemes#/Bearer"] {
        let document = requiring(name);
        assert_eq!(
            unknown_schemes(&document, SpecVersion::V3_2),
            0,
            "3.2 permits `{name}`"
        );
        assert_eq!(
            unknown_schemes(&document, SpecVersion::V3_1),
            1,
            "3.1 does not permit `{name}`"
        );
    }

    let bare = requiring("Bearer");
    assert_eq!(
        unknown_schemes(&bare, SpecVersion::V3_2),
        1,
        "a bare undeclared name is a typo under either version"
    );
}

#[test]
fn a_declared_scheme_satisfies_the_requirement() {
    let mut document = document_with(&[(
        "/users",
        PathItem::new().with_operation(
            Method::Get,
            Operation::new("listUsers")
                .with_responses(ok_responses())
                .with_security(SecurityRequirement::scheme("Bearer")),
        ),
    )]);
    document.components.security_schemes.insert(
        "Bearer".to_owned(),
        crate::RefOr::Item(crate::SecurityScheme::bearer(None)),
    );

    assert!(errors(&document).is_empty());
}

#[test]
fn an_unconstrained_schema_is_a_warning_not_an_error() {
    let mut operation = Operation::new("ingest").with_responses(ok_responses());
    operation.request_body = Some(crate::RefOr::Item(crate::RequestBody::json(Schema::any())));

    let document = document_with(&[(
        "/ingest",
        PathItem::new().with_operation(Method::Post, operation),
    )]);

    assert!(errors(&document).is_empty());

    let reported = Validator::new(SpecVersion::V3_1).validate(&document);
    assert!(
        reported
            .iter()
            .any(|v: &Violation| v.severity == super::Severity::Warning
                && matches!(v.error, SpecError::UncheckedSchema)),
        "expected an unchecked-schema warning, got {reported:?}"
    );
}

#[test]
fn using_an_undeclared_tag_is_a_warning() {
    let document = document_with(&[(
        "/users",
        PathItem::new().with_operation(
            Method::Get,
            Operation::new("listUsers")
                .with_tag("users")
                .with_responses(ok_responses()),
        ),
    )]);

    assert!(errors(&document).is_empty());
    assert!(
        Validator::new(SpecVersion::V3_1)
            .validate(&document)
            .iter()
            .any(|v| matches!(v.error, SpecError::UndocumentedTag { .. }))
    );
}

#[test]
fn duplicate_tag_names_are_rejected() {
    let mut document = document_with(&[]);
    document.tags.push(crate::Tag::new("users"));
    document.tags.push(crate::Tag::new("users"));

    assert!(
        errors(&document)
            .iter()
            .any(|e| matches!(e, SpecError::DuplicateTag { .. }))
    );
}

#[test]
fn validate_reports_errors_and_hides_warnings() {
    let item = PathItem::new().with_operation(Method::Get, Operation::new("listUsers"));
    let document = document_with(&[("/users", item)]);
    let result = document.validate(SpecVersion::V3_1);
    let reported = result.expect_err("has an error");
    assert!(
        reported
            .iter()
            .all(|v| v.severity == super::Severity::Error)
    );
}

fn violations(document: &Document) -> Vec<Violation> {
    Validator::new(SpecVersion::V3_1).validate(document)
}

fn opaque_document() -> Document {
    let mut operation = Operation::new("listUsers").with_responses(ok_responses());
    crate::annotation::Opaque::new(crate::annotation::OpaqueReason::UntypedLayer)
        .apply_to(&mut operation)
        .expect("nothing to conflict with");
    let item = PathItem::new().with_operation(Method::Get, operation);
    let mut document = document_with(&[("/users", item)]);
    document.restamp_authority();
    document
}

#[test]
fn an_opaque_operation_is_a_warning_not_an_error() {
    let document = opaque_document();

    assert!(errors(&document).is_empty());
    assert!(violations(&document).iter().any(|v| {
        v.severity == super::Severity::Warning
            && v.location == "#/paths/~1users/get"
            && matches!(v.error, SpecError::OpaqueOperation { .. })
    }));
}

#[test]
fn an_opaque_document_that_omits_the_stamp_is_an_error() {
    let mut document = opaque_document();
    document
        .extensions
        .0
        .shift_remove(crate::annotation::NOT_AUTHORITATIVE_ANNOTATION);

    assert!(
        errors(&document)
            .iter()
            .any(|e| matches!(e, SpecError::AuthorityNotStamped))
    );
}

#[test]
fn an_opaque_route_is_reported_without_inventing_a_paths_entry() {
    let mut document = document_with(&[(
        "/users",
        PathItem::new().with_operation(
            Method::Get,
            Operation::new("listUsers").with_responses(ok_responses()),
        ),
    )]);
    crate::annotation::OpaqueRoute::new(
        "/assets/{*path}",
        crate::annotation::OpaqueReason::UntypedRoute,
    )
    .append_to(&mut document)
    .expect("nothing to conflict with");
    document.restamp_authority();

    assert!(errors(&document).is_empty());
    assert!(violations(&document).iter().any(|v| {
        matches!(&v.error, SpecError::OpaqueRoute { pattern } if pattern == "/assets/{*path}")
    }));
    // The route is recorded, and `paths` is untouched by it.
    assert_eq!(document.paths.items.len(), 1);
}

#[test]
fn an_unreadable_annotation_is_an_error() {
    let mut document = document_with(&[(
        "/users",
        PathItem::new().with_operation(
            Method::Get,
            Operation::new("listUsers").with_responses(ok_responses()),
        ),
    )]);
    document.extensions.insert(
        crate::annotation::OPAQUE_ROUTES_ANNOTATION,
        serde_json::json!("nonsense"),
    );

    let reported = errors(&document);
    assert!(reported.iter().any(
        |e| matches!(e, SpecError::MalformedAnnotation { name, .. } if name == "x-kynos-opaque-routes")
    ));
    // Unreadable is not clean, so the authority stamp is demanded too.
    assert!(
        reported
            .iter()
            .any(|e| matches!(e, SpecError::AuthorityNotStamped))
    );
}

#[test]
fn a_clean_document_makes_no_opacity_noise() {
    let item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("health").with_responses(ok_responses()),
    );
    let document = document_with(&[("/health", item)]);

    assert!(!violations(&document).iter().any(|v| matches!(
        v.error,
        SpecError::NotAuthoritative
            | SpecError::AuthorityNotStamped
            | SpecError::OpaqueOperation { .. }
            | SpecError::OpaqueRoute { .. }
    )));
}

/// A description read from somewhere else never passes through
/// `PathTemplate::parse`, so validation is the only place its keys are checked.
#[test]
fn a_paths_key_that_is_not_a_template_is_reported() {
    let document: Document = serde_json::from_value(serde_json::json!({
        "openapi": "3.1.1",
        "info": { "title": "Test", "version": "1.0.0" },
        "paths": {
            "/a b|c": { "get": { "operationId": "odd", "responses": { "200": { "description": "ok" } } } }
        }
    }))
    .expect("a `paths` key is a plain string, so this parses");

    // The reason is the parse failure itself, not its text, so this can name
    // which rule the key broke rather than matching on a formatted string.
    assert!(errors(&document).iter().any(|e| matches!(
        e,
        SpecError::InvalidPathTemplate {
            template,
            reason: crate::model::paths::template::InvalidPathTemplate::IllegalLiteralCharacter { .. },
        } if template == "/a b|c"
    )));
}

/// The location must be a resolvable JSON Pointer, which means the `/` inside a
/// path key is escaped rather than left to read as a token separator.
#[test]
fn violation_locations_escape_their_path_keys() {
    let item = PathItem::new().with_operation(Method::Get, Operation::new("listUsers"));
    let document = document_with(&[("/users/{id}", item)]);

    assert!(
        violations(&document)
            .iter()
            .any(|v| v.location == "#/paths/~1users~1{id}/get")
    );
}

/// `Operation.responses` is skipped when it is empty, so a `Responses` that
/// carries only extensions must not read as empty — or a round trip drops it.
#[test]
fn a_responses_holding_only_extensions_is_not_empty() {
    let mut responses = Responses::new();
    assert!(responses.is_empty());

    responses
        .extensions
        .insert("x-poll-interval", serde_json::json!(30));
    assert!(!responses.is_empty());

    let operation = Operation::new("listUsers").with_responses(responses);
    let json = serde_json::to_string(&operation).expect("serializable");
    assert!(
        json.contains("x-poll-interval"),
        "the extension was dropped: {json}"
    );
}

/// `validate` promises violations "most structural first", so a caller
/// diffing two runs of one document must not see them shuffle.
#[test]
fn violation_order_does_not_depend_on_hashing() {
    let mut operation = Operation::new("listUsers").with_responses(ok_responses());
    for name in ["alpha", "beta", "gamma", "delta", "epsilon"] {
        operation =
            operation.with_parameter(Parameter::path(name, Schema::of_type(SchemaType::String)));
    }
    let document = document_with(&[(
        "/things",
        PathItem::new().with_operation(Method::Get, operation),
    )]);

    let first = errors(&document);
    for _ in 0..16 {
        assert_eq!(errors(&document), first);
    }
}

/// A violation is printed, not walked: `Router::validate` hands back a list and
/// `Error::Invalid` renders one, so `Display` has to carry the whole thing.
/// Offering the `SpecError` it already names as a cause as well would make every
/// reporter print that sentence twice.
#[test]
fn a_violation_says_everything_in_one_line() {
    let violation = Violation::error("/paths/~1users/get", SpecError::NoResponses);

    let rendered = violation.to_string();

    assert!(rendered.contains("/paths/~1users/get"), "{rendered}");
    assert!(
        rendered.contains(&SpecError::NoResponses.to_string()),
        "{rendered}"
    );
    assert!(std::error::Error::source(&violation).is_none());
}

// --- The variant ledger ---------------------------------------------------

/// A variant's name, as an exhaustive match.
///
/// This is the first of the two guards: adding a variant to [`SpecError`] stops
/// this file compiling until the variant is named here. The second guard,
/// [`every_variant_has_a_case`], is what then forces it to be *raised*.
fn variant_name(error: &SpecError) -> &'static str {
    match error {
        SpecError::DuplicateOperationId { .. } => "DuplicateOperationId",
        SpecError::DuplicatePathTemplate { .. } => "DuplicatePathTemplate",
        SpecError::InvalidPathTemplate { .. } => "InvalidPathTemplate",
        SpecError::UndeclaredPathVariable { .. } => "UndeclaredPathVariable",
        SpecError::UnusedPathParameter { .. } => "UnusedPathParameter",
        SpecError::PathParameterNotRequired { .. } => "PathParameterNotRequired",
        SpecError::DuplicateParameter { .. } => "DuplicateParameter",
        SpecError::ShortCircuitMismatch { .. } => "ShortCircuitMismatch",
        SpecError::IllegalStyle { .. } => "IllegalStyle",
        SpecError::IgnoredHeaderParameter { .. } => "IgnoredHeaderParameter",
        SpecError::IgnoredHeader { .. } => "IgnoredHeader",
        SpecError::NoResponses => "NoResponses",
        SpecError::MissingResponseDescription => "MissingResponseDescription",
        #[cfg(feature = "openapi32")]
        SpecError::ConflictingEncoding => "ConflictingEncoding",
        SpecError::InvalidComponentName { .. } => "InvalidComponentName",
        SpecError::DuplicateTag { .. } => "DuplicateTag",
        SpecError::UnknownTagParent { .. } => "UnknownTagParent",
        SpecError::TagParentCycle { .. } => "TagParentCycle",
        SpecError::UnknownSecurityScheme { .. } => "UnknownSecurityScheme",
        SpecError::UndocumentedTag { .. } => "UndocumentedTag",
        SpecError::EmptyServerVariableEnum { .. } => "EmptyServerVariableEnum",
        SpecError::ServerVariableDefaultNotInEnum { .. } => "ServerVariableDefaultNotInEnum",
        SpecError::InvalidExtensionName { .. } => "InvalidExtensionName",
        SpecError::UncheckedSchema => "UncheckedSchema",
        SpecError::NotAuthoritative => "NotAuthoritative",
        SpecError::OpaqueOperation { .. } => "OpaqueOperation",
        SpecError::OpaqueRoute { .. } => "OpaqueRoute",
        SpecError::AuthorityNotStamped => "AuthorityNotStamped",
        SpecError::MalformedAnnotation { .. } => "MalformedAnnotation",
        SpecError::EmptyDocument => "EmptyDocument",
        SpecError::RequiresV3_2 { .. } => "RequiresV3_2",
    }
}

/// Variants no validation run raises, and what raises each instead.
///
/// Every one of these is reachable — none is a placeholder. Listing them is
/// what keeps [`every_variant_has_a_case`] a statement about this validator
/// rather than about the enum.
const RAISED_ELSEWHERE: &[&str] = &[
    // Prevented by construction rather than reported: `Document::paths` is
    // always serialized, so every emitted document carries one of the three
    // fields the rule asks for. The variant stays because a consumer
    // validating a description Kynos did not write still needs to name the
    // failure, and because `paths` being absent and `paths` being present but
    // empty are the same value here -- only the wire tells them apart.
    "EmptyDocument",
    // A 3.1-only build has no 3.2 construct to raise this with. A 3.2-capable
    // one does, and carries a ledger case below.
    #[cfg(not(feature = "openapi32"))]
    "RequiresV3_2",
    // The same: `encoding` conflicts with `prefixEncoding` and `itemEncoding`,
    // neither of which a 3.1 build has.
    #[cfg(not(feature = "openapi32"))]
    "ConflictingEncoding",
    // `kynos`'s `short_circuit_mismatch` compares an interceptor's declared
    // statuses against the responses it describes. No document reaches it, and
    // `crates/kynos/src/response/mod.rs` covers it where it lives.
    "ShortCircuitMismatch",
    // Tag hierarchy arrived in 3.2, so `check_tag_hierarchy` is compiled out of
    // a baseline build along with the only code paths that raise these two.
    #[cfg(not(feature = "openapi32"))]
    "UnknownTagParent",
    #[cfg(not(feature = "openapi32"))]
    "TagParentCycle",
];

/// One document per variant, each named by the variant it must raise and the
/// version to validate it at.
///
/// Split by the rule module that raises each group, which is also the order
/// `Validator::validate` runs them in.
fn ledger() -> Vec<(&'static str, SpecVersion, Document)> {
    let mut cases = ledger_paths();
    cases.extend(ledger_parameters());
    cases.extend(ledger_document());
    cases.extend(ledger_opacity());
    cases
}

/// Cases for the path, template and parameter rules.
fn ledger_paths() -> Vec<(&'static str, SpecVersion, Document)> {
    use crate::model::schema::Schema;

    let operation = || Operation::new("listUsers").with_responses(ok_responses());
    let get = |operation: Operation| PathItem::new().with_operation(Method::Get, operation);

    let mut cases: Vec<(&'static str, SpecVersion, Document)> = Vec::new();
    let mut push =
        |name: &'static str, document: Document| cases.push((name, SpecVersion::V3_1, document));

    push(
        "DuplicateOperationId",
        document_with(&[("/a", get(operation())), ("/b", get(operation()))]),
    );
    push(
        "DuplicatePathTemplate",
        document_with(&[
            (
                "/pets/{petId}",
                get(Operation::new("a").with_responses(ok_responses())),
            ),
            (
                "/pets/{name}",
                get(Operation::new("b").with_responses(ok_responses())),
            ),
        ]),
    );
    push(
        "InvalidPathTemplate",
        serde_json::from_value(serde_json::json!({
            "openapi": "3.1.2",
            "info": { "title": "T", "version": "1" },
            "paths": { "/a b|c": { "get": { "responses": { "200": { "description": "ok" } } } } }
        }))
        .expect("a `paths` key is a plain string, so this parses"),
    );
    push(
        "UndeclaredPathVariable",
        document_with(&[("/users/{id}", get(operation()))]),
    );
    push(
        "UnusedPathParameter",
        document_with(&[(
            "/users",
            get(operation()
                .with_parameter(Parameter::path("id", Schema::of_type(SchemaType::String)))),
        )]),
    );
    push(
        "PathParameterNotRequired",
        document_with(&[(
            "/users/{id}",
            get(operation().with_parameter({
                let mut parameter = Parameter::path("id", Schema::of_type(SchemaType::String));
                parameter.required = None;
                parameter
            })),
        )]),
    );
    cases
}

/// Cases for the parameter and header rules.
fn ledger_parameters() -> Vec<(&'static str, SpecVersion, Document)> {
    use crate::model::{parameter::header::Header, schema::Schema};

    let operation = || Operation::new("listUsers").with_responses(ok_responses());
    let get = |operation: Operation| PathItem::new().with_operation(Method::Get, operation);

    let mut cases: Vec<(&'static str, SpecVersion, Document)> = Vec::new();
    let mut push =
        |name: &'static str, document: Document| cases.push((name, SpecVersion::V3_1, document));

    push(
        "DuplicateParameter",
        document_with(&[(
            "/users",
            get(operation()
                .with_parameter(Parameter::query("q", Schema::of_type(SchemaType::String)))
                .with_parameter(Parameter::query("q", Schema::of_type(SchemaType::String)))),
        )]),
    );
    push(
        "IllegalStyle",
        document_with(&[(
            "/users",
            get(operation().with_parameter(
                Parameter::query("q", Schema::of_type(SchemaType::String))
                    .with_style(Style::Simple, false),
            )),
        )]),
    );
    push(
        "IgnoredHeaderParameter",
        document_with(&[(
            "/users",
            get(operation().with_parameter(Parameter::header(
                "Accept",
                Schema::of_type(SchemaType::String),
            ))),
        )]),
    );
    push(
        "IgnoredHeader",
        document_with(&[(
            "/users",
            get(operation().with_responses(Responses::new().with(
                200,
                Response::new("ok").with_header(
                    "Content-Type",
                    Header::new(Schema::of_type(SchemaType::String)),
                ),
            ))),
        )]),
    );
    push(
        "NoResponses",
        document_with(&[("/users", get(Operation::new("listUsers")))]),
    );
    // A response with no description at all, which is the whole of what this
    // rule is about. `summary` would make it a *useful* 3.2 document, and is
    // 3.2-only — so naming it here would leave the variant with no case at
    // baseline features, where the rule fires just the same.
    push(
        "MissingResponseDescription",
        document_with(&[(
            "/users",
            get(Operation::new("listUsers")
                .with_responses(Responses::new().with(200, Response::default()))),
        )]),
    );
    // 3.2 only: `prefixEncoding` is what `encoding` conflicts with, and it does
    // not exist under 3.1, so neither does the conflict.
    #[cfg(feature = "openapi32")]
    push("ConflictingEncoding", {
        use crate::model::body::{RequestBody, encoding::Encoding, media_type::MediaType};

        let mut content = MediaType::new(Schema::of_type(SchemaType::Object));
        content
            .encoding
            .insert("part".to_owned(), Encoding::new("text/plain"));
        content.prefix_encoding = Some(vec![Encoding::new("text/plain")]);

        document_with(&[(
            "/uploads",
            get(Operation::new("upload")
                .with_request_body(RequestBody::new("multipart/mixed", content))
                .with_responses(ok_responses())),
        )])
    });
    cases
}

/// Cases for the whole-document rules: components, tags, servers, security.
fn ledger_document() -> Vec<(&'static str, SpecVersion, Document)> {
    use crate::model::{
        schema::Schema,
        server::{Server, ServerVariable},
        tag::Tag,
    };

    let operation = || Operation::new("listUsers").with_responses(ok_responses());
    let get = |operation: Operation| PathItem::new().with_operation(Method::Get, operation);

    let mut cases: Vec<(&'static str, SpecVersion, Document)> = Vec::new();
    let mut push =
        |name: &'static str, document: Document| cases.push((name, SpecVersion::V3_1, document));

    push("InvalidComponentName", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document
            .components
            .schemas
            .insert("not a name".to_owned(), Schema::of_type(SchemaType::String));
        document
    });
    push("DuplicateTag", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.tags = vec![Tag::new("orders"), Tag::new("orders")];
        document
    });
    #[cfg(feature = "openapi32")]
    push("UnknownTagParent", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.tags = vec![Tag::new("orders").with_parent("absent")];
        document
    });
    #[cfg(feature = "openapi32")]
    push("TagParentCycle", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.tags = vec![
            Tag::new("a").with_parent("b"),
            Tag::new("b").with_parent("a"),
        ];
        document
    });
    push(
        "UnknownSecurityScheme",
        document_with(&[(
            "/users",
            get(operation().with_security(SecurityRequirement::scheme("Undeclared"))),
        )]),
    );
    push(
        "UndocumentedTag",
        document_with(&[("/users", get(operation().with_tag("orders")))]),
    );
    push("EmptyServerVariableEnum", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.servers = vec![Server::new("https://example.com/{region}").with_variable(
            "region",
            ServerVariable {
                enumeration: Some(Vec::new()),
                default_value: "eu".to_owned(),
                description: None,
                extensions: crate::model::extensions::Extensions::new(),
            },
        )];
        document
    });
    push("ServerVariableDefaultNotInEnum", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.servers = vec![Server::new("https://example.com/{region}").with_variable(
            "region",
            ServerVariable {
                enumeration: Some(vec!["us".to_owned()]),
                default_value: "eu".to_owned(),
                description: None,
                extensions: crate::model::extensions::Extensions::new(),
            },
        )];
        document
    });
    push(
        "InvalidExtensionName",
        document_with(&[(
            "/users",
            get(operation().with_parameter({
                let mut parameter = Parameter::query("q", Schema::of_type(SchemaType::String));
                parameter.extensions.insert("not-prefixed", true);
                parameter
            })),
        )]),
    );
    cases
}

/// Cases for the opacity rules, which are what make a document's authority
/// claim checkable rather than asserted.
fn ledger_opacity() -> Vec<(&'static str, SpecVersion, Document)> {
    use crate::model::schema::Schema;

    let operation = || Operation::new("listUsers").with_responses(ok_responses());
    let get = |operation: Operation| PathItem::new().with_operation(Method::Get, operation);

    let mut cases: Vec<(&'static str, SpecVersion, Document)> = Vec::new();
    let mut push =
        |name: &'static str, document: Document| cases.push((name, SpecVersion::V3_1, document));

    push("UncheckedSchema", {
        let mut unconstrained = Operation::new("ingest").with_responses(ok_responses());
        unconstrained.request_body =
            Some(crate::RefOr::Item(crate::RequestBody::json(Schema::any())));
        document_with(&[(
            "/ingest",
            PathItem::new().with_operation(Method::Post, unconstrained),
        )])
    });

    // Validating as 3.1 a document only 3.2 can express. The same walk
    // `Document::emit` refuses on, so the two agree on what 3.1 can carry.
    #[cfg(feature = "openapi32")]
    push("RequiresV3_2", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.self_uri = Some("https://example.com/orders".to_owned());
        document
    });

    // One opaque operation raises three at once: the operation is reported, the
    // document is no longer authoritative, and the stamp saying so is present.
    push("OpaqueOperation", opaque_document());
    push("NotAuthoritative", opaque_document());
    push("AuthorityNotStamped", {
        let mut document = opaque_document();
        document
            .extensions
            .0
            .shift_remove(crate::annotation::NOT_AUTHORITATIVE_ANNOTATION);
        document
    });
    push("OpaqueRoute", {
        let mut document = document_with(&[("/users", get(operation()))]);
        crate::annotation::OpaqueRoute::new(
            "/assets/{*path}",
            crate::annotation::OpaqueReason::UntypedRoute,
        )
        .append_to(&mut document)
        .expect("nothing to conflict with");
        document.restamp_authority();
        document
    });
    push("MalformedAnnotation", {
        let mut document = document_with(&[("/users", get(operation()))]);
        document.extensions.insert(
            crate::annotation::OPAQUE_ROUTES_ANNOTATION,
            serde_json::json!("nonsense"),
        );
        document
    });

    cases
}

/// Each ledger entry raises the variant it is filed under.
#[test]
fn each_ledger_case_raises_the_variant_it_names() {
    for (expected, version, document) in ledger() {
        let raised: Vec<&'static str> = Validator::new(version)
            .validate(&document)
            .iter()
            .map(|violation| variant_name(&violation.error))
            .collect();
        assert!(
            raised.contains(&expected),
            "`{expected}` was not raised; got {raised:?}"
        );
    }
}

/// Every variant the validator can raise has a ledger entry raising it.
///
/// The count comes from the source rather than from a second list, so a variant
/// added without a case fails here instead of being silently uncovered. That is
/// the same instrument as `every_rejected_schema_type_has_a_case` in
/// `crates/kynos/tests/ui.rs`, pointed at this enum.
#[test]
fn every_variant_has_a_case() {
    let declared = include_str!("violation.rs")
        .matches("\n    #[error")
        .count();

    let mut raised: Vec<&'static str> = ledger()
        .iter()
        .flat_map(|(_, version, document)| Validator::new(*version).validate(document))
        .map(|violation| variant_name(&violation.error))
        .collect();
    raised.sort_unstable();
    raised.dedup();

    let uncovered = declared - RAISED_ELSEWHERE.len();
    assert_eq!(
        raised.len(),
        uncovered,
        "{declared} variants declared, {} raised elsewhere, {} covered here: {raised:?}",
        RAISED_ELSEWHERE.len(),
        raised.len()
    );
}

/// A media type name is a map key that always holds a `/`, and it lives under
/// `content`, which the Request Body Object requires.
///
/// Both halves are about the same thing: the location has to be a pointer a
/// caller can resolve to the offending object. `violation_locations_escape_their_path_keys`
/// covers the path key; nothing covered the media type, which is the other key
/// on the way down and the only one guaranteed to contain a separator.
#[test]
fn violation_locations_name_the_media_type_they_came_from() {
    use crate::model::body::{RequestBody, media_type::MediaType};

    let item = PathItem::new().with_operation(
        Method::Post,
        Operation::new("createOrder")
            .with_request_body(RequestBody::new(
                "application/json",
                // Unconstrained, so `check_media_type` reports it and the
                // location it reports is the thing under test.
                MediaType::new(Schema::any()),
            ))
            .with_responses(Responses::new().with(
                200,
                Response::with_content("ok", "application/json", MediaType::new(Schema::any())),
            )),
    );
    let found = violations(&document_with(&[("/orders", item)]));
    let located: Vec<&str> = found
        .iter()
        .filter(|violation| matches!(violation.error, SpecError::UncheckedSchema))
        .map(|violation| violation.location.as_str())
        .collect();

    assert!(
        located.contains(&"#/paths/~1orders/post/requestBody/content/application~1json"),
        "a request body's media type: {located:?}"
    );
    assert!(
        located.contains(&"#/paths/~1orders/post/responses/200/content/application~1json"),
        "a response's media type: {located:?}"
    );
}