grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/field/tests.rs
// Purpose:   Every field against its own regex, both ways
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use std::fmt::Write;
use std::sync::LazyLock;

use proptest::prelude::*;
use regex_automata::meta::Regex;
use regex_automata::{Anchored, Input};

use super::*;

/// Every field, the range-checked ones included.
fn table() -> impl Iterator<Item = &'static Field> {
    FIELDS.iter().chain(&CHECKED)
}

static REGEXES: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    table()
        .map(|f| Regex::new(&format!("(?:{})", f.regex)).unwrap())
        .collect()
});

/// The regex's answer: the end of its anchored match at `at`.
fn regex_end(i: usize, hay: &[u8], at: usize) -> Option<usize> {
    let input = Input::new(hay).range(at..).anchored(Anchored::Yes);
    REGEXES[i].search(&input).map(|m| m.end())
}

/// Every field's native answer equals the regex's, except a deferral.
fn agree(hay: &str, at: usize) -> Result<usize, TestCaseError> {
    let mut deferred = 0;
    for (i, f) in table().enumerate() {
        let want = regex_end(i, hay.as_bytes(), at);
        match (f.scan)(hay.as_bytes(), at) {
            Scan::Defer => deferred += 1,
            Scan::Match(end) => {
                prop_assert_eq!(Some(end), want, "{} on {:?} at {}", f.name, hay, at);
            }
            Scan::NoMatch => prop_assert_eq!(None, want, "{} on {:?} at {}", f.name, hay, at),
        }
    }
    Ok(deferred)
}

