oas3-gen 0.26.2

A rust type generator for OpenAPI v3.1.x specification.
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
use std::collections::HashMap;

use super::support::{
  assert_contains, assert_contains_all, assert_not_contains, assert_occurs_at_least, generate_types, make_orchestrator,
  make_orchestrator_with_customizations, make_orchestrator_with_ops, parse_spec, string_set,
};
use crate::generator::ast::{ClientRootNode, StructToken};

type PresenceCheck<'a> = (&'a str, usize, &'a str);
type AbsenceCheck<'a> = (&'a str, &'a str);
type EnumDedupCase<'a> = (&'a str, Vec<PresenceCheck<'a>>, Vec<AbsenceCheck<'a>>);

#[test]
fn test_metadata_and_header_generation() {
  let spec = parse_spec(include_str!("../../../fixtures/basic_api.json"));
  let metadata = ClientRootNode::builder()
    .name(StructToken::new("PembrokeApiClient"))
    .info(&spec.info)
    .servers(&spec.servers)
    .build();

  assert_eq!(metadata.title, "Basic Test API", "title mismatch");
  assert_eq!(metadata.version, "1.0.0", "version mismatch");
  assert_eq!(
    metadata.description.as_deref(),
    Some("A test API.\nWith multiple lines.\nFor testing documentation."),
    "description mismatch"
  );

  let orchestrator = make_orchestrator(spec, false);
  let output = generate_types(&orchestrator, "/path/to/spec.json");
  assert_contains_all(
    &output.code,
    &[
      ("AUTO-GENERATED CODE - DO NOT EDIT!", "auto-generated marker"),
      ("//! Basic Test API", "title in header"),
      ("//! Source: /path/to/spec.json", "source path"),
      ("//! Version: 1.0.0", "version in header"),
      ("//! A test API.", "description in header"),
      ("#![allow(clippy::doc_markdown)]", "clippy allow"),
      (
        "A test API.\n//! With multiple lines.\n//! For testing documentation.",
        "multiline description formatting",
      ),
    ],
  );
}

#[test]
fn test_operation_filtering() {
  let spec_json = include_str!("../../../fixtures/operation_filtering.json");
  let excluded = string_set(&["admin_action"]);

  let full_orchestrator = make_orchestrator(parse_spec(spec_json), false);
  let full = generate_types(&full_orchestrator, "test.json");

  let filtered_orchestrator = make_orchestrator_with_ops(parse_spec(spec_json), false, None, Some(&excluded));
  let filtered = generate_types(&filtered_orchestrator, "test.json");

  assert_eq!(full.operations_converted, 3, "full spec should have 3 ops");
  assert_eq!(
    filtered.operations_converted, 2,
    "excluded admin_action should leave 2 ops"
  );
  assert_not_contains(
    &filtered.code,
    "admin_action",
    "admin_action should be excluded from generated code",
  );
  assert_contains(
    &full.code,
    "AdminActionResponse",
    "full code should contain AdminActionResponse",
  );
  assert_not_contains(
    &filtered.code,
    "AdminActionResponse",
    "filtered code should not contain AdminActionResponse",
  );
  assert_contains(
    &filtered.code,
    "UserList",
    "filtered code should still contain UserList",
  );
  assert_contains(&filtered.code, "User", "filtered code should still contain User");
}

#[test]
fn test_all_schemas_overrides_operation_filtering() {
  let spec_json = include_str!("../../../fixtures/operation_filtering.json");
  let only = string_set(&["list_users"]);

  let without_all_schemas_orchestrator = make_orchestrator_with_ops(parse_spec(spec_json), false, Some(&only), None);
  let without_all_schemas = generate_types(&without_all_schemas_orchestrator, "test.json");

  let with_all_schemas_orchestrator = make_orchestrator_with_ops(parse_spec(spec_json), true, Some(&only), None);
  let with_all_schemas = generate_types(&with_all_schemas_orchestrator, "test.json");

  assert_eq!(without_all_schemas.operations_converted, 1, "without all_schemas: 1 op");
  assert_eq!(with_all_schemas.operations_converted, 1, "with all_schemas: still 1 op");

  assert_contains(
    &without_all_schemas.code,
    "UserList",
    "without all_schemas should contain UserList",
  );
  assert_contains(
    &without_all_schemas.code,
    "User",
    "without all_schemas should contain User",
  );
  assert_not_contains(
    &without_all_schemas.code,
    "AdminResponse",
    "without all_schemas should not contain AdminResponse",
  );
  assert_not_contains(
    &without_all_schemas.code,
    "UnreferencedSchema",
    "without all_schemas should not contain UnreferencedSchema",
  );

  assert_contains_all(
    &with_all_schemas.code,
    &[
      ("UserList", "with all_schemas should contain UserList"),
      ("User", "with all_schemas should contain User"),
      ("AdminResponse", "with all_schemas should contain AdminResponse"),
      (
        "UnreferencedSchema",
        "with all_schemas should contain UnreferencedSchema",
      ),
    ],
  );

  assert_eq!(
    without_all_schemas.orphaned_schemas_count, 2,
    "without all_schemas: 2 orphaned"
  );
  assert_eq!(
    with_all_schemas.orphaned_schemas_count, 0,
    "with all_schemas: 0 orphaned"
  );
}

