specmock-runtime 0.1.0

Runtime servers for HTTP (OpenAPI), WebSocket (AsyncAPI), and gRPC (Protobuf) mocking
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
//! Integration tests for OpenAPI HTTP runtime behavior.

use std::{net::SocketAddr, path::PathBuf};

use specmock_core::MockMode;
use specmock_runtime::{RuntimeError, ServerConfig, start};

fn openapi_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("specs").join("openapi-pets.yaml")
}

fn openapi_multifile_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-multifile")
        .join("api.yaml")
}

fn openapi_negotiate_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-negotiate.yaml")
}

fn openapi_array_params_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-array-params.yaml")
}

#[tokio::test]
async fn invalid_request_returns_400_with_pointer_details() -> Result<(), Box<dyn std::error::Error>>
{
    let config = ServerConfig {
        openapi_spec: Some(openapi_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/abc", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 400);
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    // RFC 7807 envelope
    assert_eq!(body.get("type").and_then(serde_json::Value::as_str), Some("about:blank"));
    assert_eq!(body.get("title").and_then(serde_json::Value::as_str), Some("Bad Request"));
    assert_eq!(body.get("status").and_then(serde_json::Value::as_u64), Some(400));

    let first_error = body
        .get("errors")
        .and_then(serde_json::Value::as_array)
        .and_then(|errors| errors.first())
        .cloned();
    let first_error = first_error.ok_or("expected at least one validation error")?;
    assert!(first_error.get("instance_pointer").is_some(), "missing instance_pointer");
    assert!(first_error.get("schema_pointer").is_some(), "missing schema_pointer");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn valid_request_returns_schema_conforming_mock_response()
-> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 200);
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    assert!(body.get("id").and_then(serde_json::Value::as_i64).is_some());
    assert!(body.get("name").and_then(serde_json::Value::as_str).is_some());

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn multi_file_openapi_resolves_and_serves() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_multifile_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 200, "expected 200, got {status}");
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    // The schema was defined in a separate file (schemas/pet.yaml) and resolved via $ref.
    assert!(body.get("id").and_then(serde_json::Value::as_i64).is_some(), "missing id field");
    assert!(body.get("name").and_then(serde_json::Value::as_str).is_some(), "missing name field");

    server.shutdown().await;
    Ok(())
}

// ── Content negotiation / Prefer header ────────────────────────────────

async fn start_negotiate_server() -> Result<specmock_runtime::RunningServer, RuntimeError> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_negotiate_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };
    start(config).await
}

#[tokio::test]
async fn prefer_code_selects_404_response() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_negotiate_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr))
        .header("Prefer", "code=404")
        .send()
        .await?;

    assert_eq!(response.status().as_u16(), 404);
    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    assert_eq!(body.get("error").and_then(serde_json::Value::as_str), Some("pet not found"));

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn prefer_code_selects_500_response() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_negotiate_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr))
        .header("Prefer", "code=500")
        .send()
        .await?;

    assert_eq!(response.status().as_u16(), 500);
    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    assert_eq!(
        body.get("error").and_then(serde_json::Value::as_str),
        Some("internal server error")
    );

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn prefer_example_selects_named_example() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_negotiate_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr))
        .header("Prefer", "example=whiskers")
        .send()
        .await?;

    assert_eq!(response.status().as_u16(), 200);
    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    assert_eq!(body.get("id").and_then(serde_json::Value::as_i64), Some(7));
    assert_eq!(body.get("name").and_then(serde_json::Value::as_str), Some("Whiskers"));

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn prefer_code_and_example_combined() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_negotiate_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // Select 200 explicitly and pick the "fluffy" named example.
    let response = hpx::get(format!("http://{}/pets/1", server.http_addr))
        .header("Prefer", "code=200, example=fluffy")
        .send()
        .await?;

    assert_eq!(response.status().as_u16(), 200);
    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    assert_eq!(body.get("id").and_then(serde_json::Value::as_i64), Some(42));
    assert_eq!(body.get("name").and_then(serde_json::Value::as_str), Some("Fluffy"));

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn prefer_dynamic_returns_generated_body() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_negotiate_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr))
        .header("Prefer", "dynamic=true")
        .send()
        .await?;

    assert_eq!(response.status().as_u16(), 200);
    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    // dynamic=true should still produce a conforming object with id and name
    assert!(body.get("id").and_then(serde_json::Value::as_i64).is_some(), "missing id");
    assert!(body.get("name").and_then(serde_json::Value::as_str).is_some(), "missing name");
    // The dynamic faker result should differ from the named examples
    let name = body.get("name").and_then(serde_json::Value::as_str).unwrap_or_default();
    assert_ne!(name, "Fluffy", "dynamic should not return the static example");
    assert_ne!(name, "Whiskers", "dynamic should not return the static example");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn default_response_without_prefer_returns_200() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_negotiate_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/pets/1", server.http_addr)).send().await?;
    assert_eq!(response.status().as_u16(), 200);

    server.shutdown().await;
    Ok(())
}

