typed-openapi 0.0.2

Typed Rust calls and a clap command tree from one OpenAPI document, with every write behind a dry-run gate.
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
//! What the runtime crate makes of the vendor's document plus the adopter's
//! Overlay — with no bless step anywhere, because a CLI-only adopter needs
//! none.
//!
//! The fixtures under `tests/fixtures/` are this crate's own, not the example
//! adoption's. `examples/toy/spec/` holds a document with the same content
//! today and a different owner: there it is the vendor's, and the example is
//! free to evolve it. Pointing these tests at that copy would let a change to
//! the example break the library.

#![expect(
    clippy::expect_used,
    clippy::unwrap_used,
    reason = "a test that cannot build its fixture should fail loudly and name it"
)]

use typed_openapi::model::Body;
use typed_openapi::{
    Document, Effect, Invocation, Operation, Param, Shape, Unsupported, Values, render, tree,
};

const TOY: &str = include_str!("fixtures/toy.yaml");
const CORRECTIONS: &str = include_str!("fixtures/corrections.yaml");
const CLI: &str = include_str!("fixtures/cli.yaml");

/// The layers, in the order a bless step applies them.
const OVERLAYS: &[&str] = &[CORRECTIONS, CLI];

fn document() -> Document {
    Document::load(TOY, OVERLAYS).expect("the vendor's document plus the adopter's Overlay")
}

#[test]
fn the_overlay_adds_what_the_vendor_left_out() {
    let doc = document();
    assert!(doc.get("archiveVoucher").is_some(), "the added operation");
    let Body::JsonFields(fields) = doc.get("createVoucher").unwrap().body() else {
        panic!("createVoucher takes a flat JSON body");
    };
    assert!(
        fields.iter().any(|f| f.name() == "internal_ref"),
        "the added field"
    );
}

#[test]
fn the_gate_is_default_closed_and_the_marker_can_only_add_writes() {
    let doc = document();
    let effect = |id: &str| doc.get(id).unwrap_or_else(|| panic!("{id}")).effect();
    assert_eq!(effect("listVouchers"), Effect::Read);
    assert_eq!(effect("getVoucher"), Effect::Read);
    assert_eq!(effect("createVoucher"), Effect::Write);
    assert_eq!(effect("updateVoucher"), Effect::Write);
    assert_eq!(effect("enshrineVoucher"), Effect::Write);
    assert_eq!(effect("archiveVoucher"), Effect::Write);
    // The one fact HTTP cannot carry, and the only thing `x-cli-writes` is for.
    assert_eq!(effect("renderVoucher"), Effect::Write);
}

/// The second half of the gate: the words an operation is held behind beyond
/// the confirmation. They are decided while the document is reduced and read
/// back off both doors, because a shipped binary meets the blob and never the
/// document.
#[test]
fn the_gates_an_operation_names_come_back_off_the_document_and_the_blob() {
    let doc = document();
    let gates = |doc: &Document, id: &str| -> Vec<String> {
        doc.get(id)
            .unwrap_or_else(|| panic!("{id}"))
            .gates()
            .iter()
            .map(|gate| gate.as_str().to_owned())
            .collect()
    };

    assert_eq!(gates(&doc, "enshrineVoucher"), ["enshrine"]);
    assert_eq!(gates(&doc, "sendVoucherByEmail"), ["email"]);
    assert!(
        gates(&doc, "createVoucher").is_empty(),
        "a write the document names no hazard on stands behind --commit alone"
    );
    assert!(
        gates(&doc, "getVoucher").is_empty(),
        "a read is asked nothing"
    );

    let blob = doc.to_blob().expect("the reduction encodes");
    let shipped = Document::from_blob(&blob).expect("and decodes");
    assert_eq!(gates(&shipped, "enshrineVoucher"), ["enshrine"]);
    assert_eq!(gates(&shipped, "sendVoucherByEmail"), ["email"]);
}

/// Which operations stand behind a given word is the document's answer, so a
/// suite with something to say about everything irreversible asks it rather
/// than keeping a list beside it.
#[test]
fn the_document_names_its_gates_and_what_stands_behind_each() {
    let doc = document();
    let named: Vec<&str> = doc.gates().iter().map(|gate| gate.as_str()).collect();
    assert_eq!(named, ["enshrine", "email"]);

    let behind = |gate: &str| -> Vec<&str> { doc.gated_by(gate).map(Operation::id).collect() };
    assert_eq!(behind("enshrine"), ["enshrineVoucher"]);
    assert_eq!(behind("email"), ["sendVoucherByEmail"]);
    assert!(
        behind("commit").is_empty(),
        "the write gate is not one of the named ones"
    );
}

#[test]
fn every_body_is_exactly_one_flag_set() {
    let doc = document();
    let body = |id: &str| doc.get(id).unwrap_or_else(|| panic!("{id}")).body().clone();
    assert!(matches!(body("getVoucher"), Body::None));
    assert!(matches!(body("createVoucher"), Body::JsonFields(_)));
    // `Contact.address` is nested, so there are no per-field flags at all —
    // rather than dead ones beside a required `--json-body`.
    assert!(matches!(
        body("createContact"),
        Body::JsonWhole { required: true }
    ));
    // A media type nothing here assembles: the bytes go through `--raw-body`
    // under the document's own `Content-Type`.
    assert!(matches!(
        body("uploadDocument"),
        Body::Opaque { ref media_type, .. } if media_type == "application/pdf"
    ));
    assert!(matches!(
        body("uploadDocumentMultipart"),
        Body::Multipart { .. }
    ));
}

