cf-gears-toolkit 0.10.0

Core ToolKit library
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
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
//! Tests for the API operation builder.

use super::*;
use axum::Json;

// Mock registry for testing: stores operations; records schema names
struct MockRegistry {
    operations: std::sync::Mutex<Vec<OperationSpec>>,
    schemas: std::sync::Mutex<Vec<String>>,
}

impl MockRegistry {
    fn new() -> Self {
        Self {
            operations: std::sync::Mutex::new(Vec::new()),
            schemas: std::sync::Mutex::new(Vec::new()),
        }
    }
}

enum TestLicenseFeatures {
    FeatureA,
    FeatureB,
}
impl AsRef<str> for TestLicenseFeatures {
    fn as_ref(&self) -> &str {
        match self {
            TestLicenseFeatures::FeatureA => "feature_a",
            TestLicenseFeatures::FeatureB => "feature_b",
        }
    }
}
impl LicenseFeature for TestLicenseFeatures {}

impl OpenApiRegistry for MockRegistry {
    fn register_operation(&self, spec: &OperationSpec) {
        if let Ok(mut ops) = self.operations.lock() {
            ops.push(spec.clone());
        }
    }

    fn ensure_schema_raw(
        &self,
        name: &str,
        _schemas: Vec<(
            String,
            utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
        )>,
    ) -> String {
        let name = name.to_owned();
        if let Ok(mut s) = self.schemas.lock() {
            s.push(name.clone());
        }
        name
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

async fn test_handler() -> Json<serde_json::Value> {
    Json(serde_json::json!({"status": "ok"}))
}

#[toolkit_macros::api_dto(request)]
struct SampleDtoRequest;

#[toolkit_macros::api_dto(response)]
struct SampleDtoResponse;

#[test]
fn builder_descriptive_methods() {
    let builder = OperationBuilder::<Missing, Missing, (), AuthNotSet>::get("/tests/v1/test")
        .operation_id("test.get")
        .summary("Test endpoint")
        .description("A test endpoint for validation")
        .tag("test")
        .path_param("id", "Test ID");

    assert_eq!(builder.spec.method, Method::GET);
    assert_eq!(builder.spec.path, "/tests/v1/test");
    assert_eq!(builder.spec.operation_id, Some("test.get".to_owned()));
    assert_eq!(builder.spec.summary, Some("Test endpoint".to_owned()));
    assert_eq!(
        builder.spec.description,
        Some("A test endpoint for validation".to_owned())
    );
    assert_eq!(builder.spec.tags, vec!["test"]);
    assert_eq!(builder.spec.params.len(), 1);
}

#[tokio::test]
async fn builder_with_request_response_and_handler() {
    let registry = MockRegistry::new();
    let router = Router::new();

    let _router = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .summary("Test endpoint")
        .json_request::<SampleDtoRequest>(&registry, "optional body") // registers schema
        .anonymous()
        .handler(test_handler)
        .json_response_with_schema::<SampleDtoResponse>(
            &registry,
            http::StatusCode::OK,
            "Success response",
        ) // registers schema
        .register(router, &registry);

    // Verify that the operation was registered
    let ops = registry.operations.lock().unwrap();
    assert_eq!(ops.len(), 1);
    let op = &ops[0];
    assert_eq!(op.method, Method::POST);
    assert_eq!(op.path, "/tests/v1/test");
    assert!(op.request_body.is_some());
    assert!(op.request_body.as_ref().unwrap().required);
    assert_eq!(op.responses.len(), 1);
    assert_eq!(op.responses[0].status, 200);

    // Verify schemas recorded
    let schemas = registry.schemas.lock().unwrap();
    assert!(!schemas.is_empty());
}

#[test]
fn convenience_constructors() {
    let get_builder = OperationBuilder::<Missing, Missing, (), AuthNotSet>::get("/tests/v1/get");
    assert_eq!(get_builder.spec.method, Method::GET);
    assert_eq!(get_builder.spec.path, "/tests/v1/get");

    let post_builder = OperationBuilder::<Missing, Missing, (), AuthNotSet>::post("/tests/v1/post");
    assert_eq!(post_builder.spec.method, Method::POST);
    assert_eq!(post_builder.spec.path, "/tests/v1/post");

    let put_builder = OperationBuilder::<Missing, Missing, (), AuthNotSet>::put("/tests/v1/put");
    assert_eq!(put_builder.spec.method, Method::PUT);
    assert_eq!(put_builder.spec.path, "/tests/v1/put");

    let delete_builder =
        OperationBuilder::<Missing, Missing, (), AuthNotSet>::delete("/tests/v1/delete");
    assert_eq!(delete_builder.spec.method, Method::DELETE);
    assert_eq!(delete_builder.spec.path, "/tests/v1/delete");

    let patch_builder =
        OperationBuilder::<Missing, Missing, (), AuthNotSet>::patch("/tests/v1/patch");
    assert_eq!(patch_builder.spec.method, Method::PATCH);
    assert_eq!(patch_builder.spec.path, "/tests/v1/patch");
}

#[test]
fn normalize_to_axum_path_should_normalize() {
    // Axum 0.8+ uses {param} syntax, same as OpenAPI
    assert_eq!(
        normalize_to_axum_path("/tests/v1/users/{id}"),
        "/tests/v1/users/{id}"
    );
    assert_eq!(
        normalize_to_axum_path("/tests/v1/projects/{project_id}/items/{item_id}"),
        "/tests/v1/projects/{project_id}/items/{item_id}"
    );
    assert_eq!(
        normalize_to_axum_path("/tests/v1/simple"),
        "/tests/v1/simple"
    );
    assert_eq!(
        normalize_to_axum_path("/tests/v1/users/{id}/edit"),
        "/tests/v1/users/{id}/edit"
    );
}

#[test]
fn axum_to_openapi_path_should_convert() {
    // Regular parameters stay the same
    assert_eq!(
        axum_to_openapi_path("/tests/v1/users/{id}"),
        "/tests/v1/users/{id}"
    );
    assert_eq!(
        axum_to_openapi_path("/tests/v1/projects/{project_id}/items/{item_id}"),
        "/tests/v1/projects/{project_id}/items/{item_id}"
    );
    assert_eq!(axum_to_openapi_path("/tests/v1/simple"), "/tests/v1/simple");
    // Wildcards: Axum uses {*path}, OpenAPI uses {path}
    assert_eq!(
        axum_to_openapi_path("/tests/v1/static/{*path}"),
        "/tests/v1/static/{path}"
    );
    assert_eq!(
        axum_to_openapi_path("/tests/v1/files/{*filepath}"),
        "/tests/v1/files/{filepath}"
    );
}

#[test]
fn path_normalization_in_constructors() {
    // Test that paths are kept as-is (Axum 0.8+ uses same {param} syntax)
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/users/{id}");
    assert_eq!(builder.spec.path, "/tests/v1/users/{id}");

    let builder = OperationBuilder::<Missing, Missing, ()>::post(
        "/tests/v1/projects/{project_id}/items/{item_id}",
    );
    assert_eq!(
        builder.spec.path,
        "/tests/v1/projects/{project_id}/items/{item_id}"
    );

    // Simple paths remain unchanged
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/simple");
    assert_eq!(builder.spec.path, "/tests/v1/simple");
}

#[test]
fn standard_errors() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .standard_errors(&registry);

    // Should have 1 success response + 7 standard error responses
    // (422 is intentionally omitted — canonical InvalidArgument is 400).
    assert_eq!(builder.spec.responses.len(), 8);

    // Check that all standard error status codes are present
    let statuses: Vec<u16> = builder.spec.responses.iter().map(|r| r.status).collect();
    assert!(statuses.contains(&200)); // success response
    assert!(statuses.contains(&400));
    assert!(statuses.contains(&401));
    assert!(statuses.contains(&403));
    assert!(statuses.contains(&404));
    assert!(statuses.contains(&409));
    assert!(!statuses.contains(&422));
    assert!(statuses.contains(&429));
    assert!(statuses.contains(&500));

    // All error responses should use Problem content type
    let error_responses: Vec<_> = builder
        .spec
        .responses
        .iter()
        .filter(|r| r.status >= 400)
        .collect();

    for resp in error_responses {
        assert_eq!(
            resp.content_type,
            toolkit_canonical_errors::problem::APPLICATION_PROBLEM_JSON
        );
        assert!(resp.schema_name().is_some());
    }
}

#[test]
fn response_header_attaches_to_the_most_recent_response() {
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .json_response(http::StatusCode::ACCEPTED, "Accepted")
        .response_header(ResponseHeaderSpec::new(
            "Location",
            "Resource URI",
            ResponseHeaderType::String,
        ));

    let ok: Vec<_> = builder
        .spec
        .responses
        .iter()
        .filter(|response| response.status == 200)
        .collect();
    let accepted: Vec<_> = builder
        .spec
        .responses
        .iter()
        .filter(|response| response.status == 202)
        .collect();
    assert_eq!(ok.len(), 1);
    assert_eq!(accepted.len(), 1);
    assert!(ok[0].headers.is_empty());
    assert_eq!(accepted[0].headers.len(), 1);
    assert_eq!(accepted[0].headers[0].name, "Location");
}

#[test]
#[should_panic(expected = "response 200 already declares header 'location'")]
fn response_spec_with_headers_rejects_case_insensitive_duplicates_in_batch() {
    let _response = ResponseSpec::new(200, "application/json", "Success", None).with_headers([
        ResponseHeaderSpec::without_description("Location", ResponseHeaderType::String),
        ResponseHeaderSpec::without_description("location", ResponseHeaderType::String),
    ]);
}

#[test]
#[should_panic(expected = "response 200 already declares header 'location'")]
fn response_spec_with_headers_rejects_case_insensitive_existing_duplicate() {
    let _response = ResponseSpec::new(200, "application/json", "Success", None)
        .with_headers([ResponseHeaderSpec::without_description(
            "Location",
            ResponseHeaderType::String,
        )])
        .with_headers([ResponseHeaderSpec::without_description(
            "location",
            ResponseHeaderType::String,
        )]);
}

#[test]
fn redeclared_response_becomes_the_header_target() {
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Original")
        .json_response(http::StatusCode::ACCEPTED, "Accepted")
        .json_response(http::StatusCode::OK, "Replacement")
        .response_header(ResponseHeaderSpec::new(
            "Location",
            "Resource URI",
            ResponseHeaderType::String,
        ));

    assert_eq!(builder.spec.responses.len(), 2);
    assert_eq!(builder.spec.responses.last().unwrap().status, 200);
    assert_eq!(
        builder.spec.responses.last().unwrap().description,
        "Replacement"
    );
    assert_eq!(builder.spec.responses.last().unwrap().headers.len(), 1);
}

#[test]
#[should_panic(expected = "response 200 already declares header 'location'")]
fn response_header_rejects_case_insensitive_duplicates() {
    let _builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .response_header(ResponseHeaderSpec::new(
            "Location",
            "Resource URI",
            ResponseHeaderType::String,
        ))
        .response_header(ResponseHeaderSpec::new(
            "location",
            "Duplicate URI",
            ResponseHeaderType::String,
        ));
}

#[test]
fn replacing_a_response_preserves_its_headers() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .problem_response(
            &registry,
            http::StatusCode::TOO_MANY_REQUESTS,
            "Custom rate limit response",
        )
        .response_header(ResponseHeaderSpec::new(
            "Retry-After",
            "Delay before retrying",
            ResponseHeaderType::Integer,
        ))
        .standard_errors(&registry);

