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

use aperture_cli::cache::models::{CachedCommand, CachedParameter, CachedSpec, PaginationInfo};
use aperture_cli::cli::OutputFormat;
use aperture_cli::constants;
use aperture_cli::engine::executor::execute_request;
use aperture_cli::engine::generator::{generate_command_tree, generate_command_tree_with_flags};
use aperture_cli::response_cache::{CacheConfig, ResponseCache};
use std::collections::HashMap;
use std::time::Duration;
use tempfile::TempDir;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn create_comprehensive_test_spec() -> CachedSpec {
    CachedSpec {
        cache_format_version: aperture_cli::cache::models::CACHE_FORMAT_VERSION,
        name: "comprehensive-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: "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,
                    },
                    CachedParameter {
                        name: "include_profile".to_string(),
                        location: "query".to_string(),
                        required: false,
                        description: Some("Include profile information".to_string()),
                        schema: Some(r#"{"type": "boolean"}"#.to_string()),
                        schema_type: Some("boolean".to_string()),
                        format: None,
                        default_value: None,
                        enum_values: vec![],
                        example: None,
                    },
                    CachedParameter {
                        name: "x-request-id".to_string(),
                        location: "header".to_string(),
                        required: false,
                        description: Some("Request ID for tracking".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: "posts".to_string(),
                description: Some("Create a new post".to_string()),
                summary: None,
                operation_id: "createPost".to_string(),
                method: "POST".to_string(),
                path: "/posts".to_string(),
                parameters: vec![],
                request_body: Some(aperture_cli::cache::models::CachedRequestBody {
                    description: Some("Post data".to_string()),
                    required: true,
                    content_type: constants::CONTENT_TYPE_JSON.to_string(),
                    schema: r#"{"type": "object"}"#.to_string(),
                    example: Some(
                        r#"{"title": "Test Post", "content": "This is a test post"}"#.to_string(),
                    ),
                }),
                responses: vec![],
                security_requirements: vec![],
                tags: vec!["posts".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(),
    }
}

fn create_test_cache_config() -> (CacheConfig, TempDir) {
    let temp_dir = TempDir::new().unwrap();
    let cache_config = CacheConfig {
        cache_dir: temp_dir.path().to_path_buf(),
        default_ttl: Duration::from_secs(60),
        max_entries: 100,
        enabled: true,
        allow_authenticated: false,
    };
    (cache_config, temp_dir)
}

#[tokio::test]
async fn test_flag_based_syntax_with_caching() {
    let mock_server = MockServer::start().await;
    let (cache_config, _temp_dir) = create_test_cache_config();
    let spec = create_comprehensive_test_spec();

    // Configure mock to be called only once (caching should work)
    Mock::given(method("GET"))
        .and(path("/users/123"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "123",
            "name": "Test User",
            "profile": {"age": 30}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Test with flag-based syntax (now default)
    let command = generate_command_tree_with_flags(&spec, false);
    let users_cmd = command.find_subcommand("users").unwrap();
    let get_user_cmd = users_cmd.find_subcommand("get-user-by-id").unwrap();

    // Verify that path parameter is now a flag
    let id_arg = get_user_cmd
        .get_arguments()
        .find(|arg| arg.get_id() == "id")
        .unwrap();
    assert_eq!(id_arg.get_long(), Some("id"));

    // Create matches using flag-based syntax
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "users",
            "get-user-by-id",
            "--id",
            "123",
            "--include-profile",
            "--x-request-id",
            "req-123",
        ])
        .unwrap();

    // First request should hit the API
    let result1 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result1.is_ok());

    // Second request should use cache
    let result2 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result2.is_ok());

    // Verify cache was used
    let cache = ResponseCache::new(cache_config).unwrap();
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 1);
    assert_eq!(stats.valid_entries, 1);
}

#[tokio::test]
async fn test_legacy_positional_syntax_with_caching() {
    let mock_server = MockServer::start().await;
    let (cache_config, _temp_dir) = create_test_cache_config();
    let spec = create_comprehensive_test_spec();

    // Configure mock to be called only once (caching should work)
    Mock::given(method("GET"))
        .and(path("/users/456"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "456",
            "name": "Another User"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Test with legacy positional syntax
    let command = generate_command_tree_with_flags(&spec, true);
    let users_cmd = command.find_subcommand("users").unwrap();
    let get_user_cmd = users_cmd.find_subcommand("get-user-by-id").unwrap();

    // Verify that path parameter is positional
    let id_arg = get_user_cmd
        .get_arguments()
        .find(|arg| arg.get_id() == "id")
        .unwrap();
    assert!(id_arg.get_long().is_none());

    // Create matches using positional syntax (without include-profile flag)
    let matches = command
        .try_get_matches_from(vec!["api", "users", "get-user-by-id", "456"])
        .unwrap();

    // First request should hit the API
    let result1 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result1.is_ok());

    // Second request should use cache
    let result2 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result2.is_ok());

    // Verify cache was used
    let cache = ResponseCache::new(cache_config).unwrap();
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 1);
    assert_eq!(stats.valid_entries, 1);
}