#[test]
fn a_body_field_moves_aside_for_a_path_parameter_of_the_same_name() {
    let doc = document();
    let update = doc.get("updateVoucher").unwrap();
    assert_eq!(flag_of(update.param("id").unwrap()), "id");
    let Body::JsonFields(fields) = update.body() else {
        panic!("updateVoucher takes a flat JSON body");
    };
    let id = fields.iter().find(|f| f.name() == "id").unwrap();
    assert_eq!(id.flag(), "body-id");
    assert!(id.renamed(), "and it says so in its help line");
}

/// The closest thing a runtime-built tree has to a compile-time check, and the
/// one that catches the next flag collision before a user does.
#[test]
fn the_whole_mounted_tree_is_a_valid_clap_command() {
    let doc = document();
    clap::Command::new("toy")
        .subcommand(clap::Command::new("raw").subcommands(tree::commands(&doc)))
        .debug_assert();
}

#[test]
fn a_dry_run_prints_the_request_that_commit_would_send() {
    let doc = document();
    let op = doc.get("updateVoucher").unwrap();
    let values = Values::new()
        .param("id", 5)
        .json(serde_json::json!({"total": "12.50"}));
    let request = Invocation::new(op, values)
        .expect("the values satisfy the operation")
        .request(doc.base())
        .expect("the base URL is a URL");
    assert_eq!(
        render(&request),
        "PUT /vouchers/5 HTTP/1.1\n\
         host: localhost:9999\n\
         content-type: application/json\n\
         \n\
         {\"total\":\"12.50\"}\n"
    );
}

#[test]
fn the_document_rejects_values_it_does_not_describe() {
    let doc = document();
    let op = doc.get("getVoucher").unwrap();
    assert!(
        Invocation::new(op, Values::new()).is_err(),
        "`id` is required"
    );
    assert!(
        Invocation::new(op, Values::new().param("nope", 1)).is_err(),
        "there is no `nope` parameter"
    );
    assert!(
        Invocation::new(op, Values::new().param("id", "five")).is_err(),
        "`id` is an integer"
    );
    assert!(
        Invocation::new(op, Values::new().param("id", 5).json(serde_json::json!({}))).is_err(),
        "getVoucher takes no body"
    );
}

/// Two defences, in this order: the document's own type rejects the value, and
/// anything that does get through is percent-encoded rather than interpolated.
#[test]
fn a_path_value_cannot_smuggle_a_segment_into_the_url() {
    let doc = document();
    let op = doc.get("archiveVoucher").unwrap();
    let refused = Invocation::new(op, Values::new().param("id", "1/../../etc"))
        .expect_err("`id` is `type: integer` in the document");
    assert!(
        refused.to_string().contains("is not an integer"),
        "{refused}"
    );

    // The same value under a parameter the document types as a string.
    let doc = Document::load(
        &TOY.replace(
            "        schema:\n          type: integer\n          format: int64",
            "        schema:\n          type: string",
        ),
        OVERLAYS,
    )
    .expect("a document whose ids are strings");
    let op = doc.get("getVoucher").unwrap();
    let request = Invocation::new(op, Values::new().param("id", "1/../../etc"))
        .unwrap()
        .request(doc.base())
        .unwrap();
    assert_eq!(request.uri().path(), "/vouchers/1%2F..%2F..%2Fetc");
}

/// A property pointed at a named schema carries that schema's rules onto the
/// flag. Only following the `$ref` while the document is reduced can put them
/// there: the rule is a hop away from the property that has to obey it.
#[test]
fn a_rule_a_named_schema_states_reaches_the_property_pointing_at_it() {
    let doc = document();
    let Body::JsonFields(fields) = doc.get("updateVoucher").unwrap().body() else {
        panic!("updateVoucher takes a flat JSON body");
    };
    let total = fields.iter().find(|f| f.name() == "total").unwrap();
    assert_eq!(
        total.scalar().note().as_deref(),
        Some(r"matches ^-?[0-9]+(\.[0-9]{1,2})?$"),
        "the rule the `Money` schema states did not reach `total`"
    );
    assert_eq!(
        total
            .scalar()
            .parse("1,50")
            .expect_err("a comma is not a decimal point")
            .to_string(),
        r"`1,50` does not match ^-?[0-9]+(\.[0-9]{1,2})?$"
    );
    assert!(total.scalar().parse("12.50").is_ok());
}