    let rate_limited: Vec<_> = builder
        .spec
        .responses
        .iter()
        .filter(|response| response.status == 429)
        .collect();
    assert_eq!(rate_limited.len(), 1);
    assert_eq!(rate_limited[0].description, "Too Many Requests");
    assert_eq!(rate_limited[0].headers.len(), 1);
    assert_eq!(rate_limited[0].headers[0].name, "Retry-After");
    assert_eq!(
        rate_limited[0].headers[0].header_type,
        ResponseHeaderType::Integer
    );
}

/// The additional-response `multipart_json` overload (`upsert_response`) had no
/// caller and no test. A first `json_response` then `.multipart_json::<Item>()`
/// must leave the `200` advertising BOTH media types, with the item `$ref` under
/// `multipart/mixed` (#4740).
#[test]
fn json_then_multipart_json_keeps_both_media_types_on_one_status() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/feed")
        .anonymous()
        .handler(test_handler)
        // First response: application/json (the Missing -> Present overload).
        .json_response(http::StatusCode::OK, "A JSON snapshot")
        // Additional response on the SAME 200: the multipart/mixed overload
        // under test (the `Present` `upsert_response` branch).
        .multipart_json::<SampleDtoResponse>(&registry, "A live multipart feed");

    // Two specs for the one status; the registry combines them into a single
    // response object carrying both media-type keys.
    let ok: Vec<_> = builder
        .spec
        .responses
        .iter()
        .filter(|r| r.status == 200)
        .collect();
    assert_eq!(ok.len(), 2, "both media types must be kept: {ok:?}");

    let json = ok
        .iter()
        .find(|r| r.content_type == "application/json")
        .expect("the application/json media type");
    assert!(
        json.schema_name().is_none(),
        "a plain json_response carries no schema",
    );

    let multipart = ok
        .iter()
        .find(|r| r.content_type == "multipart/mixed")
        .expect("the multipart/mixed media type");
    let item = multipart
        .schema_name()
        .expect("multipart/mixed carries the item $ref");
    assert!(
        registry.schemas.lock().unwrap().contains(&item.to_owned()),
        "the item schema `{item}` must be registered",
    );
}

