aperture-cli 0.1.9

Dynamic CLI generator for OpenAPI specifications
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
mod test_helpers;

use aperture_cli::batch::{BatchConfig, BatchFile, BatchMetadata, BatchOperation, BatchProcessor};
use aperture_cli::cache::models::{CachedCommand, CachedParameter, CachedSpec, PaginationInfo};
use aperture_cli::cli::OutputFormat;
use aperture_cli::constants;
use std::collections::HashMap;
use std::io::Write;
use tempfile::NamedTempFile;

fn create_test_spec() -> CachedSpec {
    CachedSpec {
        cache_format_version: aperture_cli::cache::models::CACHE_FORMAT_VERSION,
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        commands: vec![
            CachedCommand {
                name: "users".to_string(),
                description: Some("Get user by ID".to_string()),
                summary: None,
                operation_id: "getUserById".to_string(),
                method: constants::HTTP_METHOD_GET.to_string(),
                path: "/users/{id}".to_string(),
                parameters: vec![CachedParameter {
                    name: "id".to_string(),
                    location: "path".to_string(),
                    required: true,
                    description: Some("User ID".to_string()),
                    schema: Some(r#"{"type": "string"}"#.to_string()),
                    schema_type: Some("string".to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                }],
                request_body: None,
                responses: vec![],
                security_requirements: vec![],
                tags: vec!["users".to_string()],
                deprecated: false,
                external_docs_url: None,
                examples: vec![],
                display_group: None,
                display_name: None,
                aliases: vec![],
                hidden: false,
                pagination: PaginationInfo::default(),
            },
            CachedCommand {
                name: "users".to_string(),
                description: Some("Create a new user".to_string()),
                summary: None,
                operation_id: "createUser".to_string(),
                method: constants::HTTP_METHOD_POST.to_string(),
                path: "/users".to_string(),
                parameters: vec![],
                request_body: Some(aperture_cli::cache::models::CachedRequestBody {
                    description: Some("User data".to_string()),
                    required: true,
                    content_type: constants::CONTENT_TYPE_JSON.to_string(),
                    schema: r#"{"type": "object"}"#.to_string(),
                    example: Some(
                        r#"{"name": "John Doe", "email": "john@example.com"}"#.to_string(),
                    ),
                }),
                responses: vec![],
                security_requirements: vec![],
                tags: vec!["users".to_string()],
                deprecated: false,
                external_docs_url: None,
                examples: vec![],
                display_group: None,
                display_name: None,
                aliases: vec![],
                hidden: false,
                pagination: PaginationInfo::default(),
            },
        ],
        base_url: Some("https://api.example.com".to_string()),
        servers: vec!["https://api.example.com".to_string()],
        security_schemes: HashMap::new(),
        skipped_endpoints: vec![],
        server_variables: HashMap::new(),
    }
}

#[tokio::test]
async fn test_batch_file_parsing_json() {
    let batch_content = r#"{
        "operations": [
            {
                "id": "get-user-1",
                "args": ["users", "get-user-by-id", "--id", "123"]
            },
            {
                "id": "get-user-2",
                "args": ["users", "get-user-by-id", "--id", "456"]
            }
        ]
    }"#;

    let mut temp_file = NamedTempFile::new().unwrap();
    temp_file.write_all(batch_content.as_bytes()).unwrap();
    temp_file.flush().unwrap();

    let batch_file = BatchProcessor::parse_batch_file(temp_file.path())
        .await
        .unwrap();

    assert_eq!(batch_file.operations.len(), 2);
    assert_eq!(batch_file.operations[0].id, Some("get-user-1".to_string()));
    assert_eq!(
        batch_file.operations[0].args,
        vec!["users", "get-user-by-id", "--id", "123"]
    );
    assert_eq!(batch_file.operations[1].id, Some("get-user-2".to_string()));
    assert_eq!(
        batch_file.operations[1].args,
        vec!["users", "get-user-by-id", "--id", "456"]
    );
}

#[tokio::test]
async fn test_batch_file_parsing_yaml() {
    let batch_content = r#"
operations:
  - id: create-user-1
    args: [users, create-user, --body, '{"name": "Alice", "email": "alice@example.com"}']
  - id: create-user-2
    args: [users, create-user, --body, '{"name": "Bob", "email": "bob@example.com"}']
"#;

    let mut temp_file = NamedTempFile::new().unwrap();
    temp_file.write_all(batch_content.as_bytes()).unwrap();
    temp_file.flush().unwrap();

    let batch_file = BatchProcessor::parse_batch_file(temp_file.path())
        .await
        .unwrap();

    assert_eq!(batch_file.operations.len(), 2);
    assert_eq!(
        batch_file.operations[0].id,
        Some("create-user-1".to_string())
    );
    assert_eq!(batch_file.operations[0].args[0], "users");
    assert_eq!(batch_file.operations[0].args[1], "create-user");
    assert_eq!(
        batch_file.operations[1].id,
        Some("create-user-2".to_string())
    );
}

#[tokio::test]
async fn test_batch_file_parsing_invalid_format() {
    let batch_content = "invalid json content {";

    let mut temp_file = NamedTempFile::new().unwrap();
    temp_file.write_all(batch_content.as_bytes()).unwrap();
    temp_file.flush().unwrap();

    let result = BatchProcessor::parse_batch_file(temp_file.path()).await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_batch_file_parsing_empty_operations() {
    let batch_content = r#"{
        "operations": []
    }"#;

    let mut temp_file = NamedTempFile::new().unwrap();
    temp_file.write_all(batch_content.as_bytes()).unwrap();
    temp_file.flush().unwrap();

    let batch_file = BatchProcessor::parse_batch_file(temp_file.path())
        .await
        .unwrap();
    assert_eq!(batch_file.operations.len(), 0);
}

#[tokio::test]
async fn test_batch_config_default() {
    let config = BatchConfig::default();
    assert_eq!(config.max_concurrency, 5);
    assert_eq!(config.rate_limit, None);
    assert!(config.continue_on_error);
    assert!(config.show_progress);
}

#[tokio::test]
async fn test_batch_config_custom() {
    let config = BatchConfig {
        max_concurrency: 10,
        rate_limit: Some(100),
        continue_on_error: true,
        show_progress: true,
        suppress_output: false,
    };

    assert_eq!(config.max_concurrency, 10);
    assert_eq!(config.rate_limit, Some(100));
    assert!(config.continue_on_error);
    assert!(config.show_progress);
}

#[tokio::test]
async fn test_batch_processor_creation() {
    let config = BatchConfig {
        max_concurrency: 3,
        rate_limit: Some(50),
        continue_on_error: false,
        show_progress: false,
        suppress_output: false,
    };

    let _processor = BatchProcessor::new(config);
    // Verify the processor was created successfully
    // We can't directly access config fields as they are private
}

#[tokio::test]
async fn test_batch_operation_serialization() {
    let operation = BatchOperation {
        id: Some("test-op".to_string()),
        args: vec![
            "users".to_string(),
            "get-user-by-id".to_string(),
            "--id".to_string(),
            "123".to_string(),
        ],
        description: None,
        headers: std::collections::HashMap::new(),
        use_cache: None,
        ..Default::default()
    };

    let serialized = serde_json::to_string(&operation).unwrap();
    let deserialized: BatchOperation = serde_json::from_str(&serialized).unwrap();

    assert_eq!(deserialized.id, Some("test-op".to_string()));
    assert_eq!(
        deserialized.args,
        vec!["users", "get-user-by-id", "--id", "123"]
    );
}

#[tokio::test]
async fn test_batch_file_serialization() {
    let batch_file = BatchFile {
        metadata: None,
        operations: vec![
            BatchOperation {
                id: Some("op1".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "123".to_string(),
                ],
                description: None,
                headers: std::collections::HashMap::new(),
                use_cache: None,
                ..Default::default()
            },
            BatchOperation {
                id: Some("op2".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "456".to_string(),
                ],
                description: None,
                headers: std::collections::HashMap::new(),
                use_cache: None,
                ..Default::default()
            },
        ],
    };

    let serialized = serde_json::to_string_pretty(&batch_file).unwrap();
    let deserialized: BatchFile = serde_json::from_str(&serialized).unwrap();

    assert_eq!(deserialized.operations.len(), 2);
    assert_eq!(deserialized.operations[0].id, Some("op1".to_string()));
    assert_eq!(deserialized.operations[1].id, Some("op2".to_string()));
}

#[tokio::test]
async fn test_batch_dry_run_execution() {
    let spec = create_test_spec();
    let config = BatchConfig::default();
    let processor = BatchProcessor::new(config);

    let batch_file = BatchFile {
        metadata: None,
        operations: vec![BatchOperation {
            id: Some("test-op".to_string()),
            args: vec![
                "users".to_string(),
                "get-user-by-id".to_string(),
                "--id".to_string(),
                "123".to_string(),
            ],
            description: None,
            headers: std::collections::HashMap::new(),
            use_cache: None,
            ..Default::default()
        }],
    };

    // This test verifies dry-run mode works correctly
    let result = processor
        .execute_batch(
            &spec,
            batch_file,
            None,
            None,
            true, // dry_run
            &OutputFormat::Json,
            None,
        )
        .await;

    // Dry run should complete successfully
    assert!(result.is_ok());
    let batch_result = result.unwrap();
    assert_eq!(batch_result.results.len(), 1);
    assert_eq!(batch_result.success_count, 1);
    assert_eq!(batch_result.failure_count, 0);
}

#[tokio::test]
async fn test_batch_complex_operations() {
    let batch_content = r#"{
        "operations": [
            {
                "id": "create-user",
                "args": ["users", "create-user", "--body", "{\"name\": \"John\", \"email\": \"john@example.com\"}"]
            },
            {
                "id": "get-user",
                "args": ["users", "get-user-by-id", "--id", "123"]
            },
            {
                "id": "update-user",
                "args": ["users", "update-user", "123", "--body", "{\"name\": \"John Updated\"}"]
            }
        ]
    }"#;

    let mut temp_file = NamedTempFile::new().unwrap();
    temp_file.write_all(batch_content.as_bytes()).unwrap();
    temp_file.flush().unwrap();

    let batch_file = BatchProcessor::parse_batch_file(temp_file.path())
        .await
        .unwrap();

    assert_eq!(batch_file.operations.len(), 3);

    // Verify create operation
    assert_eq!(batch_file.operations[0].id, Some("create-user".to_string()));
    assert!(batch_file.operations[0]
        .args
        .contains(&"--body".to_string()));

    // Verify get operation
    assert_eq!(batch_file.operations[1].id, Some("get-user".to_string()));
    assert!(batch_file.operations[1]
        .args
        .contains(&"get-user-by-id".to_string()));

    // Verify update operation
    assert_eq!(batch_file.operations[2].id, Some("update-user".to_string()));
    assert!(batch_file.operations[2]
        .args
        .contains(&"update-user".to_string()));
}