#[test]
fn test_content_types_generation() {
  let orchestrator = make_orchestrator(parse_spec(include_str!("../../../fixtures/content_types.json")), false);
  let output = generate_types(&orchestrator, "test.json");
  assert_contains_all(
    &output.code,
    &[
      (
        "json_with_diagnostics",
        "JSON handling for application/json should be generated",
      ),
      ("req.text().await?", "text handling for text/plain should be generated"),
      (
        "req.bytes().await?",
        "binary handling for image/png should be generated",
      ),
    ],
  );
}

#[test]
fn test_enum_deduplication() {
  let cases: [EnumDedupCase<'_>; 2] = [
    (
      include_str!("../../../fixtures/enum_deduplication.json"),
      vec![
        ("pub enum Status", 1, "Status enum should be defined exactly once"),
        ("pub status: Option<Status>", 1, "StructA should use Status"),
        (
          "status: Option<Status>",
          3,
          "StructA, StructB, and reordered StructC should all use Status",
        ),
      ],
      vec![(
        "pub enum StructCStatus",
        "Reordered enum values should still dedupe to the shared Status enum",
      )],
    ),
    (
      include_str!("../../../fixtures/relaxed_enum_deduplication.json"),
      vec![
        ("pub enum Status", 1, "Status enum should be defined"),
        ("pub enum ComplexStatusStatus", 1, "Outer enum should be defined"),
        ("Known(Status)", 1, "Outer enum should wrap Status"),
      ],
      vec![("pub enum ComplexStatusStatusKnown", "Inner enum should be deduplicated")],
    ),
  ];

  for (spec_json, presence_checks, absence_checks) in cases {
    let orchestrator = make_orchestrator(parse_spec(spec_json), true);
    let output = generate_types(&orchestrator, "test.json");
    for (pattern, expected_count, context) in presence_checks {
      assert_occurs_at_least(&output.code, pattern, expected_count, context);
    }
    for (pattern, context) in absence_checks {
      assert_not_contains(&output.code, pattern, context);
    }
  }
}

#[test]
fn preserves_schema_property_enum_and_collection_order() {
  let spec_json = r#"{
    "openapi": "3.1.0",
    "info": { "title": "Order API", "version": "1.0.0" },
    "paths": {},
    "components": {
      "schemas": {
        "Zebra": {
          "type": "object",
          "properties": {
            "zeta": { "type": "string" },
            "alpha": { "type": "string" }
          }
        },
        "Alpha": {
          "type": "string",
          "enum": ["third", "first", "second"]
        },
        "Beta": {
          "type": "object",
          "properties": {
            "second": { "type": "string" }
          }
        },
        "UniqueNames": {
          "type": "array",
          "uniqueItems": true,
          "items": { "type": "string" }
        },
        "Labels": {
          "type": "object",
          "additionalProperties": { "type": "string" }
        }
      }
    }
  }"#;

  let orchestrator = make_orchestrator(parse_spec(spec_json), true);
  let output = generate_types(&orchestrator, "order.json");

  assert_patterns_in_order(&output.code, &["pub struct Zebra", "pub enum Alpha", "pub struct Beta"]);
  assert_patterns_in_order(&output.code, &["pub zeta", "pub alpha"]);
  assert_patterns_in_order(&output.code, &["Third", "First", "Second"]);
  assert_contains(
    &output.code,
    "pub type UniqueNames = indexmap::IndexSet<String>;",
    "uniqueItems arrays should preserve insertion order",
  );
  assert_contains(
    &output.code,
    "indexmap::IndexMap<String, String>",
    "additionalProperties maps should preserve insertion order",
  );
}