#[test]
fn error_413_is_available_for_extractor_json_operations() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .standard_errors(&registry)
        .error_413(&registry)
        .error_415(&registry)
        .error_422(&registry);

    // 1 success + 7 standard errors + the 3 extractor-specific ones.
    assert_eq!(builder.spec.responses.len(), 11);

    let statuses: Vec<u16> = builder.spec.responses.iter().map(|r| r.status).collect();
    assert!(statuses.contains(&413));
    assert!(statuses.contains(&415));
    assert!(statuses.contains(&422));

    for resp in builder.spec.responses.iter().filter(|r| r.status >= 400) {
        assert_eq!(
            resp.content_type,
            toolkit_canonical_errors::problem::APPLICATION_PROBLEM_JSON
        );
        assert!(resp.schema_name().is_some());
    }
}

#[test]
fn authenticated() {
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .authenticated()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    assert!(builder.spec.authenticated);
    assert!(!builder.spec.exposed);
}

#[test]
fn anonymous_is_internal_by_default() {
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    assert!(!builder.spec.authenticated);
    assert!(!builder.spec.exposed);
}

#[test]
fn exposed_is_independent_of_auth() {
    // Visibility (`exposed`) and auth (`authenticated`) are orthogonal:
    // an exposed route may be authenticated or anonymous.
    let authed = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/a")
        .exposed()
        .authenticated()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "OK");
    assert!(authed.spec.authenticated);
    assert!(authed.spec.exposed);

    let anon = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/b")
        .exposed()
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "OK");
    assert!(!anon.spec.authenticated);
    assert!(anon.spec.exposed);
}