#[tokio::test]
async fn test_batch_real_execution_with_mock_server() {
    // Start a mock server
    let mock_server = wiremock::MockServer::start().await;

    // Set up mock responses
    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("GET"))
                .and(wiremock::matchers::path("/users/123"))
                .respond_with(
                    wiremock::ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({
                            "id": 123,
                            "name": "John Doe",
                            "email": "john@example.com"
                        }))
                        .insert_header("content-type", constants::CONTENT_TYPE_JSON),
                ),
        )
        .await;

    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("GET"))
                .and(wiremock::matchers::path("/users/456"))
                .respond_with(
                    wiremock::ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({
                            "id": 456,
                            "name": "Jane Smith",
                            "email": "jane@example.com"
                        }))
                        .insert_header("content-type", constants::CONTENT_TYPE_JSON),
                ),
        )
        .await;

    // Create spec with mock server URL
    let mut spec = create_test_spec();
    spec.base_url = Some(mock_server.uri());
    spec.servers = vec![mock_server.uri()];

    let config = BatchConfig::default();
    let processor = BatchProcessor::new(config);

    let batch_file = BatchFile {
        metadata: Some(BatchMetadata {
            name: Some("Test Batch".to_string()),
            version: Some("1.0".to_string()),
            description: Some("Test batch execution".to_string()),
            defaults: None,
        }),
        operations: vec![
            BatchOperation {
                id: Some("get-user-123".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "123".to_string(),
                ],
                description: Some("Get user 123".to_string()),
                headers: std::collections::HashMap::new(),
                use_cache: Some(false),
                ..Default::default()
            },
            BatchOperation {
                id: Some("get-user-456".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "456".to_string(),
                ],
                description: Some("Get user 456".to_string()),
                headers: std::collections::HashMap::new(),
                use_cache: Some(false),
                ..Default::default()
            },
        ],
    };

    // Execute actual batch operations (not dry run)
    let result = processor
        .execute_batch(
            &spec,
            batch_file,
            None,
            Some(&mock_server.uri()),
            false, // real execution
            &OutputFormat::Json,
            None,
        )
        .await;

    assert!(result.is_ok(), "Batch execution should succeed");
    let batch_result = result.unwrap();
    assert_eq!(batch_result.results.len(), 2);
    assert_eq!(batch_result.success_count, 2);
    assert_eq!(batch_result.failure_count, 0);
    assert!(batch_result.total_duration.as_millis() > 0);

    // Verify that the mock server received the expected requests
    mock_server.verify().await;
}

