vimanam 1.5.0

OpenAPI/Swagger to Markdown documentation generator with grouping, filtering, and detail levels for docs and LLM context
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
use crate::common::MULTI_TAG;
use crate::common::OAS2;
use crate::common::OAS3;
use crate::common::OAS3_SCHEMA_REFS;
use crate::common::vimanam;
use predicates::prelude::*;
use std::io::Write;

const OAS3_MULTI_AUTH: &str = "tests/fixtures/multi_auth_oas3.json";
const OAS2_MULTI_AUTH: &str = "tests/fixtures/multi_auth_oas2.json";
const OAS3_EXAMPLES: &str = "tests/fixtures/examples_oas3.json";
const OAS3_REF_BODY: &str = "tests/fixtures/ref_request_body_oas3.json";

// Parse-layer correctness cluster (issues #48, #50, #51, #54, #56, #60).
const OAS2_HTTP_SCHEME: &str = "tests/fixtures/http_scheme_oas2.json";
const REF_PARAMETER: &str = "tests/fixtures/ref_parameter.json";
const REF_PATH_ITEM: &str = "tests/fixtures/ref_path_item.json";
const TYPE_ARRAY: &str = "tests/fixtures/type_array_nullable.json";
const MISSING_RESPONSES: &str = "tests/fixtures/missing_responses.json";
const OVERRIDE_PARAM: &str = "tests/fixtures/override_param.json";
const UNKNOWN_TAG: &str = "tests/fixtures/unknown_tag.json";

#[test]
fn version_flag_reports_crate_version() {
    vimanam()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn summary_lists_services_and_operations() {
    vimanam()
        .arg(OAS3)
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore API"))
        .stdout(predicate::str::contains("- Pets"))
        .stdout(predicate::str::contains("- Store"))
        // Service prefix is stripped from operation IDs in the summary view
        .stdout(predicate::str::contains("* ListPets"));
}

#[test]
fn basic_detail_writes_endpoint_sections() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("**Operation:** GET /pets"))
        .stdout(predicate::str::contains("**Operation:** POST /pets"));
}

// Regression test: optional request bodies (no `required: true`) used to be
// dropped from the parameter table entirely.
#[test]
fn optional_request_body_is_documented() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `requestBody` | body | No | Pet to add |",
        ));
}

// `--required-only` drops parameters that are not required (explicit
// `required: false` or unspecified), keeping required ones.
#[test]
fn required_only_excludes_non_required_parameters() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard", "--required-only"])
        .assert()
        .success()
        // Required path parameter is kept.
        .stdout(predicate::str::contains("| `petId` | path | Yes |"))
        // Optional query parameter is dropped.
        .stdout(predicate::str::contains("| `limit` |").not());
}

#[test]
fn required_path_param_is_documented() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `petId` | path | Yes | ID of the pet |",
        ));
}

#[test]
fn exclude_deprecated_hides_endpoint() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Store_ListOrders"));

    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--exclude-deprecated"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Store_ListOrders").not());
}

#[test]
fn method_filter_excludes_other_methods() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--method-filter", "GET"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Pets_ListPets"))
        .stdout(predicate::str::contains("Pets_CreatePet").not());
}

// Regression test for #13: methods are stored uppercase, so a lowercase
// `--method-filter` value used to match nothing and silently empty the output.
#[test]
fn method_filter_is_case_insensitive() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--method-filter", "get"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Pets_ListPets"))
        .stdout(predicate::str::contains("Pets_CreatePet").not());
}

// Regression test for #19: a case-mismatched `--service-filter` used to
// silently omit all endpoints.
#[test]
fn service_filter_is_case_insensitive() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--service-filter", "pets"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Pets_ListPets"))
        .stdout(predicate::str::contains("Store_ListOrders").not());
}

#[test]
fn path_filter_excludes_other_paths() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--path-filter", "/store"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Store_ListOrders"))
        .stdout(predicate::str::contains("Pets_ListPets").not());
}

