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
mod test_helpers;

/// Integration tests for boolean parameter handling in positional args mode
///
/// This test suite verifies that boolean parameters work correctly when --positional-args
/// flag is used. Boolean parameters must remain as flags even in positional mode to avoid
/// clap panic when executor reads them via `get_flag()`.
///
/// Key behaviors tested:
/// 1. Boolean path parameters remain as flags (not positional) even with --positional-args
/// 2. Non-boolean path parameters become positional arguments as expected
/// 3. Boolean query/header parameters remain as flags
/// 4. Mixed boolean and non-boolean parameters work together
/// 5. URL substitution works correctly with boolean flags in positional mode
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 wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// Create spec with mixed boolean and non-boolean path parameters
fn create_spec_with_mixed_path_params() -> CachedSpec {
    CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: Some("https://api.example.com".to_string()),
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: std::collections::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}/{active}".to_string(),
            parameters: vec![
                CachedParameter {
                    name: "id".to_string(),
                    location: "path".to_string(),
                    required: true,
                    schema_type: Some("string".to_string()),
                    description: Some("Item ID".to_string()),
                    schema: Some(r#"{"type": "string"}"#.to_string()),
                    format: None,
                    default_value: None,
                    enum_values: vec![],
                    example: None,
                },
                CachedParameter {
                    name: "active".to_string(),
                    location: "path".to_string(),
                    required: true,
                    schema_type: Some("boolean".to_string()),
                    description: Some("Active status".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: std::collections::HashMap::new(),
    }
}

/// Create spec with boolean query parameter for positional mode testing
fn create_spec_with_boolean_query_param() -> CachedSpec {
    CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: Some("https://api.example.com".to_string()),
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: std::collections::HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "users".to_string(),
            operation_id: "listUsers".to_string(),
            summary: Some("List users".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/users/{id}".to_string(),
            parameters: vec![
                CachedParameter {
                    name: "id".to_string(),
                    location: "path".to_string(),
                    required: true,
                    schema_type: Some("string".to_string()),
                    description: Some("User ID".to_string()),
                    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: Some("Verbose output".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: std::collections::HashMap::new(),
    }
}

#[test]
fn test_boolean_path_param_remains_flag_in_positional_mode() {
    let spec = create_spec_with_mixed_path_params();
    let cmd = generate_command_tree_with_flags(&spec, true); // use_positional_args = true

    // In positional mode:
    // - Non-boolean path params (id) become positional
    // - Boolean path params (active) remain as flags to avoid clap panic
    let result = cmd.try_get_matches_from(vec![
        "api", "items", "get-item", "123",      // positional: id
        "--active", // flag: boolean path param
    ]);

    assert!(
        result.is_ok(),
        "Boolean path param should work as flag in positional mode: {:?}",
        result.err()
    );

    let matches = result.unwrap();
    let (_, sub_matches) = matches.subcommand().unwrap();
    let (_, operation_matches) = sub_matches.subcommand().unwrap();

    // Verify the boolean flag is set
    assert!(
        operation_matches.get_flag("active"),
        "Boolean path parameter should be readable via get_flag()"
    );

    // Verify the positional arg is set
    assert_eq!(
        operation_matches.get_one::<String>("id").unwrap(),
        "123",
        "Non-boolean path parameter should be positional"
    );
}

#[test]
fn test_boolean_path_param_defaults_to_false_in_positional_mode() {
    let spec = create_spec_with_mixed_path_params();
    let cmd = generate_command_tree_with_flags(&spec, true);

    // Omit the boolean flag
    let result = cmd.try_get_matches_from(vec!["api", "items", "get-item", "123"]);

    assert!(
        result.is_ok(),
        "Should succeed without boolean flag in positional mode: {:?}",
        result.err()
    );

    let matches = result.unwrap();
    let (_, sub_matches) = matches.subcommand().unwrap();
    let (_, operation_matches) = sub_matches.subcommand().unwrap();

    // Boolean flag should default to false
    assert!(
        !operation_matches.get_flag("active"),
        "Boolean path parameter should default to false when omitted"
    );
}

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

    // Test Case 1: Boolean flag present → "true" in URL
    Mock::given(method("GET"))
        .and(path("/items/123/true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "123",
            "active": true
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let mut spec = create_spec_with_mixed_path_params();
    spec.base_url = Some(mock_server.uri());

    let cmd = generate_command_tree_with_flags(&spec, true); // positional mode
    let matches = cmd
        .try_get_matches_from(vec!["api", "items", "get-item", "123", "--active"])
        .expect("Command should parse");

    let result = execute_request(
        &spec,
        &matches,
        None,
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        None,
        false,
        None, // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with boolean=true in URL: {:?}",
        result.err()
    );

    // Test Case 2: Boolean flag absent → "false" in URL
    Mock::given(method("GET"))
        .and(path("/items/456/false"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "456",
            "active": false
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let cmd2 = generate_command_tree_with_flags(&spec, true);
    let matches2 = cmd2
        .try_get_matches_from(vec!["api", "items", "get-item", "456"])
        .expect("Command should parse without --active");

    let result2 = execute_request(
        &spec,
        &matches2,
        None,
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        None,
        false,
        None, // retry_context
    )
    .await;

    assert!(
        result2.is_ok(),
        "Request should succeed with boolean=false in URL: {:?}",
        result2.err()
    );
}

#[test]
fn test_boolean_query_param_remains_flag_in_positional_mode() {
    let spec = create_spec_with_boolean_query_param();
    let cmd = generate_command_tree_with_flags(&spec, true); // positional mode

    // Path param is positional, query param is flag
    let result = cmd.try_get_matches_from(vec![
        "api",
        "users",
        "list-users",
        "123",       // positional: id
        "--verbose", // flag: boolean query param
    ]);

    assert!(
        result.is_ok(),
        "Boolean query param should work as flag in positional mode: {:?}",
        result.err()
    );

    let matches = result.unwrap();
    let (_, sub_matches) = matches.subcommand().unwrap();
    let (_, operation_matches) = sub_matches.subcommand().unwrap();

    assert!(
        operation_matches.get_flag("verbose"),
        "Boolean query parameter should be set"
    );
}

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

    Mock::given(method("GET"))
        .and(path("/users/123"))
        .and(query_param("verbose", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "user": {"id": "123"}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let mut spec = create_spec_with_boolean_query_param();
    spec.base_url = Some(mock_server.uri());

    let cmd = generate_command_tree_with_flags(&spec, true); // positional mode
    let matches = cmd
        .try_get_matches_from(vec!["api", "users", "list-users", "123", "--verbose"])
        .expect("Command should parse");

    let result = execute_request(
        &spec,
        &matches,
        None,
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        None,
        false,
        None, // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Request should succeed with verbose=true in query string: {:?}",
        result.err()
    );
}

#[test]
fn test_non_boolean_positional_args_still_work() {
    // Verify that non-boolean parameters still work as positional args
    let spec = create_spec_with_boolean_query_param();
    let cmd = generate_command_tree_with_flags(&spec, true);

    // Just provide the positional arg, no flags
    let result = cmd.try_get_matches_from(vec!["api", "users", "list-users", "999"]);

    assert!(
        result.is_ok(),
        "Non-boolean positional args should work: {:?}",
        result.err()
    );

    let matches = result.unwrap();
    let (_, sub_matches) = matches.subcommand().unwrap();
    let (_, operation_matches) = sub_matches.subcommand().unwrap();

    assert_eq!(
        operation_matches.get_one::<String>("id").unwrap(),
        "999",
        "Positional arg should be parsed correctly"
    );
}

#[test]
fn test_multiple_boolean_path_params_in_positional_mode() {
    // Create spec with multiple boolean path parameters
    let spec = CachedSpec {
        name: "test-api".to_string(),
        version: "1.0.0".to_string(),
        base_url: Some("https://api.example.com".to_string()),
        cache_format_version: CACHE_FORMAT_VERSION,
        servers: vec![],
        server_variables: std::collections::HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "resources".to_string(),
            operation_id: "getResource".to_string(),
            summary: Some("Get resource".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/resources/{id}/{active}/{verified}".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: "active".to_string(),
                    location: "path".to_string(),
                    required: true,
                    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: "verified".to_string(),
                    location: "path".to_string(),
                    required: true,
                    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: std::collections::HashMap::new(),
    };

    let cmd = generate_command_tree_with_flags(&spec, true);

    // Test with both boolean flags provided
    let result = cmd.try_get_matches_from(vec![
        "api",
        "resources",
        "get-resource",
        "abc123",     // positional: id
        "--active",   // flag: boolean
        "--verified", // flag: boolean
    ]);

    assert!(
        result.is_ok(),
        "Multiple boolean path params should work in positional mode: {:?}",
        result.err()
    );

    let matches = result.unwrap();
    let (_, sub_matches) = matches.subcommand().unwrap();
    let (_, operation_matches) = sub_matches.subcommand().unwrap();

    assert!(operation_matches.get_flag("active"));
    assert!(operation_matches.get_flag("verified"));
    assert_eq!(operation_matches.get_one::<String>("id").unwrap(), "abc123");
}

#[tokio::test]
#[allow(clippy::too_many_lines)]
async fn test_mixed_boolean_flags_url_substitution_positional_mode() {
    let mock_server = MockServer::start().await;

    // Test different combinations of boolean flags
    Mock::given(method("GET"))
        .and(path("/resources/test1/true/false"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok": true})))
        .expect(1)
        .mount(&mock_server)
        .await;

    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: std::collections::HashMap::new(),
        skipped_endpoints: vec![],
        commands: vec![CachedCommand {
            name: "resources".to_string(),
            operation_id: "getResource".to_string(),
            summary: Some("Get resource".to_string()),
            description: None,
            method: "GET".to_string(),
            path: "/resources/{id}/{active}/{verified}".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: "active".to_string(),
                    location: "path".to_string(),
                    required: true,
                    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: "verified".to_string(),
                    location: "path".to_string(),
                    required: true,
                    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: std::collections::HashMap::new(),
    };

    let cmd = generate_command_tree_with_flags(&spec, true);
    let matches = cmd
        .try_get_matches_from(vec![
            "api",
            "resources",
            "get-resource",
            "test1",
            "--active",
            // --verified omitted, should default to false
        ])
        .expect("Command should parse");

    let result = execute_request(
        &spec,
        &matches,
        None,
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        None,
        false,
        None, // retry_context
    )
    .await;

    assert!(
        result.is_ok(),
        "Mixed boolean flags should produce correct URL: {:?}",
        result.err()
    );
}