#[tokio::test]
async fn test_batch_execution_with_error_handling() {
    // Start a mock server
    let mock_server = wiremock::MockServer::start().await;

    // Set up one successful and one failing response
    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("GET"))
                .and(wiremock::matchers::path("/users/123"))
                .respond_with(
                    wiremock::ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({
                            "id": 123,
                            "name": "John Doe",
                            "email": "john@example.com"
                        }))
                        .insert_header("content-type", constants::CONTENT_TYPE_JSON),
                ),
        )
        .await;

    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("GET"))
                .and(wiremock::matchers::path("/users/999"))
                .respond_with(wiremock::ResponseTemplate::new(404)),
        )
        .await;

    // Create spec with mock server URL
    let mut spec = create_test_spec();
    spec.base_url = Some(mock_server.uri());
    spec.servers = vec![mock_server.uri()];

    let config = BatchConfig {
        max_concurrency: 2,
        rate_limit: None,
        continue_on_error: true,
        show_progress: false,
        suppress_output: false,
    };
    let processor = BatchProcessor::new(config);

    let batch_file = BatchFile {
        metadata: None,
        operations: vec![
            BatchOperation {
                id: Some("get-user-123".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "123".to_string(),
                ],
                description: Some("Get user 123".to_string()),
                headers: std::collections::HashMap::new(),
                use_cache: Some(false),
                ..Default::default()
            },
            BatchOperation {
                id: Some("get-user-999".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "999".to_string(),
                ],
                description: Some("Get non-existent user".to_string()),
                headers: std::collections::HashMap::new(),
                use_cache: Some(false),
                ..Default::default()
            },
        ],
    };

    // Execute batch operations
    let result = processor
        .execute_batch(
            &spec,
            batch_file,
            None,
            Some(&mock_server.uri()),
            false, // real execution
            &OutputFormat::Json,
            None,
        )
        .await;

    assert!(
        result.is_ok(),
        "Batch execution should complete even with errors"
    );
    let batch_result = result.unwrap();
    assert_eq!(batch_result.results.len(), 2);
    assert_eq!(batch_result.success_count, 1); // One success
    assert_eq!(batch_result.failure_count, 1); // One failure

    // Verify that the mock server received the expected requests
    mock_server.verify().await;
}