#[test]
fn include_auth_shows_servers_and_schemes() {
    vimanam()
        .arg(OAS3)
        .arg("--include-auth")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "https://api.petstore.example.com/v1",
        ))
        .stdout(predicate::str::contains("apiKeyAuth"));
}

#[test]
fn flat_grouping_lists_all_endpoints() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--flat"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Endpoints"))
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("### Store_ListOrders"));
}

#[test]
fn oas2_spec_is_supported() {
    vimanam()
        .arg(OAS2)
        .args(["--detail", "standard", "--include-auth"])
        .assert()
        .success()
        .stdout(predicate::str::contains("# Petstore Legacy API"))
        // host + basePath are combined into a server URL
        .stdout(predicate::str::contains(
            "https://legacy.petstore.example.com/v2",
        ))
        .stdout(predicate::str::contains("Pets_CreatePet"))
        // OpenAPI 2.0 body responses infer application/json
        .stdout(predicate::str::contains(
            "| 200 | application/json | Created |",
        ));
}

// The OAS2 `schemes` field names the transfer protocol; a plain-HTTP spec must
// not be rendered with an assumed `https://` prefix. (Specs without `schemes`
// still default to https — covered by `oas2_spec_is_supported` above.)
#[test]
fn oas2_http_scheme_is_respected() {
    vimanam()
        .arg(OAS2_HTTP_SCHEME)
        .arg("--include-auth")
        .assert()
        .success()
        .stdout(predicate::str::contains("http://internal.example.com/v1"))
        .stdout(predicate::str::contains("https://internal.example.com").not());
}

#[test]
fn output_flag_writes_file() {
    let dir = tempfile::tempdir().unwrap();
    let out_path = dir.path().join("out.md");

    vimanam()
        .arg(OAS3)
        .args(["-o", out_path.to_str().unwrap()])
        .assert()
        .success();

    let content = std::fs::read_to_string(&out_path).unwrap();
    assert!(content.contains("# Petstore API"));
}

#[test]
fn invalid_json_fails() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    write!(file, "this is not json").unwrap();

    vimanam()
        .arg(file.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error:"));
}

#[test]
fn json_without_openapi_fields_fails() {
    let mut file = tempfile::NamedTempFile::new().unwrap();
    write!(file, "{{\"hello\": \"world\"}}").unwrap();

    vimanam()
        .arg(file.path())
        .assert()
        .failure()
        .stderr(predicate::str::contains("Error:"));
}

// Output must be byte-identical across runs, even with sorting disabled.
// Guards the IndexMap-based ordering of paths, responses, and content types.
#[test]
fn output_is_deterministic() {
    let run = || {
        vimanam()
            .arg(OAS3)
            .args([
                "--detail",
                "full",
                "--include-schemas",
                "--include-auth",
                "--sort",
                "none",
            ])
            .output()
            .unwrap()
            .stdout
    };

    let first = run();
    for _ in 0..4 {
        assert_eq!(first, run(), "output differed between identical runs");
    }
}

// By default (#58) component schemas are linked from their use site and expanded
// once in a trailing "Schema Definitions" section, rather than re-inlined.
#[test]
fn full_detail_links_schema_refs_to_definitions() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        // The use site is a single linked row, not a re-inlined subtree.
        .stdout(predicate::str::contains(
            "| `request` | [CreatePetRequest](#schema-createpetrequest) | - | - |",
        ))
        .stdout(predicate::str::contains(
            "| `response` | [Pet](#schema-pet) | - | - |",
        ))
        // The shared schemas are expanded once in the definitions section.
        .stdout(predicate::str::contains("## Schema Definitions"))
        .stdout(predicate::str::contains(
            "### CreatePetRequest {#schema-createpetrequest}",
        ))
        .stdout(predicate::str::contains(
            "| `CreatePetRequest.name` | string | Yes | Pet name |",
        ))
        .stdout(predicate::str::contains(
            "| `CreatePetRequest.category` | [Category](#schema-category) | Yes |",
        ))
        .stdout(predicate::str::contains(
            "| `Category.id` | string | Yes | Category identifier |",
        ))
        .stdout(predicate::str::contains(
            "| `Pet.allOf[1].id` | string | Yes | Pet identifier |",
        ));
}

