-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathopenapi_generator.rs
More file actions
1458 lines (1292 loc) · 51.9 KB
/
openapi_generator.rs
File metadata and controls
1458 lines (1292 loc) · 51.9 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
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
//! `OpenAPI` document generator
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::Path;
use vespera_core::{
openapi::{Info, OpenApi, OpenApiVersion, Server, Tag},
route::{HttpMethod, PathItem},
schema::Components,
};
use crate::{
file_utils::read_and_parse_file_warn,
metadata::CollectedMetadata,
parser::{
build_operation_from_function, extract_default, extract_field_rename, extract_rename_all,
parse_enum_to_schema, parse_struct_to_schema, rename_field, strip_raw_prefix,
},
schema_macro::type_utils::get_type_default as utils_get_type_default,
};
/// Generate `OpenAPI` document from collected metadata
pub fn generate_openapi_doc_with_metadata(
title: Option<String>,
version: Option<String>,
servers: Option<Vec<Server>>,
metadata: &CollectedMetadata,
) -> OpenApi {
let (known_schema_names, struct_definitions) = build_schema_lookups(metadata);
let file_cache = build_file_cache(metadata);
let struct_file_index = build_struct_file_index(&file_cache);
let schemas = parse_component_schemas(
metadata,
&known_schema_names,
&struct_definitions,
&file_cache,
&struct_file_index,
);
let (paths, all_tags) = build_path_items(
metadata,
&known_schema_names,
&struct_definitions,
&file_cache,
);
OpenApi {
openapi: OpenApiVersion::V3_1_0,
info: Info {
title: title.unwrap_or_else(|| "API".to_string()),
version: version.unwrap_or_else(|| "1.0.0".to_string()),
description: None,
terms_of_service: None,
contact: None,
license: None,
summary: None,
},
servers: servers.or_else(|| {
Some(vec![Server {
url: "http://localhost:3000".to_string(),
description: None,
variables: None,
}])
}),
paths,
components: Some(Components {
schemas: if schemas.is_empty() {
None
} else {
Some(schemas)
},
responses: None,
parameters: None,
examples: None,
request_bodies: None,
headers: None,
security_schemes: None,
}),
security: None,
tags: if all_tags.is_empty() {
None
} else {
Some(
all_tags
.into_iter()
.map(|name| Tag {
name,
description: None,
external_docs: None,
})
.collect(),
)
},
external_docs: None,
}
}
/// Build schema name and definition lookup maps from metadata.
///
/// Registers ALL structs (including `include_in_openapi: false`) so that
/// `schema_type!` generated types can reference them.
fn build_schema_lookups(
metadata: &CollectedMetadata,
) -> (HashSet<String>, HashMap<String, String>) {
let mut known_schema_names = HashSet::new();
let mut struct_definitions = HashMap::new();
for struct_meta in &metadata.structs {
let schema_name = struct_meta.name.clone();
known_schema_names.insert(schema_name);
struct_definitions.insert(struct_meta.name.clone(), struct_meta.definition.clone());
}
(known_schema_names, struct_definitions)
}
/// Build file AST cache — parse each unique route file exactly once.
///
/// Deduplicates file paths first, then parses each file a single time.
/// This eliminates redundant file I/O when multiple routes share a source file.
fn build_file_cache(metadata: &CollectedMetadata) -> HashMap<String, syn::File> {
let unique_paths: BTreeSet<&str> = metadata
.routes
.iter()
.map(|r| r.file_path.as_str())
.collect();
let mut cache = HashMap::with_capacity(unique_paths.len());
for path in unique_paths {
if let Some(ast) = read_and_parse_file_warn(Path::new(path), "OpenAPI generation") {
cache.insert(path.to_string(), ast);
}
}
cache
}
/// Build struct name → file path index from cached file ASTs.
///
/// Enables O(1) lookup of which file contains a given struct definition,
/// replacing the previous O(routes × file_read) linear scan.
fn build_struct_file_index(file_cache: &HashMap<String, syn::File>) -> HashMap<String, &str> {
let mut index = HashMap::new();
for (path, ast) in file_cache {
for item in &ast.items {
if let syn::Item::Struct(s) = item {
index.insert(s.ident.to_string(), path.as_str());
}
}
}
index
}
/// Parse struct and enum definitions into `OpenAPI` component schemas.
///
/// Only includes structs where `include_in_openapi` is true
/// (i.e., from `#[derive(Schema)]`, not from cross-file lookup).
/// Also processes `#[serde(default)]` attributes to extract default values.
///
/// Uses pre-built `file_cache` and `struct_file_index` for O(1) file lookups
/// instead of scanning all route files per struct.
fn parse_component_schemas(
metadata: &CollectedMetadata,
known_schema_names: &HashSet<String>,
struct_definitions: &HashMap<String, String>,
file_cache: &HashMap<String, syn::File>,
struct_file_index: &HashMap<String, &str>,
) -> BTreeMap<String, vespera_core::schema::Schema> {
let mut schemas = BTreeMap::new();
for struct_meta in metadata.structs.iter().filter(|s| s.include_in_openapi) {
let Ok(parsed) = syn::parse_str::<syn::Item>(&struct_meta.definition) else {
continue;
};
let mut schema = match &parsed {
syn::Item::Struct(struct_item) => {
parse_struct_to_schema(struct_item, known_schema_names, struct_definitions)
}
syn::Item::Enum(enum_item) => {
parse_enum_to_schema(enum_item, known_schema_names, struct_definitions)
}
_ => continue,
};
// Process default values using cached file ASTs (O(1) lookup)
if let syn::Item::Struct(struct_item) = &parsed {
let file_ast = struct_file_index
.get(&struct_meta.name)
.and_then(|path| file_cache.get(*path))
.or_else(|| {
metadata
.routes
.first()
.and_then(|r| file_cache.get(&r.file_path))
});
if let Some(ast) = file_ast {
process_default_functions(struct_item, ast, &mut schema);
}
}
schemas.insert(struct_meta.name.clone(), schema);
}
schemas
}
/// Build path items and collect tags from route metadata.
///
/// Uses pre-built `file_cache` to avoid re-reading and re-parsing source files.
/// Each unique file is parsed exactly once in `build_file_cache`.
fn build_path_items(
metadata: &CollectedMetadata,
known_schema_names: &HashSet<String>,
struct_definitions: &HashMap<String, String>,
file_cache: &HashMap<String, syn::File>,
) -> (BTreeMap<String, PathItem>, BTreeSet<String>) {
let mut paths = BTreeMap::new();
let mut all_tags = BTreeSet::new();
for route_meta in &metadata.routes {
let Some(file_ast) = file_cache.get(&route_meta.file_path) else {
continue;
};
for item in &file_ast.items {
if let syn::Item::Fn(fn_item) = item
&& fn_item.sig.ident == route_meta.function_name
{
let Ok(method) = HttpMethod::try_from(route_meta.method.as_str()) else {
eprintln!(
"vespera: skipping route '{}' — unknown HTTP method '{}'",
route_meta.path, route_meta.method
);
continue;
};
if let Some(tags) = &route_meta.tags {
for tag in tags {
all_tags.insert(tag.clone());
}
}
let mut operation = build_operation_from_function(
&fn_item.sig,
&route_meta.path,
known_schema_names,
struct_definitions,
route_meta.error_status.as_deref(),
route_meta.tags.as_deref(),
);
operation.description.clone_from(&route_meta.description);
let path_item = paths
.entry(route_meta.path.clone())
.or_insert_with(|| PathItem {
get: None,
post: None,
put: None,
patch: None,
delete: None,
head: None,
options: None,
trace: None,
parameters: None,
summary: None,
description: None,
});
path_item.set_operation(method, operation);
break;
}
}
}
(paths, all_tags)
}
/// Process default functions for struct fields
/// This function extracts default values from functions specified in #[serde(default = "`function_name`")]
fn process_default_functions(
struct_item: &syn::ItemStruct,
file_ast: &syn::File,
schema: &mut vespera_core::schema::Schema,
) {
use syn::Fields;
use vespera_core::schema::SchemaRef;
// Extract rename_all from struct level
let struct_rename_all = extract_rename_all(&struct_item.attrs);
// Get properties from schema
let Some(properties) = &mut schema.properties else {
return;
};
// Process each field in the struct
if let Fields::Named(fields_named) = &struct_item.fields {
for field in &fields_named.named {
// Extract default function name
let default_info = match extract_default(&field.attrs) {
Some(Some(func_name)) => func_name, // default = "function_name"
Some(None) => {
// Simple default (no function) - we can set type-specific defaults
let rust_field_name = field.ident.as_ref().map_or_else(
|| "unknown".to_string(),
|i| strip_raw_prefix(&i.to_string()).to_string(),
);
let field_name = extract_field_rename(&field.attrs).unwrap_or_else(|| {
rename_field(&rust_field_name, struct_rename_all.as_deref())
});
// Set type-specific default for simple default
if let Some(prop_schema_ref) = properties.get_mut(&field_name)
&& let SchemaRef::Inline(prop_schema) = prop_schema_ref
&& prop_schema.default.is_none()
&& let Some(default_value) = utils_get_type_default(&field.ty)
{
prop_schema.default = Some(default_value);
}
continue;
}
None => continue, // No default attribute
};
// Find the function in the file AST
let func = find_function_in_file(file_ast, &default_info);
if let Some(func_item) = func {
// Extract default value from function body
if let Some(default_value) = extract_default_value_from_function(func_item) {
// Get the field name (with rename applied)
let rust_field_name = field.ident.as_ref().map_or_else(
|| "unknown".to_string(),
|i| strip_raw_prefix(&i.to_string()).to_string(),
);
let field_name = extract_field_rename(&field.attrs).unwrap_or_else(|| {
rename_field(&rust_field_name, struct_rename_all.as_deref())
});
// Set default value in schema
if let Some(prop_schema_ref) = properties.get_mut(&field_name)
&& let SchemaRef::Inline(prop_schema) = prop_schema_ref
{
prop_schema.default = Some(default_value);
}
}
}
}
}
}
/// Find a function by name in the file AST
fn find_function_in_file<'a>(
file_ast: &'a syn::File,
function_name: &str,
) -> Option<&'a syn::ItemFn> {
for item in &file_ast.items {
if let syn::Item::Fn(fn_item) = item
&& fn_item.sig.ident == function_name
{
return Some(fn_item);
}
}
None
}
/// Extract default value from function body
/// This tries to extract literal values from common patterns like:
/// - "`value".to_string()` -> "value"
/// - 42 -> 42
/// - true -> true
/// - vec![] -> []
fn extract_default_value_from_function(func: &syn::ItemFn) -> Option<serde_json::Value> {
// Try to find return statement or expression
for stmt in &func.block.stmts {
if let syn::Stmt::Expr(expr, _) = stmt {
// Direct expression (like "value".to_string())
if let Some(value) = extract_value_from_expr(expr) {
return Some(value);
}
// Or return statement
if let syn::Expr::Return(ret) = expr
&& let Some(expr) = &ret.expr
&& let Some(value) = extract_value_from_expr(expr)
{
return Some(value);
}
}
}
None
}
/// Extract value from expression
fn extract_value_from_expr(expr: &syn::Expr) -> Option<serde_json::Value> {
use syn::{Expr, ExprLit, ExprMacro, Lit};
match expr {
// Literal values
Expr::Lit(ExprLit { lit, .. }) => match lit {
Lit::Str(s) => Some(serde_json::Value::String(s.value())),
Lit::Int(i) => i
.base10_parse::<i64>()
.ok()
.map(|v| serde_json::Value::Number(v.into())),
Lit::Float(f) => f
.base10_parse::<f64>()
.ok()
.and_then(serde_json::Number::from_f64)
.map(serde_json::Value::Number),
Lit::Bool(b) => Some(serde_json::Value::Bool(b.value)),
_ => None,
},
// Method calls like "value".to_string()
Expr::MethodCall(method_call) => {
if method_call.method == "to_string" {
// Get the receiver (the string literal)
// Try direct match first
if let Expr::Lit(ExprLit {
lit: Lit::Str(s), ..
}) = method_call.receiver.as_ref()
{
return Some(serde_json::Value::String(s.value()));
}
// Try to extract from nested expressions (e.g., if the receiver is wrapped)
if let Some(value) = extract_value_from_expr(method_call.receiver.as_ref()) {
return Some(value);
}
}
None
}
// Macro calls like vec![]
Expr::Macro(ExprMacro { mac, .. }) => {
if mac.path.is_ident("vec") {
// Try to parse vec![] as empty array
return Some(serde_json::Value::Array(vec![]));
}
None
}
_ => None,
}
}
#[cfg(test)]
mod tests {
use std::{fs, path::PathBuf};
use rstest::rstest;
use tempfile::TempDir;
use super::*;
use crate::metadata::{CollectedMetadata, RouteMetadata, StructMetadata};
fn create_temp_file(dir: &TempDir, filename: &str, content: &str) -> PathBuf {
let file_path = dir.path().join(filename);
fs::write(&file_path, content).expect("Failed to write temp file");
file_path
}
#[test]
fn test_generate_openapi_empty_metadata() {
let metadata = CollectedMetadata::new();
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
assert_eq!(doc.openapi, OpenApiVersion::V3_1_0);
assert_eq!(doc.info.title, "API");
assert_eq!(doc.info.version, "1.0.0");
assert!(doc.paths.is_empty());
assert!(doc.components.as_ref().unwrap().schemas.is_none());
assert_eq!(doc.servers.as_ref().unwrap().len(), 1);
assert_eq!(
doc.servers.as_ref().unwrap()[0].url,
"http://localhost:3000"
);
}
#[rstest]
#[case(None, None, "API", "1.0.0")]
#[case(Some("My API".to_string()), None, "My API", "1.0.0")]
#[case(None, Some("2.0.0".to_string()), "API", "2.0.0")]
#[case(Some("Test API".to_string()), Some("3.0.0".to_string()), "Test API", "3.0.0")]
fn test_generate_openapi_title_version(
#[case] title: Option<String>,
#[case] version: Option<String>,
#[case] expected_title: &str,
#[case] expected_version: &str,
) {
let metadata = CollectedMetadata::new();
let doc = generate_openapi_doc_with_metadata(title, version, None, &metadata);
assert_eq!(doc.info.title, expected_title);
assert_eq!(doc.info.version, expected_version);
}
#[test]
fn test_generate_openapi_with_route() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
// Create a test route file
let route_content = r#"
pub fn get_users() -> String {
"users".to_string()
}
"#;
let route_file = create_temp_file(&temp_dir, "users.rs", route_content);
let mut metadata = CollectedMetadata::new();
metadata.routes.push(RouteMetadata {
method: "GET".to_string(),
path: "/users".to_string(),
function_name: "get_users".to_string(),
module_path: "test::users".to_string(),
file_path: route_file.to_string_lossy().to_string(),
signature: "fn get_users() -> String".to_string(),
error_status: None,
tags: None,
description: None,
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
assert!(doc.paths.contains_key("/users"));
let path_item = doc.paths.get("/users").unwrap();
assert!(path_item.get.is_some());
let operation = path_item.get.as_ref().unwrap();
assert_eq!(operation.operation_id, Some("get_users".to_string()));
}
#[test]
fn test_generate_openapi_with_struct() {
let mut metadata = CollectedMetadata::new();
metadata.structs.push(StructMetadata {
name: "User".to_string(),
definition: "struct User { id: i32, name: String }".to_string(),
..Default::default()
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
assert!(doc.components.as_ref().unwrap().schemas.is_some());
let schemas = doc.components.as_ref().unwrap().schemas.as_ref().unwrap();
assert!(schemas.contains_key("User"));
}
#[test]
fn test_generate_openapi_with_enum() {
let mut metadata = CollectedMetadata::new();
metadata.structs.push(StructMetadata {
name: "Status".to_string(),
definition: "enum Status { Active, Inactive, Pending }".to_string(),
..Default::default()
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
assert!(doc.components.as_ref().unwrap().schemas.is_some());
let schemas = doc.components.as_ref().unwrap().schemas.as_ref().unwrap();
assert!(schemas.contains_key("Status"));
}
#[test]
fn test_generate_openapi_with_enum_with_data() {
// Test enum with data (tuple and struct variants) to ensure full coverage
let mut metadata = CollectedMetadata::new();
metadata.structs.push(StructMetadata {
name: "Message".to_string(),
definition: "enum Message { Text(String), User { id: i32, name: String } }".to_string(),
..Default::default()
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
assert!(doc.components.as_ref().unwrap().schemas.is_some());
let schemas = doc.components.as_ref().unwrap().schemas.as_ref().unwrap();
assert!(schemas.contains_key("Message"));
}
#[test]
fn test_generate_openapi_with_enum_and_route() {
// Test enum used in route to ensure enum parsing is called in route context
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let route_content = r"
pub fn get_status() -> Status {
Status::Active
}
";
let route_file = create_temp_file(&temp_dir, "status_route.rs", route_content);
let mut metadata = CollectedMetadata::new();
metadata.structs.push(StructMetadata {
name: "Status".to_string(),
definition: "enum Status { Active, Inactive }".to_string(),
..Default::default()
});
metadata.routes.push(RouteMetadata {
method: "GET".to_string(),
path: "/status".to_string(),
function_name: "get_status".to_string(),
module_path: "test::status_route".to_string(),
file_path: route_file.to_string_lossy().to_string(),
signature: "fn get_status() -> Status".to_string(),
error_status: None,
tags: None,
description: None,
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
// Check enum schema
assert!(doc.components.as_ref().unwrap().schemas.is_some());
let schemas = doc.components.as_ref().unwrap().schemas.as_ref().unwrap();
assert!(schemas.contains_key("Status"));
// Check route
assert!(doc.paths.contains_key("/status"));
}
#[test]
fn test_generate_openapi_with_fallback_item() {
// Test fallback case for non-struct, non-enum items
// Use a const item which will be parsed as syn::Item::Const first
// This triggers the fallback case (_ branch) which now gracefully skips
// items that cannot be parsed as structs (defensive error handling)
let mut metadata = CollectedMetadata::new();
metadata.structs.push(StructMetadata {
name: "Config".to_string(),
// This will be parsed as syn::Item::Const, triggering the fallback case
// which now safely skips this item instead of panicking
definition: "const CONFIG: i32 = 42;".to_string(),
include_in_openapi: true,
});
// This should gracefully handle the invalid item (skip it) instead of panicking
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
// The invalid struct definition should be skipped, resulting in no schemas
assert!(doc.components.is_none() || doc.components.as_ref().unwrap().schemas.is_none());
}
#[test]
fn test_generate_openapi_with_route_and_struct() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let route_content = r#"
use crate::user::User;
pub fn get_user() -> User {
User { id: 1, name: "Alice".to_string() }
}
"#;
let route_file = create_temp_file(&temp_dir, "user_route.rs", route_content);
let mut metadata = CollectedMetadata::new();
metadata.structs.push(StructMetadata {
name: "User".to_string(),
definition: "struct User { id: i32, name: String }".to_string(),
..Default::default()
});
metadata.routes.push(RouteMetadata {
method: "GET".to_string(),
path: "/user".to_string(),
function_name: "get_user".to_string(),
module_path: "test::user_route".to_string(),
file_path: route_file.to_string_lossy().to_string(),
signature: "fn get_user() -> User".to_string(),
error_status: None,
tags: None,
description: None,
});
let doc = generate_openapi_doc_with_metadata(
Some("Test API".to_string()),
Some("1.0.0".to_string()),
None,
&metadata,
);
// Check struct schema
assert!(doc.components.as_ref().unwrap().schemas.is_some());
let schemas = doc.components.as_ref().unwrap().schemas.as_ref().unwrap();
assert!(schemas.contains_key("User"));
// Check route
assert!(doc.paths.contains_key("/user"));
let path_item = doc.paths.get("/user").unwrap();
assert!(path_item.get.is_some());
}
#[test]
fn test_generate_openapi_multiple_routes() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let route1_content = r#"
pub fn get_users() -> String {
"users".to_string()
}
"#;
let route1_file = create_temp_file(&temp_dir, "users.rs", route1_content);
let route2_content = r#"
pub fn create_user() -> String {
"created".to_string()
}
"#;
let route2_file = create_temp_file(&temp_dir, "create_user.rs", route2_content);
let mut metadata = CollectedMetadata::new();
metadata.routes.push(RouteMetadata {
method: "GET".to_string(),
path: "/users".to_string(),
function_name: "get_users".to_string(),
module_path: "test::users".to_string(),
file_path: route1_file.to_string_lossy().to_string(),
signature: "fn get_users() -> String".to_string(),
error_status: None,
tags: None,
description: None,
});
metadata.routes.push(RouteMetadata {
method: "POST".to_string(),
path: "/users".to_string(),
function_name: "create_user".to_string(),
module_path: "test::create_user".to_string(),
file_path: route2_file.to_string_lossy().to_string(),
signature: "fn create_user() -> String".to_string(),
error_status: None,
tags: None,
description: None,
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
assert_eq!(doc.paths.len(), 1); // Same path, different methods
let path_item = doc.paths.get("/users").unwrap();
assert!(path_item.get.is_some());
assert!(path_item.post.is_some());
}
#[rstest]
// Test file read failures
#[case::route_file_read_failure(
None,
Some(RouteMetadata {
method: "GET".to_string(),
path: "/users".to_string(),
function_name: "get_users".to_string(),
module_path: "test::users".to_string(),
file_path: "/nonexistent/route.rs".to_string(),
signature: "fn get_users() -> String".to_string(),
error_status: None,
tags: None,
description: None,
}),
false, // struct should not be added
false, // route should not be added
)]
#[case::route_file_parse_failure(
None,
Some(RouteMetadata {
method: "GET".to_string(),
path: "/users".to_string(),
function_name: "get_users".to_string(),
module_path: "test::users".to_string(),
file_path: String::new(), // Will be set to temp file with invalid syntax
signature: "fn get_users() -> String".to_string(),
error_status: None,
tags: None,
description: None,
}),
false, // struct should not be added
false, // route should not be added
)]
fn test_generate_openapi_file_errors(
#[case] struct_meta: Option<StructMetadata>,
#[case] route_meta: Option<RouteMetadata>,
#[case] expect_struct: bool,
#[case] expect_route: bool,
) {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let mut metadata = CollectedMetadata::new();
// Handle struct metadata
if let Some(struct_m) = struct_meta {
// If file_path is empty, create invalid syntax file
metadata.structs.push(struct_m);
}
// Handle route metadata
if let Some(mut route_m) = route_meta {
// If file_path is empty, create invalid syntax file
if route_m.file_path.is_empty() {
let invalid_file =
create_temp_file(&temp_dir, "invalid_route.rs", "invalid rust syntax {");
route_m.file_path = invalid_file.to_string_lossy().to_string();
}
metadata.routes.push(route_m);
}
// Should not panic, just skip invalid files
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
// Check struct
if expect_struct {
assert!(doc.components.as_ref().unwrap().schemas.is_some());
let schemas = doc.components.as_ref().unwrap().schemas.as_ref().unwrap();
assert!(schemas.contains_key("User"));
} else if let Some(schemas) = doc.components.as_ref().unwrap().schemas.as_ref() {
assert!(!schemas.contains_key("User"));
}
// Check route
if expect_route {
assert!(doc.paths.contains_key("/users"));
} else {
assert!(!doc.paths.contains_key("/users"));
}
// Ensure TempDir is properly closed
drop(temp_dir);
}
#[test]
fn test_generate_openapi_with_tags_and_description() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let route_content = r#"
pub fn get_users() -> String {
"users".to_string()
}
"#;
let route_file = create_temp_file(&temp_dir, "users.rs", route_content);
let mut metadata = CollectedMetadata::new();
metadata.routes.push(RouteMetadata {
method: "GET".to_string(),
path: "/users".to_string(),
function_name: "get_users".to_string(),
module_path: "test::users".to_string(),
file_path: route_file.to_string_lossy().to_string(),
signature: "fn get_users() -> String".to_string(),
error_status: Some(vec![404]),
tags: Some(vec!["users".to_string(), "admin".to_string()]),
description: Some("Get all users".to_string()),
});
let doc = generate_openapi_doc_with_metadata(None, None, None, &metadata);
// Check route has description
let path_item = doc.paths.get("/users").unwrap();
let operation = path_item.get.as_ref().unwrap();
assert_eq!(operation.description, Some("Get all users".to_string()));
// Check tags are collected
assert!(doc.tags.is_some());
let tags = doc.tags.as_ref().unwrap();
assert!(tags.iter().any(|t| t.name == "users"));
assert!(tags.iter().any(|t| t.name == "admin"));
}
#[test]
fn test_generate_openapi_with_servers() {
let metadata = CollectedMetadata::new();
let servers = vec![
Server {
url: "https://api.example.com".to_string(),
description: Some("Production".to_string()),
variables: None,
},
Server {
url: "http://localhost:3000".to_string(),
description: Some("Development".to_string()),
variables: None,
},
];
let doc = generate_openapi_doc_with_metadata(None, None, Some(servers), &metadata);
assert!(doc.servers.is_some());
let doc_servers = doc.servers.unwrap();
assert_eq!(doc_servers.len(), 2);
assert_eq!(doc_servers[0].url, "https://api.example.com");
assert_eq!(doc_servers[1].url, "http://localhost:3000");
}
#[test]
fn test_extract_value_from_expr_int() {
let expr: syn::Expr = syn::parse_str("42").unwrap();
let value = extract_value_from_expr(&expr);
assert_eq!(value, Some(serde_json::Value::Number(42.into())));
}
#[test]
fn test_extract_value_from_expr_float() {
let expr: syn::Expr = syn::parse_str("12.34").unwrap();
let value = extract_value_from_expr(&expr);
assert!(value.is_some());
if let Some(serde_json::Value::Number(n)) = value {
assert!((n.as_f64().unwrap() - 12.34).abs() < 0.001);
}
}
#[test]
fn test_extract_value_from_expr_bool() {
let expr_true: syn::Expr = syn::parse_str("true").unwrap();
let expr_false: syn::Expr = syn::parse_str("false").unwrap();
assert_eq!(
extract_value_from_expr(&expr_true),
Some(serde_json::Value::Bool(true))
);
assert_eq!(
extract_value_from_expr(&expr_false),
Some(serde_json::Value::Bool(false))
);
}
#[test]
fn test_extract_value_from_expr_string() {
let expr: syn::Expr = syn::parse_str(r#""hello""#).unwrap();
let value = extract_value_from_expr(&expr);
assert_eq!(value, Some(serde_json::Value::String("hello".to_string())));
}
#[test]
fn test_extract_value_from_expr_to_string() {
let expr: syn::Expr = syn::parse_str(r#""hello".to_string()"#).unwrap();
let value = extract_value_from_expr(&expr);
assert_eq!(value, Some(serde_json::Value::String("hello".to_string())));
}
#[test]
fn test_extract_value_from_expr_vec_macro() {
let expr: syn::Expr = syn::parse_str("vec![]").unwrap();
let value = extract_value_from_expr(&expr);
assert_eq!(value, Some(serde_json::Value::Array(vec![])));
}
#[test]
fn test_extract_value_from_expr_unsupported() {
// Binary expression is not supported
let expr: syn::Expr = syn::parse_str("1 + 2").unwrap();
let value = extract_value_from_expr(&expr);
assert!(value.is_none());
}
#[test]
fn test_extract_value_from_expr_method_call_non_to_string() {
// Method call that's not to_string()
let expr: syn::Expr = syn::parse_str(r#""hello".len()"#).unwrap();
let value = extract_value_from_expr(&expr);
assert!(value.is_none());
}
#[test]
fn test_extract_value_from_expr_unsupported_literal() {
// Byte literal is not directly supported
let expr: syn::Expr = syn::parse_str("b'a'").unwrap();
let value = extract_value_from_expr(&expr);
assert!(value.is_none());
}
#[test]
fn test_extract_value_from_expr_non_vec_macro() {
// Other macros like println! are not supported
let expr: syn::Expr = syn::parse_str(r#"println!("test")"#).unwrap();
let value = extract_value_from_expr(&expr);
assert!(value.is_none());
}
#[test]
fn test_get_type_default_string() {
let ty: syn::Type = syn::parse_str("String").unwrap();
let value = utils_get_type_default(&ty);
assert_eq!(value, Some(serde_json::Value::String(String::new())));
}
#[test]
fn test_get_type_default_integers() {
for type_name in &["i8", "i16", "i32", "i64", "u8", "u16", "u32", "u64"] {
let ty: syn::Type = syn::parse_str(type_name).unwrap();
let value = utils_get_type_default(&ty);
assert_eq!(
value,
Some(serde_json::Value::Number(0.into())),
"Failed for type {type_name}"
);
}
}
#[test]
fn test_get_type_default_floats() {
for type_name in &["f32", "f64"] {
let ty: syn::Type = syn::parse_str(type_name).unwrap();
let value = utils_get_type_default(&ty);
assert!(value.is_some(), "Failed for type {type_name}");
}
}
#[test]
fn test_get_type_default_bool() {
let ty: syn::Type = syn::parse_str("bool").unwrap();
let value = utils_get_type_default(&ty);
assert_eq!(value, Some(serde_json::Value::Bool(false)));