checkmate-cli 0.4.1

Checkmate - API Testing Framework CLI
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
//! Test subcommand - Run API tests

use std::path::PathBuf;
use std::time::Instant;

use clap::Subcommand;

use crate::config::Config;
use crate::history::{self, RunRecord};
use crate::hooks;
use crate::project::CheckmateProject;
use crate::runner::{
    AssertionEvaluator, TestExecutor, TestSpec,
    TestResult, TestSuiteResult, TestStatus, AssertionSummary, TestFailure,
};

#[derive(Subcommand)]
pub enum TestCommands {
    /// Run test specifications
    Run {
        /// Test spec files to run
        specs: Vec<String>,

        /// Run specific test by name
        #[arg(short, long)]
        test: Option<String>,

        /// Verbose output
        #[arg(short, long)]
        verbose: bool,
    },
    /// Validate test specs without running
    Validate {
        /// Test spec files to validate
        specs: Vec<String>,
    },
    /// List available tests in spec files
    List {
        /// Test spec files to list tests from
        specs: Vec<String>,
    },
}

pub fn run(command: TestCommands) -> Result<(), Box<dyn std::error::Error>> {
    match command {
        TestCommands::Run { specs, test, verbose } => run_tests(&specs, test.as_deref(), verbose),
        TestCommands::Validate { specs } => validate_specs(&specs),
        TestCommands::List { specs } => list_tests(&specs),
    }
}

fn run_tests(spec_files: &[String], filter: Option<&str>, verbose: bool) -> Result<(), Box<dyn std::error::Error>> {
    // Auto-discover project and load config
    let project = CheckmateProject::discover();
    let config = Config::load(project.as_ref());

    // Resolve spec files - discover or resolve names
    let resolved_specs = resolve_spec_files(spec_files, project.as_ref())?;

    if resolved_specs.is_empty() {
        if project.is_some() {
            eprintln!("No test specs found in .checkmate/tests/");
            eprintln!("Create spec files with .yaml extension, or provide spec paths explicitly.");
        } else {
            eprintln!("No test spec files provided and no .checkmate/ found.");
            eprintln!("Run 'cm init' or provide spec files explicitly.");
        }
        return Ok(());
    }

    if verbose {
        if let Some(ref base_url) = config.env.base_url {
            println!("Using base_url: {}", base_url);
        }
    }

    let mut all_passed = true;

    for spec_path in &resolved_specs {
        let spec_name = spec_path.file_name()
            .map(|s| s.to_string_lossy().to_string());

        if verbose {
            println!("Running: {}", spec_path.display());
        }

        // Fire pre_run hook
        if let Some(ref proj) = project {
            hooks::fire_pre_run(proj, spec_name.as_deref());
        }

        let mut spec = TestSpec::from_file(spec_path.to_string_lossy().as_ref())?;

        // Apply config overrides to spec
        if spec.env.base_url.is_none() {
            spec.env.base_url = config.env.base_url.clone();
        }
        if spec.env.timeout_ms.is_none() {
            spec.env.timeout_ms = Some(config.env.timeout_ms);
        }

        let result = run_spec(&spec, filter, verbose, &config)?;

        // Save run to history if project exists
        let run_id = if let Some(ref proj) = project {
            let record = RunRecord::from_suite_result(&result, spec_name.as_deref());
            let id = record.id.clone();

            if let Err(e) = history::save_run(proj, &record) {
                if verbose {
                    eprintln!("Warning: Failed to save run history: {}", e);
                }
            } else if verbose {
                println!("Recorded: {}", record.id);
            }

            // Fire post_run hooks
            hooks::fire_post_run(
                proj,
                &id,
                spec_name.as_deref(),
                result.summary.total,
                result.summary.passed,
                result.summary.failed,
                result.summary.errors,
                result.duration_ms,
            );

            Some(id)
        } else {
            None
        };

        let _ = run_id; // Suppress unused warning

        // Output JSON result
        let json = serde_json::to_string_pretty(&result)?;
        println!("{}", json);

        if !result.all_passed() {
            all_passed = false;
        }
    }

    if !all_passed {
        std::process::exit(1);
    }

    Ok(())
}

