typed-openapi 0.0.1

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
//! 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, 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);
}

#[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 }
    ));
    assert!(matches!(
        body("uploadDocument"),
        Body::Opaque { ref media_type, .. } if media_type == "form-data"
    ));
    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!(update.param("id").unwrap().flag(), "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"
    );
}

/// 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}");
}

/// 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"
    );
}

/// 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-]"
    );
}