#[tokio::test]
async fn test_different_parameter_combinations_cache_separately() {
    let mock_server = MockServer::start().await;
    let (cache_config, _temp_dir) = create_test_cache_config();
    let spec = create_comprehensive_test_spec();

    // Configure mocks for different parameter combinations
    Mock::given(method("GET"))
        .and(path("/users/123"))
        .and(wiremock::matchers::query_param("include_profile", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "123",
            "name": "User with profile",
            "profile": {"age": 30}
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    Mock::given(method("GET"))
        .and(path("/users/123"))
        .and(wiremock::matchers::query_param_is_missing(
            "include_profile",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "123",
            "name": "User without profile"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    // Request with include_profile=true (flag present)
    let command1 = generate_command_tree_with_flags(&spec, false);
    let matches1 = command1
        .try_get_matches_from(vec![
            "api",
            "users",
            "get-user-by-id",
            "--id",
            "123",
            "--include-profile",
        ])
        .unwrap();

    let result1 = execute_request(
        &spec,
        &matches1,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result1.is_ok());

    // Request without include_profile (flag absent, should be cached separately)
    let command2 = generate_command_tree_with_flags(&spec, false);
    let matches2 = command2
        .try_get_matches_from(vec!["api", "users", "get-user-by-id", "--id", "123"])
        .unwrap();

    let result2 = execute_request(
        &spec,
        &matches2,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result2.is_ok());

    // Verify both combinations were cached separately
    let cache = ResponseCache::new(cache_config).unwrap();
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 2);
    assert_eq!(stats.valid_entries, 2);
}

#[tokio::test]
async fn test_post_request_with_body_and_caching() {
    let mock_server = MockServer::start().await;
    let (cache_config, _temp_dir) = create_test_cache_config();
    let spec = create_comprehensive_test_spec();

    // Configure mock for POST request
    Mock::given(method("POST"))
        .and(path("/posts"))
        .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({
            "id": "post-123",
            "title": "Test Post",
            "content": "This is a test post",
            "created_at": "2023-01-01T00:00:00Z"
        })))
        .expect(1)
        .mount(&mock_server)
        .await;

    let command = generate_command_tree_with_flags(&spec, false);

    // Create matches for POST request with body
    let matches = command
        .try_get_matches_from(vec![
            "api",
            "posts",
            "create-post",
            "--body",
            r#"{"title": "Test Post", "content": "This is a test post"}"#,
        ])
        .unwrap();

    // First request should hit the API
    let result1 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result1.is_ok());

    // Second identical request should use cache
    let result2 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result2.is_ok());

    // Verify cache was used
    let cache = ResponseCache::new(cache_config).unwrap();
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 1);
    assert_eq!(stats.valid_entries, 1);
}

#[tokio::test]
async fn test_dry_run_with_flag_based_syntax() {
    let mock_server = MockServer::start().await;
    let (cache_config, _temp_dir) = create_test_cache_config();
    let spec = create_comprehensive_test_spec();

    // Mock should not be called in dry run mode
    Mock::given(method("GET"))
        .and(path("/users/123"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
        .expect(0)
        .mount(&mock_server)
        .await;

    let command = generate_command_tree_with_flags(&spec, false);

    let matches = command
        .try_get_matches_from(vec![
            "api",
            "users",
            "get-user-by-id",
            "--id",
            "123",
            "--include-profile",
        ])
        .unwrap();

    // Dry run should not hit the API or cache
    let result = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        true, // dry_run = true
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result.is_ok());

    // Verify no cache entries were created
    let cache = ResponseCache::new(cache_config).unwrap();
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 0);
}

#[tokio::test]
async fn test_cache_with_custom_ttl() {
    let mock_server = MockServer::start().await;
    let (mut cache_config, _temp_dir) = create_test_cache_config();
    cache_config.default_ttl = Duration::from_millis(800); // Short TTL for fast testing
    let spec = create_comprehensive_test_spec();

    // Configure mock to be called twice (initial + after expiration)
    Mock::given(method("GET"))
        .and(path("/users/789"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "id": "789",
            "name": "TTL Test User"
        })))
        .expect(2)
        .mount(&mock_server)
        .await;

    let command = generate_command_tree(&spec);

    let matches = command
        .try_get_matches_from(vec!["api", "users", "get-user-by-id", "--id", "789"])
        .unwrap();

    // First request
    let result1 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result1.is_ok());

    // Verify cache entry exists
    let cache = ResponseCache::new(cache_config.clone()).unwrap();
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 1);
    assert_eq!(stats.valid_entries, 1);

    // Wait for TTL to expire (800ms TTL + buffer)
    tokio::time::sleep(Duration::from_millis(1000)).await;

    // Second request should hit API again due to expiration
    let result2 = execute_request(
        &spec,
        &matches,
        Some(&mock_server.uri()),
        false,
        None,
        None,
        &OutputFormat::Json,
        None,
        Some(&cache_config),
        false, // capture_output
        None,  // retry_context
    )
    .await;
    assert!(result2.is_ok());

    // Verify cache entry was refreshed
    let stats = cache.get_stats(Some("comprehensive-api")).await.unwrap();
    assert_eq!(stats.total_entries, 1);
    assert_eq!(stats.valid_entries, 1);
}