cli-testing-specialist 1.0.10

Comprehensive testing framework for CLI tools - automated analysis, test generation, and security validation
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
use crate::error::{Error, Result};
use crate::generator::TemplateEngine;
use crate::types::{Assertion, TestCase, TestCategory};
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};

/// BATS file writer for generating test files
pub struct BatsWriter {
    /// Output directory for generated BATS files
    output_dir: PathBuf,

    /// Template engine for rendering templates (currently unused, reserved for future use)
    #[allow(dead_code)]
    template_engine: TemplateEngine,

    /// Binary name for test execution
    binary_name: String,

    /// Binary path for test execution
    binary_path: PathBuf,
}

impl BatsWriter {
    /// Create a new BATS writer
    pub fn new(output_dir: PathBuf, binary_name: String, binary_path: PathBuf) -> Result<Self> {
        // Create output directory if it doesn't exist
        if !output_dir.exists() {
            fs::create_dir_all(&output_dir)
                .map_err(|e| Error::Config(format!("Failed to create output directory: {}", e)))?;
        }

        // Initialize template engine
        let mut template_engine = TemplateEngine::new()?;
        template_engine.load_templates()?;

        Ok(Self {
            output_dir,
            template_engine,
            binary_name,
            binary_path,
        })
    }

    /// Write test cases to BATS files, organized by category
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use cli_testing_specialist::generator::{TestGenerator, BatsWriter};
    /// use cli_testing_specialist::analyzer::CliParser;
    /// use cli_testing_specialist::types::TestCategory;
    /// use std::path::{Path, PathBuf};
    ///
    /// let parser = CliParser::new();
    /// let analysis = parser.analyze(Path::new("/usr/bin/curl"))?;
    ///
    /// let generator = TestGenerator::new(
    ///     analysis.clone(),
    ///     vec![TestCategory::Basic, TestCategory::Security]
    /// );
    /// let tests = generator.generate()?;
    ///
    /// let writer = BatsWriter::new(
    ///     PathBuf::from("tests"),
    ///     analysis.binary_name.clone(),
    ///     analysis.binary_path.clone()
    /// )?;
    ///
    /// let bats_files = writer.write_tests(&tests)?;
    /// println!("Generated {} BATS files", bats_files.len());
    /// # Ok::<(), cli_testing_specialist::error::CliTestError>(())
    /// ```
    pub fn write_tests(&self, test_cases: &[TestCase]) -> Result<Vec<PathBuf>> {
        log::info!("Writing {} test cases to BATS files", test_cases.len());

        // Group tests by category
        let mut by_category: HashMap<TestCategory, Vec<&TestCase>> = HashMap::new();

        for test in test_cases {
            by_category.entry(test.category).or_default().push(test);
        }

        let mut output_files = Vec::new();

        // Write one BATS file per category
        for (category, tests) in by_category {
            let output_file = self.write_category_file(category, tests)?;
            output_files.push(output_file);
        }

        log::info!("Generated {} BATS files", output_files.len());
        Ok(output_files)
    }

    /// Write a single BATS file for a category
    fn write_category_file(
        &self,
        category: TestCategory,
        tests: Vec<&TestCase>,
    ) -> Result<PathBuf> {
        let filename = format!("{}.bats", category.as_str());
        let output_path = self.output_dir.join(&filename);

        log::debug!(
            "Writing {} tests to {} ({:?})",
            tests.len(),
            filename,
            category
        );

        let file = File::create(&output_path)
            .map_err(|e| Error::Config(format!("Failed to create BATS file: {}", e)))?;

        let mut writer = BufWriter::new(file);

        // Write file header
        self.write_header(&mut writer, category)?;

        // Write setup function
        self.write_setup(&mut writer)?;

        // Write teardown function
        self.write_teardown(&mut writer)?;

        // Write test cases
        for test in tests {
            self.write_test_case(&mut writer, test)?;
        }

        writer
            .flush()
            .map_err(|e| Error::Config(format!("Failed to flush BATS file: {}", e)))?;

        log::debug!("Successfully wrote {}", filename);
        Ok(output_path)
    }

