momus-cli 0.6.2

Momus API test harness — CLI runner
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
//! Integration tests for the `momus` CLI binary.
//!
//! These tests exercise the full CLI pipeline: argument parsing, plan loading,
//! execution, and output. Tests that start external servers are marked `#[ignore]`
//! to keep the common `cargo test` fast.

use assert_cmd::Command;
use predicates::prelude::*;
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// A valid minimal test plan JSON string.
fn valid_plan_json(base_url: &str) -> String {
    format!(
        r#"{{
            "name": "integration-test",
            "base_url": "{base_url}",
            "default_headers": {{ "Accept": "application/json" }},
            "steps": [
                {{
                    "type": "request",
                    "name": "health",
                    "method": "GET",
                    "url": "/health",
                    "assert": [
                        {{ "status": 200 }},
                        {{ "content_type": "application/json" }},
                        {{ "valid_json": null }}
                    ]
                }}
            ]
        }}"#
    )
}

/// Start a mock server on a random port and return (server, base_url).
/// The mock server responds to GET /health with 200 {"status": "ok"}.
async fn start_mock_server() -> (momus_mock::MockServer, String) {
    let mut routes = HashMap::new();
    routes.insert(
        "GET /health".into(),
        momus_mock::MockResponse::json(200, serde_json::json!({"status": "ok"})),
    );
    let server = momus_mock::MockServer::start(routes).await;
    let url = server.addr.clone();
    (server, url)
}

// ---------------------------------------------------------------------------
// CLI argument parsing
// ---------------------------------------------------------------------------

#[test]
fn test_help_exits_with_0() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    cmd.arg("--help");
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("Usage:"))
        .stdout(predicate::str::contains("run"))
        .stdout(predicate::str::contains("validate"))
        .stdout(predicate::str::contains("mock"))
        .stdout(predicate::str::contains("bench"))
        .stdout(predicate::str::contains("fuzz"))
        .stdout(predicate::str::contains("chaos"))
        .stdout(predicate::str::contains("convert"))
        .stdout(predicate::str::contains("contract"))
        .stdout(predicate::str::contains("guard"))
        .stdout(predicate::str::contains("diff"))
        .stdout(predicate::str::contains("init"))
        .stdout(predicate::str::contains("plan"))
        .stdout(predicate::str::contains("fhir-generate"));
}

#[test]
fn test_run_help_shows_run_flags() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    cmd.args(["run", "--help"]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("--base-url"))
        .stdout(predicate::str::contains("--output"))
        .stdout(predicate::str::contains("--format"));
}

#[test]
fn test_version_exits_with_0() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    cmd.arg("--version");
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("momus"));
}

#[test]
fn test_unknown_subcommand_exits_nonzero() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    cmd.arg("nonexistent-subcommand");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("error"));
}

// ---------------------------------------------------------------------------
// momus validate
// ---------------------------------------------------------------------------

#[test]
fn test_validate_valid_plan() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("test-plan.json");
    std::fs::write(
        &plan_path,
        r#"{
            "name": "test",
            "base_url": "http://localhost:9999",
            "steps": [
                {
                    "type": "request",
                    "name": "ping",
                    "method": "GET",
                    "url": "/ping",
                    "assert": [{ "status": 200 }]
                }
            ]
        }"#,
    )
    .unwrap();

    cmd.args(["validate", plan_path.to_str().unwrap()]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("Valid test plan"))
        .stdout(predicate::str::contains("test"));
}

#[test]
fn test_validate_invalid_json() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("bad-plan.json");
    std::fs::write(&plan_path, "this is not json").unwrap();

    cmd.args(["validate", plan_path.to_str().unwrap()]);
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("Failed to parse test plan"));
}

#[test]
fn test_validate_malformed_plan() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("bad-plan.json");
    // Step is missing required fields like `name`, `method`, `url`
    std::fs::write(
        &plan_path,
        r#"{
            "name": "bad",
            "base_url": "http://localhost",
            "steps": [
                { "type": "request" }
            ]
        }"#,
    )
    .unwrap();

    cmd.args(["validate", plan_path.to_str().unwrap()]);
    // The plan is valid JSON but the step is missing required fields
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("Failed to parse test plan"));
}

// ---------------------------------------------------------------------------
// momus run
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_run_health_check_plan() {
    let (_server, base_url) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(&plan_path, valid_plan_json(&base_url)).unwrap();

    cmd.args(["run", plan_path.to_str().unwrap()]);
    // Use spawn_blocking so the tokio runtime can drive the mock server
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result
        .success()
        .stdout(predicate::str::contains("Passed"))
        .stdout(predicate::str::contains("health"));
}

#[tokio::test]
async fn test_run_with_base_url_override() {
    let (_server, base_url) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    // Use a different base_url in the plan; override with --base-url
    let plan_json = r#"{
            "name": "override-test",
            "base_url": "http://localhost:1",
            "steps": [
                {
                    "type": "request",
                    "name": "health",
                    "method": "GET",
                    "url": "/health",
                    "assert": [
                        { "status": 200 },
                        { "valid_json": null }
                    ]
                }
            ]
        }"#
    .to_string();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(&plan_path, &plan_json).unwrap();

    cmd.args(["run", plan_path.to_str().unwrap(), "--base-url", &base_url]);
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result.success().stdout(predicate::str::contains("Passed"));
}

