grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/parse/tests.rs
// Purpose:   Tests for the chain grammar, the config and the parse contract
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The driver's own tests run on the stock parsers, in
//! `src/format/chain_tests.rs`.

use std::sync::Arc;

use serde_json::json;

use super::*;
use crate::strmatch::{Signature, Specificity};

fn hops(text: &str) -> serde_json::Value {
    let chain: Chain = text.parse().unwrap_or_else(|e| panic!("{text}: {e}"));
    serde_json::to_value(chain).unwrap()
}

#[test]
fn a_chain_string_reads_into_the_list_it_is_short_for() {
    let cases = [
        ("syslog", json!([{"format": "syslog"}])),
        (
            "syslog > cef",
            json!([{"format": "syslog"}, {"format": "cef"}]),
        ),
        (
            "syslog->cef",
            json!([{"format": "syslog"}, {"format": "cef"}]),
        ),
        ("  auto  ", json!([{"format": "auto"}])),
        ("auto*", json!([{"format": "auto*"}])),
        (
            "syslog > auto*",
            json!([{"format": "syslog"}, {"format": "auto*"}]),
        ),
        (
            "syslog > ( cef , leef,ndjson )",
            json!([{"format": "syslog"}, {"format": ["cef", "leef", "ndjson"]}]),
        ),
        (
            r#"syslog > cef > field("msg"):xml"#,
            json!([{"format": "syslog"}, {"format": "cef"}, {"format": "xml", "field": "msg"}]),
        ),
        (
            r#"cef > field ( "a \"b\" > c:d" ) : (xml, kv)"#,
            json!([{"format": "cef"}, {"format": ["xml", "kv"], "field": "a \"b\" > c:d"}]),
        ),
        (
            "cef > each:auto*",
            json!([{"format": "cef"}, {"format": "auto*", "each": true}]),
        ),
        (
            "grok:firewall->cef",
            json!([{"format": "grok:firewall"}, {"format": "cef"}]),
        ),
        (
            "grok:firewall- > grok:asa-6.x",
            json!([{"format": "grok:firewall-"}, {"format": "grok:asa-6.x"}]),
        ),
        ("grok:auto", json!([{"format": "grok:auto"}])),
    ];
    for (text, want) in cases {
        assert_eq!(hops(text), want, "{text}");
    }
}