// ── Multi-value query parameters ───────────────────────────────────────

async fn start_array_params_server() -> Result<specmock_runtime::RunningServer, RuntimeError> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_array_params_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };
    start(config).await
}

#[tokio::test]
async fn multi_value_query_param_accepted_for_array_schema()
-> Result<(), Box<dyn std::error::Error>> {
    let server = match start_array_params_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // ?tag=dog&tag=cat — both values should be preserved as an array.
    let response =
        hpx::get(format!("http://{}/search?tag=dog&tag=cat", server.http_addr)).send().await?;
    let status = response.status().as_u16();

    assert_eq!(status, 200, "expected 200 for valid array query params, got {status}");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn single_value_query_param_accepted_for_array_schema()
-> Result<(), Box<dyn std::error::Error>> {
    let server = match start_array_params_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // Single value should still form a valid one-element array.
    let response = hpx::get(format!("http://{}/search?tag=dog", server.http_addr)).send().await?;
    let status = response.status().as_u16();

    assert_eq!(status, 200, "expected 200 for single-element array query, got {status}");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn missing_required_array_query_param_returns_400() -> Result<(), Box<dyn std::error::Error>>
{
    let server = match start_array_params_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // No tag parameter at all — should be rejected.
    let response = hpx::get(format!("http://{}/search", server.http_addr)).send().await?;
    let status = response.status().as_u16();

    assert_eq!(status, 400, "expected 400 for missing required array param, got {status}");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn non_array_query_param_uses_first_value() -> Result<(), Box<dyn std::error::Error>> {
    let server = match start_array_params_server().await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // Duplicate non-array param "limit" — first value (5) should be used for validation.
    let response = hpx::get(format!("http://{}/search?tag=dog&limit=5&limit=10", server.http_addr))
        .send()
        .await?;
    let status = response.status().as_u16();

    assert_eq!(status, 200, "expected 200 when first non-array value is valid, got {status}");

    server.shutdown().await;
    Ok(())
}

// ── Body size limit and Content-Type validation ────────────────────────

fn openapi_body_limit_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-body-limit.yaml")
}

#[tokio::test]
async fn large_body_returns_413_payload_too_large() -> Result<(), Box<dyn std::error::Error>> {
    // Use a tiny max_body_size so we can trigger 413 without allocating megabytes.
    let config = ServerConfig {
        openapi_spec: Some(openapi_body_limit_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        max_body_size: 64,
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // Send a body larger than 64 bytes.
    let oversized = "x".repeat(128);
    let response = hpx::Client::new()
        .post(format!("http://{}/items", server.http_addr))
        .header("Content-Type", "application/json")
        .body(oversized)
        .send()
        .await?;

    assert_eq!(
        response.status().as_u16(),
        413,
        "expected 413 Payload Too Large for oversized body"
    );

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn wrong_content_type_returns_415_unsupported_media_type()
-> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_body_limit_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // POST with text/plain Content-Type on an endpoint that expects application/json.
    let response = hpx::Client::new()
        .post(format!("http://{}/items", server.http_addr))
        .header("Content-Type", "text/plain")
        .body(r#"{"name":"test"}"#)
        .send()
        .await?;

    assert_eq!(
        response.status().as_u16(),
        415,
        "expected 415 Unsupported Media Type for wrong Content-Type"
    );
    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    // RFC 7807 envelope
    assert_eq!(body.get("type").and_then(serde_json::Value::as_str), Some("about:blank"));
    assert_eq!(
        body.get("title").and_then(serde_json::Value::as_str),
        Some("Unsupported Media Type")
    );
    assert_eq!(body.get("status").and_then(serde_json::Value::as_u64), Some(415));

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn malformed_json_body_returns_400_bad_request() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_body_limit_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::Client::new()
        .post(format!("http://{}/items", server.http_addr))
        .header("Content-Type", "application/json")
        .body(r#"{"name":"oops""#)
        .send()
        .await?;

    assert_eq!(response.status().as_u16(), 400, "expected 400 Bad Request for malformed JSON body");

    let body: serde_json::Value = serde_json::from_slice(&response.bytes().await?)?;
    assert_eq!(body.get("status").and_then(serde_json::Value::as_u64), Some(400));
    assert_eq!(body.pointer("/errors/0/keyword").and_then(serde_json::Value::as_str), Some("json"));

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn correct_content_type_post_returns_success() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_body_limit_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // POST with correct Content-Type should succeed.
    let response = hpx::Client::new()
        .post(format!("http://{}/items", server.http_addr))
        .header("Content-Type", "application/json")
        .body(r#"{"name":"test"}"#)
        .send()
        .await?;

    let status = response.status().as_u16();
    assert_eq!(status, 201, "expected 201 for valid POST, got {status}");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn empty_body_skips_content_type_check() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_body_limit_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // GET with no body should not trigger Content-Type validation even though
    // the same spec has POST endpoints with request body schemas.
    let response = hpx::get(format!("http://{}/items", server.http_addr)).send().await?;

    let status = response.status().as_u16();
    assert_eq!(status, 200, "expected 200 for GET, got {status}");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn proxy_mode_without_upstream_returns_config_error() {
    let config = ServerConfig {
        openapi_spec: Some(openapi_spec_path()),
        mode: MockMode::Proxy,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let result = start(config).await;
    assert!(
        matches!(
            result,
            Err(RuntimeError::Config(ref message))
                if message.contains("proxy mode requires upstream")
        ),
        "expected proxy config error, got {result:?}"
    );
}

fn openapi_callbacks_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-callbacks.yaml")
}

fn openapi_polymorphic_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-polymorphic.yaml")
}

fn openapi_content_types_spec_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("specs")
        .join("openapi-content-types.yaml")
}

#[tokio::test]
async fn callbacks_are_fired_after_mock_response() -> Result<(), Box<dyn std::error::Error>> {
    use std::sync::Arc;

    use tokio::sync::Notify;

    // 1. Start a small capture server that records incoming callback requests.
    let callback_received = Arc::new(Notify::new());
    let callback_received_clone = Arc::clone(&callback_received);

    let capture_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let capture_addr = capture_listener.local_addr()?;

    let capture_task = tokio::spawn(async move {
        // Accept a single connection, read enough to confirm a POST arrived,
        // then signal via Notify.
        if let Ok((mut stream, _addr)) = capture_listener.accept().await {
            let mut buf = vec![0u8; 4096];
            let _n = tokio::io::AsyncReadExt::read(&mut stream, &mut buf).await;
            // Send a minimal HTTP 200 response so the client doesn't error.
            let response = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n";
            let _w = tokio::io::AsyncWriteExt::write_all(&mut stream, response).await;
            callback_received_clone.notify_one();
        }
    });

    // 2. Start spec-mock with the callbacks spec.
    let config = ServerConfig {
        openapi_spec: Some(openapi_callbacks_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    // 3. POST to /subscribe with a callbackUrl pointing to our capture server.
    let callback_url = format!("http://{capture_addr}");
    let body = serde_json::json!({ "callbackUrl": callback_url });
    let response = hpx::Client::new()
        .post(format!("http://{}/subscribe", server.http_addr))
        .header("Content-Type", "application/json")
        .body(serde_json::to_vec(&body)?)
        .send()
        .await?;

    let status = response.status().as_u16();
    assert_eq!(status, 201, "expected 201 for subscribe, got {status}");

    // 4. Wait for the callback to arrive (with timeout).
    let received =
        tokio::time::timeout(std::time::Duration::from_secs(5), callback_received.notified()).await;
    assert!(received.is_ok(), "callback was not received within timeout");

    capture_task.abort();
    server.shutdown().await;
    Ok(())
}

// ── Polymorphic (oneOf + discriminator) ────────────────────────────────

#[tokio::test]
async fn polymorphic_discriminator_returns_valid_shape() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_polymorphic_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/shapes/1", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 200, "expected 200 for GET /shapes/1, got {status}");
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    // The mock response should be a valid oneOf variant with a discriminator property
    assert!(body.is_object(), "expected an object body");
    let shape_type = body.get("shapeType").and_then(serde_json::Value::as_str);
    assert!(shape_type.is_some(), "missing shapeType discriminator field");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn polymorphic_list_returns_array_of_shapes() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_polymorphic_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/shapes", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 200, "expected 200 for GET /shapes, got {status}");
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    assert!(body.is_array(), "expected an array body for list endpoint");

    server.shutdown().await;
    Ok(())
}

// ── Multiple content types per response ────────────────────────────────

#[tokio::test]
async fn content_types_returns_json_by_default() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_content_types_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/report", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 200, "expected 200 for GET /report, got {status}");
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    // Default content negotiation should produce JSON
    assert!(body.get("title").and_then(serde_json::Value::as_str).is_some(), "missing title");
    assert!(body.get("data").and_then(serde_json::Value::as_array).is_some(), "missing data");

    server.shutdown().await;
    Ok(())
}

#[tokio::test]
async fn content_types_health_check() -> Result<(), Box<dyn std::error::Error>> {
    let config = ServerConfig {
        openapi_spec: Some(openapi_content_types_spec_path()),
        mode: MockMode::Mock,
        http_addr: SocketAddr::from(([127, 0, 0, 1], 0)),
        ..ServerConfig::default()
    };

    let server = match start(config).await {
        Ok(value) => value,
        Err(RuntimeError::Io(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => {
            return Ok(());
        }
        Err(error) => return Err(error.to_string().into()),
    };

    let response = hpx::get(format!("http://{}/health", server.http_addr)).send().await?;
    let status = response.status().as_u16();
    let bytes = response.bytes().await?;

    assert_eq!(status, 200, "expected 200 for GET /health, got {status}");
    let body: serde_json::Value = serde_json::from_slice(&bytes)?;

    assert_eq!(body.get("status").and_then(serde_json::Value::as_str), Some("ok"));

    server.shutdown().await;
    Ok(())
}