    /// Write BATS file header
    fn write_header(&self, writer: &mut BufWriter<File>, category: TestCategory) -> Result<()> {
        writeln!(writer, "#!/usr/bin/env bats")?;
        writeln!(writer, "#")?;
        writeln!(
            writer,
            "# BATS Test Suite: {}",
            category.as_str().to_uppercase()
        )?;
        writeln!(writer, "# Generated by CLI Testing Specialist")?;
        writeln!(writer, "# Target CLI: {}", self.binary_name)?;
        writeln!(writer, "#")?;
        writeln!(writer)?;

        Ok(())
    }

    /// Write setup function
    fn write_setup(&self, writer: &mut BufWriter<File>) -> Result<()> {
        writeln!(writer, "# Setup function (runs before each test)")?;
        writeln!(writer, "setup() {{")?;
        writeln!(writer, "    # Set CLI binary path")?;
        writeln!(writer, "    CLI_BINARY=\"{}\"", self.binary_path.display())?;
        writeln!(writer, "    BINARY_BASENAME=\"{}\"", self.binary_name)?;
        writeln!(writer)?;
        writeln!(
            writer,
            "    # Export CLI_BINARY for subshell tests (multi-shell compatibility)"
        )?;
        writeln!(writer, "    export CLI_BINARY")?;
        writeln!(writer)?;
        writeln!(
            writer,
            "    # Create temporary directory for test artifacts"
        )?;
        writeln!(writer, "    TEST_TEMP_DIR=\"$(mktemp -d)\"")?;
        writeln!(writer, "    export TEST_TEMP_DIR")?;
        writeln!(writer)?;
        writeln!(writer, "    # Set secure umask")?;
        writeln!(writer, "    umask 077")?;
        writeln!(writer, "}}")?;
        writeln!(writer)?;

        Ok(())
    }

    /// Write teardown function
    fn write_teardown(&self, writer: &mut BufWriter<File>) -> Result<()> {
        writeln!(writer, "# Teardown function (runs after each test)")?;
        writeln!(writer, "teardown() {{")?;
        writeln!(writer, "    # Cleanup temporary directory")?;
        writeln!(
            writer,
            "    if [[ -n \"${{TEST_TEMP_DIR:-}}\" ]] && [[ -d \"$TEST_TEMP_DIR\" ]]; then"
        )?;
        writeln!(writer, "        rm -rf \"$TEST_TEMP_DIR\"")?;
        writeln!(writer, "    fi")?;
        writeln!(writer, "}}")?;
        writeln!(writer)?;

        Ok(())
    }

    /// Write a single test case
    fn write_test_case(&self, writer: &mut BufWriter<File>, test: &TestCase) -> Result<()> {
        // Write test annotation
        writeln!(
            writer,
            "@test \"[{}] {}\" {{",
            test.category.as_str(),
            test.name
        )?;

        // Write test description comment
        writeln!(writer, "    # Test ID: {}", test.id)?;
        if !test.tags.is_empty() {
            writeln!(writer, "    # Tags: {}", test.tags.join(", "))?;
        }
        writeln!(writer)?;

        // Write command execution
        writeln!(writer, "    # Execute command")?;
        writeln!(writer, "    run {}", test.command)?;
        writeln!(writer)?;

        // Write exit code assertion
        writeln!(writer, "    # Assert exit code")?;
        match test.expected_exit {
            Some(code) => writeln!(writer, "    [ \"$status\" -eq {} ]", code)?,
            None => writeln!(writer, "    [ \"$status\" -ne 0 ]")?,
        }

        // Write additional assertions
        if !test.assertions.is_empty() {
            writeln!(writer)?;
            writeln!(writer, "    # Additional assertions")?;

            for assertion in &test.assertions {
                self.write_assertion(writer, assertion)?;
            }
        }

        writeln!(writer, "}}")?;
        writeln!(writer)?;

        Ok(())
    }

