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
//! The exact JSON each model type emits.
//!
//! `properties.rs` proves that `parse ∘ emit` is the identity. That is not the
//! same guarantee: a misspelled field name round-trips perfectly, because
//! nothing in the model sets `deny_unknown_fields` and the flattened
//! `Extensions` absorbs whatever it does not recognise. A round trip proves
//! nothing was lost. These cases are what hold the shape to the specification.
//!
//! One case per type with a wire form, and
//! [`every_wire_type_has_a_case`] counts them against the source so a type
//! added without one fails the build.

// `every_keyword` pins sixty keys in one `json!`, and the macro recurses once
// per key.
#![recursion_limit = "256"]

use std::collections::BTreeSet;

use kynos_openapi::{
    Callback, ComponentName, Components, Contact, Discriminator, Document, Encoding, EncodingStyle,
    Example, Extensions, ExternalDocumentation, Header, HeaderStyle, Info, License, Link, Map,
    MediaType, Method, OAuthFlow, OAuthFlows, Operation, Parameter, ParameterIn, PathItem,
    PathTemplate, Paths, Ref, RefOr, RequestBody, Response, Responses, Schema, SchemaObject,
    SecurityRequirement, SecurityScheme, Server, ServerVariable, SpecVersion, Style, Tag, Xml,
    model::schema::types::{SchemaType, TypeSet},
};
use serde::Serialize;
use serde_json::{Value, json};

/// A type, a value of it, and the JSON that value must produce.
struct Case {
    type_name: &'static str,
    emitted: Value,
    expected: Value,
}

fn case<T: Serialize>(type_name: &'static str, value: &T, expected: Value) -> Case {
    Case {
        type_name,
        emitted: serde_json::to_value(value).expect("every model value is representable"),
        expected,
    }
}

fn schema() -> Schema {
    Schema::of_type(SchemaType::String)
}

// --- Info, servers, tags -------------------------------------------------

fn metadata_cases() -> Vec<Case> {
    vec![
        case(
            "Info",
            &Info::new("Orders", "1.0.0"),
            json!({ "title": "Orders", "version": "1.0.0" }),
        ),
        case(
            "Contact",
            &Contact {
                name: Some("API Team".to_owned()),
                url: None,
                email: Some("api@example.com".to_owned()),
                extensions: Extensions::new(),
            },
            json!({ "name": "API Team", "email": "api@example.com" }),
        ),
        // The three shapes the specification allows, one of which is the whole
        // reason `License` holds a private enum rather than two `Option`s.
        case(
            "License",
            &License::spdx("MIT", "MIT"),
            json!({ "name": "MIT", "identifier": "MIT" }),
        ),
        case(
            "ExternalDocumentation",
            &ExternalDocumentation::new("https://example.com/docs"),
            json!({ "url": "https://example.com/docs" }),
        ),
        case(
            "Server",
            &Server::new("https://example.com/{region}").with_variable(
                "region",
                ServerVariable {
                    enumeration: Some(vec!["eu".to_owned(), "us".to_owned()]),
                    default_value: "eu".to_owned(),
                    description: None,
                    extensions: Extensions::new(),
                },
            ),
            json!({
                "url": "https://example.com/{region}",
                "variables": { "region": { "enum": ["eu", "us"], "default": "eu" } }
            }),
        ),
        case(
            "ServerVariable",
            &ServerVariable {
                enumeration: None,
                default_value: "eu".to_owned(),
                description: None,
                extensions: Extensions::new(),
            },
            json!({ "default": "eu" }),
        ),
        case("Tag", &Tag::new("orders"), json!({ "name": "orders" })),
        case(
            "Extensions",
            &{
                let mut extensions = Extensions::new();
                extensions.insert("x-internal-id", 7);
                extensions
            },
            json!({ "x-internal-id": 7 }),
        ),
    ]
}

// --- Schemas -------------------------------------------------------------