#[tokio::test]
async fn test_batch_operation_body_file_field_is_parsed() {
    // `body_file` is a convenience field in BatchOperation.
    // Verify that the batch parser deserialises it and makes it available.
    let batch_content = r#"{
        "operations": [
            {
                "id": "create-event",
                "args": ["events", "add"],
                "body_file": "/tmp/payload.json"
            }
        ]
    }"#;

    let mut temp_file = NamedTempFile::new().unwrap();
    temp_file.write_all(batch_content.as_bytes()).unwrap();
    temp_file.flush().unwrap();

    let batch_file = BatchProcessor::parse_batch_file(temp_file.path())
        .await
        .unwrap();

    assert_eq!(batch_file.operations.len(), 1);
    assert_eq!(
        batch_file.operations[0].body_file.as_deref(),
        Some("/tmp/payload.json"),
        "body_file field should be deserialised from the batch file"
    );
}

#[tokio::test]
async fn test_batch_execution_with_body_file() {
    // Verifies that a BatchOperation using `body_file` reads the JSON from the
    // file and sends it as the HTTP request body, exercising the full path
    // through execute_single_operation (not just deserialization).
    let body_json = r#"{"name":"Alice","email":"alice@example.com"}"#;
    let mut tmp = NamedTempFile::new().unwrap();
    tmp.write_all(body_json.as_bytes()).unwrap();
    tmp.flush().unwrap();

    let mock_server = wiremock::MockServer::start().await;

    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("POST"))
                .and(wiremock::matchers::path("/users"))
                .and(wiremock::matchers::body_json(serde_json::json!({
                    "name": "Alice",
                    "email": "alice@example.com"
                })))
                .respond_with(
                    wiremock::ResponseTemplate::new(201)
                        .set_body_json(serde_json::json!({"id": 1}))
                        .insert_header("content-type", constants::CONTENT_TYPE_JSON),
                )
                .expect(1),
        )
        .await;

    let mut spec = create_test_spec();
    spec.base_url = Some(mock_server.uri());
    spec.servers = vec![mock_server.uri()];

    let config = BatchConfig::default();
    let processor = BatchProcessor::new(config);

    let batch_file = BatchFile {
        metadata: None,
        operations: vec![BatchOperation {
            id: Some("create-alice".to_string()),
            args: vec!["users".to_string(), "create-user".to_string()],
            body_file: Some(tmp.path().to_str().unwrap().to_string()),
            ..Default::default()
        }],
    };

    let result = processor
        .execute_batch(
            &spec,
            batch_file,
            None,
            Some(&mock_server.uri()),
            false,
            &OutputFormat::Json,
            None,
        )
        .await
        .expect("batch execution with body_file should succeed");

    assert_eq!(result.success_count, 1);
    assert_eq!(result.failure_count, 0);

    // Verify the mock received exactly one request with the expected body.
    mock_server.verify().await;
}