/// Resolve spec file arguments to actual paths
/// - If no specs given and project exists, discover from .checkmate/tests/
/// - If spec is a path that exists, use it
/// - If spec is a name (no extension), try .checkmate/tests/{name}.yaml
pub fn resolve_spec_files(specs: &[String], project: Option<&CheckmateProject>) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    // If no specs provided, discover from project
    if specs.is_empty() {
        if let Some(project) = project {
            return discover_test_specs(&project.tests_dir);
        }
        return Ok(Vec::new());
    }

    // Resolve each spec
    let mut resolved = Vec::new();
    for spec in specs {
        let path = PathBuf::from(spec);

        // If it exists as-is, use it
        if path.exists() {
            resolved.push(path);
            continue;
        }

        // Try resolving as name in project tests dir
        if let Some(project) = project {
            // Try with .yaml extension
            let with_yaml = project.tests_dir.join(format!("{}.yaml", spec));
            if with_yaml.exists() {
                resolved.push(with_yaml);
                continue;
            }

            // Try with .yml extension
            let with_yml = project.tests_dir.join(format!("{}.yml", spec));
            if with_yml.exists() {
                resolved.push(with_yml);
                continue;
            }
        }

        // Fall back to original path (will error on load)
        resolved.push(path);
    }

    Ok(resolved)
}

/// Discover all test specs in a directory
fn discover_test_specs(tests_dir: &PathBuf) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    if !tests_dir.exists() {
        return Ok(Vec::new());
    }

    let mut specs: Vec<PathBuf> = std::fs::read_dir(tests_dir)?
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension()
                .map_or(false, |ext| ext == "yaml" || ext == "yml")
        })
        .collect();

    specs.sort();
    Ok(specs)
}