fn schema_cases() -> Vec<Case> {
    vec![
        // `Schema` is untagged over a bool and an object, so the boolean form
        // has to emit a bare `true` rather than a wrapper.
        case("Schema", &Schema::any(), json!(true)),
        // Every keyword at once rather than a representative one. See
        // [`every_keyword`] for why one is not enough.
        {
            let (object, expected) = every_keyword();
            case("SchemaObject", &object, expected)
        },
        case("SchemaType", &SchemaType::Integer, json!("integer")),
        // Untagged again: one type is a string, several are an array. This is
        // how 3.1 spells nullability, and why `nullable` is never emitted.
        case(
            "TypeSet",
            &TypeSet::One(SchemaType::String),
            json!("string"),
        ),
        case(
            "Discriminator",
            &Discriminator::new("petType"),
            json!({ "propertyName": "petType" }),
        ),
        case(
            "Xml",
            &Xml {
                name: Some("order".to_owned()),
                ..Xml::default()
            },
            json!({ "name": "order" }),
        ),
    ]
}

// --- References ----------------------------------------------------------

fn reference_cases() -> Vec<Case> {
    vec![
        case(
            "Ref",
            &Ref::schema("Order"),
            json!({ "$ref": "#/components/schemas/Order" }),
        ),
        // `RefOr` is untagged with `Ref` first, so a reference emits as the
        // bare Reference Object rather than as a tagged wrapper.
        case(
            "RefOr",
            &RefOr::<Schema>::Ref(Ref::schema("Order")),
            json!({ "$ref": "#/components/schemas/Order" }),
        ),
        case(
            "ComponentName",
            &ComponentName::new("Order").expect("valid"),
            json!("Order"),
        ),
    ]
}

// --- Parameters and headers ----------------------------------------------

fn parameter_cases() -> Vec<Case> {
    vec![
        case(
            "Parameter",
            &Parameter::path("id", schema()),
            json!({
                "name": "id",
                "in": "path",
                "required": true,
                "schema": { "type": "string" }
            }),
        ),
        case("ParameterIn", &ParameterIn::Query, json!("query")),
        case("Style", &Style::DeepObject, json!("deepObject")),
        case("HeaderStyle", &HeaderStyle::Simple, json!("simple")),
        case(
            "EncodingStyle",
            &EncodingStyle::SpaceDelimited,
            json!("spaceDelimited"),
        ),
        case(
            "Header",
            &Header::new(schema()),
            json!({ "schema": { "type": "string" } }),
        ),
    ]
}

// --- Bodies and content --------------------------------------------------

fn content_cases() -> Vec<Case> {
    vec![
        case(
            "MediaType",
            &MediaType::new(schema()),
            json!({ "schema": { "type": "string" } }),
        ),
        case(
            "Encoding",
            &Encoding::new("text/plain"),
            json!({ "contentType": "text/plain" }),
        ),
        case(
            "RequestBody",
            &RequestBody::json(schema()),
            json!({
                "content": { "application/json": { "schema": { "type": "string" } } },
                "required": true
            }),
        ),
        case(
            "Example",
            &Example::new(json!("sample")),
            json!({ "value": "sample" }),
        ),
    ]
}

// --- Responses -----------------------------------------------------------

fn response_cases() -> Vec<Case> {
    vec![
        case(
            "Response",
            &Response::new("ok"),
            json!({ "description": "ok" }),
        ),
        // `Responses` is a hand-written map: status keys, `default`, and `x-`
        // extensions, with nothing else accepted on the way back in.
        case(
            "Responses",
            &Responses::new().with(200, Response::new("ok")),
            json!({ "200": { "description": "ok" } }),
        ),
        case(
            "Link",
            &Link::to_operation("getOrder").with_parameter("orderId", json!("$response.body#/id")),
            json!({
                "operationId": "getOrder",
                "parameters": { "orderId": "$response.body#/id" }
            }),
        ),
    ]
}

// --- Paths and operations ------------------------------------------------

