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
// These lints are overly pedantic for test code
#![allow(clippy::too_many_lines)]

mod test_helpers;

/// Integration tests for boolean header parameter handling
///
/// Verifies that boolean header parameters:
/// 1. Are treated as flags (no value required)
/// 2. Send "true" as header value when flag is present
/// 3. Omit the header when optional flag is absent
/// 4. Error appropriately when required flag is missing
/// 5. Work with kebab-case name conversion
/// 6. Work alongside other parameter types
use aperture_cli::cache::models::{
    CachedCommand, CachedParameter, CachedSpec, PaginationInfo, CACHE_FORMAT_VERSION,
};
use aperture_cli::cli::OutputFormat;
use aperture_cli::engine::executor::execute_request;
use aperture_cli::engine::generator::generate_command_tree_with_flags;
use std::collections::HashMap;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Helper to create a spec with boolean header parameters
fn create_spec_with_boolean_headers(
    required_bool_header: bool,
    optional_bool_header: bool,
) -> CachedSpec {
    let mut parameters = vec![];

    if required_bool_header {
        parameters.push(CachedParameter {
            name: "X-Enable-Feature".to_string(),
            location: "header".to_string(),
            required: true,
            schema_type: Some("boolean".to_string()),
            description: Some("Required boolean header".to_string()),
            schema: Some(r#"{"type": "boolean"}"#.to_string()),
            format: None,
            default_value: None,
            enum_values: vec![],
            example: None,
        });
    }

    if optional_bool_header {
        parameters.push(CachedParameter {
            name: "X-Verbose".to_string(),
            location: "header".to_string(),
            required: false,
            schema_type: Some("boolean".to_string()),
            description: Some("Optional boolean header".to_string()),
            schema: Some(r#"{"type": "boolean"}"#.to_string()),
            format: None,
            default_value: None,
            enum_values: vec![],
            example: None,
        });
    }

    CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: None, // Will use mock server URL
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "resources".to_string(),
            operation_id: "getResources".to_string(),
            summary: Some("Get resources".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/resources".to_string(),
            parameters,
            request_body: None,
            security_requirements: vec![],
            examples: vec![],
            deprecated: false,
            external_docs_url: None,
            responses: vec![],
            tags: vec![],
            display_group: None,
            display_name: None,
            aliases: vec![],
            hidden: false,
            pagination: PaginationInfo::default(),
        }],
        security_schemes: HashMap::new(),
    }
}