#[tokio::test]
async fn test_body_file_field_conflicts_with_body_file_in_args() {
    // body_file field + --body-file in args would silently discard the args
    // entry because execute_single_operation appends --body-file last and
    // clap's Set action picks the last value. The guard must catch this early.
    let body_json = r#"{"name":"Alice"}"#;
    let mut tmp = NamedTempFile::new().unwrap();
    tmp.write_all(body_json.as_bytes()).unwrap();
    tmp.flush().unwrap();

    let spec = create_test_spec();
    let config = BatchConfig::default();
    let processor = BatchProcessor::new(config);

    let batch_file = BatchFile {
        metadata: None,
        operations: vec![BatchOperation {
            id: Some("create-alice".to_string()),
            // Both body_file field and --body-file in args: should be rejected.
            args: vec![
                "users".to_string(),
                "create-user".to_string(),
                "--body-file".to_string(),
                "/other.json".to_string(),
            ],
            body_file: Some(tmp.path().to_str().unwrap().to_string()),
            ..Default::default()
        }],
    };

    let result = processor
        .execute_batch(
            &spec,
            batch_file,
            None,
            None,
            false,
            &OutputFormat::Json,
            None,
        )
        .await
        .expect("batch should not hard-fail; conflict is reported per-operation");

    assert_eq!(result.failure_count, 1, "conflict should produce a failure");
    let err = result.results[0].error.as_deref().unwrap_or("");
    assert!(
        err.contains("conflicts"),
        "error should mention the conflict; got: {err}"
    );
}