    /// Write an assertion
    fn write_assertion(&self, writer: &mut BufWriter<File>, assertion: &Assertion) -> Result<()> {
        match assertion {
            Assertion::ExitCode(code) => {
                writeln!(writer, "    [ \"$status\" -eq {} ]", code)?;
            }
            Assertion::OutputContains(text) => {
                // Special case for "Usage:" - support both uppercase and lowercase
                // Python argparse uses "usage:" (lowercase)
                // Most other CLIs use "Usage:" (uppercase)
                if text == "Usage:" {
                    writeln!(
                        writer,
                        "    [[ \"$output\" =~ \"Usage:\" ]] || [[ \"$output\" =~ \"usage:\" ]] || [[ \"$stderr\" =~ \"Usage:\" ]] || [[ \"$stderr\" =~ \"usage:\" ]]"
                    )?;
                } else {
                    writeln!(
                        writer,
                        "    [[ \"$output\" =~ \"{}\" ]] || [[ \"$stderr\" =~ \"{}\" ]]",
                        escape_regex(text),
                        escape_regex(text)
                    )?;
                }
            }
            Assertion::OutputMatches(pattern) => {
                writeln!(
                    writer,
                    "    [[ \"$output\" =~ {} ]] || [[ \"$stderr\" =~ {} ]]",
                    pattern, pattern
                )?;
            }
            Assertion::OutputNotContains(text) => {
                writeln!(
                    writer,
                    "    ! [[ \"$output\" =~ \"{}\" ]] && ! [[ \"$stderr\" =~ \"{}\" ]]",
                    escape_regex(text),
                    escape_regex(text)
                )?;
            }
            Assertion::FileExists(path) => {
                writeln!(writer, "    [ -f \"{}\" ]", path.display())?;
            }
            Assertion::FileNotExists(path) => {
                writeln!(writer, "    [ ! -f \"{}\" ]", path.display())?;
            }
        }

        Ok(())
    }

    /// Validate generated BATS file syntax
    pub fn validate_bats_file(&self, file_path: &Path) -> Result<()> {
        // Check if file exists
        if !file_path.exists() {
            return Err(Error::Validation(format!(
                "BATS file does not exist: {}",
                file_path.display()
            )));
        }

        // Read file content
        let content = fs::read_to_string(file_path)
            .map_err(|e| Error::Config(format!("Failed to read BATS file: {}", e)))?;

        // Basic validation checks
        if !content.starts_with("#!/usr/bin/env bats") {
            return Err(Error::Validation(
                "BATS file missing shebang line".to_string(),
            ));
        }

        // Check for at least one @test block
        if !content.contains("@test") {
            return Err(Error::Validation(
                "BATS file contains no test cases".to_string(),
            ));
        }

        // Check for balanced braces (simple check)
        let open_braces = content.matches('{').count();
        let close_braces = content.matches('}').count();

        if open_braces != close_braces {
            return Err(Error::Validation(format!(
                "Unbalanced braces: {} open, {} close",
                open_braces, close_braces
            )));
        }

        log::debug!("BATS file validation passed: {}", file_path.display());
        Ok(())
    }
}

