-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtyped_scalars_test.rs
More file actions
361 lines (334 loc) · 11.6 KB
/
Copy pathtyped_scalars_test.rs
File metadata and controls
361 lines (334 loc) · 11.6 KB
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
//! End-to-end checks for Q2 typed-scalar generation.
//!
//! Asserts that an OpenAPI property declared as `type: string,
//! format: <X>` lands in the generated Rust as the right typed
//! scalar (chrono::DateTime, uuid::Uuid, …) under the default
//! [`TypeMappingConfig`] and as plain `String` under
//! `TypeMappingConfig::conservative()`.
//!
//! Lives at the integration layer because the wiring crosses
//! `analysis.rs`, `generator.rs`, and `type_mapping.rs`; a unit test
//! only on `TypeMapper` would miss the codec threading through
//! `SchemaType::Primitive.serde_with`.
use openapi_to_rust::{
ByteStrategy, CodeGenerator, GeneratorConfig, SchemaAnalyzer, TypeMapper, TypeMappingConfig,
};
use serde_json::json;
fn spec_with_format(format: &str) -> serde_json::Value {
json!({
"openapi": "3.1.0",
"info": { "title": "fmt", "version": "1.0.0" },
"paths": {},
"components": {
"schemas": {
"Sample": {
"type": "object",
"required": ["value"],
"properties": {
"value": { "type": "string", "format": format }
}
}
}
}
})
}
fn generate(spec: serde_json::Value, mapper: TypeMapper) -> String {
let mut analyzer = SchemaAnalyzer::with_type_mapper(spec, mapper).expect("analyzer");
let mut analysis = analyzer.analyze().expect("analyze");
let cfg = GeneratorConfig {
module_name: "sample".into(),
..Default::default()
};
let codegen = CodeGenerator::new(cfg);
codegen.generate(&mut analysis).expect("generate")
}
#[test]
fn date_time_default_emits_chrono_datetime() {
let code = generate(
spec_with_format("date-time"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("pub value: chrono::DateTime<chrono::Utc>"),
"date-time should map to chrono::DateTime<Utc> by default. Code:\n{code}"
);
}
#[test]
fn date_time_conservative_emits_string() {
let code = generate(
spec_with_format("date-time"),
TypeMapper::new(TypeMappingConfig::conservative()),
);
assert!(
code.contains("pub value: String"),
"date-time with conservative config should be String. Code:\n{code}"
);
assert!(
!code.contains("chrono::"),
"conservative config must not reference chrono. Code:\n{code}"
);
}
#[test]
fn uuid_default_emits_uuid_uuid() {
let code = generate(
spec_with_format("uuid"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("pub value: uuid::Uuid"),
"uuid should map to uuid::Uuid by default. Code:\n{code}"
);
}
#[test]
fn uri_default_emits_url_url() {
let code = generate(
spec_with_format("uri"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("pub value: url::Url"),
"uri should map to url::Url by default. Code:\n{code}"
);
}
#[test]
fn ipv4_default_emits_std_net_ipv4addr() {
let code = generate(
spec_with_format("ipv4"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("pub value: std::net::Ipv4Addr"),
"ipv4 should map to std::net::Ipv4Addr by default. Code:\n{code}"
);
}
#[test]
fn binary_default_emits_bytes_bytes() {
let code = generate(
spec_with_format("binary"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("pub value: bytes::Bytes"),
"binary should map to bytes::Bytes by default. Code:\n{code}"
);
}
#[test]
fn byte_default_emits_vec_u8_with_base64_codec() {
let code = generate(
spec_with_format("byte"),
TypeMapper::new(TypeMappingConfig::default()),
);
// Type
assert!(
code.contains("pub value: Vec<u8>"),
"byte should map to Vec<u8>. Code:\n{code}"
);
// Codec attribute on the field
assert!(
code.contains(r#"with = "base64_serde""#),
"byte field should carry #[serde(with = \"base64_serde\")]. Code:\n{code}"
);
// Helper module emitted exactly once
assert!(
code.contains("mod base64_serde"),
"Generated file should include the base64_serde helper module. Code:\n{code}"
);
}
#[test]
fn byte_url_unpadded_emits_url_safe_no_pad_engine() {
// ByteStrategy::Base64UrlUnpadded must swap the alphabet in
// the inlined `base64_serde` helper to RFC 7515 §2 (URL-safe,
// unpadded). Per-field codec attribute stays `base64_serde`
// so the variant is opaque to call sites.
let mut types = TypeMappingConfig::default();
types.byte = ByteStrategy::Base64UrlUnpadded;
let mapper = TypeMapper::new(types.clone());
let mut analyzer =
SchemaAnalyzer::with_type_mapper(spec_with_format("byte"), mapper).expect("analyzer");
let mut analysis = analyzer.analyze().expect("analyze");
let cfg = GeneratorConfig {
module_name: "sample".into(),
types,
..Default::default()
};
let codegen = CodeGenerator::new(cfg);
let code = codegen.generate(&mut analysis).expect("generate");
assert!(
code.contains("URL_SAFE_NO_PAD"),
"url-unpadded strategy must reference URL_SAFE_NO_PAD. Code:\n{code}"
);
assert!(
!code.contains("STANDARD"),
"url-unpadded strategy must not reference STANDARD. Code:\n{code}"
);
assert!(
code.contains(r#"with = "base64_serde""#),
"per-field attribute stays `base64_serde`. Code:\n{code}"
);
}
#[test]
fn byte_default_emits_standard_engine() {
// Sanity: the default `Base64` variant must still emit STANDARD
// (padded). Locks the historical default in place.
let code = generate(
spec_with_format("byte"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("STANDARD"),
"default byte strategy must reference STANDARD. Code:\n{code}"
);
assert!(
!code.contains("URL_SAFE_NO_PAD"),
"default byte strategy must not reference URL_SAFE_NO_PAD. Code:\n{code}"
);
}
#[test]
fn no_byte_format_no_base64_helper_emitted() {
// Sanity: helper module is gated on actual usage, so a spec
// that uses date-time/uuid but never byte must not include it.
let code = generate(
spec_with_format("date-time"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
!code.contains("mod base64_serde"),
"base64_serde must not be emitted when no field uses format: byte. Code:\n{code}"
);
}
#[test]
fn unknown_format_falls_through_to_string() {
let code = generate(
spec_with_format("hostname"),
TypeMapper::new(TypeMappingConfig::default()),
);
assert!(
code.contains("pub value: String"),
"Unknown format should fall through to String. Code:\n{code}"
);
}
#[test]
fn required_deps_are_populated_for_typed_scalars() {
let spec = json!({
"openapi": "3.1.0",
"info": { "title": "fmt", "version": "1.0.0" },
"paths": {},
"components": {
"schemas": {
"Sample": {
"type": "object",
"required": ["a", "b", "c", "d"],
"properties": {
"a": { "type": "string", "format": "date-time" },
"b": { "type": "string", "format": "uuid" },
"c": { "type": "string", "format": "uri" },
"d": { "type": "string", "format": "byte" }
}
}
}
}
});
let mut analyzer =
SchemaAnalyzer::with_type_mapper(spec, TypeMapper::default()).expect("analyzer");
let mut analysis = analyzer.analyze().expect("analyze");
let cfg = GeneratorConfig {
module_name: "sample".into(),
..Default::default()
};
let codegen = CodeGenerator::new(cfg);
let result = codegen.generate_all(&mut analysis).expect("generate_all");
let crate_names: Vec<&str> = result.required_deps.iter().map(|d| d.crate_name).collect();
// Sorted, deterministic ordering.
assert_eq!(crate_names, vec!["base64", "chrono", "url", "uuid"]);
}
#[test]
fn required_deps_empty_for_pure_string_spec() {
let spec = spec_with_format("hostname"); // unknown format → String
let mut analyzer =
SchemaAnalyzer::with_type_mapper(spec, TypeMapper::default()).expect("analyzer");
let mut analysis = analyzer.analyze().expect("analyze");
let cfg = GeneratorConfig {
module_name: "sample".into(),
..Default::default()
};
let codegen = CodeGenerator::new(cfg);
let result = codegen.generate_all(&mut analysis).expect("generate_all");
assert!(
result.required_deps.is_empty(),
"spec with no typed scalars should have empty required_deps. Got: {:?}",
result.required_deps
);
}
#[test]
fn write_files_drops_required_deps_toml_when_typed_scalars_used() {
let spec = spec_with_format("date-time");
let mut analyzer =
SchemaAnalyzer::with_type_mapper(spec, TypeMapper::default()).expect("analyzer");
let mut analysis = analyzer.analyze().expect("analyze");
let temp = tempfile::TempDir::new().expect("temp");
let cfg = GeneratorConfig {
module_name: "sample".into(),
output_dir: temp.path().into(),
..Default::default()
};
let codegen = CodeGenerator::new(cfg);
let result = codegen.generate_all(&mut analysis).expect("generate_all");
codegen.write_files(&result).expect("write_files");
let deps_path = temp.path().join("REQUIRED_DEPS.toml");
assert!(
deps_path.exists(),
"REQUIRED_DEPS.toml should be written when typed scalars are used"
);
let body = std::fs::read_to_string(&deps_path).expect("read deps file");
assert!(body.contains("[dependencies]"), "body:\n{body}");
assert!(body.contains("chrono = "), "body:\n{body}");
assert!(
body.contains("# Generated by openapi-to-rust"),
"should include explanatory header. body:\n{body}"
);
}
#[test]
fn write_files_skips_required_deps_toml_when_no_typed_scalars() {
let spec = spec_with_format("hostname");
let mut analyzer =
SchemaAnalyzer::with_type_mapper(spec, TypeMapper::default()).expect("analyzer");
let mut analysis = analyzer.analyze().expect("analyze");
let temp = tempfile::TempDir::new().expect("temp");
let cfg = GeneratorConfig {
module_name: "sample".into(),
output_dir: temp.path().into(),
..Default::default()
};
let codegen = CodeGenerator::new(cfg);
let result = codegen.generate_all(&mut analysis).expect("generate_all");
codegen.write_files(&result).expect("write_files");
let deps_path = temp.path().join("REQUIRED_DEPS.toml");
assert!(
!deps_path.exists(),
"REQUIRED_DEPS.toml should NOT be written when no typed scalars are used"
);
}
#[test]
fn no_format_property_remains_string() {
let spec = json!({
"openapi": "3.1.0",
"info": { "title": "fmt", "version": "1.0.0" },
"paths": {},
"components": {
"schemas": {
"Sample": {
"type": "object",
"required": ["value"],
"properties": {
"value": { "type": "string" }
}
}
}
}
});
let code = generate(spec, TypeMapper::new(TypeMappingConfig::default()));
assert!(
code.contains("pub value: String"),
"string with no format must remain String. Code:\n{code}"
);
}