#[tokio::test]
async fn test_optional_boolean_header_present() {
    let mock_server = MockServer::start().await;

    // Mock expects X-Verbose header with value "true"
    Mock::given(method("GET"))
        .and(path("/resources"))
        .and(header("X-Verbose", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let mut spec = create_spec_with_boolean_headers(false, true);
    spec.base_url = Some(mock_server.uri());

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resources",
            "--x-verbose", // Boolean flag provided
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(result.is_ok(), "Request should succeed with boolean header");
}

#[tokio::test]
async fn test_optional_boolean_header_absent() {
    let mock_server = MockServer::start().await;

    // Mock expects NO X-Verbose header (it's optional and flag not provided)
    Mock::given(method("GET"))
        .and(path("/resources"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let mut spec = create_spec_with_boolean_headers(false, true);
    spec.base_url = Some(mock_server.uri());

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resources",
            // --x-verbose flag NOT provided
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed without optional boolean header"
    );
}

#[tokio::test]
async fn test_required_boolean_header_present() {
    let mock_server = MockServer::start().await;

    // Mock expects X-Enable-Feature header with value "true"
    Mock::given(method("GET"))
        .and(path("/resources"))
        .and(header("X-Enable-Feature", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let mut spec = create_spec_with_boolean_headers(true, false);
    spec.base_url = Some(mock_server.uri());

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resources",
            "--x-enable-feature", // Required boolean flag provided
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with required boolean header"
    );
}

#[test]
fn test_required_boolean_header_missing_errors_at_parse_time() {
    // Required boolean headers are enforced by clap at argument parsing time
    // This test verifies that clap errors when a required boolean flag is missing

    let spec = create_spec_with_boolean_headers(true, false);
    let command = generate_command_tree_with_flags(&spec, false);

    // Try to parse args without the required --x-enable-feature flag
    let result = command.try_get_matches_from(vec![
        "api",
        "resources",
        "get-resources",
        // --x-enable-feature flag NOT provided (but it's required!)
    ]);

    assert!(
        result.is_err(),
        "Clap should error when required boolean header flag is missing"
    );

    let error = result.unwrap_err();
    let error_message = error.to_string();
    assert!(
        error_message.contains("x-enable-feature") || error_message.contains("required"),
        "Error should mention the missing required parameter or 'required'. Got: {error_message}"
    );
}

#[tokio::test]
async fn test_mixed_boolean_and_string_headers() {
    let mock_server = MockServer::start().await;

    // Mock expects both boolean header (X-Verbose: true) and string header (X-API-Key: secret)
    Mock::given(method("GET"))
        .and(path("/resources"))
        .and(header("X-Verbose", "true"))
        .and(header("X-API-Key", "secret-123"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let mut spec = create_spec_with_boolean_headers(false, true);

    // Add a string header parameter
    spec.commands[0].parameters.push(CachedParameter {
        name: "X-API-Key".to_string(),
        location: "header".to_string(),
        required: false,
        schema_type: Some("string".to_string()),
        description: Some("API Key".to_string()),
        schema: Some(r#"{"type": "string"}"#.to_string()),
        format: None,
        default_value: None,
        enum_values: vec![],
        example: None,
    });

    spec.base_url = Some(mock_server.uri());

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resources",
            "--x-verbose", // Boolean flag
            "--x-api-key", // String parameter
            "secret-123",
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with both boolean and string headers"
    );
}

#[tokio::test]
async fn test_kebab_case_boolean_header_conversion() {
    let mock_server = MockServer::start().await;

    // Create spec with camelCase header name
    let spec = CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: Some(mock_server.uri()),
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "resources".to_string(),
            operation_id: "getResources".to_string(),
            summary: Some("Get resources".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/resources".to_string(),
            parameters: vec![CachedParameter {
                name: "enableCaching".to_string(), // camelCase
                location: "header".to_string(),
                required: false,
                schema_type: Some("boolean".to_string()),
                description: Some("Enable caching".to_string()),
                schema: Some(r#"{"type": "boolean"}"#.to_string()),
                format: None,
                default_value: None,
                enum_values: vec![],
                example: None,
            }],
            request_body: None,
            security_requirements: vec![],
            examples: vec![],
            deprecated: false,
            external_docs_url: None,
            responses: vec![],
            tags: vec![],
            display_group: None,
            display_name: None,
            aliases: vec![],
            hidden: false,
            pagination: PaginationInfo::default(),
        }],
        security_schemes: HashMap::new(),
    };

    // Mock expects header with original camelCase name
    Mock::given(method("GET"))
        .and(path("/resources"))
        .and(header("enableCaching", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resources",
            "--enable-caching", // kebab-case in CLI
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with kebab-case boolean header flag"
    );
}

#[tokio::test]
async fn test_boolean_header_with_query_and_path_params() {
    let mock_server = MockServer::start().await;

    // Create spec with boolean header + query param + path param
    let spec = CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: Some(mock_server.uri()),
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "items".to_string(),
            operation_id: "getItem".to_string(),
            summary: Some("Get item".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/items/{id}".to_string(),
            parameters: vec![
                CachedParameter {
                    name: "id".to_string(),
                    location: "path".to_string(),
                    required: true,
                    schema_type: Some("string".to_string()),
                    description: None,
                    schema: Some(r#"{"type": "string"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
                CachedParameter {
                    name: "verbose".to_string(),
                    location: "query".to_string(),
                    required: false,
                    schema_type: Some("boolean".to_string()),
                    description: None,
                    schema: Some(r#"{"type": "boolean"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
                CachedParameter {
                    name: "X-Include-Metadata".to_string(),
                    location: "header".to_string(),
                    required: false,
                    schema_type: Some("boolean".to_string()),
                    description: None,
                    schema: Some(r#"{"type": "boolean"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
            ],
            request_body: None,
            security_requirements: vec![],
            examples: vec![],
            deprecated: false,
            external_docs_url: None,
            responses: vec![],
            tags: vec![],
            display_group: None,
            display_name: None,
            aliases: vec![],
            hidden: false,
            pagination: PaginationInfo::default(),
        }],
        security_schemes: HashMap::new(),
    };

    // Mock expects path param, query param, and header all set correctly
    Mock::given(method("GET"))
        .and(path("/items/123"))
        .and(wiremock::matchers::query_param("verbose", "true"))
        .and(header("X-Include-Metadata", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "items",
            "get-item",
            "--id",
            "123",
            "--verbose",            // Boolean query param
            "--x-include-metadata", // Boolean header param
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with boolean params across all locations"
    );
}

#[tokio::test]
async fn test_multiple_boolean_headers() {
    let mock_server = MockServer::start().await;

    // Create spec with multiple boolean headers
    let spec = CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: Some(mock_server.uri()),
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "resources".to_string(),
            operation_id: "getResources".to_string(),
            summary: Some("Get resources".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/resources".to_string(),
            parameters: vec![
                CachedParameter {
                    name: "X-Enable-Cache".to_string(),
                    location: "header".to_string(),
                    required: false,
                    schema_type: Some("boolean".to_string()),
                    description: None,
                    schema: Some(r#"{"type": "boolean"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
                CachedParameter {
                    name: "X-Verbose".to_string(),
                    location: "header".to_string(),
                    required: false,
                    schema_type: Some("boolean".to_string()),
                    description: None,
                    schema: Some(r#"{"type": "boolean"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
                CachedParameter {
                    name: "X-Debug".to_string(),
                    location: "header".to_string(),
                    required: false,
                    schema_type: Some("boolean".to_string()),
                    description: None,
                    schema: Some(r#"{"type": "boolean"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
            ],
            request_body: None,
            security_requirements: vec![],
            examples: vec![],
            deprecated: false,
            external_docs_url: None,
            responses: vec![],
            tags: vec![],
            display_group: None,
            display_name: None,
            aliases: vec![],
            hidden: false,
            pagination: PaginationInfo::default(),
        }],
        security_schemes: HashMap::new(),
    };

    // Mock expects two headers (X-Enable-Cache and X-Debug), but NOT X-Verbose
    Mock::given(method("GET"))
        .and(path("/resources"))
        .and(header("X-Enable-Cache", "true"))
        .and(header("X-Debug", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "status": "success"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let command = generate_command_tree_with_flags(&spec, false);
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resources",
            "--x-enable-cache", // Provided
            "--x-debug",        // Provided
                                // --x-verbose NOT provided
        ])
        .unwrap();

    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false, // dry_run
        None,  // idempotency_key
        None,  // global_config
        &OutputFormat::Json,
        None,  // jq_filter
        None,  // cache_config
        false, // capture_output
        None,  // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with selective boolean headers"
    );
}