fn run_spec(spec: &TestSpec, filter: Option<&str>, verbose: bool, _config: &Config) -> Result<TestSuiteResult, Box<dyn std::error::Error>> {
    let suite_start = Instant::now();
    let mut suite_result = TestSuiteResult::new(spec.name.clone());

    let executor = TestExecutor::new(&spec.env)?;

    for (test_name, test_case) in &spec.tests {
        // Apply filter if provided
        if let Some(f) = filter {
            if test_name != f {
                continue;
            }
        }

        if verbose {
            println!("  Running test: {}", test_name);
        }

        let test_start = Instant::now();
        let mut evaluator = AssertionEvaluator::new();
        let mut failures: Vec<TestFailure> = Vec::new();
        let mut assertion_summary = AssertionSummary::default();
        let mut test_status = TestStatus::Passed;

        for (req_idx, request_name) in test_case.requests.iter().enumerate() {
            if verbose {
                println!("    Request {}: {}", req_idx + 1, request_name);
            }

            // Execute request
            let result = executor.execute(
                spec,
                request_name,
                &test_case.endpoint,
                &test_case.method,
                test_case.timeout_ms,
            );

            let response = match result {
                Ok(r) => r,
                Err(e) => {
                    test_status = TestStatus::Error;
                    failures.push(TestFailure {
                        request_index: req_idx,
                        assertion: "HTTP request".to_string(),
                        expected: None,
                        actual: None,
                        message: None,
                        error: Some(e.to_string()),
                    });
                    if test_case.fail_fast {
                        break;
                    }
                    continue;
                }
            };

            // Check HTTP status
            if response.status != test_case.expect_status {
                test_status = TestStatus::Failed;
                failures.push(TestFailure {
                    request_index: req_idx,
                    assertion: "HTTP status".to_string(),
                    expected: Some(test_case.expect_status.to_string()),
                    actual: Some(response.status.to_string()),
                    message: Some("Unexpected HTTP status".to_string()),
                    error: None,
                });
                if test_case.fail_fast {
                    break;
                }
            }

            // Extract variables if defined on this request
            let request_def = spec.resolve_request(request_name)?;
            if !request_def.extract.is_empty() {
                if let Err(e) = executor.extract_variables(&request_def.extract, &response.body) {
                    if verbose {
                        eprintln!("      Warning: extraction failed: {}", e);
                    }
                }
            }

            // Set current response for assertion evaluation
            evaluator.set_current(response.body);

            // Skip assertions on first request if skip_first is set
            if test_case.skip_first && req_idx == 0 {
                if verbose {
                    println!("      Skipping assertions (skip_first)");
                }
                continue;
            }

            // Run assertions
            for assertion in &test_case.assertions {
                assertion_summary.total += 1;

                let result = evaluator.evaluate(assertion);

                if result.passed {
                    assertion_summary.passed += 1;
                    if verbose {
                        println!("{}", assertion.query.as_deref().unwrap_or("(no query)"));
                    }
                } else {
                    assertion_summary.failed += 1;
                    test_status = TestStatus::Failed;

                    let failure = TestFailure {
                        request_index: req_idx,
                        assertion: assertion.query.clone().unwrap_or_default(),
                        expected: result.expected,
                        actual: result.actual,
                        message: result.message,
                        error: result.error,
                    };

                    if verbose {
                        println!("{}", assertion.query.as_deref().unwrap_or("(no query)"));
                        if let Some(ref msg) = failure.message {
                            println!("        {}", msg);
                        }
                    }

                    failures.push(failure);

                    if test_case.fail_fast {
                        break;
                    }
                }
            }

            if test_case.fail_fast && test_status != TestStatus::Passed {
                break;
            }
        }

        let test_result = TestResult {
            name: test_name.clone(),
            description: test_case.description.clone(),
            status: test_status,
            duration_ms: test_start.elapsed().as_millis() as u64,
            request_count: test_case.requests.len(),
            assertions: assertion_summary,
            failures,
        };

        suite_result.add_result(test_result);
    }

    suite_result.set_duration(suite_start.elapsed().as_millis() as u64);
    Ok(suite_result)
}

fn validate_specs(spec_files: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let project = CheckmateProject::discover();
    let resolved_specs = resolve_spec_files(spec_files, project.as_ref())?;

    if resolved_specs.is_empty() {
        eprintln!("No test specs to validate.");
        return Ok(());
    }

    let mut all_valid = true;

    for spec_path in &resolved_specs {
        match TestSpec::from_file(spec_path.to_string_lossy().as_ref()) {
            Ok(spec) => {
                println!("{} - valid", spec_path.display());
                println!("  {} requests, {} tests",
                    spec.requests.len(),
                    spec.tests.len()
                );
            }
            Err(e) => {
                println!("{} - invalid: {}", spec_path.display(), e);
                all_valid = false;
            }
        }
    }

    if !all_valid {
        std::process::exit(1);
    }

    Ok(())
}

fn list_tests(spec_files: &[String]) -> Result<(), Box<dyn std::error::Error>> {
    let project = CheckmateProject::discover();
    let resolved_specs = resolve_spec_files(spec_files, project.as_ref())?;

    if resolved_specs.is_empty() {
        eprintln!("No test specs found.");
        return Ok(());
    }

    for spec_path in &resolved_specs {
        let spec = TestSpec::from_file(spec_path.to_string_lossy().as_ref())?;

        println!("{}:", spec_path.display());

        if let Some(ref name) = spec.name {
            println!("  Suite: {}", name);
        }

        println!("  Tests:");
        for (name, test) in &spec.tests {
            let desc = test.description.as_deref().unwrap_or("");
            if desc.is_empty() {
                println!("    - {}", name);
            } else {
                println!("    - {}: {}", name, desc);
            }
        }

        println!();
    }

    Ok(())
}