#[test]
fn known_lines_match_as_the_regex_does() {
    let rows: &[(&str, &str, Option<&str>)] = &[
        ("IPV4", "10.1.2.3:443", Some("10.1.2.3")),
        ("IPV4", "175.16.199.1", Some("175.16.199.1")),
        ("IPV4", "1.2.3.4567", None),
        ("IPV4", "x1.2.3.4", None),
        ("WORD", "error: disk", Some("error")),
        ("INT", "-42ms", Some("-42")),
        ("INT", "+x", None),
        ("NUMBER", "3.14.15", Some("3.14")),
        ("NUMBER", ".5", Some(".5")),
        ("NUMBER", "7.", Some("7")),
        ("POSINT", "012", None),
        ("NONNEGINT", "12ab", None),
        ("MAC", "00:1a:2b:3c:4d:5e", Some("00:1a:2b:3c:4d:5e")),
        ("MAC", "001a.2b3c.4d5e", Some("001a.2b3c.4d5e")),
        (
            "UUID",
            "123e4567-e89b-12d3-a456-426614174000",
            Some("123e4567-e89b-12d3-a456-426614174000"),
        ),
        (
            "QUOTEDSTRING",
            r#""a \"b\" c" tail"#,
            Some(r#""a \"b\" c""#),
        ),
        ("QUOTEDSTRING", "''", Some("''")),
        ("LOGLEVEL", "ERROR:", Some("ERROR")),
        ("LOGLEVEL", "Warning", Some("Warning")),
        ("MONTH", "June", Some("June")),
        ("MONTH", "Junk", Some("Jun")),
        ("YEAR", "123", Some("12")),
        ("HOUR", "24", Some("2")),
        ("TIME", "9:05:07.123 x", Some("9:05:07.123")),
        ("TIME", "123:45", None),
        ("ISO8601_TIMEZONE", "+130", Some("+130")),
        (
            "TIMESTAMP_ISO8601",
            "2026-11-26T11:22:33.456+11:00 x",
            Some("2026-11-26T11:22:33.456+11:00"),
        ),
        (
            "TIMESTAMP_ISO8601",
            "2026-11-26 11:22Z",
            Some("2026-11-26 11:22Z"),
        ),
        (
            "SYSLOGTIMESTAMP",
            "Nov  6 08:01:02 host",
            Some("Nov  6 08:01:02"),
        ),
        (
            "HTTPDATE",
            "26/Nov/2026:11:22:33 +1100]",
            Some("26/Nov/2026:11:22:33 +1100"),
        ),
        ("BASE10NUM", "-3.25e", Some("-3.25")),
        ("BASE10NUM", "+.5", Some("+.5")),
        ("BASE16NUM", "0x1Fz", Some("0x1F")),
        ("BASE16NUM", "0xg", Some("0")),
        ("URIPATH", "/a/b.html?q=1", Some("/a/b.html")),
        ("URIPATH", "a/b", None),
        ("URIPARAM", "?q=1&r=[2] x", Some("?q=1&r=[2]")),
        ("UNIXPATH", "/var/log/syslog.1 x", Some("/var/log/syslog.1")),
        ("WINPATH", r"C:\Windows\x.dll? y", Some(r"C:\Windows\x.dll")),
        ("WINPATH", r"\\srv\share", Some(r"\\srv\share")),
        ("WINPATH", r"\srv", None),
        (
            "JAVACLASS",
            "org.example.Main.run()",
            Some("org.example.Main.run"),
        ),
        ("JAVACLASS", "a..b", Some("a")),
        (
            "EMAILADDRESS",
            "ops+alerts@mail.example.com>",
            Some("ops+alerts@mail.example.com"),
        ),
        ("EMAILADDRESS", "a@b", None),
    ];
    for (name, hay, want) in rows {
        let f = field(name).unwrap();
        let got = match (f.scan)(hay.as_bytes(), 0) {
            Scan::Match(end) => Some(&hay[..end]),
            Scan::NoMatch => None,
            Scan::Defer => panic!("{name} deferred on ASCII {hay:?}"),
        };
        assert_eq!(got, *want, "{name} on {hay:?}");
        let i = FIELDS.iter().position(|g| g.name == *name).unwrap();
        assert_eq!(
            regex_end(i, hay.as_bytes(), 0).map(|e| &hay[..e]),
            *want,
            "{name} regex on {hay:?}"
        );
    }
}

#[test]
fn the_ascii_classes_hold_what_their_char_tests_do() {
    for byte in 0..=255_u8 {
        let ascii = byte.is_ascii().then(|| char::from(byte));
        assert_eq!(
            NOTSPACE.has(byte),
            ascii.is_some_and(|c| !c.is_whitespace()),
            "NOTSPACE {byte:#x}"
        );
        assert_eq!(WORD.has(byte), ascii.is_some_and(is_word), "WORD {byte:#x}");
    }
    // A vertical tab ends a run, and so does a space past ASCII.
    for (line, end) in [("abc\u{b}def", 3), ("abc\u{a0}def", 3), ("ab\u{e9}c d", 5)] {
        assert_eq!(notspace(line.as_bytes(), 0), Scan::Match(end), "{line:?}");
    }
    assert_eq!(word("na\u{ef}ve_1 x".as_bytes(), 0), Scan::Match(8));
    // Runs long enough for whole vector steps on either side of a char past
    // ASCII, at every offset into a step.
    for lead in 0..40 {
        let line = format!(
            "{}{}\u{e9}{} tail",
            " ".repeat(lead),
            "a".repeat(45),
            "b".repeat(37)
        );
        let end = lead + 45 + 2 + 37;
        assert_eq!(notspace(line.as_bytes(), lead), Scan::Match(end), "{lead}");
        assert_eq!(word(line.as_bytes(), lead), Scan::Match(end), "{lead}");
    }
}

#[test]
fn a_unicode_digit_defers_and_a_unicode_letter_is_a_word() {
    let arabic_three = "\u{0663}";
    let hay = format!("1{arabic_three}");
    assert_eq!((field("INT").unwrap().scan)(hay.as_bytes(), 0), Scan::Defer);
    let hay = "é12";
    assert_eq!(
        (field("NONNEGINT").unwrap().scan)(hay.as_bytes(), 2),
        Scan::NoMatch
    );
    assert_eq!(field("NOPE").map(|f| f.name), None);
}

fn pieces() -> Vec<&'static str> {
    vec![
        "0",
        "1",
        "2",
        "3",
        "5",
        "6",
        "9",
        "12",
        "60",
        "255",
        "256",
        "2026",
        "-",
        "+",
        ".",
        ",",
        ":",
        "/",
        "T",
        " ",
        "  ",
        "Z",
        "a",
        "e",
        "A",
        "_",
        "x",
        "Jan",
        "June",
        "Jul",
        "Nov",
        "Sep",
        "err",
        "INFO",
        "warn",
        "\"",
        "'",
        "`",
        "\\",
        "\n",
        "\t",
        "%",
        "fe",
        "1a",
        "é",
        "\u{0663}",
        "\u{00a0}",
        // Near-valid tokens, so the structured fields get exercised at their edges.
        "fe80::1",
        "2001:db8::8a2e:370:7334",
        "::1",
        "::ffff:192.168.1.1",
        "1:2:3:4:5:6:7:8",
        "%eth0",
        "%3",
        "::",
        "1::",
        "abcd:",
        "256.1.2.3",
        "host.example.com",
        "a-b.",
        "web01",
        "http",
        "x+y-z.w",
        "10.1.2.3",
        "1.2.3.4567",
        "255.255.255.255",
        "1.2.3.",
        "00:1a:2b:3c:4d:5e",
        "001a.2b3c.4d5e",
        "123e4567-e89b-12d3-a456-426614174000",
        "2026-11-26T11:22:33",
        "2026-11-26 11:22",
        ".456",
        "+11:00",
        "+1100",
        "-0530",
        "Nov  6 08:01:02",
        "26/Nov/2026:11:22:33 +1100",
        "23:59",
        "9:05",
        "\"a\\\"b\"",
        "\\\n",
        "C:",
        "\\",
        "\\\\srv\\share",
        "?",
        "*",
        "?a=b&c=[1]",
        "/var/log",
        "/a(b)",
        "@",
        "a.B$c_1",
        "0x",
        "0x1F",
        "0X",
        "g",
        "user+tag@",
        "x=y:z",
    ]
}