/// A parameter never passes through a generated body type, so what the document
/// says about one is the only thing that can ever check it. All of it is
/// checked, and every refusal carries the document's own number.
#[test]
fn every_rule_a_parameter_states_is_checked_because_nothing_else_can_check_it() {
    const PARAMETERS: &str = "  /vouchers:\n\
         \x20   get:\n\
         \x20     operationId: listVouchers\n\
         \x20     parameters:\n\
         \x20       - { name: since, in: query, schema: { type: string, pattern: '^[0-9]{4}-[0-9]{2}$' } }\n\
         \x20       - { name: code, in: query, schema: { type: string, minLength: 3, maxLength: 3 } }\n\
         \x20       - { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 100, multipleOf: 5 } }\n\
         \x20     responses: { \"200\": { description: OK } }\n";

    let doc = Document::load(&synthetic(PARAMETERS), &[]).expect("a document");
    let op = doc.get("listVouchers").unwrap();
    let refused = |name: &str, value: &str| {
        Invocation::new(op, Values::new().param(name, value))
            .expect_err("the document refuses it")
            .to_string()
    };

    assert_eq!(
        refused("since", "2026-9"),
        "listVouchers: `since`: `2026-9` does not match ^[0-9]{4}-[0-9]{2}$"
    );
    assert_eq!(
        refused("code", "EU"),
        "listVouchers: `code`: `EU` is shorter than 3 characters"
    );
    assert_eq!(
        refused("code", "EURO"),
        "listVouchers: `code`: `EURO` is longer than 3 characters"
    );
    assert_eq!(
        refused("limit", "0"),
        "listVouchers: `limit`: `0` is not at least 1"
    );
    assert_eq!(
        refused("limit", "105"),
        "listVouchers: `limit`: `105` is not at most 100"
    );
    assert_eq!(
        refused("limit", "7"),
        "listVouchers: `limit`: `7` is not a multiple of 5"
    );
    assert!(
        Invocation::new(
            op,
            Values::new()
                .param("since", "2026-09")
                .param("code", "EUR")
                .param("limit", "25"),
        )
        .is_ok()
    );
}

/// A `pattern` the engine cannot read would refuse every value at the flag,
/// which is a command line nothing can satisfy. The document is refused while
/// it is reduced instead, naming the operation and the value it was stated
/// about.
#[test]
fn a_pattern_no_engine_can_read_is_refused_while_the_document_is_reduced() {
    let error = Document::load(
        &synthetic(
            "  /vouchers:\n\
             \x20   get:\n\
             \x20     operationId: listVouchers\n\
             \x20     parameters:\n\
             \x20       - { name: since, in: query, schema: { type: string, pattern: '[unterminated' } }\n\
             \x20     responses: { \"200\": { description: OK } }\n",
        ),
        &[],
    )
    .expect_err("`[unterminated` is not a regular expression");
    assert_eq!(
        error.to_string(),
        "listVouchers: `since`: `[unterminated` is not a regular expression: Unbalanced bracket"
    );
}

/// One operation with a body, under whatever `content` key is handed in.
fn upload(content_key: &str) -> String {
    synthetic(&format!(
        "  /documents:\n\
         \x20   post:\n\
         \x20     operationId: uploadDocument\n\
         \x20     requestBody:\n\
         \x20       required: true\n\
         \x20       content:\n\
         \x20         '{content_key}':\n\
         \x20           schema: {{ type: string, format: binary }}\n\
         \x20     responses: {{ \"201\": {{ description: Created }} }}\n"
    ))
}

/// A `content` key with no `/` in it names no media type, so there is nothing
/// to send the body under: carrying it would put a `Content-Type` on the wire
/// that no server parses. Which type the vendor meant is a judgement, and the
/// refusal is what leaves that judgement to an adopter writing an Overlay a
/// reviewer can read.
#[test]
fn a_content_key_that_is_not_a_media_type_is_refused_while_the_document_is_reduced() {
    // The way out the message names: `remove` takes the key out, `update` puts
    // the one the vendor meant in its place.
    const REPAIR: &str = "overlay: 1.1.0\n\
         info: { title: t, version: \"1\" }\n\
         actions:\n\
         \x20 - target: \"$.paths['/documents'].post.requestBody.content['form-data']\"\n\
         \x20   description: The vendor means `multipart/form-data`.\n\
         \x20   remove: true\n\
         \x20 - target: $.paths['/documents'].post.requestBody.content\n\
         \x20   description: Say it the way the wire spells it.\n\
         \x20   update:\n\
         \x20     multipart/form-data:\n\
         \x20       schema: { type: object, properties: { file: { type: string } } }\n";

    let error =
        Document::load(&upload("form-data"), &[]).expect_err("`form-data` names no media type");
    assert_eq!(
        error.to_string(),
        "uploadDocument: `form-data` is not a media type; \
         an Overlay is where a document's content type is corrected"
    );

    let repaired = Document::load(&upload("form-data"), &[REPAIR]).expect("the Overlay repairs it");
    assert!(matches!(
        repaired
            .get("uploadDocument")
            .expect("the operation")
            .body(),
        Body::Multipart { .. }
    ));
}

/// What `Opaque` is for, and what the refusal above must not swallow: a media
/// type this crate cannot assemble is still a media type, so the body goes
/// through `--raw-body` under the document's own spelling of it.
#[test]
fn a_media_type_this_crate_cannot_assemble_is_carried_rather_than_refused() {
    let body = |key: &str| {
        Document::load(&upload(key), &[])
            .unwrap_or_else(|error| panic!("{key}: {error}"))
            .get("uploadDocument")
            .expect("the operation")
            .body()
            .clone()
    };
    assert!(matches!(
        body("application/pdf"),
        Body::Opaque { ref media_type, .. } if media_type == "application/pdf"
    ));
    // The parameters travel too: they are part of the `Content-Type` the
    // document asks for.
    assert!(matches!(
        body("text/csv; charset=utf-8"),
        Body::Opaque { ref media_type, .. } if media_type == "text/csv; charset=utf-8"
    ));
    assert!(matches!(
        body("application/x-www-form-urlencoded"),
        Body::Opaque { .. }
    ));
}

