tests/cli_grep.rs

//! End-to-end tests for `ripgrab grep`.

use std::io::Write;

use assert_cmd::Command;
use predicates::str::contains;
use tempfile::NamedTempFile;

fn bin() -> Command {
    Command::cargo_bin("ripgrab").unwrap()
}

#[test]
fn grep_matches_regex() {
    let mut tmp = NamedTempFile::new().unwrap();
    writeln!(tmp, "apples are red").unwrap();
    writeln!(tmp, "bananas are yellow").unwrap();
    writeln!(tmp, "cherries are red").unwrap();
    tmp.flush().unwrap();

    bin()
        .args(["grep", tmp.path().to_str().unwrap(), "-i", "red"])
        .env("NO_COLOR", "1")
        .assert()
        .success()
        .stdout(contains("apples are red"))
        .stdout(contains("cherries are red"))
        .stdout(contains("yellow").not());
}

#[test]
fn grep_applies_where_clause() {
    let mut tmp = NamedTempFile::new().unwrap();
    writeln!(tmp, "host=api status=200 ok").unwrap();
    writeln!(tmp, "host=api status=503 retry").unwrap();
    tmp.flush().unwrap();

    bin()
        .args([
            "grep",
            tmp.path().to_str().unwrap(),
            "--where", "body ~ /retry/",
        ])
        .env("NO_COLOR", "1")
        .assert()
        .success()
        .stdout(contains("status=503"))
        .stdout(contains("status=200").not());
}

#[test]
fn grep_multiple_paths_preserves_order() {
    let mut a = NamedTempFile::new().unwrap();
    let mut b = NamedTempFile::new().unwrap();
    writeln!(a, "from-a-1\nfrom-a-2").unwrap();
    writeln!(b, "from-b-1").unwrap();
    a.flush().unwrap();
    b.flush().unwrap();

    let out = bin()
        .args([
            "grep",
            a.path().to_str().unwrap(),
            b.path().to_str().unwrap(),
            "-i", ".",
        ])
        .env("NO_COLOR", "1")
        .output()
        .unwrap();
    let stdout = String::from_utf8(out.stdout).unwrap();
    let pos_a2 = stdout.find("from-a-2").expect("a-2 present");
    let pos_b1 = stdout.find("from-b-1").expect("b-1 present");
    assert!(pos_a2 < pos_b1, "expected a-2 before b-1: {:?}", stdout);
}

#[test]
fn grep_rejects_missing_paths() {
    bin().args(["grep", "/does/not/exist", "-i", "."]).assert().failure();
}