fn ascii_pieces() -> Vec<&'static str> {
    pieces().into_iter().filter(|p| p.is_ascii()).collect()
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(4096))]

    #[test]
    fn every_field_agrees_with_its_regex(
        before in prop::collection::vec(prop::sample::select(pieces()), 0..3),
        body in prop::collection::vec(prop::sample::select(pieces()), 0..14),
    ) {
        let before = before.concat();
        let hay = format!("{before}{}", body.concat());
        agree(&hay, before.len())?;
    }

    #[test]
    fn ascii_input_never_defers(
        before in prop::collection::vec(prop::sample::select(ascii_pieces()), 0..3),
        body in prop::collection::vec(prop::sample::select(ascii_pieces()), 0..14),
    ) {
        let before = before.concat();
        let hay = format!("{before}{}", body.concat());
        prop_assert_eq!(agree(&hay, before.len())?, 0);
    }
}

#[test]
fn validation_is_opt_in_and_steps_away_from_the_regex_on_purpose() {
    let ipv4 = field("IPV4").unwrap();
    assert_eq!(
        (ipv4.scan)(b"192.168.1.256", 0),
        Scan::Match(13),
        "exact to the regex"
    );
    let check = validator("IPV4").unwrap();
    for (text, want) in [
        ("192.168.1.255", true),
        ("192.168.1.256", false),
        ("0.0.0.0", true),
        ("010.1.1.0001", true),
        ("+1.2.3.4", true),
        ("1.2.3.999", false),
        ("1.2..4", false),
        ("1.2.3.", false),
        ("1.2.3.+", false),
        ("1.2.3.-4", false),
        ("1.2.3.4a", false),
        ("1.2.3.\u{663}", false),
    ] {
        let parsed = text.split('.').all(|o| o.parse::<u8>().is_ok());
        assert_eq!(check(text.as_bytes()), want, "{text}");
        assert_eq!(parsed, want, "{text} as str::parse reads it");
    }
    let port = validator("PORT").unwrap();
    for (text, want) in [
        ("65535", true),
        ("65536", false),
        ("0", true),
        ("00443", true),
        ("+80", true),
        ("", false),
        ("+", false),
        ("-1", false),
        ("99999999999", false),
        ("8o", false),
    ] {
        assert_eq!(port(text.as_bytes()), want, "{text}");
        assert_eq!(
            text.parse::<u16>().is_ok(),
            want,
            "{text} as str::parse reads it"
        );
    }
    let ip = validator("IP").unwrap();
    assert!(ip(b"fe80::1"));
    assert!(!ip(b"999.1.1.1"));
    assert!(validator("WORD").is_none());
}

#[test]
fn the_replacement_list_in_docs_matches_the_table() {
    let mut want =
        String::from("| Pattern | Dialect | Replaced by | Tier |\n| --- | --- | --- | --- |\n");
    for f in FIELDS {
        writeln!(want, "| `{0}` | grok | `field(\"{0}\")` | Field |", f.name).unwrap();
    }
    let doc = include_str!("../../docs/replaces.md");
    let table = doc
        .split("<!-- replaces:begin -->\n")
        .nth(1)
        .and_then(|rest| rest.split("<!-- replaces:end -->").next())
        .unwrap_or_default();
    assert_eq!(table, want, "docs/replaces.md disagrees with field::FIELDS");
}