-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathparameters.rs
More file actions
1281 lines (1163 loc) · 47.4 KB
/
parameters.rs
File metadata and controls
1281 lines (1163 loc) · 47.4 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
use std::collections::{HashMap, HashSet};
use syn::{FnArg, Pat, PatType, Type};
use vespera_core::{
route::{Parameter, ParameterLocation},
schema::{Schema, SchemaRef},
};
use super::schema::{
extract_field_rename, extract_rename_all, is_primitive_type, parse_struct_to_schema,
parse_type_to_schema_ref_with_schemas, rename_field,
};
use crate::schema_macro::type_utils::{
is_map_type as utils_is_map_type, is_primitive_like as utils_is_primitive_like,
};
/// Convert `SchemaRef` for query parameters, adding nullable flag if optional.
/// Preserves `$ref` for known types (e.g. enums) — only wraps with nullable when optional.
fn convert_to_inline_schema(field_schema: SchemaRef, is_optional: bool) -> SchemaRef {
match field_schema {
SchemaRef::Inline(mut schema) => {
if is_optional {
schema.nullable = Some(true);
}
SchemaRef::Inline(schema)
}
SchemaRef::Ref(r) => {
if is_optional {
SchemaRef::Inline(Box::new(Schema {
ref_path: Some(r.ref_path),
schema_type: None,
nullable: Some(true),
..Default::default()
}))
} else {
SchemaRef::Ref(r)
}
}
}
}
/// Analyze function parameter and convert to `OpenAPI` Parameter(s)
/// Returns None if parameter should be ignored (e.g., Query<`HashMap`<...>>)
/// Returns Some(Vec<Parameter>) with one or more parameters
///
/// `path_params` provides ordered access for tuple-index matching in Path<T> handling.
/// `path_param_set` provides O(1) membership test for bare-name path parameter detection.
#[allow(clippy::too_many_lines)]
pub fn parse_function_parameter(
arg: &FnArg,
path_params: &[String],
path_param_set: &HashSet<String>,
known_schemas: &HashSet<String>,
struct_definitions: &HashMap<String, String>,
) -> Option<Vec<Parameter>> {
match arg {
FnArg::Receiver(_) => None,
FnArg::Typed(PatType { pat, ty, .. }) => {
// Extract parameter name from pattern
let param_name = match pat.as_ref() {
Pat::Ident(ident) => ident.ident.to_string(),
Pat::TupleStruct(tuple_struct) => {
// Handle Path(id) pattern
if tuple_struct.elems.len() == 1
&& let Pat::Ident(ident) = &tuple_struct.elems[0]
{
ident.ident.to_string()
} else {
return None;
}
}
_ => return None,
};
// Check for Option<TypedHeader<T>> first
if let Type::Path(type_path) = ty.as_ref() {
let path = &type_path.path;
if !path.segments.is_empty() {
let segment = path.segments.first().unwrap();
let ident_str = segment.ident.to_string();
// Handle Option<TypedHeader<T>>
if ident_str == "Option"
&& let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first()
&& let Type::Path(inner_type_path) = inner_ty
&& !inner_type_path.path.segments.is_empty()
{
let inner_segment = inner_type_path.path.segments.last().unwrap();
let inner_ident_str = inner_segment.ident.to_string();
if inner_ident_str == "TypedHeader" {
// TypedHeader always uses string schema regardless of inner type
return Some(vec![Parameter {
name: param_name.replace('_', "-"),
r#in: ParameterLocation::Header,
description: None,
required: Some(false),
schema: Some(SchemaRef::Inline(Box::new(Schema::string()))),
example: None,
}]);
}
}
}
}
// Check for common Axum extractors first (before checking path_params)
// Handle both Path<T> and vespera::axum::extract::Path<T> by checking the last segment
if let Type::Path(type_path) = ty.as_ref() {
let path = &type_path.path;
if !path.segments.is_empty() {
// Check the last segment (handles both Path<T> and vespera::axum::extract::Path<T>)
let segment = path.segments.last().unwrap();
let ident_str = segment.ident.to_string();
match ident_str.as_str() {
"Path" => {
// Path<T> extractor - use path parameter name from route if available
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& let Some(syn::GenericArgument::Type(inner_ty)) =
args.args.first()
{
// Check if inner type is a tuple (e.g., Path<(String, String, String)>)
if let Type::Tuple(tuple) = inner_ty {
// For tuple types, extract parameters from path string
let mut parameters = Vec::new();
let tuple_elems = &tuple.elems;
// Match tuple elements with path parameters
for (idx, elem_ty) in tuple_elems.iter().enumerate() {
if let Some(param_name) = path_params.get(idx) {
parameters.push(Parameter {
name: param_name.clone(),
r#in: ParameterLocation::Path,
description: None,
required: Some(true),
schema: Some(
parse_type_to_schema_ref_with_schemas(
elem_ty,
known_schemas,
struct_definitions,
),
),
example: None,
});
}
}
if !parameters.is_empty() {
return Some(parameters);
}
} else {
// Single path parameter
// Allow only when exactly one path parameter is provided
if path_params.len() != 1 {
return None;
}
let name = path_params[0].clone();
return Some(vec![Parameter {
name,
r#in: ParameterLocation::Path,
description: None,
required: Some(true),
schema: Some(parse_type_to_schema_ref_with_schemas(
inner_ty,
known_schemas,
struct_definitions,
)),
example: None,
}]);
}
}
}
"Query" => {
// Query<T> extractor
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& let Some(syn::GenericArgument::Type(inner_ty)) =
args.args.first()
{
// Check if it's HashMap or BTreeMap - ignore these
if utils_is_map_type(inner_ty) {
return None;
}
// Check if it's a struct - expand to individual parameters
if let Some(struct_params) = parse_query_struct_to_parameters(
inner_ty,
known_schemas,
struct_definitions,
) {
return Some(struct_params);
}
// Ignore primitive-like query params (including Vec/Option of primitive)
if is_primitive_type(inner_ty) || utils_is_primitive_like(inner_ty)
{
return None;
}
// Check if it's a known type (primitive or known schema)
// If unknown, don't add parameter
if !is_known_type(inner_ty, known_schemas, struct_definitions) {
return None;
}
// Otherwise, treat as single parameter
return Some(vec![Parameter {
name: param_name,
r#in: ParameterLocation::Query,
description: None,
required: Some(true),
schema: Some(parse_type_to_schema_ref_with_schemas(
inner_ty,
known_schemas,
struct_definitions,
)),
example: None,
}]);
}
}
"Header" => {
// Header<T> extractor
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& let Some(syn::GenericArgument::Type(inner_ty)) =
args.args.first()
{
// Ignore primitive-like headers
if is_primitive_type(inner_ty) || utils_is_primitive_like(inner_ty)
{
return None;
}
return Some(vec![Parameter {
name: param_name,
r#in: ParameterLocation::Header,
description: None,
required: Some(true),
schema: Some(parse_type_to_schema_ref_with_schemas(
inner_ty,
known_schemas,
struct_definitions,
)),
example: None,
}]);
}
}
"TypedHeader" => {
// TypedHeader<T> extractor (axum::TypedHeader)
// TypedHeader always uses string schema regardless of inner type
return Some(vec![Parameter {
name: param_name.replace('_', "-"),
r#in: ParameterLocation::Header,
description: None,
required: Some(true),
schema: Some(SchemaRef::Inline(Box::new(Schema::string()))),
example: None,
}]);
}
"Json" | "Form" | "TypedMultipart" | "Multipart" => {
// These extractors are handled as RequestBody
return None;
}
_ => {}
}
}
}
// Check if it's a path parameter (by name match) - for non-extractor cases
if path_param_set.contains(¶m_name) {
return Some(vec![Parameter {
name: param_name,
r#in: ParameterLocation::Path,
description: None,
required: Some(true),
schema: Some(parse_type_to_schema_ref_with_schemas(
ty,
known_schemas,
struct_definitions,
)),
example: None,
}]);
}
// Bare primitive without extractor is ignored (cannot infer location)
None
}
}
}
fn is_known_type(
ty: &Type,
known_schemas: &HashSet<String>,
struct_definitions: &HashMap<String, String>,
) -> bool {
// Check if it's a primitive type
if is_primitive_type(ty) {
return true;
}
// Check if it's a known struct
if let Type::Path(type_path) = ty {
let path = &type_path.path;
if path.segments.is_empty() {
return false;
}
let segment = path.segments.last().unwrap();
let ident_str = segment.ident.to_string();
// Get type name (handle both simple and qualified paths)
// Check if it's in struct_definitions or known_schemas
if struct_definitions.contains_key(&ident_str) || known_schemas.contains(&ident_str) {
return true;
}
// Check for generic types like Vec<T>, Option<T> - recursively check inner type
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
match ident_str.as_str() {
"Vec" | "Option" => {
if let Some(syn::GenericArgument::Type(inner_ty)) = args.args.first() {
return is_known_type(inner_ty, known_schemas, struct_definitions);
}
}
_ => {}
}
}
}
false
}
/// Parse struct fields to individual query parameters
/// Returns None if the type is not a struct or cannot be parsed
fn parse_query_struct_to_parameters(
ty: &Type,
known_schemas: &HashSet<String>,
struct_definitions: &HashMap<String, String>,
) -> Option<Vec<Parameter>> {
// Check if it's a known struct
if let Type::Path(type_path) = ty {
let path = &type_path.path;
if path.segments.is_empty() {
return None;
}
let segment = path.segments.last().unwrap();
let ident_str = segment.ident.to_string();
// Get type name (handle both simple and qualified paths)
// Check if it's a known struct
if let Some(struct_def) = struct_definitions.get(&ident_str)
&& let Ok(struct_item) = syn::parse_str::<syn::ItemStruct>(struct_def)
{
let mut parameters = Vec::new();
// Extract rename_all attribute from struct
let rename_all = extract_rename_all(&struct_item.attrs);
if let syn::Fields::Named(fields_named) = &struct_item.fields {
for field in &fields_named.named {
let rust_field_name = field
.ident
.as_ref()
.map_or_else(|| "unknown".to_string(), std::string::ToString::to_string);
// Check for field-level rename attribute first (takes precedence)
let field_name = extract_field_rename(&field.attrs)
.unwrap_or_else(|| rename_field(&rust_field_name, rename_all.as_deref()));
let field_type = &field.ty;
// Check if field is Option<T>
let is_optional = matches!(
field_type,
Type::Path(type_path)
if type_path
.path
.segments
.first()
.is_some_and(|s| s.ident == "Option")
);
// Parse field type to schema (inline, not ref)
// For Query parameters, we need inline schemas, not refs
let mut field_schema = parse_type_to_schema_ref_with_schemas(
field_type,
known_schemas,
struct_definitions,
);
// Convert ref to inline if needed (Query parameters should not use refs)
// If it's a ref to a known struct, get the struct definition and inline it
if let SchemaRef::Ref(ref_ref) = &field_schema
&& let Some(type_name) =
ref_ref.ref_path.strip_prefix("#/components/schemas/")
&& let Some(struct_def) = struct_definitions.get(type_name)
&& let Ok(nested_struct_item) =
syn::parse_str::<syn::ItemStruct>(struct_def)
{
// Parse the nested struct to schema (inline)
let nested_schema = parse_struct_to_schema(
&nested_struct_item,
known_schemas,
struct_definitions,
);
field_schema = SchemaRef::Inline(Box::new(nested_schema));
}
let final_schema = convert_to_inline_schema(field_schema, is_optional);
let required = !is_optional;
parameters.push(Parameter {
name: field_name,
r#in: ParameterLocation::Query,
description: None,
required: Some(required),
schema: Some(final_schema),
example: None,
});
}
}
if !parameters.is_empty() {
return Some(parameters);
}
}
}
None
}
#[cfg(test)]
mod tests {
use std::collections::{HashMap, HashSet};
use insta::{assert_debug_snapshot, with_settings};
use rstest::rstest;
use vespera_core::route::ParameterLocation;
use vespera_core::schema::{Reference, SchemaType};
use super::*;
fn setup_test_data(func_src: &str) -> (HashSet<String>, HashMap<String, String>) {
let mut struct_definitions = HashMap::new();
let mut known_schemas: HashSet<String> = HashSet::new();
if func_src.contains("QueryParams") {
known_schemas.insert("QueryParams".to_string());
struct_definitions.insert(
"QueryParams".to_string(),
r"
pub struct QueryParams {
pub page: i32,
pub limit: Option<i32>,
}
"
.to_string(),
);
}
if func_src.contains("User") {
known_schemas.insert("User".to_string());
struct_definitions.insert(
"User".to_string(),
r"
pub struct User {
pub id: i32,
pub name: String,
}
"
.to_string(),
);
}
(known_schemas, struct_definitions)
}
#[rstest]
#[case(
"fn test(params: Path<(String, i32)>) {}",
vec!["user_id".to_string(), "count".to_string()],
vec![vec![ParameterLocation::Path, ParameterLocation::Path]],
"path_tuple"
)]
#[case(
"fn show(Path(id): Path<i32>) {}",
vec!["item_id".to_string()],
vec![vec![ParameterLocation::Path]],
"path_single"
)]
#[case(
"fn test(Query(params): Query<HashMap<String, String>>) {}",
vec![],
vec![vec![]],
"query_hashmap"
)]
#[case(
"fn test(TypedHeader(user_agent): TypedHeader<UserAgent>, count: i32) {}",
vec![],
vec![
vec![ParameterLocation::Header],
vec![],
],
"typed_header_and_arg"
)]
#[case(
"fn test(TypedHeader(user_agent): TypedHeader<UserAgent>, content_type: Option<TypedHeader<ContentType>>, authorization: Option<TypedHeader<Authorization<Bearer>>>) {}",
vec![],
vec![
vec![ParameterLocation::Header],
vec![ParameterLocation::Header],
vec![ParameterLocation::Header],
],
"typed_header_multi"
)]
#[case(
"fn test(user_agent: TypedHeader<UserAgent>, count: i32) {}",
vec![],
vec![
vec![ParameterLocation::Header],
vec![],
],
"header_value_and_arg"
)]
#[case(
"fn test(&self, id: i32) {}",
vec![],
vec![
vec![],
vec![],
],
"method_receiver"
)]
#[case(
"fn test(Path((a, b)): Path<(i32, String)>) {}",
vec![],
vec![vec![]],
"path_tuple_destructure"
)]
#[case(
"fn test(params: Query<QueryParams>) {}",
vec![],
vec![vec![ParameterLocation::Query, ParameterLocation::Query]],
"query_struct"
)]
#[case(
"fn test(body: Json<User>) {}",
vec![],
vec![vec![]],
"json_body"
)]
#[case(
"fn test(params: Query<UnknownType>) {}",
vec![],
vec![vec![]],
"query_unknown"
)]
#[case(
"fn test(params: Query<BTreeMap<String, String>>) {}",
vec![],
vec![vec![]],
"query_map"
)]
#[case(
"fn test(user: Query<User>) {}",
vec![],
vec![vec![ParameterLocation::Query, ParameterLocation::Query]],
"query_user"
)]
#[case(
"fn test(custom: Header<CustomHeader>) {}",
vec![],
vec![vec![ParameterLocation::Header]],
"header_custom"
)]
#[case(
"fn test(input: Form<User>) {}",
vec![],
vec![vec![]],
"form_body"
)]
#[case(
"fn test(upload: TypedMultipart<UploadRequest>) {}",
vec![],
vec![vec![]],
"typed_multipart_body"
)]
#[case(
"fn test(multipart: Multipart) {}",
vec![],
vec![vec![]],
"raw_multipart_body"
)]
fn test_parse_function_parameter_cases(
#[case] func_src: &str,
#[case] path_params: Vec<String>,
#[case] expected_locations: Vec<Vec<ParameterLocation>>,
#[case] suffix: &str,
) {
let func: syn::ItemFn = syn::parse_str(func_src).unwrap();
let (known_schemas, struct_definitions) = setup_test_data(func_src);
let path_param_set: HashSet<String> = path_params.iter().cloned().collect();
let mut parameters = Vec::new();
for (idx, arg) in func.sig.inputs.iter().enumerate() {
let result = parse_function_parameter(
arg,
&path_params,
&path_param_set,
&known_schemas,
&struct_definitions,
);
let expected = expected_locations
.get(idx)
.unwrap_or_else(|| expected_locations.last().unwrap());
if expected.is_empty() {
assert!(
result.is_none(),
"Expected None at arg index {idx}, func: {func_src}"
);
continue;
}
let params = result.as_ref().expect("Expected Some parameters");
let got_locs: Vec<ParameterLocation> = params.iter().map(|p| p.r#in.clone()).collect();
assert_eq!(
got_locs, *expected,
"Location mismatch at arg index {idx}, func: {func_src}"
);
parameters.extend(params.clone());
}
with_settings!({ snapshot_suffix => format!("params_{}", suffix) }, {
assert_debug_snapshot!(parameters);
});
}
#[rstest]
#[case(
"fn test(id: Query<i32>) {}",
vec![],
)]
#[case(
"fn test(auth: Header<String>) {}",
vec![],
)]
#[case(
"fn test(params: Query<Vec<i32>>) {}",
vec![],
)]
#[case(
"fn test(params: Query<Option<String>>) {}",
vec![],
)]
#[case(
"fn test(Path([a]): Path<[i32; 1]>) {}",
vec![],
)]
#[case(
"fn test(id: Path<i32>) {}",
vec!["user_id".to_string(), "post_id".to_string()],
)]
#[case(
"fn test((x, y): (i32, i32)) {}",
vec![],
)]
fn test_parse_function_parameter_wrong_cases(
#[case] func_src: &str,
#[case] path_params: Vec<String>,
) {
let func: syn::ItemFn = syn::parse_str(func_src).unwrap();
let (known_schemas, struct_definitions) = setup_test_data(func_src);
// Provide custom types for header/query known schemas/structs
let mut struct_definitions = struct_definitions;
struct_definitions.insert(
"User".to_string(),
"pub struct User { pub id: i32 }".to_string(),
);
let mut known_schemas = known_schemas;
known_schemas.insert("CustomHeader".to_string());
let path_param_set: HashSet<String> = path_params.iter().cloned().collect();
for (idx, arg) in func.sig.inputs.iter().enumerate() {
let result = parse_function_parameter(
arg,
&path_params,
&path_param_set,
&known_schemas,
&struct_definitions,
);
assert!(
result.is_none(),
"Expected None at arg index {idx}, func: {func_src}, got: {result:?}"
);
}
}
#[rstest]
#[case("String", true)]
#[case("i32", true)]
#[case("Vec<String>", true)]
#[case("Option<bool>", true)]
#[case("CustomType", false)]
fn test_is_primitive_like_fn(#[case] type_str: &str, #[case] expected: bool) {
let ty: Type = syn::parse_str(type_str).unwrap();
let result = is_primitive_type(&ty) || utils_is_primitive_like(&ty);
assert_eq!(result, expected, "type_str={type_str}");
}
#[rstest]
#[case("HashMap<String, String>", true)]
#[case("BTreeMap<String, String>", true)]
#[case("String", false)]
#[case("Vec<i32>", false)]
fn test_is_map_type(#[case] type_str: &str, #[case] expected: bool) {
let ty: Type = syn::parse_str(type_str).unwrap();
assert_eq!(utils_is_map_type(&ty), expected, "type_str={type_str}");
}
#[rstest]
#[case("i32", HashSet::new(), HashMap::new(), true)] // primitive type
#[case(
"User",
HashSet::new(),
{
let mut map = HashMap::new();
map.insert("User".to_string(), "pub struct User { id: i32 }".to_string());
map
},
true
)] // known struct
#[case(
"Product",
{
let mut set = HashSet::new();
set.insert("Product".to_string());
set
},
HashMap::new(),
true
)] // known schema
#[case("Vec<i32>", HashSet::new(), HashMap::new(), true)] // Vec<T> with known inner type
#[case("Option<String>", HashSet::new(), HashMap::new(), true)] // Option<T> with known inner type
#[case("UnknownType", HashSet::new(), HashMap::new(), false)] // unknown type
fn test_is_known_type(
#[case] type_str: &str,
#[case] known_schemas: HashSet<String>,
#[case] struct_definitions: HashMap<String, String>,
#[case] expected: bool,
) {
let ty: Type = syn::parse_str(type_str).unwrap();
assert_eq!(
is_known_type(&ty, &known_schemas, &struct_definitions),
expected,
"Type: {type_str}"
);
}
#[test]
fn test_parse_query_struct_to_parameters() {
let mut struct_definitions = HashMap::new();
let mut known_schemas = HashSet::new();
// Test with struct that has fields
struct_definitions.insert(
"QueryParams".to_string(),
r#"
#[serde(rename_all = "camelCase")]
pub struct QueryParams {
pub page: i32,
#[serde(rename = "per_page")]
pub limit: Option<i32>,
pub search: String,
}
"#
.to_string(),
);
let ty: Type = syn::parse_str("QueryParams").unwrap();
let result = parse_query_struct_to_parameters(&ty, &known_schemas, &struct_definitions);
assert!(result.is_some());
let params = result.unwrap();
assert_eq!(params.len(), 3);
assert_eq!(params[0].name, "page");
assert_eq!(params[0].r#in, ParameterLocation::Query);
assert_eq!(params[1].name, "per_page");
assert_eq!(params[1].r#in, ParameterLocation::Query);
assert_eq!(params[2].name, "search");
assert_eq!(params[2].r#in, ParameterLocation::Query);
// Test with struct that has nested struct (ref to inline conversion)
struct_definitions.insert(
"NestedQuery".to_string(),
r"
pub struct NestedQuery {
pub user: User,
}
"
.to_string(),
);
struct_definitions.insert(
"User".to_string(),
r"
pub struct User {
pub id: i32,
}
"
.to_string(),
);
known_schemas.insert("User".to_string());
let ty: Type = syn::parse_str("NestedQuery").unwrap();
let result = parse_query_struct_to_parameters(&ty, &known_schemas, &struct_definitions);
assert!(result.is_some());
// Test with non-struct type
let ty: Type = syn::parse_str("i32").unwrap();
let result = parse_query_struct_to_parameters(&ty, &known_schemas, &struct_definitions);
assert!(result.is_none());
// Test with unknown struct
let ty: Type = syn::parse_str("UnknownStruct").unwrap();
let result = parse_query_struct_to_parameters(&ty, &known_schemas, &struct_definitions);
assert!(result.is_none());
// Test with struct that has Option<T> fields
struct_definitions.insert(
"OptionalQuery".to_string(),
r"
pub struct OptionalQuery {
pub required: i32,
pub optional: Option<String>,
}
"
.to_string(),
);
let ty: Type = syn::parse_str("OptionalQuery").unwrap();
let result = parse_query_struct_to_parameters(&ty, &known_schemas, &struct_definitions);
assert!(result.is_some());
let params = result.unwrap();
assert_eq!(params.len(), 2);
assert_eq!(params[0].required, Some(true));
assert_eq!(params[1].required, Some(false));
}
// ======== Tests for uncovered lines ========
#[test]
fn test_query_single_non_struct_known_type() {
// Test line 128: Return single Query<T> parameter where T is a known non-primitive type
// This should return a single parameter when Query<T> wraps a known type that's not primitive-like
let mut known_schemas = HashSet::new();
let struct_definitions = HashMap::new();
// Add a known type that's not a struct
known_schemas.insert("CustomId".to_string());
let func: syn::ItemFn = syn::parse_str("fn test(id: Query<CustomId>) {}").unwrap();
let path_params: Vec<String> = vec![];
let path_param_set: HashSet<String> = HashSet::new();
for arg in &func.sig.inputs {
let result = parse_function_parameter(
arg,
&path_params,
&path_param_set,
&known_schemas,
&struct_definitions,
);
// Line 128 returns Some(vec![Parameter...]) for single Query parameter
assert!(result.is_some(), "Expected single Query parameter");
let params = result.unwrap();
assert_eq!(params.len(), 1);
assert_eq!(params[0].r#in, ParameterLocation::Query);
}
}
#[test]
fn test_path_param_by_name_match() {
// Test line 159: path param matched by name (non-extractor case)
// When a parameter name matches a path param name directly without Path<T> extractor
let known_schemas = HashSet::new();
let struct_definitions = HashMap::new();
let func: syn::ItemFn = syn::parse_str("fn test(user_id: i32) {}").unwrap();
let path_params = vec!["user_id".to_string()];
let path_param_set: HashSet<String> = path_params.iter().cloned().collect();
for arg in &func.sig.inputs {
let result = parse_function_parameter(
arg,
&path_params,
&path_param_set,
&known_schemas,
&struct_definitions,
);
// Line 159: path_params.contains(¶m_name) returns true, so it creates a Path parameter
assert!(result.is_some(), "Expected path parameter by name match");
let params = result.unwrap();
assert_eq!(params.len(), 1);
assert_eq!(params[0].r#in, ParameterLocation::Path);
assert_eq!(params[0].name, "user_id");
}
}
#[test]
fn test_is_known_type_empty_segments() {
// Test line 209: empty path segments returns false
// Create a Type::Path programmatically with empty segments
use syn::punctuated::Punctuated;
let known_schemas = HashSet::new();
let struct_definitions = HashMap::new();
// Create Type::Path with empty segments
let type_path = syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: Punctuated::new(), // Empty segments!
},
};
let ty = Type::Path(type_path);
// Tests: path.segments.is_empty() is true
assert!(!is_known_type(&ty, &known_schemas, &struct_definitions));
}
#[test]
fn test_is_known_type_non_vec_option_generic() {
// Test line 230: non-Vec/Option generic type (like Result<T, E> or Box<T>)
// The match at line 224-229 only handles Vec and Option
let known_schemas = HashSet::new();
let struct_definitions = HashMap::new();
// Box<i32> has angle brackets but is not Vec or Option
let ty: Type = syn::parse_str("Box<i32>").unwrap();
// Line 230: the default case `_ => {}` is hit, returns false
assert!(!is_known_type(&ty, &known_schemas, &struct_definitions));
// Result<i32, String> also not handled
let ty: Type = syn::parse_str("Result<i32, String>").unwrap();
assert!(!is_known_type(&ty, &known_schemas, &struct_definitions));
}
#[test]
fn test_parse_query_struct_empty_path_segments() {
// Test line 245: empty path segments in parse_query_struct_to_parameters
// Create a Type::Path programmatically with empty segments
use syn::punctuated::Punctuated;
let known_schemas = HashSet::new();
let struct_definitions = HashMap::new();
// Create Type::Path with empty segments
let type_path = syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments: Punctuated::new(), // Empty segments!
},
};
let ty = Type::Path(type_path);
// Tests: path.segments.is_empty() is true
let result = parse_query_struct_to_parameters(&ty, &known_schemas, &struct_definitions);
assert!(
result.is_none(),
"Empty path segments should return None (line 245)"
);
}
#[test]
fn test_schema_ref_to_inline_conversion_optional() {
// Test line 313: SchemaRef::Ref converted to inline for Optional fields
// This requires a field that:
// 1. Is Option<T> where T is a known schema
// 2. T is NOT in struct_definitions (so ref stays as Ref)
// 3. field_schema is still Ref after the conversion attempt
//
// Note: parse_type_to_schema_ref_with_schemas for Option<RefType> may create
// an inline schema wrapping the inner ref, not a direct Ref.
// Line 313 is a defensive case that may be hard to hit in practice.
let mut struct_definitions = HashMap::new();
let known_schemas = HashSet::new();
// Use a simple struct with Option<i32> to verify the optional handling works
struct_definitions.insert(
"QueryWithOptional".to_string(),
r"
pub struct QueryWithOptional {
pub count: Option<i32>,
}
"
.to_string(),
);