// CreatePetRequest is referenced from the /pets request body and again from
// Pet's `allOf`; it must be expanded exactly once (the #58 win).
#[test]
fn shared_schema_is_expanded_once() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS3_SCHEMA_REFS)
            .args(["--detail", "full", "--include-schemas"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    let definitions = output
        .matches("### CreatePetRequest {#schema-createpetrequest}")
        .count();
    assert_eq!(
        definitions, 1,
        "CreatePetRequest expanded {definitions} times"
    );
}

// A self-referential schema (Node.next -> Node) renders once and links back to
// itself instead of looping or printing a "cycle detected" row.
#[test]
fn linked_mode_handles_self_reference_with_a_link() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        .stdout(predicate::str::contains("### Node {#schema-node}"))
        .stdout(predicate::str::contains(
            "| `Node.next` | [Node](#schema-node) | No |",
        ))
        .stdout(predicate::str::contains("Cycle detected").not());
}

// `--inline-schemas` restores the fully self-contained output: every `$ref` is
// expanded inline at each use site, with no shared definitions section.
#[test]
fn inline_schemas_expands_refs_at_each_use_site() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas", "--inline-schemas"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `request.name` | string | Yes | Pet name |",
        ))
        .stdout(predicate::str::contains(
            "| `request.category.id` | string | Yes | Category identifier |",
        ))
        .stdout(predicate::str::contains(
            "| `response.allOf[1].id` | string | Yes | Pet identifier |",
        ))
        .stdout(predicate::str::contains("request.variant.oneOf[0]"))
        .stdout(predicate::str::contains("## Schema Definitions").not());
}

// #69 follow-up: the "no effect" warning reports the current detail level in the
// same lowercase spelling the user types (`standard`), not the Debug-derived
// `Standard`.
#[test]
fn include_schemas_warning_uses_lowercase_detail_name() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard", "--include-schemas"])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "--include-schemas has no effect at --detail standard; use --detail full.",
        ));
}

// At `--detail full` the flag takes effect, so no warning is emitted.
#[test]
fn include_schemas_at_full_detail_emits_no_warning() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        .stderr(predicate::str::contains("no effect").not());
}

// `--inline-schemas` only changes how schemas render, so it warns when used
// without `--include-schemas`.
#[test]
fn inline_schemas_without_include_schemas_warns() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "full", "--inline-schemas"])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "--inline-schemas has no effect without --include-schemas.",
        ));
}

// `--required-only` only filters the parameters table, which basic/summary
// detail never renders — so it warns there like the other no-effect flags.
#[test]
fn required_only_at_basic_detail_warns() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--required-only"])
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "--required-only has no effect at --detail basic; use --detail standard or full.",
        ));
}

// At `--detail standard` the flag takes effect, so no warning is emitted.
#[test]
fn required_only_at_standard_detail_emits_no_warning() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "standard", "--required-only"])
        .assert()
        .success()
        .stderr(predicate::str::contains("no effect").not());
}

// `--toc` is the explicit opposite of `--no-toc`; the TOC is on by default, and
// when both flags are given the later one wins.
#[test]
fn toc_flag_is_accepted_and_last_one_wins() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--toc"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Services"));

    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--no-toc", "--toc"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Services"));

    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--toc", "--no-toc"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Services").not());
}

