use std::borrow::Cow;
use std::collections::HashMap;
use proptest::prelude::*;
use serde_json::{Map, Number, Value as Json, json};
use super::{Options, Outcome, Program, ProgramSet, Value, ValueProgram};
use crate::record::{Miss, Record, Typed};
fn json_to_cel(json: &Json) -> cel::Value {
match json {
Json::Null => cel::Value::Null,
Json::Bool(b) => cel::Value::Bool(*b),
Json::Number(n) => n.as_i64().map_or_else(
|| {
n.as_u64().map_or_else(
|| cel::Value::Float(n.as_f64().unwrap_or(0.0)),
cel::Value::UInt,
)
},
cel::Value::Int,
),
Json::String(s) => cel::Value::String(s.clone().into()),
Json::Array(a) => cel::Value::List(a.iter().map(json_to_cel).collect::<Vec<_>>().into()),
Json::Object(o) => {
let map: HashMap<cel::objects::Key, cel::Value> = o
.iter()
.map(|(k, v)| (k.clone().into(), json_to_cel(v)))
.collect();
cel::Value::Map(map.into())
}
}
}
#[derive(Debug, Clone, Copy)]
struct Lazy<'a>(crate::record::Json<'a>);
impl<'a> Record<'a> for Lazy<'a> {
type At = &'a str;
fn find<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
self.0.find(path)
}
fn find_below<K: AsRef<str>>(self, at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
self.0.find_below(at, path)
}
fn typed(self, at: &'a str) -> Result<Typed<'a>, Miss> {
self.0.typed(at)
}
fn text(self, at: &'a str) -> Result<Cow<'a, str>, Miss> {
self.0.text(at)
}
}
fn cel_says(text: &str, record: &Json) -> Option<bool> {
let program = cel::Program::compile(text).unwrap_or_else(|e| panic!("cel rejects {text}: {e}"));
let mut ctx = cel::Context::default();
if let Json::Object(roots) = record {
for (k, v) in roots {
ctx.add_variable_from_value(k.clone(), json_to_cel(v));
}
}
match program.execute(&ctx) {
Ok(cel::Value::Bool(b)) => Some(b),
Ok(other) => panic!("{text} gave {other:?}, not a bool"),
Err(_) => None,
}
}
fn agree(text: &str, record: &Json) -> Result<(), TestCaseError> {
let program = Program::compile_with(text, &Options::with_regex())
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let ours = match program.eval(&bytes) {
Outcome::True => Some(true),
Outcome::False => Some(false),
Outcome::Error(_) => None,
};
prop_assert_eq!(ours, cel_says(text, record), "{} on {}", text, record);
prop_assert_eq!(
program.eval_record(Lazy(crate::record::Json::new(&bytes))),
program.eval(&bytes),
"{} read by sonic-rs lookups on {}",
text,
record
);
let pretty =
serde_json::to_vec_pretty(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
prop_assert_eq!(
program.eval(&pretty),
program.eval(&bytes),
"{} on pretty {}",
text,
record
);
Ok(())
}
const PATHS: &[&str] = &["a", "b", "a.x", "a.y", "b.x", "c.x.y"];
fn path() -> impl Strategy<Value = &'static str> {
prop::sample::select(PATHS)
}
fn literal() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
r#""""#,
r#""q""#,
r#""query""#,
r#""answer""#,
r#""Qé""#,
r#""a\nb""#,
r"'q'",
r#"r"q""#,
"0",
"1",
"-1",
"5158",
"9223372036854775807",
"1u",
"18446744073709551615u",
"1.0",
"-0.0",
"0.5",
"5158.0",
"9007199254740992.0",
"1e3",
"true",
"false",
"null",
][..],
)
}
fn ordered_literal() -> impl Strategy<Value = &'static str> {
literal().prop_filter("no ordering on bool or null", |l| {
!matches!(*l, "true" | "false" | "null")
})
}
fn string_arg() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
r#""""#, r#""q""#, r#""que""#, r#""ery""#, r#""é""#, r#""x""#, r#""\n""#,
][..],
)
}
fn leaf() -> impl Strategy<Value = String> {
prop_oneof![
(path(), prop::sample::select(&["x", "y"][..])).prop_map(|(p, k)| format!("has({p}.{k})")),
(path(), prop::sample::select(&["==", "!="][..]), literal())
.prop_map(|(p, op, l)| format!("{p} {op} {l}")),
(
path(),
prop::sample::select(&["<", "<=", ">", ">="][..]),
ordered_literal()
)
.prop_map(|(p, op, l)| format!("{p} {op} {l}")),
(literal(), path()).prop_map(|(l, p)| format!("{l} == {p}")),
(
path(),
prop::sample::select(&["startsWith", "endsWith", "contains"][..]),
string_arg()
)
.prop_map(|(p, m, s)| format!("{p}.{m}({s})")),
(path(), literal(), literal()).prop_map(|(p, l1, l2)| format!("{p} in [{l1}, {l2}]")),
(path(), pattern()).prop_map(|(p, re)| format!("{p}.matches({re})")),
]
}
fn pattern() -> impl Strategy<Value = &'static str> {
prop::sample::select(
&[
r#""""#,
r#""q""#,
r#""^q""#,
r#""y$""#,
r#""^qu.*y$""#,
r#""(?i)QUERY""#,
r#""\\d+""#,
r#""é""#,
r#"".""#,
r#""an|qu""#,
r#""^$""#,
r#""^a\nb$""#,
r#""[a-z]{5}""#,
][..],
)
}
fn expr() -> impl Strategy<Value = String> {
leaf().prop_recursive(3, 12, 3, |inner| {
prop_oneof![
(inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} && {b})")),
(inner.clone(), inner.clone()).prop_map(|(a, b)| format!("({a} || {b})")),
inner.prop_map(|a| format!("!({a})")),
]
})
}
fn scalar() -> impl Strategy<Value = Json> {
prop_oneof![
prop::sample::select(
&[
"", "q", "query", "answer", "Q\u{e9}", "a\nb", "xqueryx", "é"
][..]
)
.prop_map(|s| Json::String(s.to_owned())),
prop::sample::select(&[0_i64, 1, -1, 5158, i64::MAX, i64::MIN, 3][..])
.prop_map(|n| json!(n)),
prop::sample::select(&[9_223_372_036_854_775_808_u64, u64::MAX][..]).prop_map(|n| json!(n)),
prop::sample::select(&[1.0_f64, -0.0, 0.5, 5158.0, 9_007_199_254_740_992.0, 1e3][..])
.prop_map(|f| Number::from_f64(f).map_or(Json::Null, Json::Number)),
any::<bool>().prop_map(Json::Bool),
Just(Json::Null),
prop::collection::vec(prop::sample::select(&["q", "x", "query"][..]), 0..3)
.prop_map(|v| json!(v)),
]
}
fn object(depth: u32) -> BoxedStrategy<Json> {
let value = if depth == 0 {
scalar().boxed()
} else {
prop_oneof![3 => scalar(), 2 => object(depth - 1)].boxed()
};
prop::collection::vec((prop::sample::select(&["x", "y", "q"][..]), value), 0..3)
.prop_map(|kvs| {
Json::Object(
kvs.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect::<Map<_, _>>(),
)
})
.boxed()
}
fn record() -> impl Strategy<Value = Json> {
let root = prop_oneof![2 => scalar(), 3 => object(2)];
prop::collection::vec((prop::sample::select(&["a", "b", "c"][..]), root), 0..4).prop_map(
|kvs| {
Json::Object(
kvs.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect::<Map<_, _>>(),
)
},
)
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn a_lowered_program_gives_what_cel_gives(text in expr(), rec in record()) {
agree(&text, &rec)?;
}
}
#[test]
fn named_cases_agree_with_cel() {
let dns = r#"event.network.direction == "outbound" && event.dns.type == "query""#;
let either = r#"event.dns.type == "query" || event.dns.type == "answer""#;
let neither = r#"!(event.network.direction == "outbound" && event.dns.type == "answer")"#;
let records = [
json!({}),
json!({"event": {}}),
json!({"event": {"network": {"direction": "outbound"}, "dns": {"type": "query"}}}),
json!({"event": {"network": {"direction": "inbound"}, "dns": {"type": "answer"}}}),
json!({"event": {"dns": {"type": "answer"}}}),
json!({"event": null}),
json!({"event": 3}),
json!({"event": {"dns": {"type": 7}}}),
json!({"f": 123}),
json!({"f": "123"}),
json!({"f": null}),
json!({"f": 9_007_199_254_740_993_u64}),
json!({"f": "a\u{0061}"}),
json!({"a": {}}),
json!({"a": {"b": null}}),
json!({"a": []}),
json!({"a": ["x", "q"]}),
json!({"a": {"x": 1}}),
];
let exprs = [
dns,
either,
neither,
r#"f == "123""#,
r#"f != "123""#,
r#"!(f == "x")"#,
r#"!f.startsWith("1")"#,
r#"f.contains("2")"#,
"f == 9007199254740992.0",
"f > 3",
"f >= 1u",
r#"f == "aa""#,
"has(a.b)",
"!has(a.b)",
r#"a.contains("x")"#,
r#"a.contains("q") || f == null"#,
r#"f in ["123", 123]"#,
"true && f == 1",
];
for text in exprs {
for rec in &records {
if let Err(e) = agree(text, rec) {
panic!("{e}");
}
}
}
}
fn cel_value(text: &str, record: &Json) -> Option<cel::Value> {
let program = cel::Program::compile(text).unwrap_or_else(|e| panic!("cel rejects {text}: {e}"));
let mut ctx = cel::Context::default();
if let Json::Object(roots) = record {
for (k, v) in roots {
ctx.add_variable_from_value(k.clone(), json_to_cel(v));
}
}
program.execute(&ctx).ok()
}
fn as_cel(v: &Value<'_>) -> cel::Value {
match v {
Value::Str(s) => cel::Value::String(s.to_string().into()),
Value::Int(n) => cel::Value::Int(*n),
Value::Uint(n) => cel::Value::UInt(*n),
Value::Double(n) => cel::Value::Float(*n),
Value::Bool(b) => cel::Value::Bool(*b),
Value::Null => cel::Value::Null,
Value::Json(text) => json_to_cel(&serde_json::from_str(text).unwrap_or(Json::Null)),
}
}
fn agree_value(text: &str, record: &Json) -> Result<(), TestCaseError> {
let program = ValueProgram::compile_with(text, &Options::with_regex())
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let ours = program.eval(&bytes).ok().map(|v| as_cel(&v));
let lazy = program
.eval_record(Lazy(crate::record::Json::new(&bytes)))
.ok()
.map(|v| as_cel(&v));
prop_assert_eq!(
&lazy,
&ours,
"{} read by sonic-rs lookups on {}",
text,
record
);
let theirs = cel_value(text, record);
if ours != theirs {
let sorted = |v: Option<cel::Value>| match v {
Some(cel::Value::List(items)) => {
let mut items: Vec<String> = items.iter().map(|i| format!("{i:?}")).collect();
items.sort();
Some(items)
}
_ => None,
};
prop_assert!(
sorted(ours.clone()).is_some() && sorted(ours) == sorted(theirs),
"{} on {}",
text,
record
);
}
Ok(())
}
fn value_atom() -> impl Strategy<Value = String> {
prop_oneof![
path().prop_map(str::to_owned),
literal().prop_map(str::to_owned)
]
}
fn value_expr() -> impl Strategy<Value = String> {
prop_oneof![
value_atom(),
(value_atom(), value_atom()).prop_map(|(a, b)| format!("{a} + {b}")),
(expr(), value_atom(), value_atom()).prop_map(|(c, a, b)| format!("{c} ? {a} : {b}")),
(expr(), value_atom(), expr(), value_atom(), value_atom())
.prop_map(|(c1, a, c2, b, d)| format!("{c1} ? {a} : {c2} ? {b} : {d}")),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn a_lowered_value_gives_what_cel_gives(text in value_expr(), rec in record()) {
agree_value(&text, &rec)?;
}
}
#[test]
fn computed_columns_agree_with_cel() {
let exprs = [
r#"risk_score > 80 ? "high" : risk_score > 40 ? "medium" : "low""#,
r#"src_ip.startsWith("10.") || src_ip.startsWith("192.168.")"#,
"bytes_in + bytes_out",
r#"value + "_enriched""#,
r#"risk_score > 90 ? "critical" : "ok""#,
];
let records = [
json!({}),
json!({"risk_score": 95, "src_ip": "10.0.0.1", "bytes_in": 10, "bytes_out": 20, "value": "v"}),
json!({"risk_score": 50.5, "src_ip": "8.8.8.8", "bytes_in": 10, "bytes_out": 2.5, "value": 3}),
json!({"risk_score": "high", "bytes_in": i64::MAX, "bytes_out": 1}),
json!({"bytes_in": [1], "bytes_out": [2, 3]}),
];
for text in exprs {
for rec in &records {
if let Err(e) = agree_value(text, rec) {
panic!("{e}");
}
}
}
}
fn agree_set(texts: &[String], record: &Json) -> Result<(), TestCaseError> {
let options = Options::with_regex();
let set =
ProgramSet::compile(texts, &options).map_err(|r| TestCaseError::fail(r.to_string()))?;
prop_assert!(set.refused().is_empty(), "{:?}", set.refused());
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let alone: Vec<usize> = texts
.iter()
.enumerate()
.filter(|(_, t)| {
Program::compile_with(t, &options).is_ok_and(|p| p.eval(&bytes) == Outcome::True)
})
.map(|(i, _)| i)
.collect();
let (mut got, mut lazy) = (Vec::new(), Vec::new());
set.matching(&bytes, &mut got);
set.matching_record(Lazy(crate::record::Json::new(&bytes)), &mut lazy);
prop_assert_eq!(
&got,
&lazy,
"{:?} read by sonic-rs lookups on {}",
texts,
record
);
prop_assert_eq!(got, alone, "{:?} on {}", texts, record);
Ok(())
}
fn equals() -> impl Strategy<Value = String> {
(
path(),
prop::sample::select(&[r#""q""#, r#""query""#, r#""answer""#, r#""""#][..]),
)
.prop_map(|(p, l)| format!("{p} == {l}"))
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(1024))]
#[test]
fn a_set_matches_what_each_filter_matches_alone(
texts in prop::collection::vec(prop_oneof![3 => equals(), 1 => expr()], 1..30),
rec in record(),
) {
agree_set(&texts, &rec)?;
}
}
#[cfg(feature = "parse")]
fn flatten(record: &Json) -> crate::parse::Fields<'static> {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
fn put(name: &str, value: &Json, out: &mut Fields<'static>) {
let (bytes, hint) = match value {
Json::Object(map) if !map.is_empty() => {
for (k, v) in map {
put(&format!("{name}.{k}"), v, out);
}
return;
}
Json::String(s) => (s.clone().into_bytes(), Hint::Text),
Json::Number(n) if n.is_f64() => (n.to_string().into_bytes(), Hint::Float),
Json::Number(n) => (n.to_string().into_bytes(), Hint::Int),
Json::Bool(b) => (b.to_string().into_bytes(), Hint::Bool),
other => (other.to_string().into_bytes(), Hint::Json),
};
out.field(name, FieldValue::owned(bytes, hint));
}
let mut out = Fields::new();
if let Json::Object(map) = record {
for (k, v) in map {
put(k, v, &mut out);
}
}
out
}
#[cfg(feature = "parse")]
fn agree_on_fields(text: &str, value: &str, record: &Json) -> Result<(), TestCaseError> {
let options = Options::with_regex();
let bytes = serde_json::to_vec(record).map_err(|e| TestCaseError::fail(e.to_string()))?;
let fields = flatten(record);
let program = Program::compile_with(text, &options)
.map_err(|r| TestCaseError::fail(format!("{text}: {r}")))?;
prop_assert_eq!(
program.eval_record(&fields),
program.eval(&bytes),
"{} on {:?}",
text,
fields.as_slice()
);
let set =
ProgramSet::compile(&[text], &options).map_err(|r| TestCaseError::fail(r.to_string()))?;
let (mut ours, mut theirs) = (Vec::new(), Vec::new());
set.matching_record(&fields, &mut ours);
set.matching(&bytes, &mut theirs);
prop_assert_eq!(ours, theirs, "set of {} on {:?}", text, fields.as_slice());
let program = ValueProgram::compile_with(value, &options)
.map_err(|r| TestCaseError::fail(format!("{value}: {r}")))?;
let ours = program.eval_record(&fields).map(|v| as_cel(&v));
let theirs = program.eval(&bytes).map(|v| as_cel(&v));
prop_assert_eq!(ours, theirs, "{} on {:?}", value, fields.as_slice());
Ok(())
}
#[cfg(feature = "parse")]
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn fields_give_what_their_json_gives(
text in expr(),
value in value_expr(),
rec in record(),
) {
agree_on_fields(&text, &value, &rec)?;
}
}
#[cfg(feature = "parse")]
fn nest(fields: &crate::parse::Fields<'_>) -> Json {
use crate::parse::Hint;
let mut root = Map::new();
for (name, value) in fields.as_slice() {
let text = String::from_utf8(value.bytes.to_vec()).unwrap_or_default();
let leaf = match value.hint {
Hint::Json => serde_json::from_str(&text).unwrap_or(Json::Null),
Hint::Int | Hint::Float => serde_json::from_str::<Number>(&text)
.map_or_else(|_| Json::String(text.clone()), Json::Number),
Hint::Bool if text == "true" || text == "false" => Json::Bool(text == "true"),
_ => Json::String(text),
};
let keys: Vec<&str> = name.split('.').collect();
let Some((last, parents)) = keys.split_last() else {
continue;
};
let mut at = &mut root;
for key in parents {
let next = at
.entry((*key).to_owned())
.or_insert_with(|| Json::Object(Map::new()));
let Json::Object(map) = next else {
panic!("{name} runs below a value");
};
at = map;
}
match at.get_mut(*last) {
Some(Json::Array(items)) => items.push(leaf),
Some(first) => *first = Json::Array(vec![first.take(), leaf]),
None => {
at.insert((*last).to_owned(), leaf);
}
}
}
Json::Object(root)
}
#[cfg(all(feature = "parse-syslog", feature = "parse-cef"))]
#[test]
fn a_syslog_cef_chain_reads_as_its_json_record() {
use crate::format;
use crate::parse::{Fields, ParsePlan, Parsers};
use super::ErrorKind;
let mut registry = Parsers::new();
format::register_stock(&mut registry).expect("stock parsers register");
let plan = ParsePlan::chain("syslog > cef", ®istry).expect("the chain compiles");
let line =
b"<134>Oct 30 16:05:55 fw01 CEF:0|Acme|Gate|1.0|100|login ok|5|src=10.0.0.1 suser=bob";
let mut fields = Fields::new();
plan.parse_stateless(line, &mut fields);
let record = nest(&fields);
assert_eq!(record["cef"]["src"], json!("10.0.0.1"), "{record}");
assert_eq!(record["severity"], json!(6), "{record}");
let bytes = serde_json::to_vec(&record).expect("serialises");
let error = Outcome::Error;
let cases: &[(&str, Outcome)] = &[
(r#"cef.name == "login ok""#, Outcome::True),
(
r#"cef.src.startsWith("10.") && hostname == "fw01""#,
Outcome::True,
),
(r#"cef.suser in ["alice", "bob"]"#, Outcome::True),
(
r#"cef.device_vendor == "Acme" || cef.dst == "x""#,
Outcome::True,
),
(r#"cef.src.matches("^10\\.0\\.")"#, Outcome::True),
("severity == 6 && pri > 100", Outcome::True),
(r#"cef.severity == "5""#, Outcome::True),
("cef.severity == 5", Outcome::False),
(r#"cef == "x""#, Outcome::False),
("has(cef.suser) && !has(cef.dst)", Outcome::True),
("has(cef.dst)", Outcome::False),
("cef.severity > 3", error(ErrorKind::TypeMismatch)),
(r#"cef.contains("x")"#, error(ErrorKind::TypeMismatch)),
("has(cef.name.x)", error(ErrorKind::TypeMismatch)),
(r#"cef.dst == "x""#, error(ErrorKind::MissingField)),
("cef.name.x == 1", error(ErrorKind::MissingField)),
(r#"leef.src == "x""#, error(ErrorKind::MissingRoot)),
(r#"!has(cef.dst) || cef.dst == "x""#, Outcome::True),
];
let options = Options::with_regex();
for &(text, want) in cases {
let program = Program::compile_with(text, &options).expect(text);
assert_eq!(program.eval_record(&fields), want, "{text} on {record}");
assert_eq!(program.eval(&bytes), want, "{text} on the JSON {record}");
assert_eq!(
cel_says(text, &record),
want_cel(want),
"cel: {text} on {record}"
);
}
let presence = Options {
root_presence: true,
..Options::default()
};
for (text, want) in [("has(cef)", true), ("has(leef)", false)] {
let program = Program::compile_with(text, &presence).expect(text);
assert_eq!(program.matches_record(&fields), want, "{text}");
assert_eq!(program.matches(&bytes), want, "{text} on the JSON");
}
let texts: Vec<&str> = cases.iter().map(|(t, _)| *t).collect();
let set = ProgramSet::compile(&texts, &options).expect("the set compiles");
let (mut ours, mut theirs) = (Vec::new(), Vec::new());
set.matching_record(&fields, &mut ours);
set.matching(&bytes, &mut theirs);
assert_eq!(ours, theirs);
for value in [
r#"cef.src + ":" + cef.suser"#,
r#"severity > 3 ? "high" : "low""#,
"cef",
"pri + facility",
] {
let program = ValueProgram::compile(value).expect(value);
let ours = program.eval_record(&fields).map(|v| as_cel(&v));
assert_eq!(ours, program.eval(&bytes).map(|v| as_cel(&v)), "{value}");
assert_eq!(ours.ok(), cel_value(value, &record), "cel: {value}");
}
}
#[test]
fn a_raw_line_reads_as_its_message_field() {
use crate::record::Line;
use super::ErrorKind;
let line = "login denied for bob from 10.0.0.1";
let record = json!({ "message": line });
let bytes = serde_json::to_vec(&record).expect("serialises");
let error = Outcome::Error;
let cases: &[(&str, Outcome)] = &[
(r#"message.contains("denied")"#, Outcome::True),
(
r#"message.startsWith("login") && !message.endsWith("x")"#,
Outcome::True,
),
(r#"message.matches("from [0-9.]+$")"#, Outcome::True),
(r#"message == "login""#, Outcome::False),
("message > 3", error(ErrorKind::TypeMismatch)),
("has(message.x)", error(ErrorKind::TypeMismatch)),
(r#"msg.contains("denied")"#, error(ErrorKind::MissingRoot)),
(r#"message.x == "y""#, error(ErrorKind::MissingField)),
(r#"msg == "x" || message.contains("bob")"#, Outcome::True),
];
let options = Options::with_regex();
for &(text, want) in cases {
let program = Program::compile_with(text, &options).expect(text);
assert_eq!(
program.eval_record(Line::new(line.as_bytes())),
want,
"{text}"
);
assert_eq!(program.eval(&bytes), want, "{text} on the JSON");
assert_eq!(cel_says(text, &record), want_cel(want), "cel: {text}");
let renamed = Program::compile_with(&text.replace("message", "raw"), &options).expect(text);
assert_eq!(
renamed.eval_record(Line::named(line.as_bytes(), "raw")),
want,
"{text} on a line named raw"
);
}
let presence = Options {
root_presence: true,
..Options::default()
};
for (text, want) in [("has(message)", true), ("has(msg)", false)] {
let program = Program::compile_with(text, &presence).expect(text);
assert_eq!(
program.matches_record(Line::new(line.as_bytes())),
want,
"{text}"
);
assert_eq!(program.matches(&bytes), want, "{text} on the JSON");
}
let bad = Line::new(b"bad \xff byte");
let program = Program::compile(r#"message.contains("bad")"#).expect("compiles");
assert_eq!(program.eval_record(bad), error(ErrorKind::Malformed));
let value = ValueProgram::compile(r#"message + "!""#).expect("compiles");
assert_eq!(
value.eval_record(Line::new(b"up")),
Ok(Value::Str("up!".into()))
);
}
fn want_cel(outcome: Outcome) -> Option<bool> {
match outcome {
Outcome::True => Some(true),
Outcome::False => Some(false),
Outcome::Error(_) => None,
}
}