fn path_cases() -> Vec<Case> {
    let operation = || {
        Operation::new("getOrder").with_responses(Responses::new().with(200, Response::new("ok")))
    };

    vec![
        case("Method", &Method::Delete, json!("delete")),
        case(
            "PathTemplate",
            &PathTemplate::parse("/orders/{id}").expect("valid"),
            json!("/orders/{id}"),
        ),
        case(
            "Operation",
            &operation(),
            json!({
                "operationId": "getOrder",
                "responses": { "200": { "description": "ok" } }
            }),
        ),
        case(
            "PathItem",
            &PathItem::new().with_operation(Method::Get, operation()),
            json!({
                "get": {
                    "operationId": "getOrder",
                    "responses": { "200": { "description": "ok" } }
                }
            }),
        ),
        case(
            "Paths",
            &{
                let mut paths = Paths::new();
                paths.insert(
                    &PathTemplate::parse("/orders").expect("valid"),
                    PathItem::new().with_operation(Method::Get, operation()),
                );
                paths
            },
            json!({
                "/orders": {
                    "get": {
                        "operationId": "getOrder",
                        "responses": { "200": { "description": "ok" } }
                    }
                }
            }),
        ),
        case(
            "Callback",
            &Callback::new().with(
                "{$request.body#/callbackUrl}",
                PathItem::new().with_operation(Method::Post, operation()),
            ),
            json!({
                "{$request.body#/callbackUrl}": {
                    "post": {
                        "operationId": "getOrder",
                        "responses": { "200": { "description": "ok" } }
                    }
                }
            }),
        ),
    ]
}

// --- Security ------------------------------------------------------------

fn security_cases() -> Vec<Case> {
    vec![
        // Internally tagged on `type`, with the wire spellings the
        // specification gives rather than the Rust ones.
        case(
            "SecurityScheme",
            &SecurityScheme::api_key_header("X-Api-Key"),
            json!({ "type": "apiKey", "name": "X-Api-Key", "in": "header" }),
        ),
        case(
            "SecurityRequirement",
            &SecurityRequirement::scoped("OAuth", ["read:orders"]),
            json!({ "OAuth": ["read:orders"] }),
        ),
        case(
            "OAuthFlow",
            &OAuthFlow::new([("read:orders".to_owned(), "Read orders".to_owned())])
                .with_token_url("https://example.com/token"),
            json!({
                "tokenUrl": "https://example.com/token",
                "scopes": { "read:orders": "Read orders" }
            }),
        ),
        case(
            "OAuthFlows",
            &OAuthFlows {
                client_credentials: Some(
                    OAuthFlow::new([("read:orders".to_owned(), "Read orders".to_owned())])
                        .with_token_url("https://example.com/token"),
                ),
                ..OAuthFlows::default()
            },
            json!({
                "clientCredentials": {
                    "tokenUrl": "https://example.com/token",
                    "scopes": { "read:orders": "Read orders" }
                }
            }),
        ),
    ]
}

// --- Document and components ---------------------------------------------

fn document_cases() -> Vec<Case> {
    vec![
        case(
            "Components",
            &{
                let mut components = Components::new();
                components.insert_schema(&ComponentName::new("Order").expect("valid"), schema());
                components
            },
            json!({ "schemas": { "Order": { "type": "string" } } }),
        ),
        case(
            "Document",
            &Document::new(SpecVersion::V3_1, Info::new("Orders", "1.0.0")),
            json!({
                "openapi": "3.1.2",
                "info": { "title": "Orders", "version": "1.0.0" },
                // Always present, even empty: a document carrying none of
                // `paths`, `components` or `webhooks` violates a MUST in every
                // version, and this is the one of the three that is always
                // true of an API.
                "paths": {}
            }),
        ),
    ]
}

fn cases() -> Vec<Case> {
    let mut cases = metadata_cases();
    cases.extend(schema_cases());
    cases.extend(reference_cases());
    cases.extend(parameter_cases());
    cases.extend(content_cases());
    cases.extend(response_cases());
    cases.extend(path_cases());
    cases.extend(security_cases());
    cases.extend(document_cases());
    cases
}

#[test]
fn each_type_emits_the_shape_the_specification_gives_it() {
    for Case {
        type_name,
        emitted,
        expected,
    } in cases()
    {
        assert_eq!(emitted, expected, "`{type_name}` emitted the wrong shape");
    }
}