// #70 follow-up: an operation carrying multiple tags is rendered under each
// service section, so its heading anchor must be scoped per service to stay
// unique — and each TOC link must point at the matching copy.
#[test]
fn multi_tag_endpoint_gets_unique_anchors_per_service() {
    let output = String::from_utf8(
        vimanam()
            .arg(MULTI_TAG)
            .args(["--detail", "basic"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    // Distinct, service-scoped heading anchors (no duplicate `#delete-pets-petid`).
    assert!(
        output.contains("### DeletePet {#pets-delete-pets-petid}"),
        "missing Pets-scoped anchor:\n{output}"
    );
    assert!(
        output.contains("### DeletePet {#admin-delete-pets-petid}"),
        "missing Admin-scoped anchor:\n{output}"
    );

    // Each TOC entry links to the copy under its own service.
    assert!(
        output.contains("* [DeletePet](#pets-delete-pets-petid)")
            && output.contains("* [DeletePet](#admin-delete-pets-petid)"),
        "TOC links do not match per-service anchors:\n{output}"
    );
}

// Regression test for #16: the Authentication section is emitted in spec
// (file) order, not the random order of a HashMap, and is stable across runs.
#[test]
fn multiple_security_schemes_preserve_spec_order() {
    let run = || {
        String::from_utf8(
            vimanam()
                .arg(OAS3_MULTI_AUTH)
                .arg("--include-auth")
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap()
    };

    let output = run();

    let zebra = output.find("zebraAuth").expect("zebraAuth missing");
    let api_key = output.find("apiKeyAuth").expect("apiKeyAuth missing");
    let middle = output.find("middleAuth").expect("middleAuth missing");

    // Schemes appear in the order they are declared in the spec file.
    assert!(
        zebra < api_key && api_key < middle,
        "security schemes not in spec order: {output}"
    );

    // And that order is deterministic across runs.
    for _ in 0..4 {
        assert_eq!(output, run(), "authentication order differed between runs");
    }
}

// Companion to #16 for OpenAPI 2.0: `securityDefinitions` are read through the
// extensions map, so they only preserve spec order with serde_json's
// `preserve_order` feature (otherwise they sort alphabetically). The schemes
// are declared zebra/apiKey/middle, which is not alphabetical.
#[test]
fn oas2_security_schemes_preserve_spec_order() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS2_MULTI_AUTH)
            .arg("--include-auth")
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    let zebra = output.find("zebraAuth").expect("zebraAuth missing");
    let api_key = output.find("apiKey").expect("apiKey missing");
    let middle = output.find("middleAuth").expect("middleAuth missing");

    assert!(
        zebra < api_key && api_key < middle,
        "OAS2 security schemes not in spec order: {output}"
    );
}

// Regression test for #20: `--group-by method` must behave like `--method`,
// producing HTTP-method sections rather than service sections.
#[test]
fn group_by_method_groups_by_http_method() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--group-by", "method"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## GET"))
        .stdout(predicate::str::contains("## POST"));
}