#[test]
fn test_customization_generates_serde_as_attributes() {
  let spec_json = r#"{
    "openapi": "3.0.0",
    "info": { "title": "Test API", "version": "1.0.0" },
    "paths": {},
    "components": {
      "schemas": {
        "Frappe": {
          "type": "object",
          "properties": {
            "id": { "type": "string" },
            "created_at": { "type": "string", "format": "date-time" },
            "updated_at": { "type": "string", "format": "date-time" }
          },
          "required": ["id", "created_at"]
        }
      }
    }
  }"#;

  let customizations = HashMap::from([("date_time".to_string(), "crate::MyDateTime".to_string())]);
  let orchestrator = make_orchestrator_with_customizations(parse_spec(spec_json), true, customizations);
  let output = generate_types(&orchestrator, "test.json");

  assert_contains(
    &output.code,
    "#[serde_with::serde_as]",
    "Struct should have #[serde_with::serde_as] outer attribute",
  );
  assert_contains(
    &output.code,
    r#"#[serde_as(as = "crate::MyDateTime")]"#,
    "required field should have serde_as attribute with custom type",
  );
  assert_contains(
    &output.code,
    r#"#[serde_as(as = "Option<crate::MyDateTime>")]"#,
    "optional field should have serde_as attribute wrapped in Option",
  );
}

fn assert_patterns_in_order(code: &str, patterns: &[&str]) {
  let mut last = 0;
  for pattern in patterns {
    let next = code[last..]
      .find(pattern)
      .map_or_else(|| panic!("missing ordered pattern '{pattern}'"), |idx| last + idx);
    assert!(next >= last, "pattern '{pattern}' appeared out of order");
    last = next + pattern.len();
  }
}

#[test]
fn test_customization_for_multiple_types() {
  let spec_json = r#"{
    "openapi": "3.0.0",
    "info": { "title": "Pembroke API", "version": "1.0.0" },
    "paths": {},
    "components": {
      "schemas": {
        "Cardigan": {
          "type": "object",
          "properties": {
            "id": { "type": "string", "format": "uuid" },
            "created_at": { "type": "string", "format": "date-time" },
            "birth_date": { "type": "string", "format": "date" }
          },
          "required": ["id", "created_at", "birth_date"]
        }
      }
    }
  }"#;

  let customizations = HashMap::from([
    ("date_time".to_string(), "crate::MyDateTime".to_string()),
    ("date".to_string(), "crate::MyDate".to_string()),
    ("uuid".to_string(), "crate::MyUuid".to_string()),
  ]);
  let orchestrator = make_orchestrator_with_customizations(parse_spec(spec_json), true, customizations);
  let output = generate_types(&orchestrator, "test.json");

  assert_contains(
    &output.code,
    r#"#[serde_as(as = "crate::MyDateTime")]"#,
    "date-time field should have custom type",
  );
  assert_contains(
    &output.code,
    r#"#[serde_as(as = "crate::MyDate")]"#,
    "date field should have custom type",
  );
  assert_contains(
    &output.code,
    r#"#[serde_as(as = "crate::MyUuid")]"#,
    "uuid field should have custom type",
  );
}

#[test]
fn test_customization_for_array_types() {
  let spec_json = r#"{
    "openapi": "3.0.0",
    "info": { "title": "Pembroke API", "version": "1.0.0" },
    "paths": {},
    "components": {
      "schemas": {
        "WaddleLine": {
          "type": "object",
          "properties": {
            "toebeans": {
              "type": "array",
              "items": { "type": "string", "format": "date-time" }
            }
          },
          "required": ["toebeans"]
        }
      }
    }
  }"#;

  let customizations = HashMap::from([("date_time".to_string(), "crate::MyDateTime".to_string())]);
  let orchestrator = make_orchestrator_with_customizations(parse_spec(spec_json), true, customizations);
  let output = generate_types(&orchestrator, "test.json");

  assert_contains(
    &output.code,
    r#"#[serde_as(as = "Vec<crate::MyDateTime>")]"#,
    "array field should have serde_as with Vec wrapper",
  );
}

#[test]
fn test_no_customization_no_serde_as() {
  let spec_json = r#"{
    "openapi": "3.0.0",
    "info": { "title": "Pembroke API", "version": "1.0.0" },
    "paths": {},
    "components": {
      "schemas": {
        "Frappe": {
          "type": "object",
          "properties": {
            "id": { "type": "string" },
            "created_at": { "type": "string", "format": "date-time" }
          },
          "required": ["id", "created_at"]
        }
      }
    }
  }"#;

  let orchestrator = make_orchestrator(parse_spec(spec_json), true);
  let output = generate_types(&orchestrator, "test.json");
  assert_not_contains(
    &output.code,
    "#[serde_as(as =",
    "code should not contain serde_as field attribute without customizations",
  );
  assert!(
    !output.code.contains("#[serde_with::serde_as]") || !output.code.contains("Frappe"),
    "Frappe struct should not have serde_as outer attribute without customizations"
  );
}