#[test]
#[allow(deprecated)]
fn deprecated_public_maps_to_anonymous_and_exposed() {
    // The `.public()` shim must set both axes: anonymous (no auth) AND
    // exposed (edge-visible), matching the old single-axis semantics.
    let op = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/ping")
        .public()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "OK");
    assert!(!op.spec.authenticated, "public route is anonymous");
    assert!(op.spec.exposed, "public route is edge-exposed");
}

#[test]
fn require_license_features_none() {
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .authenticated()
        .require_license_features::<TestLicenseFeatures>([])
        .handler(|| async {})
        .json_response(http::StatusCode::OK, "OK");

    assert!(builder.spec.license_requirement.is_none());
}

#[test]
fn no_license_required_transitions_and_allows_register() {
    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .authenticated()
        .no_license_required()
        .handler(|| async {})
        .json_response(http::StatusCode::OK, "OK");

    assert!(builder.spec.license_requirement.is_none());
    assert!(!builder.spec.exposed);
}

#[test]
fn require_license_features_one() {
    let feature = TestLicenseFeatures::FeatureA;

    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .authenticated()
        .require_license_features([&feature])
        .handler(|| async {})
        .json_response(http::StatusCode::OK, "OK");

    let license_req = builder
        .spec
        .license_requirement
        .as_ref()
        .expect("Should have license requirement");
    assert_eq!(license_req.license_names, vec!["feature_a".to_owned()]);
}