// Regression test for #18: under alphabetical sort the TOC operation links must
// appear in the same order as the endpoint sections in the body.
#[test]
fn toc_order_matches_body_order() {
    let output = String::from_utf8(
        vimanam()
            .arg(OAS3)
            .args(["--detail", "basic", "--sort", "alpha"])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();

    // The Pets service has CreatePet (POST /pets) and ListPets (GET /pets);
    // sorted by path then method, GET sorts before POST, so ListPets precedes
    // CreatePet in both the TOC and the body.
    let toc_list = output
        .find("[Pets_ListPets]")
        .expect("ListPets TOC link missing");
    let toc_create = output
        .find("[Pets_CreatePet]")
        .expect("CreatePet TOC link missing");
    let body_list = output
        .find("### Pets_ListPets")
        .expect("ListPets section missing");
    let body_create = output
        .find("### Pets_CreatePet")
        .expect("CreatePet section missing");

    assert!(toc_list < toc_create, "TOC order unexpected: {output}");
    assert!(body_list < body_create, "body order unexpected: {output}");
}

// #6: `--include-examples` at `--detail full` renders the request body's inline
// example and the response example resolved from a `$ref` into
// `components/examples`.
#[test]
fn include_examples_renders_request_and_response() {
    vimanam()
        .arg(OAS3_EXAMPLES)
        .args(["--detail", "full", "--include-examples"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#### Examples"))
        // Inline request body example.
        .stdout(predicate::str::contains("**Request**"))
        .stdout(predicate::str::contains("\"name\": \"Fluffy\""))
        // Response example resolved through #/components/examples/CreatedPet.
        .stdout(predicate::str::contains("Response `201`"))
        .stdout(predicate::str::contains("\"id\": 7"));
}

// Examples only render at `--detail full`, matching `--include-schemas`.
#[test]
fn include_examples_only_at_full_detail() {
    vimanam()
        .arg(OAS3_EXAMPLES)
        .args(["--detail", "standard", "--include-examples"])
        .assert()
        .success()
        .stdout(predicate::str::contains("#### Examples").not());
}

// A `requestBody` given as a `$ref` into `components/requestBodies` is resolved
// during parsing: its description/required surface in the parameter table, and
// at `--detail full` its referenced schema expands. Before resolution such a
// spec failed to parse at all.
#[test]
fn ref_request_body_is_resolved() {
    vimanam()
        .arg(OAS3_REF_BODY)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `requestBody` | body | Yes | Pet to add |",
        ));

    vimanam()
        .arg(OAS3_REF_BODY)
        .args(["--detail", "full", "--include-schemas"])
        .assert()
        .success()
        // The resolved body schema is linked and expanded in the definitions
        // section.
        .stdout(predicate::str::contains("## Schema Definitions"))
        .stdout(predicate::str::contains(
            "| `Pet.name` | string | Yes | Pet name |",
        ));
}

// #8: `--group-by path` produces one section per path with its operations
// underneath.
#[test]
fn group_by_path_groups_by_path() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--group-by", "path"])
        .assert()
        .success()
        .stdout(predicate::str::contains("## Paths"))
        .stdout(predicate::str::contains("## /pets/{petId}"))
        .stdout(predicate::str::contains("## /store/orders"))
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stdout(predicate::str::contains("### Pets_CreatePet"));
}

// #7: a tiny `--max-tokens` budget forces a full-detail request down to a lower
// detail level and reports the reduction on stderr.
#[test]
fn max_tokens_steps_down_detail_level() {
    vimanam()
        .arg(OAS3)
        .args([
            "--detail",
            "full",
            "--include-schemas",
            "--max-tokens",
            "40",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("token budget"))
        .stderr(predicate::str::contains("--detail summary"));
}

// A generous `--max-tokens` budget leaves the requested detail untouched and
// emits no stderr note.
#[test]
fn max_tokens_keeps_detail_when_it_fits() {
    vimanam()
        .arg(OAS3)
        .args(["--detail", "basic", "--max-tokens", "100000"])
        .assert()
        .success()
        .stdout(predicate::str::contains("### Pets_ListPets"))
        .stderr(predicate::str::is_empty());
}

// Under `--inline-schemas` the recursive expansion still guards against `$ref`
// cycles, breaking the chain with a "cycle detected" row.
#[test]
fn inline_schema_expansion_detects_ref_cycles() {
    vimanam()
        .arg(OAS3_SCHEMA_REFS)
        .args(["--detail", "full", "--include-schemas", "--inline-schemas"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Cycle detected while expanding schema reference",
        ));
}

// #48: a parameter declared as a component `$ref` is resolved instead of
// failing the whole parse (a bare `$ref` param used to crash on `missing field name`).
#[test]
fn ref_parameter_is_resolved() {
    vimanam()
        .arg(REF_PARAMETER)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `limit` | query | No | Max results |",
        ));
}

// #50: a path item declared as a `$ref` yields its operation instead of being
// silently dropped.
#[test]
fn path_item_ref_yields_operation() {
    vimanam()
        .arg(REF_PATH_ITEM)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Things_ListThings"))
        .stdout(predicate::str::contains("**Operation:** GET /things"));
}