#[test]
fn a_string_that_is_no_chain_says_where() {
    let cases = [
        ("", 0, "expected a parser name"),
        ("syslog >", 8, "expected a parser name"),
        ("syslog cef", 7, "expected `>`"),
        ("Syslog", 0, "expected a parser name"),
        ("syslog > ()", 10, "expected a parser name"),
        ("syslog > (cef leef)", 14, "expected `,` or `)`"),
        ("syslog > (cef, auto)", 15, "auto can't sit in a list"),
        ("auto:x", 4, "auto takes no instance name"),
        ("grok:", 5, "expected an instance name"),
        ("grok :fw", 5, "expected `>`"),
        ("syslog > each", 13, "expected `:` after the selector"),
        ("syslog > each:", 14, "expected a parser name"),
        ("syslog > field:cef", 14, "expected `(` after field"),
        (
            "syslog > field(msg):cef",
            15,
            "expected a quoted field name",
        ),
        (r#"syslog > field("msg):cef"#, 24, "no closing quote"),
        (r#"syslog > field("\q"):cef"#, 15, "isn't a JSON string"),
        (
            r#"syslog > field("msg") cef"#,
            22,
            "expected `:` after the selector",
        ),
        ("syslog > raw", 9, "a reserved word"),
        ("syslog - > cef", 7, "expected `>`"),
    ];
    for (text, offset, reason) in cases {
        let err = text.parse::<Chain>().unwrap_err();
        assert_eq!(err.offset, offset, "{text}: {err}");
        assert!(err.reason.contains(reason), "{text}: {err}");
    }
}

#[test]
fn config_reads_a_string_a_list_and_a_mix_of_both() {
    let text: ParseConfig = serde_json::from_value(json!({"chain": "syslog > auto"})).unwrap();
    assert_eq!(text, ParseConfig::chain("syslog > auto").unwrap());
    assert_eq!(
        (text.fallback.clone(), text.max_depth, text.max_invocations),
        (FallbackConfig::Raw, 4, 256)
    );

    let list: ParseConfig = serde_json::from_value(json!({
        "chain": [
            "syslog",
            {"format": ["cef", "leef"], "prefix": "event."},
            r#"field("msg"):grok:fw"#,
            {"format": "auto*", "each": true, "fallback": "reject"},
        ],
        "fallback": "kv",
        "settings": {"grok:fw": {"patterns": ["x"]}},
    }))
    .unwrap();
    let hops = &list.chain.0;
    assert_eq!(
        hops[0],
        HopConfig::new(FormatChoice::Named(vec!["syslog".into()]))
    );
    assert_eq!(hops[1].prefix.as_deref(), Some("event."));
    assert_eq!(hops[2].field.as_deref(), Some("msg"));
    assert_eq!(hops[2].format, FormatChoice::Named(vec!["grok:fw".into()]));
    assert_eq!(
        (
            hops[3].format.clone(),
            hops[3].each,
            hops[3].fallback.clone()
        ),
        (FormatChoice::AutoStar, true, Some(FallbackConfig::Reject))
    );
    assert_eq!(list.fallback, FallbackConfig::Format("kv".into()));

    let back = serde_json::to_value(&list).unwrap();
    assert_eq!(
        back["chain"],
        json!([
            {"format": "syslog"},
            {"format": ["cef", "leef"], "prefix": "event."},
            {"format": "grok:fw", "field": "msg"},
            {"format": "auto*", "each": true, "fallback": "reject"},
        ])
    );
    assert_eq!(serde_json::from_value::<ParseConfig>(back).unwrap(), list);
}

#[test]
fn a_config_that_names_nothing_or_uses_a_key_that_is_gone_does_not_load() {
    let err = |config: serde_json::Value| {
        serde_json::from_value::<ParseConfig>(config)
            .unwrap_err()
            .to_string()
    };
    assert!(err(json!({})).contains("missing field `chain`"));
    for gone in ["format", "layers", "fields", "identify"] {
        let message = err(json!({"chain": "syslog", gone: "auto"}));
        assert!(
            message.contains(gone) && message.contains("`chain`"),
            "{message}"
        );
    }
    assert!(
        err(json!({"chain": [{"format": "cef", "grok": {}}]})).contains("unknown field `grok`")
    );
    assert!(err(json!({"chain": [{"field": "msg"}]})).contains("missing field `format`"));
    assert!(err(json!({"chain": "syslog >"})).contains("expected a parser name at byte 8"));
    assert!(err(json!({"chain": ["syslog > cef"]})).contains("expected `>` or the end"));
    assert!(err(json!({"chain": 4})).contains("a chain such as"));
    assert!(err(json!({"chain": "syslog", "framing": {"kind": "nope"}})).contains("nope"));
}

#[test]
fn prefix_stack_builds_full_names_in_one_buffer() {
    let mut p = PrefixStack::new();
    p.push("syslog.");
    p.push("cef.");
    assert_eq!(p.with_full("host", str::to_owned), "syslog.cef.host");
    p.pop();
    assert_eq!(p.current(), "syslog.");
    // A quoted key takes the place of the `.` before it, and gives it back.
    assert_eq!(p.with_full(r#"["a.b"]"#, str::to_owned), r#"syslog["a.b"]"#);
    p.push(r#"["k.v"]"#);
    p.push(".");
    assert_eq!(p.with_full("x", str::to_owned), r#"syslog["k.v"].x"#);
    assert_eq!(
        p.with_full(r#"["y"]"#, str::to_owned),
        r#"syslog["k.v"]["y"]"#
    );
    p.pop();
    p.pop();
    assert_eq!(p.current(), "syslog.");
    // Text that opens no quoted key keeps its `.`.
    assert_eq!(p.with_full(r#"["x"#, str::to_owned), r#"syslog.["x"#);
    assert_eq!(p.with_full("[0]", str::to_owned), "syslog.[0]");
    p.pop();
    p.pop();
    assert_eq!(p.current(), "");
    assert_eq!(p.with_full(r#"["a.b"]"#, str::to_owned), r#"["a.b"]"#);
}

/// A parser with a name no registry takes. No stock parser has one.
struct Named(&'static str, Signature);

impl Parser for Named {
    fn name(&self) -> &str {
        self.0
    }
    fn tier(&self) -> MatcherTier {
        MatcherTier::Byte
    }
    fn signature(&self) -> &Signature {
        &self.1
    }
    fn parse<'a>(&self, _: &'a [u8], _: &mut dyn FieldSink<'a>) -> Result<Parsed, ParseError> {
        Ok(Parsed::NoMatch)
    }
}

#[test]
fn parser_names_are_format_or_format_and_instance() {
    for good in [
        "syslog",
        "cef",
        "grok:firewall",
        "grok:asa-6",
        "x9_y:a.b",
        "grok:auto",
        "automatic",
    ] {
        assert!(valid_parser_name(good), "{good}");
    }
    for bad in [
        "",
        "Syslog",
        "9x",
        "grok:",
        ":x",
        "grok:Fw",
        "a:b:c",
        "has space",
        "auto",
        "auto:x",
        "each",
        "field",
        "raw",
        "reject:x",
    ] {
        assert!(!valid_parser_name(bad), "{bad}");
    }
    for name in ["Bad Name", "auto"] {
        let err = Parsers::new()
            .register(Arc::new(Named(name, Signature::builder().build().unwrap())))
            .unwrap_err();
        assert!(matches!(err, ResolveError::BadName(_)), "{name}");
    }
    assert_eq!(Specificity::default(), Specificity::Specific);
}

/// A grippo format this build left out is named with its feature, and any
/// other name no registry holds stays unknown.
#[test]
fn a_format_left_out_names_its_feature() {
    let err = ParsePlan::chain("yaml", &Parsers::new()).unwrap_err();
    let named = |e: &CompileError| match e {
        CompileError::Resolve(r) => r.to_string(),
        other => panic!("{other:?}"),
    };
    let want = if cfg!(feature = "parse-yaml") {
        r#"no parser named "yaml""#
    } else {
        r#""yaml" needs grippo's `parse-yaml` feature, which this build left out"#
    };
    assert_eq!(named(&err), want);
    assert!(matches!(
        ResolveError::unknown("nope"),
        ResolveError::Unknown(_)
    ));
    assert_eq!(
        missing_feature("zstd:big"),
        (!cfg!(feature = "decode-zstd")).then_some("decode-zstd")
    );
    assert_eq!(missing_feature("nope"), None);
}