/// Escape special regex characters for bash pattern matching
fn escape_regex(text: &str) -> String {
    text.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('$', "\\$")
        .replace('`', "\\`")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::TestCategory;
    use tempfile::TempDir;

    fn create_test_cases() -> Vec<TestCase> {
        vec![
            TestCase::new(
                "basic-001".to_string(),
                "Help display test".to_string(),
                TestCategory::Basic,
                "test-cli --help".to_string(),
            )
            .with_exit_code(0)
            .with_assertion(Assertion::OutputContains("Usage:".to_string()))
            .with_tag("help".to_string()),
            TestCase::new(
                "basic-002".to_string(),
                "Version display test".to_string(),
                TestCategory::Basic,
                "test-cli --version".to_string(),
            )
            .with_exit_code(0)
            .with_tag("version".to_string()),
            TestCase::new(
                "security-001".to_string(),
                "Command injection test".to_string(),
                TestCategory::Security,
                "test-cli --name 'test; rm -rf /'".to_string(),
            )
            .with_tag("injection".to_string()),
        ]
    }

    #[test]
    fn test_bats_writer_creation() {
        let temp_dir = TempDir::new().unwrap();
        let output_dir = temp_dir.path().join("output");

        let result = BatsWriter::new(
            output_dir.clone(),
            "test-cli".to_string(),
            PathBuf::from("/usr/bin/test-cli"),
        );

        assert!(result.is_ok());
        assert!(output_dir.exists());
    }

    #[test]
    fn test_write_tests() {
        let temp_dir = TempDir::new().unwrap();
        let output_dir = temp_dir.path().join("output");

        let writer = BatsWriter::new(
            output_dir.clone(),
            "test-cli".to_string(),
            PathBuf::from("/usr/bin/test-cli"),
        )
        .unwrap();

        let test_cases = create_test_cases();
        let result = writer.write_tests(&test_cases);

        assert!(result.is_ok());
        let files = result.unwrap();
        assert_eq!(files.len(), 2); // basic.bats and security.bats

        // Check that files exist
        for file in &files {
            assert!(file.exists());
        }
    }

    #[test]
    fn test_write_category_file() {
        let temp_dir = TempDir::new().unwrap();
        let output_dir = temp_dir.path().join("output");

        let writer = BatsWriter::new(
            output_dir.clone(),
            "test-cli".to_string(),
            PathBuf::from("/usr/bin/test-cli"),
        )
        .unwrap();

        let test_cases = create_test_cases();
        let basic_tests: Vec<&TestCase> = test_cases
            .iter()
            .filter(|t| t.category == TestCategory::Basic)
            .collect();

        let result = writer.write_category_file(TestCategory::Basic, basic_tests);

        assert!(result.is_ok());
        let file_path = result.unwrap();
        assert!(file_path.exists());
        assert_eq!(file_path.file_name().unwrap(), "basic.bats");
    }

    #[test]
    fn test_validate_bats_file() {
        let temp_dir = TempDir::new().unwrap();
        let output_dir = temp_dir.path().join("output");

        let writer = BatsWriter::new(
            output_dir.clone(),
            "test-cli".to_string(),
            PathBuf::from("/usr/bin/test-cli"),
        )
        .unwrap();

        let test_cases = create_test_cases();
        let files = writer.write_tests(&test_cases).unwrap();

        // Validate each generated file
        for file in &files {
            let result = writer.validate_bats_file(file);
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_validate_invalid_bats_file() {
        let temp_dir = TempDir::new().unwrap();
        let output_dir = temp_dir.path().join("output");
        fs::create_dir_all(&output_dir).unwrap();

        let writer = BatsWriter::new(
            output_dir.clone(),
            "test-cli".to_string(),
            PathBuf::from("/usr/bin/test-cli"),
        )
        .unwrap();

        // Create invalid BATS file (missing shebang)
        let invalid_file = output_dir.join("invalid.bats");
        fs::write(&invalid_file, "@test \"test\" { echo \"test\" }").unwrap();

        let result = writer.validate_bats_file(&invalid_file);
        assert!(result.is_err());
    }

    #[test]
    fn test_escape_regex() {
        assert_eq!(escape_regex("test"), "test");
        assert_eq!(escape_regex("test$var"), "test\\$var");
        assert_eq!(escape_regex("test\"quote\""), "test\\\"quote\\\"");
        assert_eq!(escape_regex("test\\path"), "test\\\\path");
    }

    #[test]
    fn test_bats_file_content() {
        let temp_dir = TempDir::new().unwrap();
        let output_dir = temp_dir.path().join("output");

        let writer = BatsWriter::new(
            output_dir.clone(),
            "test-cli".to_string(),
            PathBuf::from("/usr/bin/test-cli"),
        )
        .unwrap();

        let test_cases = vec![TestCase::new(
            "basic-001".to_string(),
            "Help test".to_string(),
            TestCategory::Basic,
            "test-cli --help".to_string(),
        )
        .with_exit_code(0)
        .with_assertion(Assertion::OutputContains("Usage".to_string()))];

        let files = writer.write_tests(&test_cases).unwrap();
        let content = fs::read_to_string(&files[0]).unwrap();

        // Verify content structure
        assert!(content.contains("#!/usr/bin/env bats"));
        assert!(content.contains("setup()"));
        assert!(content.contains("teardown()"));
        assert!(content.contains("@test"));
        assert!(content.contains("Help test"));
        assert!(content.contains("test-cli --help"));
        assert!(content.contains("[ \"$status\" -eq 0 ]"));
    }
}