// #51: OpenAPI 3.1 `type` arrays (e.g. ["string","null"]) parse instead of
// failing on "invalid type: sequence".
#[test]
fn type_array_parameter_parses() {
    vimanam()
        .arg(TYPE_ARRAY)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "| `q` | query | No | Search term |",
        ));
}

// #56: an operation missing its `responses` block no longer fails the whole
// document; both operations are still rendered.
#[test]
fn operation_missing_responses_still_parses() {
    vimanam()
        .arg(MISSING_RESPONSES)
        .args(["--detail", "basic"])
        .assert()
        .success()
        .stdout(predicate::str::contains("A_NoResponses"))
        .stdout(predicate::str::contains("B_HasResponses"));
}

// #54: an operation-level parameter overrides a path-level one of the same
// (name, in) — it should appear exactly once.
#[test]
fn duplicate_parameter_is_deduplicated() {
    let output = vimanam()
        .arg(OVERRIDE_PARAM)
        .args(["--detail", "standard"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(output).unwrap();
    let id_rows = text.matches("| `id` | path |").count();
    assert_eq!(id_rows, 1, "expected a single `id` row, got {id_rows}");
    // The operation-level definition wins.
    assert!(text.contains("Operation-level id wins"));
}

// #60: an operation tagged with a value not in the declared `tags` list gets its
// own service section instead of being silently reassigned to the first service.
#[test]
fn unknown_operation_tag_keeps_its_own_service() {
    vimanam()
        .arg(UNKNOWN_TAG)
        .args(["--detail", "basic"])
        .assert()
        .success()
        // The undeclared tag Gamma becomes its own service section (under the
        // bug it would not exist — the endpoint was dumped under Alpha)...
        .stdout(predicate::str::contains("## Gamma"))
        .stdout(predicate::str::contains("W_Get"))
        // ...and the first declared service ends up with no endpoints.
        .stdout(predicate::str::contains(
            "## Alpha {#alpha}\n\nNo endpoints found for this service.",
        ));
}

// Shell completions (#41): `vimanam completions <SHELL>` prints a completion
// script for every shell clap_complete supports, without needing a spec file.
#[test]
fn completions_are_generated_for_each_supported_shell() {
    // Each shell is paired with a marker unique to its script format, so the
    // test fails if every shell were to emit the same (e.g. bash) script.
    let shells = [
        ("bash", "complete -F _vimanam"),
        ("zsh", "#compdef vimanam"),
        ("fish", "complete -c vimanam"),
        ("powershell", "Register-ArgumentCompleter"),
        ("elvish", "edit:completion:arg-completer[vimanam]"),
    ];
    for (shell, marker) in shells {
        vimanam()
            .args(["completions", shell])
            .assert()
            .success()
            .stdout(predicate::str::contains(marker))
            .stderr(predicate::str::is_empty());
    }

    // The script must actually cover the CLI's options.
    vimanam()
        .args(["completions", "bash"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--group-by"));
}

#[test]
fn completions_rejects_unsupported_shell() {
    vimanam()
        .args(["completions", "nushell"])
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("invalid value 'nushell'"));
}

#[test]
fn completions_requires_a_shell() {
    vimanam()
        .arg("completions")
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("<SHELL>"));
}

// The subcommand must not loosen the normal path: with no subcommand the spec
// file is still required.
#[test]
fn no_arguments_still_requires_input_file() {
    vimanam()
        .assert()
        .failure()
        .code(2)
        .stderr(predicate::str::contains("<FILE>"));
}

// Conversion flags and the spec file are meaningless alongside a subcommand,
// so mixing them is an error rather than being silently ignored.
#[test]
fn completions_conflicts_with_conversion_arguments() {
    vimanam()
        .args([OAS3, "completions", "bash"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}