/// Every model type with a wire form has a case above.
///
/// The set comes from the source rather than from a second list, so a type
/// added without a case fails here rather than going uncovered. `Serialize` is
/// the discriminator because it is what `docs/testing.md` uses to recognise the
/// kind: a type without it has no wire shape of its own to pin.
#[test]
fn every_wire_type_has_a_case() {
    let declared = wire_types_in_source();
    let covered: BTreeSet<String> = cases()
        .iter()
        .map(|case| case.type_name.to_owned())
        .collect();

    let uncovered: Vec<&String> = declared.difference(&covered).collect();
    let unknown: Vec<&String> = covered.difference(&declared).collect();

    assert!(
        uncovered.is_empty() && unknown.is_empty(),
        "types with no case: {uncovered:?}; cases naming no type: {unknown:?}"
    );
}

/// Types under `src/model/` that derive `Serialize`.
///
/// Reading the crate's own committed source keeps this hermetic — there is no
/// shared state and no ordering to depend on — and `CARGO_MANIFEST_DIR` keeps
/// it independent of where the suite is run from.
fn wire_types_in_source() -> BTreeSet<String> {
    fn walk(directory: &std::path::Path, found: &mut BTreeSet<String>) {
        for entry in std::fs::read_dir(directory).expect("the crate's own source is readable") {
            let path = entry.expect("readable entry").path();
            if path.is_dir() {
                walk(&path, found);
                continue;
            }
            if path.extension().is_none_or(|extension| extension != "rs") {
                continue;
            }

            let source = std::fs::read_to_string(&path).expect("readable source");
            let lines: Vec<&str> = source.lines().collect();

            // A hand-written implementation is as much a wire form as a
            // derived one. Reading only the derive made this depend on prose:
            // `Responses` was counted because its doc comment happens to say
            // "Serializes", and `Paths` and `Callback` were not counted at all
            // once they grew implementations of their own.
            for line in &lines {
                let Some(rest) = line.strip_prefix("impl Serialize for ") else {
                    continue;
                };
                found.insert(
                    rest.chars()
                        .take_while(|c| c.is_alphanumeric() || *c == '_')
                        .collect(),
                );
            }

            for (index, line) in lines.iter().enumerate() {
                let Some(rest) = line
                    .strip_prefix("pub struct ")
                    .or_else(|| line.strip_prefix("pub enum "))
                else {
                    continue;
                };
                let name: String = rest
                    .chars()
                    .take_while(|c| c.is_alphanumeric() || *c == '_')
                    .collect();

                // The derive sits in the attribute block immediately above.
                let derives_serialize = lines[..index]
                    .iter()
                    .rev()
                    .take_while(|above| {
                        above.starts_with('#') || above.starts_with("//") || above.trim().is_empty()
                    })
                    .any(|above| above.contains("Serialize"));

                if derives_serialize {
                    found.insert(name);
                }
            }
        }
    }

    let mut found = BTreeSet::new();
    walk(
        &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/model"),
        &mut found,
    );
    found
}

// --- The round-trip gap `nfr.md` records ---------------------------------
//
// Excluded from the generators in `support/`, which keeps the round-trip
// property honest but leaves the behaviour unrecorded. This is the record. It
// asserts what happens *today*, so closing the gap turns a test red on purpose
// rather than passing in silence.