/// One JSON body whose properties are handed in, over a named schema stating a
/// rule: the route `docs/overlay.md` recommends, written out for both spellings
/// OpenAPI 3.0 offers. Every property line is indented to sit under
/// `properties:`.
fn pointing(properties: &str) -> String {
    format!(
        "openapi: 3.0.3\n\
         info: {{ title: t, version: \"1\" }}\n\
         servers: [{{ url: 'http://localhost:9999' }}]\n\
         paths:\n\
         \x20 /notes:\n\
         \x20   post:\n\
         \x20     operationId: createNote\n\
         \x20     requestBody:\n\
         \x20       required: true\n\
         \x20       content:\n\
         \x20         application/json:\n\
         \x20           schema:\n\
         \x20             type: object\n\
         \x20             properties:\n\
         {properties}\
         \x20     responses: {{ \"201\": {{ description: Created }} }}\n\
         components:\n\
         \x20 schemas:\n\
         \x20   Day:\n\
         \x20     type: string\n\
         \x20     description: A calendar day.\n\
         \x20     pattern: '^[0-9]{{4}}-[0-9]{{2}}-[0-9]{{2}}$'\n"
    )
}

/// A `$ref` erases everything written beside it, so the only way a 3.0 document
/// names a rule *and* keeps a sentence about the field pointing at it is to
/// wrap the reference in an `allOf` of one element. The wrapper composes
/// nothing, so it is read as the element it wraps: the rule reaches the flag,
/// and the field keeps its own words.
#[test]
fn a_single_element_all_of_is_read_as_the_schema_it_wraps() {
    let doc = Document::load(
        &pointing(
            "\x20               booked:\n\
             \x20                 allOf: [{ $ref: '#/components/schemas/Day' }]\n\
             \x20                 description: The day this note is booked under.\n\
             \x20               due:\n\
             \x20                 allOf: [{ $ref: '#/components/schemas/Day' }]\n",
        ),
        &[],
    )
    .expect("a document");
    let Body::JsonFields(fields) = doc.get("createNote").unwrap().body() else {
        panic!("both properties are scalars, so both are flags");
    };
    let field = |name: &str| {
        fields
            .iter()
            .find(|f| f.name() == name)
            .unwrap_or_else(|| panic!("{name}"))
    };

    // The rule the named schema states arrives through the wrapper.
    assert_eq!(
        field("booked").scalar().note().as_deref(),
        Some(r"matches ^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
    );
    assert!(field("booked").scalar().parse("2026-09-14").is_ok());
    assert!(field("booked").scalar().parse("14.09.2026").is_err());

    // The sentence about this field, which a bare `$ref` would have erased.
    assert_eq!(
        field("booked").description(),
        Some("The day this note is booked under.")
    );
    // And the named schema's, for the field that says nothing of its own.
    assert_eq!(field("due").description(), Some("A calendar day."));
}

/// An `allOf` that is more than a wrapper composes schemas, and a composition
/// is not one value: the whole body goes through `--json-body` rather than a
/// flag standing for something the request builder would have to invent. Two
/// schemas is one way to be more than a wrapper; a keyword of the node's own
/// beside the `allOf` is the other.
#[test]
fn an_all_of_that_is_more_than_a_wrapper_is_not_a_scalar() {
    let whole = |properties: &str| {
        let doc = Document::load(&pointing(properties), &[]).expect("a document");
        matches!(
            doc.get("createNote").expect("createNote").body(),
            Body::JsonWhole { required: true }
        )
    };
    assert!(whole(
        "\x20               booked:\n\
         \x20                 allOf:\n\
         \x20                   - { $ref: '#/components/schemas/Day' }\n\
         \x20                   - { type: string, minLength: 1 }\n"
    ));
    assert!(whole(
        "\x20               booked:\n\
         \x20                 type: string\n\
         \x20                 allOf: [{ $ref: '#/components/schemas/Day' }]\n"
    ));
}
/// One query parameter that is a list of strings. `explode` is the one line
/// that decides how its values reach the wire.
const LISTED: &str = r"  /vouchers:
    get:
      operationId: listVouchers
      parameters:
        - name: tag
          in: query
          explode: true
          schema: { type: array, items: { type: string } }
      responses: { '200': { description: OK } }
";

/// One operation declaring three shapes at once — a list this CLI spells, an
/// object it cannot, and a plain integer — beside a second operation that
/// declares none of them.
const SHAPES: &str = r"  /vouchers:
    get:
      operationId: listVouchers
      parameters:
        - name: tag
          in: query
          schema: { type: array, items: { type: string } }
        - name: filter
          in: query
          required: false
          schema:
            type: object
            properties:
              opened:
                type: object
                properties:
                  from: { type: string }
        - name: limit
          in: query
          schema: { type: integer }
      responses: { '200': { description: OK } }
  /contacts:
    post:
      operationId: createContact
      responses: { '201': { description: OK } }
";

/// The request one document builds from one set of values, as a whole URL.
fn sent(document: &str, id: &str, values: Values) -> String {
    let doc = Document::load(document, &[]).expect("a document");
    let op = doc.get(id).unwrap_or_else(|| panic!("{id}"));
    Invocation::new(op, values)
        .expect("the values satisfy the operation")
        .request(doc.base())
        .expect("the base URL is a URL")
        .uri()
        .to_string()
}

/// A list is one flag given more than once, and what becomes of the repeats is
/// the document's `explode` rather than this crate's preference. `form` with
/// `explode: true` is what OpenAPI defaults a query parameter to.
#[test]
fn a_list_parameter_reaches_the_query_the_way_the_document_explodes_it() {
    let both = |document: &str| {
        sent(
            document,
            "listVouchers",
            Values::new().each("tag", ["a", "b"]),
        )
    };

    assert_eq!(
        both(&synthetic(LISTED)),
        "http://localhost:9999/vouchers?tag=a&tag=b"
    );
    // The default is the same rendering, written down.
    assert_eq!(
        both(&synthetic(&LISTED.replace("          explode: true\n", ""))),
        "http://localhost:9999/vouchers?tag=a&tag=b"
    );
    assert_eq!(
        both(&synthetic(
            &LISTED.replace("explode: true", "explode: false")
        )),
        "http://localhost:9999/vouchers?tag=a,b"
    );
}

/// Percent-encoding runs before the comma is written, so the comma *between*
/// two values and a comma *inside* one value are not the same character on the
/// wire, and a server reading the field gets the two values that were given.
#[test]
fn a_comma_inside_a_value_is_not_the_comma_between_two_values() {
    assert_eq!(
        sent(
            &synthetic(&LISTED.replace("explode: true", "explode: false")),
            "listVouchers",
            Values::new().each("tag", ["a,b", "c"]),
        ),
        "http://localhost:9999/vouchers?tag=a%2Cb,c"
    );
}

/// The regression this shape exists for. One parameter no flag can carry is an
/// operation's problem; it used to be the whole document's, which made every
/// other operation in it unreachable as well.
#[test]
fn a_parameter_no_flag_can_carry_leaves_every_other_operation_standing() {
    let doc = Document::load(&synthetic(SHAPES), &[])
        .expect("an unreachable parameter does not stop the document reducing");
    let list = doc.get("listVouchers").expect("listVouchers");

    assert!(
        matches!(
            list.param("filter")
                .expect("it is in the reduction")
                .shape(),
            Shape::Unreachable(Unsupported::Structured)
        ),
        "an object parameter is carried, not dropped and not refused"
    );
    // The operation that declares it is mounted, and its other parameters work.
    assert_eq!(flag_of(list.param("limit").expect("limit")), "limit");
    assert_eq!(
        sent(
            &synthetic(SHAPES),
            "listVouchers",
            Values::new().each("tag", ["a"]).param("limit", 5),
        ),
        "http://localhost:9999/vouchers?tag=a&limit=5"
    );
    // And so is every operation that never mentioned it.
    assert!(doc.get("createContact").is_some(), "the other operation");

    // A value for it is refused rather than dropped: a request quietly missing
    // the filter it was given is worse than one that was never built.
    let refused = Invocation::new(list, Values::new().param("filter", "{}"))
        .expect_err("there is nowhere to put it");
    assert_eq!(
        refused.to_string(),
        "listVouchers: `filter` is neither a value nor a list of values, \
         so there is nowhere in the request to put a value for it"
    );
}

/// An operation whose caller *must* send what this CLI cannot spell could never
/// be invoked correctly, so it is named while the document is reduced rather
/// than mounted as a subcommand guaranteed to build the wrong request.
#[test]
fn a_required_parameter_no_flag_can_carry_names_itself_and_the_way_out() {
    let error = Document::load(
        &synthetic(&SHAPES.replace("required: false", "required: true")),
        &[],
    )
    .expect_err("a required parameter with no flag");
    assert_eq!(
        error.to_string(),
        "listVouchers: parameter `filter` is neither a value nor a list of values, \
         and the document requires it; correct the parameter in an Overlay, \
         or drop its `required`"
    );
}

/// `in: cookie` and a parameter described by `content` are the same shape as an
/// object: something one operation asks for that this CLI has no spelling for.
/// One rule covers all three, so none of them costs the document anything.
#[test]
fn a_cookie_and_a_content_parameter_are_carried_the_way_an_object_is() {
    const NEIGHBOURS: &str = r"  /vouchers:
    get:
      operationId: listVouchers
      parameters:
        - name: session
          in: cookie
          schema: { type: string }
        - name: window
          in: query
          content:
            application/json:
              schema: { type: object }
      responses: { '200': { description: OK } }
";

    let doc = Document::load(&synthetic(NEIGHBOURS), &[]).expect("the document still reduces");
    let op = doc.get("listVouchers").expect("listVouchers");
    let why = |name: &str| match op.param(name).expect("it is in the reduction").shape() {
        Shape::Unreachable(why) => why.clone(),
        Shape::Flag { .. } => panic!("`{name}` has no command-line spelling"),
    };
    assert_eq!(why("session"), Unsupported::Cookie);
    assert_eq!(why("window"), Unsupported::Encoded);

    // Neither grows a flag, and the long help says why rather than leaving a
    // reader of `--help` to wonder where the parameter went.
    let command = tree::command(op);
    let longs: Vec<&str> = command
        .get_arguments()
        .filter_map(clap::Arg::get_long)
        .collect();
    assert!(
        !longs.contains(&"session") && !longs.contains(&"window"),
        "{longs:?}"
    );
    let long_about = command.get_long_about().expect("a long help").to_string();
    assert!(
        long_about
            .contains("`session` has no flag: it is `in: cookie`, which this CLI does not send."),
        "{long_about}"
    );
    assert!(
        long_about.contains(
            "`window` has no flag: it is described by `content`, which this CLI does not encode."
        ),
        "{long_about}"
    );
}

/// A serialisation this crate does not write is named on the parameter that
/// declares it. Writing it as `form` instead would put the values on the wire
/// in a shape the server does not read, which is a request that looks sent.
#[test]
fn a_style_this_crate_does_not_serialise_names_itself() {
    const STYLED: &str = r"  /vouchers:
    get:
      operationId: listVouchers
      parameters:
        - name: tag
          in: query
          required: false
          style: pipeDelimited
          schema: { type: array, items: { type: string } }
      responses: { '200': { description: OK } }
";

    /// The same list in a path segment, where a parameter has styles of its own
    /// and is required by definition.
    const SEGMENTED: &str = r"  /vouchers/{ids}:
    get:
      operationId: getVouchers
      parameters:
        - name: ids
          in: path
          required: true
          style: matrix
          schema: { type: array, items: { type: integer } }
      responses: { '200': { description: OK } }
";

    for style in ["spaceDelimited", "pipeDelimited", "deepObject"] {
        let document = synthetic(&STYLED.replace("pipeDelimited", style));
        let doc = Document::load(&document, &[]).expect("the document still reduces");
        let op = doc.get("listVouchers").expect("listVouchers");
        let Shape::Unreachable(why) = op.param("tag").expect("tag").shape() else {
            panic!("`{style}` is not a serialisation this crate writes");
        };
        assert_eq!(
            why.to_string(),
            format!("declared with `style: {style}`, which this CLI does not serialise")
        );

        // Required, the same parameter is the document's problem, and the
        // refusal carries the style's own spelling.
        let error = Document::load(&document.replace("required: false", "required: true"), &[])
            .expect_err("a required parameter with no flag");
        assert!(
            error.to_string().contains(&format!("`style: {style}`")),
            "{error}"
        );
    }

    // A path has styles of its own, and they are not only about delimiters:
    // `matrix` puts a `;ids=` in front of one value as surely as in front of a
    // list, so both schemas answer the same way. A path parameter is required
    // by definition, so both are the document's problem.
    for style in ["matrix", "label"] {
        for schema in [
            "{ type: integer }",
            "{ type: array, items: { type: integer } }",
        ] {
            let document = synthetic(
                &SEGMENTED
                    .replace("matrix", style)
                    .replace("{ type: array, items: { type: integer } }", schema),
            );
            let error =
                Document::load(&document, &[]).expect_err("a path style this crate does not write");
            assert!(
                error.to_string().contains(&format!("`style: {style}`")),
                "{schema}: {error}"
            );
        }
    }
}

/// A path segment and a header are `style: simple`, which comma-separates a list
/// however it explodes. A path parameter given twice is one segment, not a
/// second value silently dropped.
#[test]
fn a_list_in_a_path_segment_or_a_header_is_comma_separated() {
    const SEGMENTED: &str = r"  /vouchers/{ids}:
    get:
      operationId: getVouchers
      parameters:
        - name: ids
          in: path
          required: true
          schema: { type: array, items: { type: integer } }
        - name: X-Trace
          in: header
          schema: { type: array, items: { type: string } }
      responses: { '200': { description: OK } }
";

    let doc = Document::load(&synthetic(SEGMENTED), &[]).expect("a document");
    let op = doc.get("getVouchers").expect("getVouchers");
    let request = Invocation::new(
        op,
        Values::new()
            .each("ids", [3, 4, 5])
            .each("X-Trace", ["one", "two"]),
    )
    .expect("the values satisfy the operation")
    .request(doc.base())
    .expect("the base URL is a URL");

    assert_eq!(request.uri().path(), "/vouchers/3,4,5");
    assert_eq!(
        request.headers().get("x-trace").expect("the header"),
        "one,two"
    );
}

/// A parameter the document declares one value for, given two, is refused: the
/// list the caller meant is not a list the document describes.
#[test]
fn a_parameter_that_is_not_a_list_is_refused_a_second_value() {
    let doc = Document::load(&synthetic(SHAPES), &[]).expect("a document");
    let op = doc.get("listVouchers").expect("listVouchers");
    let refused = Invocation::new(op, Values::new().each("limit", [5, 6]))
        .expect_err("`limit` is one integer");
    assert_eq!(
        refused.to_string(),
        "listVouchers: `limit` takes one value, and was given 2"
    );
}

/// The command line's half of the same facts: the flag is repeatable, its help
/// line says what the repeats become, and what the tree reads back builds the
/// request the document describes.
#[test]
fn a_repeatable_flag_says_what_it_does_and_reaches_the_request_builder_repeated() {
    let doc = Document::load(&synthetic(SHAPES), &[]).expect("a document");
    let op = doc.get("listVouchers").expect("listVouchers");
    let command = tree::command(op);
    let tag = command
        .get_arguments()
        .find(|arg| arg.get_long() == Some("tag"))
        .expect("--tag");

    assert!(matches!(tag.get_action(), clap::ArgAction::Append));
    let help = tag.get_help().expect("a help line").to_string();
    assert!(
        help.contains("repeatable; each value is sent as its own field"),
        "{help}"
    );

    let matches = clap::Command::new("toy")
        .subcommands(tree::commands(&doc))
        .get_matches_from(["toy", "vouchers", "list", "--tag", "a", "--tag", "b"]);
    let selected = tree::select(&doc, &matches).expect("the subcommand names an operation");
    let request = Invocation::new(selected.operation(), selected.values().clone())
        .expect("the flags satisfy the operation")
        .request(doc.base())
        .expect("the base URL is a URL");

    assert_eq!(request.uri().query(), Some("tag=a&tag=b"));
}

/// The two doors onto one reduction. A bless step writes the blob, a binary
/// reads it, and nothing between them may change what the document said —
/// including the flag renames, which are decided while reducing and would be a
/// different command line if they were decided again on the way back.
#[test]
fn a_reduction_survives_the_round_trip_the_bless_step_makes() {
    let doc = document();
    let blob = doc.to_blob().expect("the reduction encodes");
    assert_eq!(Document::from_blob(&blob).expect("and decodes"), doc);
}

/// A blob that is not one is a named error, not a panic and not a CLI that
/// starts with half an API.
#[test]
fn a_blob_that_is_not_a_reduction_is_refused_by_name() {
    let error = Document::from_blob(b"not a reduction").expect_err("not a reduction");
    assert!(error.to_string().contains("reduced model"), "{error}");
}

/// The flag a parameter grows, for a test that is about the name rather than
/// about the shape.
fn flag_of(param: &Param) -> &str {
    match param.shape() {
        Shape::Flag { flag, .. } => flag,
        Shape::Unreachable(why) => panic!("`{}` has no flag: it is {why}", param.name()),
    }
}

/// A document of this test's own, `paths` and nothing else — for the naming
/// rules, which are about shapes the toy fixture does not have.
fn synthetic(paths: &str) -> String {
    format!(
        "openapi: 3.0.3\n\
         info: {{ title: t, version: \"1\" }}\n\
         servers: [{{ url: 'http://localhost:9999' }}]\n\
         paths:\n{paths}"
    )
}

/// What the tree calls every operation, in document order.
fn placements(document: &str) -> Vec<String> {
    Document::load(document, &[])
        .expect("a document")
        .iter()
        .map(|op| format!("{} {}", op.group(), op.command()))
        .collect()
}

/// A segment every path shares tells nothing apart, so it is not the group: a
/// document served entirely under `/v1` must not collapse into one group
/// named `v1`.
#[test]
fn a_prefix_every_path_shares_is_not_the_group() {
    let placed = placements(&synthetic(
        "  /v1/vouchers:\n\
         \x20   get: { operationId: listVouchers, responses: { \"200\": { description: OK } } }\n\
         \x20 /v1/contacts:\n\
         \x20   post: { operationId: createContact, responses: { \"201\": { description: OK } } }\n",
    ));
    assert_eq!(placed, ["vouchers list", "contacts create"]);
}

/// Two operations under one name would silently shadow each other. The
/// document is refused instead, naming both and the way out.
#[test]
fn two_operations_under_one_name_are_refused_by_both_ids() {
    const COLLIDING: &str = "  /vouchers/{id}/render:\n\
         \x20   get: { operationId: renderVoucher, responses: { \"200\": { description: OK } } }\n\
         \x20 /vouchers/{id}/pdf/render:\n\
         \x20   get: { operationId: renderVoucherPdf, responses: { \"200\": { description: OK } } }\n";

    let error = Document::load(&synthetic(COLLIDING), &[]).expect_err("both are `vouchers render`");

    assert_eq!(
        error.to_string(),
        "`renderVoucher` and `renderVoucherPdf` are both `vouchers render` on the \
         command line; give one of them an `x-cli-command`"
    );

    // And the way out the message names is the way out.
    let resolved = COLLIDING.replace(
        "operationId: renderVoucherPdf",
        "operationId: renderVoucherPdf, x-cli-command: render-pdf",
    );
    assert_eq!(
        placements(&synthetic(&resolved)),
        ["vouchers render", "vouchers render-pdf"]
    );
}

/// The path is where a name comes from; the document is where it is overruled.
/// `x-cli-group` and `x-cli-command` are the adopter's say, written in the
/// same Overlay as every other correction.
#[test]
fn the_document_may_name_its_own_group_and_command() {
    let placed = placements(&synthetic(
        "  /vouchers/{id}/render:\n\
         \x20   get:\n\
         \x20     operationId: renderVoucher\n\
         \x20     x-cli-group: reports\n\
         \x20     x-cli-command: pdf\n\
         \x20     responses: { \"200\": { description: OK } }\n\
         \x20 /contacts:\n\
         \x20   post: { operationId: createContact, responses: { \"201\": { description: OK } } }\n",
    ));
    assert_eq!(placed, ["reports pdf", "contacts create"]);
}

/// A marker that is there and is not a name is the document saying something
/// this crate has no reading for — refused, rather than passed over in favour
/// of the name it was meant to override.
#[test]
fn a_marker_that_is_not_a_name_is_refused() {
    let error = Document::load(
        &synthetic(
            "  /vouchers:\n\
             \x20   get:\n\
             \x20     operationId: listVouchers\n\
             \x20     x-cli-command: [a, b]\n\
             \x20     responses: { \"200\": { description: OK } }\n",
        ),
        &[],
    )
    .expect_err("a list is not a name");
    assert_eq!(
        error.to_string(),
        "listVouchers: `x-cli-command` is not a string"
    );
}

/// Every way a gate can be wrong, refused while the document is reduced and
/// naming the operation and the word.
///
/// A gate that reached a shipped binary would be a flag somebody is about to
/// type, so all of this is the adopter's failure at bless time rather than a
/// user's at the prompt.
#[test]
fn a_gate_the_command_line_cannot_offer_is_refused_by_name() {
    let refused = |method: &str, marker: &str| {
        let paths = format!(
            "  /vouchers/{{id}}/enshrine:\n\
             \x20   {method}:\n\
             \x20     operationId: enshrineVoucher\n\
             \x20     x-cli-gates: {marker}\n\
             \x20     responses: {{ \"200\": {{ description: OK }} }}\n"
        );
        Document::load(&synthetic(&paths), &[])
            .expect_err("the document names a gate it cannot offer")
            .to_string()
    };

    // One word where a list goes would otherwise be no gate at all, which is
    // the one outcome a default-closed gate must never reach by accident.
    assert_eq!(
        refused("post", "enshrine"),
        "enshrineVoucher: `x-cli-gates` is not a list of names"
    );
    assert_eq!(
        refused("post", "[3]"),
        "enshrineVoucher: `x-cli-gates` is not a list of names"
    );
    assert_eq!(
        refused("post", "[\"???\"]"),
        "the x-cli-gates `???` does not kebab-case into [a-z0-9-]"
    );
    assert_eq!(
        refused("post", "[commit]"),
        "enshrineVoucher: the gate `commit` is one of the flags every subcommand \
         already spends"
    );
    assert_eq!(
        refused("post", "[enshrine, enshrine]"),
        "enshrineVoucher: the gate `enshrine` is named twice"
    );
    // A read runs on sight, so there is nothing for a gate to hold back: the
    // document is saying two things at once and does not say which it meant.
    assert_eq!(
        refused("get", "[enshrine]"),
        "enshrineVoucher: a read stands behind no gate, and this one names \
         `enshrine`; mark the operation `x-cli-writes: true` or drop the gate"
    );
}

/// A gate's flag is claimed before the document's own names are, so a body
/// field the vendor happens to spell like one moves aside instead of shadowing
/// the word standing in front of the hazard.
#[test]
fn a_body_field_that_collides_with_a_gate_moves_aside() {
    let doc = Document::load(
        &synthetic(
            "  /vouchers/{id}/enshrine:\n\
             \x20   post:\n\
             \x20     operationId: enshrineVoucher\n\
             \x20     x-cli-gates: [enshrine]\n\
             \x20     requestBody:\n\
             \x20       content:\n\
             \x20         application/json:\n\
             \x20           schema:\n\
             \x20             type: object\n\
             \x20             properties:\n\
             \x20               enshrine: { type: string }\n\
             \x20     responses: { \"200\": { description: OK } }\n",
        ),
        &[],
    )
    .expect("a document whose body field is spelled like its gate");

    let op = doc.get("enshrineVoucher").unwrap();
    let Body::JsonFields(fields) = op.body() else {
        panic!("enshrineVoucher takes a flat JSON body");
    };
    let field = fields.iter().find(|f| f.name() == "enshrine").unwrap();
    assert_eq!(field.flag(), "body-enshrine");
    assert!(field.renamed(), "and it says so in its help line");
    // Both flags are on the subcommand, which they could not be if one had
    // shadowed the other: clap panics on a duplicate name, and this is where.
    tree::command(op).debug_assert();
}

/// An override that will not reduce to a command name is rejected rather than
/// mangled, and the message says which of the document's own words to look at.
#[test]
fn an_override_that_is_not_spellable_names_itself() {
    let error = Document::load(
        &synthetic(
            "  /vouchers:\n\
             \x20   get:\n\
             \x20     operationId: listVouchers\n\
             \x20     x-cli-group: \"???\"\n\
             \x20     responses: { \"200\": { description: OK } }\n",
        ),
        &[],
    )
    .expect_err("`???` is not a name");
    assert_eq!(
        error.to_string(),
        "the x-cli-group `???` does not kebab-case into [a-z0-9-]"
    );
}