#[tokio::test]
async fn test_run_with_output_dir() {
    let (_server, base_url) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(&plan_path, valid_plan_json(&base_url)).unwrap();

    let out_dir = dir.path().join("run-output");
    cmd.args([
        "run",
        plan_path.to_str().unwrap(),
        "--output",
        out_dir.to_str().unwrap(),
    ]);
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result.success();

    // Verify output files were written
    // The CLI writes results to {output}/results/{group_name}.json
    let results_dir = out_dir.join("results");
    assert!(
        results_dir.join("integration-test.json").exists(),
        "Expected integration-test.json in {:?}. Contents: {:?}",
        results_dir,
        std::fs::read_dir(&results_dir)
            .map(|e| e.map(|e| e.unwrap().path()).collect::<Vec<_>>())
            .unwrap_or_default()
    );
}

// ---------------------------------------------------------------------------
// momus convert
// ---------------------------------------------------------------------------

#[test]
fn test_convert_curl() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    cmd.args([
        "convert",
        "curl",
        "curl -X GET https://api.example.com/health -H 'Accept: application/json'",
    ]);
    cmd.assert()
        .success()
        .stdout(predicate::str::contains("GET"))
        .stdout(predicate::str::contains("/health"));
}

#[test]
fn test_convert_curl_to_file() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let out_path = dir.path().join("converted.json");

    cmd.args([
        "convert",
        "curl",
        "curl -X POST https://api.example.com/data -d '{\"key\":\"value\"}'",
        "--output",
        out_path.to_str().unwrap(),
    ]);
    cmd.assert().success();

    // Verify the output file was created and contains valid JSON
    let content = std::fs::read_to_string(&out_path).unwrap();
    let plan: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert!(plan["name"].as_str().unwrap().contains("cURL"));
}

#[test]
fn test_convert_unknown_format() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    cmd.args(["convert", "unknown-format", "input.txt"]);
    // clap's value parser rejects unknown formats before the function runs
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("invalid value"))
        .stderr(predicate::str::contains("unknown-format"));
}

// ---------------------------------------------------------------------------
// momus bench
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "bench tests are slow"]
async fn test_bench_steady_mode() {
    let (_server, base_url) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(&plan_path, valid_plan_json(&base_url)).unwrap();

    cmd.args([
        "bench",
        plan_path.to_str().unwrap(),
        "--mode",
        "steady",
        "--concurrency",
        "1",
        "--duration",
        "1",
        "--base-url",
        &base_url,
    ]);
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result.success();
}

// ---------------------------------------------------------------------------
// momus fuzz
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "fuzz tests are slow"]
async fn test_fuzz_basic() {
    let (_server, base_url) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(&plan_path, valid_plan_json(&base_url)).unwrap();

    cmd.args([
        "fuzz",
        plan_path.to_str().unwrap(),
        "--iterations",
        "5",
        "--base-url",
        &base_url,
    ]);
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result.success();
}

// ---------------------------------------------------------------------------
// momus guard
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "guard tests are slow"]
async fn test_guard_basic() {
    let (_server, base_url) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(&plan_path, valid_plan_json(&base_url)).unwrap();

    cmd.args([
        "guard",
        plan_path.to_str().unwrap(),
        "--base-url",
        &base_url,
    ]);
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result.success();
}

// ---------------------------------------------------------------------------
// momus diff
// ---------------------------------------------------------------------------

#[tokio::test]
#[ignore = "diff tests are slow"]
async fn test_diff_basic() {
    let (_server1, base_url1) = start_mock_server().await;
    let (_server2, base_url2) = start_mock_server().await;

    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    // Use a plan with a base_url that will be overridden by --baseline and --target
    std::fs::write(
        &plan_path,
        r#"{
            "name": "diff-test",
            "base_url": "http://localhost:1",
            "steps": [
                {
                    "type": "request",
                    "name": "health",
                    "method": "GET",
                    "url": "/health",
                    "assert": [{ "status": 200 }]
                }
            ]
        }"#,
    )
    .unwrap();

    cmd.args([
        "diff",
        plan_path.to_str().unwrap(),
        "--baseline",
        &base_url1,
        "--target",
        &base_url2,
    ]);
    let result = tokio::task::spawn_blocking(move || cmd.assert())
        .await
        .unwrap();
    result.success();
}

// ---------------------------------------------------------------------------
// momus init
// ---------------------------------------------------------------------------

#[test]
fn test_init_plan() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let out_path = dir.path().join("test-plan.json");

    cmd.args(["init", "plan", "--output", out_path.to_str().unwrap()]);
    cmd.assert().success();

    // Verify the output file was created and contains valid JSON
    let content = std::fs::read_to_string(&out_path).unwrap();
    let plan: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert!(plan["name"].is_string());
    assert!(plan["steps"].is_array());
}

// ---------------------------------------------------------------------------
// momus plan (display a plan)
// ---------------------------------------------------------------------------

#[test]
fn test_plan_display() {
    let mut cmd = Command::cargo_bin("momus").unwrap();
    let dir = tempfile::TempDir::new().unwrap();
    let plan_path = dir.path().join("plan.json");
    std::fs::write(
        &plan_path,
        r#"{
            "name": "display-test",
            "base_url": "http://localhost:9999",
            "steps": [
                {
                    "type": "request",
                    "name": "ping",
                    "method": "GET",
                    "url": "/ping",
                    "assert": [{ "status": 200 }]
                }
            ]
        }"#,
    )
    .unwrap();

    cmd.args(["plan", plan_path.to_str().unwrap()]);
    cmd.assert().success();

    // The plan command writes to ./output/plan.txt by default
    let output_path = std::path::Path::new("./output/plan.txt");
    if output_path.exists() {
        let content = std::fs::read_to_string(output_path).unwrap();
        assert!(
            content.contains("display-test"),
            "Expected plan name in output"
        );
        assert!(content.contains("ping"), "Expected step name in output");
    }
}