/// A JSON `null` survives a round trip wherever the model admits a value.
///
/// It used not to. `Option<Value>` folds a present `null` back into `None` on
/// the way in, so `Some(Value::Null)` was written faithfully and read back as
/// absent — and JSON `null` is a legal `example`, a legal `default` and a legal
/// `const`, which made a description using one silently different after a
/// round trip.
///
/// Every site is asserted rather than one. The previous single case was right
/// to say that one records the *shape* of a gap; a fix is the other way round,
/// because a site that kept the old behaviour is exactly what a single case
/// would not see.
// `SchemaObject::example` is deprecated in favour of `examples` and is still a
// field a description can carry, so it is still a field a round trip has to
// keep. Deprecated is not the same as gone.
#[expect(deprecated)]
#[test]
fn a_null_survives_a_round_trip_at_every_site() {
    fn round_trip<T>(original: &T, expected_json: &str) -> T
    where
        T: serde::Serialize + serde::de::DeserializeOwned,
    {
        let json = serde_json::to_string(original).expect("serializable");
        assert_eq!(json, expected_json, "the null is written out");
        serde_json::from_str(&json).expect("what the model emits, it reads")
    }

    let example = Example::new(Value::Null);
    assert_eq!(
        round_trip(&example, r#"{"value":null}"#),
        example,
        "an Example Object's `value`"
    );

    let schema = SchemaObject {
        const_value: Some(Value::Null),
        ..SchemaObject::default()
    };
    assert_eq!(
        round_trip(&schema, r#"{"const":null}"#),
        schema,
        "a Schema Object's `const`"
    );

    let schema = SchemaObject {
        default: Some(Value::Null),
        ..SchemaObject::default()
    };
    assert_eq!(
        round_trip(&schema, r#"{"default":null}"#),
        schema,
        "a Schema Object's `default`"
    );

    let schema = SchemaObject {
        example: Some(Value::Null),
        ..SchemaObject::default()
    };
    assert_eq!(
        round_trip(&schema, r#"{"example":null}"#),
        schema,
        "a Schema Object's `example`"
    );

    let mut link = Link::to_operation("getOrder");
    link.request_body = Some(Value::Null);
    assert_eq!(
        round_trip(&link, r#"{"operationId":"getOrder","requestBody":null}"#),
        link,
        "a Link Object's `requestBody`"
    );

    let parameter =
        Parameter::new("id", ParameterIn::Query, Schema::any()).with_example(Value::Null);
    assert_eq!(
        round_trip(
            &parameter,
            r#"{"name":"id","in":"query","schema":true,"example":null}"#
        ),
        parameter,
        "a Parameter Object's `example`"
    );

    let header = Header::new(Schema::any()).with_example(Value::Null);
    assert_eq!(
        round_trip(&header, r#"{"schema":true,"example":null}"#),
        header,
        "a Header Object's `example`"
    );

    let media_type = MediaType::new(Schema::any()).with_example(Value::Null);
    assert_eq!(
        round_trip(&media_type, r#"{"schema":true,"example":null}"#),
        media_type,
        "a Media Type Object's `example`"
    );
}

/// Every object the specification lets carry an extension round-trips one.
///
/// `references/3.1.2.md` says "This object MAY be extended with Specification
/// Extensions" of the Paths Object (`:790`), the Callback Object (`:2154`), the
/// Discriminator Object (`:3337`) and the XML Object (`:3499`). Four objects
/// modelled it and four did not, and the two failure modes differ:
/// `Xml` and `Discriminator` have no catch-all, so serde drops an `x-` member
/// on the floor; `Paths` and `Callback` are `#[serde(transparent)]` over a bare
/// map, so an `x-` member whose value is not an object of the map's type makes
/// a **legal document fail to parse at all**.
///
/// The values here are deliberately not objects. An object-valued extension on
/// `Paths` happens to parse — as an empty `PathItem` — which is the shape that
/// would let a narrower test pass while the gap stayed open.
#[test]
fn every_extensible_object_round_trips_an_extension() {
    fn round_trips<T>(name: &str, json: &str)
    where
        T: serde::Serialize + serde::de::DeserializeOwned,
    {
        let parsed: T = serde_json::from_str(json)
            .unwrap_or_else(|error| panic!("{name} must read an `x-` member: {error}"));
        assert_eq!(
            serde_json::to_string(&parsed).expect("serializable"),
            json,
            "{name} must write the `x-` member back"
        );
    }

    round_trips::<Paths>("a Paths Object", r#"{"x-audience":"internal"}"#);
    round_trips::<Callback>("a Callback Object", r#"{"x-audience":"internal"}"#);
    round_trips::<Discriminator>(
        "a Discriminator Object",
        r#"{"propertyName":"petType","x-audience":"internal"}"#,
    );
    round_trips::<Xml>(
        "an XML Object",
        r#"{"name":"order","x-audience":"internal"}"#,
    );
}

/// A `PathItem` carrying both `$ref` and siblings loses the siblings.
///
/// `RefOr` is untagged with `Ref` first, so anything carrying `$ref`
/// deserializes as a reference and its sibling fields are dropped. Kynos never
/// emits one, but the type permits constructing it, so the model can hold a
/// value it cannot write down.
#[test]
fn a_path_item_with_a_ref_and_siblings_loses_its_siblings() {
    let mut item = PathItem::new().with_operation(
        Method::Get,
        Operation::new("getOrder").with_responses(Responses::new().with(200, Response::new("ok"))),
    );
    item.reference = Some("#/components/pathItems/Shared".to_owned());

    let original = RefOr::Item(item);
    let json = serde_json::to_string(&original).expect("serializable");
    let parsed: RefOr<PathItem> = serde_json::from_str(&json).expect("reads back");

    assert!(
        parsed.is_ref(),
        "the item read back as a reference, not as itself"
    );
    assert_ne!(parsed, original, "so the operation did not survive");
}

// --- Every schema keyword ------------------------------------------------

/// A `SchemaObject` with every keyword set, beside the exact JSON it emits.
///
/// `SchemaObject` carries sixty keywords and the case in `schema_cases`
/// pins one of them. The other fifty-nine were spelled by a `serde(rename)`
/// nothing read: `unknown_keywords` is `#[serde(flatten)]`, so a misspelled
/// rename is written under the wrong key, read back into the flattened map,
/// and compares equal through the round-trip property. The keyword simply
/// stops existing, and every test in the crate still passes.
///
/// Each value is distinguishable from its neighbours so that two renames
/// swapped between adjacent fields do not cancel out.
fn every_keyword() -> (SchemaObject, Value) {
    (every_keyword_set(), every_keyword_emitted())
}

/// The value half of [`every_keyword`].
#[expect(
    deprecated,
    reason = "`example` is superseded by `examples` and still emits, so its spelling is still \
              part of the wire shape; a deprecated keyword nobody pins is one that can be \
              renamed silently"
)]
fn every_keyword_set() -> SchemaObject {
    let one = || [("Node".to_owned(), Schema::any())].into_iter().collect();

    SchemaObject {
        schema_dialect: Some("https://json-schema.org/draft/2020-12/schema".to_owned()),
        id: Some("https://example.com/order.json".to_owned()),
        reference: Some("#/components/schemas/Order".to_owned()),
        anchor: Some("order".to_owned()),
        dynamic_ref: Some("#node".to_owned()),
        dynamic_anchor: Some("node".to_owned()),
        comment: Some("not part of the description".to_owned()),
        defs: one(),
        all_of: Some(vec![Schema::any()]),
        any_of: Some(vec![Schema::any(), Schema::never()]),
        one_of: Some(vec![Schema::never()]),
        not: Some(Box::new(Schema::never())),
        if_schema: Some(Box::new(Schema::any())),
        then_schema: Some(Box::new(Schema::never())),
        else_schema: Some(Box::new(Schema::any())),
        dependent_schemas: one(),
        prefix_items: Some(vec![Schema::never()]),
        items: Some(Box::new(Schema::any())),
        contains: Some(Box::new(Schema::never())),
        properties: one(),
        pattern_properties: one(),
        additional_properties: Some(Box::new(Schema::never())),
        property_names: Some(Box::new(Schema::any())),
        unevaluated_items: Some(Box::new(Schema::never())),
        unevaluated_properties: Some(Box::new(Schema::any())),
        ty: Some(TypeSet::One(SchemaType::Object)),
        const_value: Some(json!("fixed")),
        enumeration: Some(vec![json!("a"), json!("b")]),
        multiple_of: Some(2.5),
        maximum: Some(10.5),
        exclusive_maximum: Some(11.5),
        minimum: Some(1.5),
        exclusive_minimum: Some(0.5),
        max_length: Some(64),
        min_length: Some(1),
        pattern: Some("^order-".to_owned()),
        max_items: Some(9),
        min_items: Some(2),
        unique_items: Some(true),
        max_contains: Some(4),
        min_contains: Some(3),
        max_properties: Some(6),
        min_properties: Some(5),
        required: Some(vec!["id".to_owned()]),
        dependent_required: [("id".to_owned(), vec!["revision".to_owned()])]
            .into_iter()
            .collect(),
        format: Some("uuid".to_owned()),
        content_encoding: Some("base64".to_owned()),
        content_media_type: Some("application/json".to_owned()),
        content_schema: Some(Box::new(Schema::any())),
        title: Some("Order".to_owned()),
        description: Some("A placed order.".to_owned()),
        default: Some(json!({ "id": "none" })),
        deprecated: Some(true),
        read_only: Some(true),
        write_only: Some(false),
        examples: Some(vec![json!("order-1")]),
        discriminator: Some(Discriminator::new("petType")),
        xml: Some(Xml {
            name: Some("order".to_owned()),
            ..Xml::default()
        }),
        external_docs: Some(ExternalDocumentation::new("https://example.com/docs")),
        example: Some(json!("order-0")),
        // Left empty on purpose: it is `#[serde(flatten)]`, so anything here
        // would emit keys that are not keywords and the count below would stop
        // meaning what it says.
        unknown_keywords: Map::default(),
    }
}

/// The JSON half of [`every_keyword`].
fn every_keyword_emitted() -> Value {
    json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://example.com/order.json",
        "$ref": "#/components/schemas/Order",
        "$anchor": "order",
        "$dynamicRef": "#node",
        "$dynamicAnchor": "node",
        "$comment": "not part of the description",
        "$defs": { "Node": true },
        "allOf": [true],
        "anyOf": [true, false],
        "oneOf": [false],
        "not": false,
        "if": true,
        "then": false,
        "else": true,
        "dependentSchemas": { "Node": true },
        "prefixItems": [false],
        "items": true,
        "contains": false,
        "properties": { "Node": true },
        "patternProperties": { "Node": true },
        "additionalProperties": false,
        "propertyNames": true,
        "unevaluatedItems": false,
        "unevaluatedProperties": true,
        "type": "object",
        "const": "fixed",
        "enum": ["a", "b"],
        "multipleOf": 2.5,
        "maximum": 10.5,
        "exclusiveMaximum": 11.5,
        "minimum": 1.5,
        "exclusiveMinimum": 0.5,
        "maxLength": 64,
        "minLength": 1,
        "pattern": "^order-",
        "maxItems": 9,
        "minItems": 2,
        "uniqueItems": true,
        "maxContains": 4,
        "minContains": 3,
        "maxProperties": 6,
        "minProperties": 5,
        "required": ["id"],
        "dependentRequired": { "id": ["revision"] },
        "format": "uuid",
        "contentEncoding": "base64",
        "contentMediaType": "application/json",
        "contentSchema": true,
        "title": "Order",
        "description": "A placed order.",
        "default": { "id": "none" },
        "deprecated": true,
        "readOnly": true,
        "writeOnly": false,
        "examples": ["order-1"],
        "discriminator": { "propertyName": "petType" },
        "xml": { "name": "order" },
        "externalDocs": { "url": "https://example.com/docs" },
        "example": "order-0",
    })
}

/// The pinned keys, counted against the fields the struct declares.
///
/// Without this, a keyword added to `SchemaObject` is a keyword with no pinned
/// spelling — which is the state this test was written to end.
#[test]
fn every_schema_keyword_has_a_pinned_spelling() {
    const SOURCE: &str = include_str!("../src/model/schema/object.rs");

    let body = SOURCE
        .split_once("pub struct SchemaObject {")
        .expect("the struct is declared in this file")
        .1;
    // One `pub` field per keyword, less the flattened catch-all, which is not
    // a keyword and emits no key of its own.
    let declared = body
        .lines()
        .filter(|line| line.trim_start().starts_with("pub "))
        .count()
        - 1;

    let (_, expected) = every_keyword();
    let pinned = expected.as_object().expect("a JSON object").len();

    assert_eq!(
        pinned, declared,
        "`SchemaObject` declares {declared} keyword(s) and {pinned} have a pinned spelling; a \
         keyword added without one is written under whatever name its rename says, absorbed by \
         the flattened `unknown_keywords` on the way back, and round-trips perfectly while \
         meaning nothing"
    );
}