#[tokio::test]
async fn test_body_file_path_interpolated_in_dependent_batch() {
    // Exercises the dependent batch path where body_file contains a {{variable}}
    // placeholder. The variable is captured from the first operation's response
    // and interpolated into the file path before the second operation reads it.
    //
    // Op 1: GET /users/1  — captures `.role` as `user_role`
    // Op 2: POST /users   — body_file points to a pre-created file whose name
    //                       embeds {{user_role}}, exercising interpolate_string.

    let role = "admin";
    let tmp_dir = tempfile::tempdir().unwrap();

    // Pre-create the file that body_file will resolve to after interpolation.
    let resolved_path = tmp_dir.path().join(format!("body-{role}.json"));
    std::fs::write(&resolved_path, r#"{"name":"Eve","role":"admin"}"#).unwrap();

    // Template path contains the placeholder; the batch engine will substitute it.
    let body_file_template = format!("{}/body-{{{{user_role}}}}.json", tmp_dir.path().display());

    let mock_server = wiremock::MockServer::start().await;

    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("GET"))
                .and(wiremock::matchers::path("/users/1"))
                .respond_with(
                    wiremock::ResponseTemplate::new(200)
                        .set_body_json(serde_json::json!({"id": 1, "role": role}))
                        .insert_header("content-type", constants::CONTENT_TYPE_JSON),
                )
                .expect(1),
        )
        .await;

    mock_server
        .register(
            wiremock::Mock::given(wiremock::matchers::method("POST"))
                .and(wiremock::matchers::path("/users"))
                .and(wiremock::matchers::body_json(serde_json::json!({
                    "name": "Eve",
                    "role": "admin"
                })))
                .respond_with(
                    wiremock::ResponseTemplate::new(201)
                        .set_body_json(serde_json::json!({"id": 2}))
                        .insert_header("content-type", constants::CONTENT_TYPE_JSON),
                )
                .expect(1),
        )
        .await;

    let mut spec = create_test_spec();
    spec.base_url = Some(mock_server.uri());
    spec.servers = vec![mock_server.uri()];

    let config = BatchConfig {
        show_progress: false,
        suppress_output: false,
        ..BatchConfig::default()
    };
    let processor = BatchProcessor::new(config);

    let batch_file = BatchFile {
        metadata: None,
        operations: vec![
            BatchOperation {
                id: Some("get-user".to_string()),
                args: vec![
                    "users".to_string(),
                    "get-user-by-id".to_string(),
                    "--id".to_string(),
                    "1".to_string(),
                ],
                capture: Some(std::collections::HashMap::from([(
                    "user_role".to_string(),
                    ".role".to_string(),
                )])),
                ..Default::default()
            },
            BatchOperation {
                id: Some("create-user".to_string()),
                args: vec!["users".to_string(), "create-user".to_string()],
                body_file: Some(body_file_template),
                depends_on: Some(vec!["get-user".to_string()]),
                ..Default::default()
            },
        ],
    };

    let result = processor
        .execute_batch(
            &spec,
            batch_file,
            None,
            Some(&mock_server.uri()),
            false,
            &OutputFormat::Json,
            None,
        )
        .await
        .expect("dependent batch with body_file interpolation should succeed");

    assert_eq!(result.success_count, 2, "both operations should succeed");
    assert_eq!(result.failure_count, 0);
    mock_server.verify().await;
}