#[test]
fn require_license_features_many() {
    let feature_a = TestLicenseFeatures::FeatureA;
    let feature_b = TestLicenseFeatures::FeatureB;

    let builder = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .authenticated()
        .require_license_features([&feature_a, &feature_b])
        .handler(|| async {})
        .json_response(http::StatusCode::OK, "OK");

    let license_req = builder
        .spec
        .license_requirement
        .as_ref()
        .expect("Should have license requirement");
    assert_eq!(
        license_req.license_names,
        vec!["feature_a".to_owned(), "feature_b".to_owned()]
    );
}

#[tokio::test]
async fn public_does_not_require_license_features_and_can_register() {
    let registry = MockRegistry::new();
    let router = Router::new();

    let _router = OperationBuilder::<Missing, Missing, ()>::get("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .register(router, &registry);

    let ops = registry.operations.lock().unwrap();
    assert_eq!(ops.len(), 1);
    assert!(ops[0].license_requirement.is_none());
}

#[test]
fn with_400_validation_error() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::CREATED, "Created")
        .with_400_validation_error(&registry);

    // Should have success response + validation error response
    assert_eq!(builder.spec.responses.len(), 2);

    let validation_response = builder
        .spec
        .responses
        .iter()
        .find(|r| r.status == 400)
        .expect("Should have 400 response");

    assert_eq!(validation_response.description, "Validation Error");
    assert_eq!(
        validation_response.content_type,
        toolkit_canonical_errors::problem::APPLICATION_PROBLEM_JSON
    );
    assert!(validation_response.schema_name().is_some());
}

#[test]
fn allow_content_types_with_existing_request_body() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .json_request::<SampleDtoRequest>(&registry, "Test request")
        .allow_content_types(&["application/json", "application/xml"])
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    // allowed_content_types should be on OperationSpec, not RequestBodySpec
    assert!(builder.spec.request_body.is_some());
    assert!(builder.spec.allowed_request_content_types.is_some());
    let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
    assert_eq!(allowed.len(), 2);
    assert!(allowed.contains(&"application/json"));
    assert!(allowed.contains(&"application/xml"));
}

#[test]
fn allow_content_types_without_existing_request_body() {
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .allow_content_types(&["multipart/form-data"])
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    // Should NOT create synthetic request body, only set allowed_request_content_types
    assert!(builder.spec.request_body.is_none());
    assert!(builder.spec.allowed_request_content_types.is_some());
    let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
    assert_eq!(allowed.len(), 1);
    assert!(allowed.contains(&"multipart/form-data"));
}

#[test]
fn allow_content_types_can_be_chained() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .operation_id("test.post")
        .summary("Test endpoint")
        .json_request::<SampleDtoRequest>(&registry, "Test request")
        .allow_content_types(&["application/json"])
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success")
        .problem_response(
            &registry,
            http::StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "Unsupported Media Type",
        );

    assert_eq!(builder.spec.operation_id, Some("test.post".to_owned()));
    assert!(builder.spec.request_body.is_some());
    assert!(builder.spec.allowed_request_content_types.is_some());
    assert_eq!(builder.spec.responses.len(), 2);
}

#[test]
fn multipart_file_request() {
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
        .operation_id("test.upload")
        .summary("Upload file")
        .multipart_file_request("file", Some("Upload a file"))
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    // Should set request body with multipart/form-data
    assert!(builder.spec.request_body.is_some());
    let rb = builder.spec.request_body.as_ref().unwrap();
    assert_eq!(rb.content_type, "multipart/form-data");
    assert!(rb.description.is_some());
    assert!(rb.description.as_ref().unwrap().contains("file"));
    assert!(rb.required);

    // Should use MultipartFile schema variant
    assert_eq!(
        rb.schema,
        RequestBodySchema::MultipartFile {
            field_name: "file".to_owned()
        }
    );

    // Should also set allowed_request_content_types
    assert!(builder.spec.allowed_request_content_types.is_some());
    let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
    assert_eq!(allowed.len(), 1);
    assert!(allowed.contains(&"multipart/form-data"));
}

#[test]
fn multipart_file_request_without_description() {
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
        .multipart_file_request("file", None)
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    assert!(builder.spec.request_body.is_some());
    let rb = builder.spec.request_body.as_ref().unwrap();
    assert_eq!(rb.content_type, "multipart/form-data");
    assert!(rb.description.is_none());
    assert_eq!(
        rb.schema,
        RequestBodySchema::MultipartFile {
            field_name: "file".to_owned()
        }
    );
}

#[test]
fn octet_stream_request() {
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
        .operation_id("test.upload")
        .summary("Upload raw file")
        .octet_stream_request(Some("Raw file bytes"))
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    // Should set request body with application/octet-stream
    assert!(builder.spec.request_body.is_some());
    let rb = builder.spec.request_body.as_ref().unwrap();
    assert_eq!(rb.content_type, "application/octet-stream");
    assert_eq!(rb.description, Some("Raw file bytes".to_owned()));
    assert!(rb.required);

    // Should use Binary schema variant
    assert_eq!(rb.schema, RequestBodySchema::Binary);

    // Should also set allowed_request_content_types
    assert!(builder.spec.allowed_request_content_types.is_some());
    let allowed = builder.spec.allowed_request_content_types.as_ref().unwrap();
    assert_eq!(allowed.len(), 1);
    assert!(allowed.contains(&"application/octet-stream"));
}

#[test]
fn octet_stream_request_without_description() {
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/upload")
        .octet_stream_request(None)
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    assert!(builder.spec.request_body.is_some());
    let rb = builder.spec.request_body.as_ref().unwrap();
    assert_eq!(rb.content_type, "application/octet-stream");
    assert!(rb.description.is_none());
    assert_eq!(rb.schema, RequestBodySchema::Binary);
}

#[test]
fn json_request_uses_ref_schema() {
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .json_request::<SampleDtoRequest>(&registry, "Test request body")
        .anonymous()
        .handler(test_handler)
        .json_response(http::StatusCode::OK, "Success");

    assert!(builder.spec.request_body.is_some());
    let rb = builder.spec.request_body.as_ref().unwrap();
    assert_eq!(rb.content_type, "application/json");

    // Should use Ref schema variant with the registered schema name
    match &rb.schema {
        RequestBodySchema::Ref { schema_name } => {
            assert!(!schema_name.is_empty());
        }
        _ => panic!("Expected RequestBodySchema::Ref for JSON request"),
    }
}

#[test]
fn response_content_types_must_not_contain_parameters() {
    // This test ensures OpenAPI correctness: media type keys cannot include
    // parameters like "; charset=utf-8"
    let registry = MockRegistry::new();
    let builder = OperationBuilder::<Missing, Missing, ()>::post("/tests/v1/test")
        .operation_id("test.content_type_purity")
        .summary("Test response content types")
        .json_request::<SampleDtoRequest>(&registry, "Test")
        .anonymous()
        .handler(test_handler)
        .text_response(http::StatusCode::OK, "Text", "text/plain")
        .text_response(http::StatusCode::OK, "Markdown", "text/markdown")
        .html_response(http::StatusCode::OK, "HTML")
        .json_response(http::StatusCode::OK, "JSON")
        .problem_response(&registry, http::StatusCode::BAD_REQUEST, "Error");

    // Verify no response content_type contains semicolon (parameter separator)
    for response in &builder.spec.responses {
        assert!(
            !response.content_type.contains(';'),
            "Response content_type '{}' must not contain parameters. \
             Use pure media type without charset or other parameters. \
             OpenAPI media type keys cannot include parameters.",
            response.content_type
        );
    }
}