use std::borrow::Cow;
use super::{Json, Line, Miss, Record, Typed};
fn read<'a, R: Record<'a>>(record: R, path: &str) -> Result<(Typed<'a>, Cow<'a, str>), Miss> {
let keys: Vec<&str> = path.split('/').collect();
let at = record.find(&keys)?;
Ok((record.typed(at)?, record.text(at)?))
}
fn string(s: &str) -> Typed<'_> {
Typed::Str(Cow::Borrowed(s))
}
#[test]
fn json_reads_each_type_and_names_each_miss() {
let json = Json::new(
br#" {"s":"a\"b","n":-3,"u":18446744073709551615,"d":1.50,"t":true,"z":null,
"l":[1,2],"m":{"k":{"x":"v"}}}"#,
);
let cases: &[(&str, Result<(Typed<'_>, &str), Miss>)] = &[
("s", Ok((Typed::Str("a\"b".into()), "a\"b"))),
("n", Ok((Typed::Int(-3), "-3"))),
("u", Ok((Typed::Uint(u64::MAX), "18446744073709551615"))),
("d", Ok((Typed::Double(1.5), "1.50"))),
("t", Ok((Typed::Bool(true), "true"))),
("z", Ok((Typed::Null, "null"))),
("l", Ok((Typed::List, "[1,2]"))),
("m/k/x", Ok((string("v"), "v"))),
("m/k", Ok((Typed::Map, r#"{"x":"v"}"#))),
("nope", Err(Miss::MissingRoot)),
("m/nope", Err(Miss::MissingField)),
("m/k/nope/deeper", Err(Miss::MissingField)),
("s/x", Err(Miss::WrongParentType)),
("l/0", Err(Miss::WrongParentType)),
("", Err(Miss::MissingRoot)),
];
for (path, want) in cases {
let got = read(json, path);
let want = want.clone().map(|(t, text)| (t, Cow::Borrowed(text)));
assert_eq!(got, want, "{path}");
}
for bytes in [&b"[1]"[..], &b""[..], &br#""x""#[..], &b" 7"[..]] {
assert_eq!(
Json::new(bytes).find(&["a"]),
Err(Miss::MissingRoot),
"{bytes:?}"
);
}
for bytes in [&br#"{"bad":}"#[..], &br#"{"bad":"\x"}"#[..]] {
assert_eq!(
read(Json::new(bytes), "bad"),
Err(Miss::Malformed),
"{bytes:?}"
);
}
let unread: &[(&[u8], &str, Result<(), Miss>)] = &[
(br#"{"a":}"#, "b", Err(Miss::MissingRoot)),
(br#"{"a":"b"}"#, "b", Err(Miss::MissingRoot)),
(br#"{"a":"b":}"#, "b", Err(Miss::Malformed)),
(br#"{"a":"\u0041",}"#, "b", Err(Miss::Malformed)),
(br#"{"\u0062":1}"#, "b", Ok(())),
(br#"{"b":1}"#, "b", Ok(())),
(br#"{"a\/b":1}"#, "a/b", Ok(())),
(br#"{"a\"b":1}"#, "a\"b", Ok(())),
(br#"{"":1}"#, "", Ok(())),
(br#"{"x":1}"#, "", Err(Miss::MissingRoot)),
];
for (bytes, key, want) in unread {
let got = Json::new(bytes).find(&[key]).map(|_| ());
assert_eq!(got, *want, "{key} in {}", String::from_utf8_lossy(bytes));
}
let m = json.find(&["m"]).expect("m is there");
let x = json.find_below(m, &["k", "x"]).expect("below m");
assert_eq!(json.typed(x), Ok(string("v")));
assert_eq!(json.find_below(m, &[] as &[&str]), Ok(m));
}
#[test]
fn a_line_is_one_string_field() {
let line = Line::new(b"link up on port 3");
let named = Line::named(b"x", "raw");
let cases: &[(Line<'_>, &str, Result<(Typed<'_>, &str), Miss>)] = &[
(
line,
"message",
Ok((string("link up on port 3"), "link up on port 3")),
),
(line, "msg", Err(Miss::MissingRoot)),
(line, "message/x", Err(Miss::WrongParentType)),
(line, "", Err(Miss::MissingRoot)),
(named, "raw", Ok((string("x"), "x"))),
(named, "message", Err(Miss::MissingRoot)),
(Line::new(b"\xff"), "message", Err(Miss::Malformed)),
(Line::new(b""), "message", Ok((string(""), ""))),
];
for (record, path, want) in cases {
let want = want.clone().map(|(t, text)| (t, Cow::Borrowed(text)));
assert_eq!(read(*record, path), want, "{path}");
}
}
#[cfg(feature = "parse")]
#[test]
fn fields_read_as_a_nested_record_by_dotted_name() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
let mut fields = Fields::new();
let rows: &[(&str, &[u8], Hint)] = &[
("host", b"fw01", Hint::Text),
("syslog.pri", b"134", Hint::Int),
("syslog.big", b"18446744073709551615", Hint::Int),
("syslog.ratio", b"0.5", Hint::Float),
("syslog.ok", b"true", Hint::Bool),
("syslog.odd", b"yes", Hint::Bool),
("syslog.port", b"n/a", Hint::Int),
("cef.src", b"10.0.0.1", Hint::Ip),
("cef.ext", br#"{"a":{"b":7},"s":"q\"x"}"#, Hint::Json),
("tag", b"a", Hint::Text),
("tag", b"b", Hint::Text),
("bad", b"\xff", Hint::Text),
("a.b.c", b"deep", Hint::Text),
("a.b.d", b"1", Hint::Int),
(r#"["a.b"]"#, b"one key", Hint::Text),
(r#"labels["app.kind"]"#, b"web", Hint::Text),
(r#"labels["x.y"].z"#, b"2", Hint::Int),
("labels[0]", b"plain", Hint::Text),
];
for (name, bytes, hint) in rows {
fields.field(name, FieldValue::borrowed(bytes, *hint));
}
let record = &fields;
let cases: &[(&str, Result<(Typed<'_>, &str), Miss>)] = &[
("a.b", Ok((string("one key"), "one key"))),
("labels/app.kind", Ok((string("web"), "web"))),
("labels/x.y/z", Ok((Typed::Int(2), "2"))),
(
"labels",
Ok((Typed::Map, r#"{"app.kind":"web","x.y":{"z":2}}"#)),
),
("labels[0]", Ok((string("plain"), "plain"))),
("labels/app", Err(Miss::MissingField)),
("labels/x/y", Err(Miss::MissingField)),
("a.b/c", Err(Miss::WrongParentType)),
("host", Ok((string("fw01"), "fw01"))),
("syslog/pri", Ok((Typed::Int(134), "134"))),
(
"syslog/big",
Ok((Typed::Uint(u64::MAX), "18446744073709551615")),
),
("syslog/ratio", Ok((Typed::Double(0.5), "0.5"))),
("syslog/ok", Ok((Typed::Bool(true), "true"))),
("syslog/odd", Ok((string("yes"), "yes"))),
("syslog/port", Ok((string("n/a"), "n/a"))),
("cef/src", Ok((string("10.0.0.1"), "10.0.0.1"))),
("cef/ext/a/b", Ok((Typed::Int(7), "7"))),
("cef/ext/s", Ok((Typed::Str("q\"x".into()), "q\"x"))),
("cef/ext/a", Ok((Typed::Map, r#"{"b":7}"#))),
("tag", Ok((Typed::List, r#"["a","b"]"#))),
("a", Ok((Typed::Map, r#"{"b":{"c":"deep","d":1}}"#))),
("a/b/c", Ok((string("deep"), "deep"))),
("nope", Err(Miss::MissingRoot)),
("syslog/nope", Err(Miss::MissingField)),
("a/b/nope", Err(Miss::MissingField)),
("cef/ext/nope", Err(Miss::MissingField)),
("host/x", Err(Miss::WrongParentType)),
("tag/x", Err(Miss::WrongParentType)),
("cef/ext/a/b/c", Err(Miss::WrongParentType)),
("syslog.pri", Err(Miss::MissingRoot)),
("bad", Err(Miss::Malformed)),
("", Err(Miss::MissingRoot)),
];
for (path, want) in cases {
let want = want.clone().map(|(t, text)| (t, Cow::Borrowed(text)));
assert_eq!(read(record, path), want, "{path}");
}
assert_eq!(record.find(&["a", "b.c"]), Err(Miss::MissingField));
let a = record.find(&["a"]).expect("a is there");
let b = record.find_below(a, &["b"]).expect("a.b is there");
let d = record.find_below(b, &["d"]).expect("a.b.d is there");
assert_eq!(record.typed(d), Ok(Typed::Int(1)));
assert_eq!(record.find_below(b, &["nope"]), Err(Miss::MissingField));
assert_eq!((&Fields::new()).find(&["x"]).err(), Some(Miss::MissingRoot));
}
fn both_readings<'a, R: Record<'a>>(
record: R,
path: &str,
) -> (Result<Typed<'a>, Miss>, Result<Typed<'a>, Miss>) {
let keys: Vec<&str> = path.split('/').collect();
let at = record.find(&keys).expect("the path is there");
(record.typed(at), record.typed_exact(at))
}
#[test]
fn json_rounds_a_wide_integer_under_typed_and_keeps_its_text_under_typed_exact() {
let json = Json::new(
br#"{"i":-9223372036854775808,"u":18446744073709551615,"past":18446744073709551616,
"low":-9223372036854775809,"f":1.50,"huge":1e999,"s":"18446744073709551616",
"t":true,"z":null,"l":[1]}"#,
);
let wide = 18_446_744_073_709_551_616.0;
let cases: &[(&str, Typed<'_>, Typed<'_>)] = &[
("i", Typed::Int(i64::MIN), Typed::Int(i64::MIN)),
("u", Typed::Uint(u64::MAX), Typed::Uint(u64::MAX)),
("past", Typed::Double(wide), string("18446744073709551616")),
(
"low",
Typed::Double(-9_223_372_036_854_775_808.0),
string("-9223372036854775809"),
),
("f", Typed::Double(1.5), Typed::Double(1.5)),
(
"s",
string("18446744073709551616"),
string("18446744073709551616"),
),
("t", Typed::Bool(true), Typed::Bool(true)),
("z", Typed::Null, Typed::Null),
("l", Typed::List, Typed::List),
];
for (path, cel, exact) in cases {
assert_eq!(
both_readings(json, path),
(Ok(cel.clone()), Ok(exact.clone())),
"{path}"
);
}
assert_eq!(
both_readings(json, "huge"),
(Err(Miss::Malformed), Ok(string("1e999")))
);
}
#[test]
fn a_source_with_no_numbers_has_one_reading() {
let line = Line::new(b"18446744073709551616");
let (cel, exact) = both_readings(line, "message");
assert_eq!(cel, Ok(string("18446744073709551616")));
assert_eq!(cel, exact);
}
#[cfg(feature = "parse")]
#[test]
fn a_field_reads_under_its_hint_for_typed_exact_and_by_spelling_for_typed() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
let mut fields = Fields::new();
let rows: &[(&str, &[u8], Hint)] = &[
("past", b"18446744073709551616", Hint::Int),
("u", b"18446744073709551615", Hint::Int),
("spelled", b"1e5", Hint::Int),
("whole", b"3", Hint::Float),
("fraction", b"0.5", Hint::Float),
("inf", b"inf", Hint::Float),
("text", b"007", Hint::Text),
("json", b"18446744073709551616", Hint::Json),
("doc", br#"{"n":18446744073709551616}"#, Hint::Json),
];
for (name, bytes, hint) in rows {
fields.field(name, FieldValue::borrowed(bytes, *hint));
}
let record = &fields;
let wide = 18_446_744_073_709_551_616.0;
let cases: &[(&str, Typed<'_>, Typed<'_>)] = &[
("past", Typed::Double(wide), string("18446744073709551616")),
("u", Typed::Uint(u64::MAX), Typed::Uint(u64::MAX)),
("spelled", Typed::Double(100_000.0), string("1e5")),
("whole", Typed::Int(3), Typed::Double(3.0)),
("fraction", Typed::Double(0.5), Typed::Double(0.5)),
("inf", string("inf"), string("inf")),
("text", string("007"), string("007")),
("json", Typed::Double(wide), string("18446744073709551616")),
("doc/n", Typed::Double(wide), string("18446744073709551616")),
];
for (path, cel, exact) in cases {
assert_eq!(
both_readings(record, path),
(Ok(cel.clone()), Ok(exact.clone())),
"{path}"
);
}
}
#[cfg(feature = "parse")]
#[test]
fn an_objects_text_keeps_every_digit_of_an_int_field() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
let rows: &[(&[u8], Hint, &str)] = &[
(b"18446744073709551615", Hint::Int, "18446744073709551615"),
(b"18446744073709551616", Hint::Int, "18446744073709551616"),
(
b"+000018446744073709551617",
Hint::Int,
"18446744073709551617",
),
(b"-9223372036854775808", Hint::Int, "-9223372036854775808"),
(b"-9223372036854775809", Hint::Int, "-9223372036854775809"),
(b"-0", Hint::Int, "0"),
(b"007", Hint::Int, "7"),
(
b"99999999999999999999999999999999999999999",
Hint::Int,
"99999999999999999999999999999999999999999",
),
(
b"18446744073709551616",
Hint::Float,
"1.8446744073709552e+19",
),
(b"1.50", Hint::Float, "1.5"),
];
for (bytes, hint, want) in rows {
let mut fields = Fields::new();
fields.field("a.b", FieldValue::borrowed(bytes, *hint));
let record = &fields;
let at = record.find(&["a"]).expect("a is there");
assert_eq!(
record.text(at).as_deref(),
Ok(format!(r#"{{"b":{want}}}"#).as_str()),
"{}",
String::from_utf8_lossy(bytes)
);
}
}
#[cfg(feature = "parse")]
#[test]
fn a_name_is_read_before_longer_names_below_it() {
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
let mut fields = Fields::new();
fields.field("a.b", FieldValue::borrowed(b"below", Hint::Text));
fields.field("a", FieldValue::borrowed(b"top", Hint::Text));
let record = &fields;
assert_eq!(read(record, "a").map(|(t, _)| t), Ok(string("top")));
assert_eq!(read(record, "a/b").map(|(t, _)| t), Ok(string("below")));
}
fn walked<'a, R: super::Walk<'a>>(
record: R,
) -> Result<Vec<(usize, Option<String>, super::Kind, String)>, Miss> {
let mut nodes = Vec::new();
record.walk(|n| nodes.push(n))?;
nodes
.into_iter()
.map(|n| {
let text = String::from_utf8_lossy(&record.bytes(n.at)?).into_owned();
Ok((n.depth, n.key.map(Cow::into_owned), n.kind, text))
})
.collect()
}
#[test]
fn a_json_walk_gives_every_value_in_document_order() {
use super::Kind::{Bool, List, Map, Null, Number, Str};
let node = |depth, key: Option<&str>, kind, text: &str| {
(depth, key.map(str::to_owned), kind, text.to_owned())
};
let cases: &[(&[u8], Vec<_>)] = &[
(
br#" {"a":-1.5e3,"b":{"c":"x\"y","d":[true,null]},"e":[],"fg":{}} "#,
vec![
node(0, Some("a"), Number, "-1.5e3"),
node(0, Some("b"), Map, r#"{"c":"x\"y","d":[true,null]}"#),
node(1, Some("c"), Str, "x\"y"),
node(1, Some("d"), List, "[true,null]"),
node(2, None, Bool, "true"),
node(2, None, Null, "null"),
node(0, Some("e"), List, "[]"),
node(0, Some("fg"), Map, "{}"),
],
),
(
br#"[1, {"k" : 0}]"#,
vec![
node(0, None, List, r#"[1, {"k" : 0}]"#),
node(1, None, Number, "1"),
node(1, None, Map, r#"{"k" : 0}"#),
node(2, Some("k"), Number, "0"),
],
),
(b"\t7\n", vec![node(0, None, Number, "7")]),
(br#""s""#, vec![node(0, None, Str, "s")]),
(b"{}", vec![]),
];
for (bytes, want) in cases {
assert_eq!(walked(Json::new(bytes)).as_ref(), Ok(want), "{bytes:?}");
}
let malformed: &[&[u8]] = &[
b"",
b" ",
br#"{"a":}"#,
br#"{"a":1,}"#,
b"[1,]",
b"[,1]",
b"[1 2]",
br#"{"a" 1}"#,
b"{1:2}",
br#"{"a":1}}"#,
br#"{"a":1} x"#,
b"[",
b"01",
b"1.",
b"1e",
b"-",
b"+1",
b"tru",
b"nul",
br#""\x""#,
br#""\u12""#,
b"\"tab\there\"",
br#""open"#,
b"\xff",
br#"{"\q":1}"#,
];
for bytes in malformed {
let mut calls = 0;
let got = super::Walk::walk(Json::new(bytes), |_| calls += 1);
assert_eq!((got, calls), (Err(Miss::Malformed), 0), "{bytes:?}");
}
}
#[cfg(feature = "scrub")]
type RawNodes<'a> = Vec<(usize, Option<String>, super::Kind, &'a str)>;
#[cfg(feature = "scrub")]
fn walked_raw(bytes: &[u8]) -> (Result<RawNodes<'_>, Miss>, Result<RawNodes<'_>, Miss>) {
use super::Kind::{List, Map};
use super::Walked;
let mut two = Vec::new();
let two_got = super::Walk::walk(Json::new(bytes), |n| {
two.push((n.depth, n.key.map(Cow::into_owned), n.kind, n.at));
});
let (mut one, mut open) = (Vec::new(), Vec::new());
let one_got =
Json::new(bytes).walk_once_in(&mut super::WalkBufs::default(), |step| match step {
Walked::Value(n) => {
if let List | Map = n.kind {
open.push(one.len());
}
one.push((n.depth, n.key.map(Cow::into_owned), n.kind, n.at));
}
Walked::Closed(at) => {
if let Some(i) = open.pop() {
one[i].3 = at;
}
}
});
(two_got.map(|()| two), one_got.map(|()| one))
}
#[cfg(feature = "scrub")]
#[test]
fn a_json_walk_in_one_pass_matches_two() {
let rows: &[&[u8]] = &[
br#" {"a":-1.5e3,"b":{"c":"x\"y","d":[true,null]},"e":[],"fg":{}} "#,
br#"[1, {"k" : 0}, [[], [{}]]]"#,
br#"{"k\u00e9y":"a\nb","long":"0123456789abcdef0123456789","n":{"m":{"o":[1]}}}"#,
b"\t7\n",
br#""s""#,
b"{}",
b"[]",
b"",
br#"{"a":1,}"#,
br#"{"a":[1,{"b":"\q"}]}"#,
br#"{"a":"open"#,
b"\"tab\there\"",
br#"{"a":1}}"#,
b"[1 2]",
b"\xff",
];
for bytes in rows {
let (two, one) = walked_raw(bytes);
assert_eq!(one, two, "{:?}", String::from_utf8_lossy(bytes));
}
}
#[test]
fn a_json_record_is_rebuilt_with_strings_spliced_in() {
let bytes = br#"{"a": 1, "b": {"c": [2, "x"]}, "d": "\u00e9"}"#;
let json = Json::new(bytes);
let mut ats = Vec::new();
super::Walk::walk(json, |n| ats.push(n.at)).expect("walks");
let mut out = Vec::new();
let edits = [(ats[0], &b"T\"1"[..]), (ats[2], b"L"), (ats[5], b"\xffd")];
json.splice_strings(&edits, &mut out).expect("splices");
let want = r#"{"a": "T\"1", "b": {"c": "L"}, "d": "?d"}"#.replace('?', "\u{fffd}");
assert_eq!(String::from_utf8(out).expect("utf-8"), want);
let mut out = b"kept".to_vec();
let backwards = [(ats[5], &b""[..]), (ats[0], b"")];
assert_eq!(
json.splice_strings(&backwards, &mut out),
Err(Miss::Malformed)
);
let foreign = [("elsewhere", &b""[..])];
assert_eq!(
json.splice_strings(&foreign, &mut out),
Err(Miss::Malformed)
);
assert_eq!(out, b"kept");
}
#[test]
fn a_line_walks_as_its_one_field() {
use super::Kind::Str;
let want = vec![(0, Some("raw".to_owned()), Str, "\u{fffd}x".to_owned())];
assert_eq!(walked(Line::named(b"\xffx", "raw")), Ok(want));
}
#[cfg(feature = "parse")]
#[test]
fn a_fields_walk_reaches_every_field() {
use super::Kind::{List, Map, Number, Str};
use crate::parse::{FieldSink, FieldValue, Fields, Hint};
let mut fields = Fields::new();
let rows: &[(&str, &[u8], Hint)] = &[
("host", b"fw01", Hint::Text),
("syslog.pri", b"134", Hint::Int),
("tag", b"a", Hint::Text),
("tag", b"b", Hint::Text),
("cef.ext", br#" {"a":{"b":7}} "#, Hint::Json),
("a.b", b"below", Hint::Text),
("a", b"top", Hint::Text),
("j", b"{", Hint::Json),
("port", b"n/a", Hint::Int),
("x..y", b"z", Hint::Text),
(r#"k["p.q"]"#, b"v", Hint::Text),
("bad", b"\xff", Hint::Text),
];
for (name, bytes, hint) in rows {
fields.field(name, FieldValue::borrowed(bytes, *hint));
}
let node =
|depth, key: &str, kind, text: &str| (depth, Some(key.to_owned()), kind, text.to_owned());
let item = |text: &str| (1, None, Str, text.to_owned());
let want = vec![
node(0, "host", Str, "fw01"),
node(0, "syslog", Map, r#"{"pri":134}"#),
node(1, "pri", Number, "134"),
node(0, "tag", List, r#"["a","b"]"#),
item("a"),
item("b"),
node(0, "cef", Map, r#"{"ext": {"a":{"b":7}} }"#),
node(1, "ext", Map, r#"{"a":{"b":7}}"#),
node(2, "a", Map, r#"{"b":7}"#),
node(3, "b", Number, "7"),
node(0, "a", Str, "top"),
node(0, "a", Map, r#"{"b":"below"}"#),
node(1, "b", Str, "below"),
node(0, "j", Str, "{"),
node(0, "port", Str, "n/a"),
node(0, "x", Map, r#"{"":{"y":"z"}}"#),
node(1, "", Map, r#"{"y":"z"}"#),
node(2, "y", Str, "z"),
node(0, "k", Map, r#"{"p.q":"v"}"#),
node(1, "p.q", Str, "v"),
node(0, "bad", Str, "\u{fffd}"),
];
assert_eq!(walked(&fields), Ok(want));
assert!(!super::Walk::read_whole(&fields));
fields.as_mut_slice()[7].1 = FieldValue::borrowed(b"{}", Hint::Json);
assert!(super::Walk::read_whole(&fields));
let mut deep = Fields::new();
deep.field(&"a.".repeat(65), FieldValue::borrowed(b"x", Hint::Text));
assert_eq!(walked(&deep), Err(Miss::Malformed));
}
#[cfg(feature = "parse-ndjson")]
fn ndjson(record: &[u8]) -> crate::parse::Fields<'_> {
use crate::format::ndjson::Ndjson;
use crate::parse::{Fields, Parsed, Parser};
let mut fields = Fields::new();
assert!(matches!(
Ndjson::new().parse(record, &mut fields),
Ok(Parsed::Done)
));
fields
}
#[cfg(feature = "parse-ndjson")]
#[test]
fn a_dotted_key_and_a_nested_key_read_back_apart() {
let record = br#"{"a.b":1,"a":{"b":2},"labels":{"app.kind":"web","x[0]":"i"},"q\"t":3}"#;
let fields = ndjson(record);
let names: Vec<&str> = fields.as_slice().iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(
names,
[
r#"["a.b"]"#,
"a.b",
r#"labels["app.kind"]"#,
r#"labels["x[0]"]"#,
r#"["q\"t"]"#,
]
);
let fields = &fields;
let cases: &[(&[&str], &str)] = &[
(&["a.b"], "1"),
(&["a", "b"], "2"),
(&["labels", "app.kind"], "web"),
(&["labels", "x[0]"], "i"),
(&["q\"t"], "3"),
];
for &(path, want) in cases {
let at = fields.find(path);
assert_eq!(
at.and_then(|at| fields.text(at)).as_deref(),
Ok(want),
"{path:?}"
);
}
assert_eq!(fields.find(&["a", "b.c"]), Err(Miss::MissingField));
#[cfg(feature = "expr")]
{
use crate::expr::{Outcome, Program};
let rules = [
("has(a.b) && a.b == 2", Outcome::True),
(r#"a["b"] == 2"#, Outcome::True),
(r#"labels["app.kind"] == "web""#, Outcome::True),
(r"has(labels.app)", Outcome::False),
];
for (rule, want) in rules {
let program = Program::compile(rule).expect(rule);
assert_eq!(program.eval_record(fields), want, "{rule}");
assert_eq!(program.eval(record), want, "{rule} on the JSON");
}
}
}
#[cfg(feature = "parse-ndjson")]
mod ndjson_round_trip {
use std::collections::BTreeMap;
use proptest::prelude::*;
use serde_json::Value;
use super::{Record, ndjson};
use crate::path::Path;
fn key() -> impl Strategy<Value = String> {
"[ab.\\[\\]\"]{1,4}"
}
fn object() -> impl Strategy<Value = Value> {
let leaf = prop_oneof![
any::<i32>().prop_map(Value::from),
"[a-z]{0,3}".prop_map(Value::from),
any::<bool>().prop_map(Value::from),
];
leaf.prop_recursive(3, 24, 4, |inner| {
prop::collection::btree_map(key(), inner, 1..4)
.prop_map(|map: BTreeMap<String, Value>| Value::Object(map.into_iter().collect()))
})
.prop_filter("an object at the root", Value::is_object)
}
fn leaves(value: &Value, keys: &mut Vec<String>, out: &mut Vec<(Vec<String>, String)>) {
match value {
Value::Object(map) => {
for (k, v) in map {
keys.push(k.clone());
leaves(v, keys, out);
keys.pop();
}
}
Value::String(s) => out.push((keys.clone(), s.clone())),
other => out.push((keys.clone(), other.to_string())),
}
}
proptest! {
#[test]
fn every_value_reads_back_by_its_keys(value in object()) {
let record = serde_json::to_vec(&value).expect("a value writes");
let fields = ndjson(&record);
let mut want = Vec::new();
leaves(&value, &mut Vec::new(), &mut want);
prop_assert_eq!(fields.len(), want.len());
for ((name, _), (keys, _)) in fields.as_slice().iter().zip(&want) {
prop_assert_eq!(Path::parse(name), Path::from_keys(keys.clone()), "{}", name);
}
let fields = &fields;
for (keys, text) in &want {
let got = fields.find(keys).and_then(|at| fields.text(at));
prop_assert_eq!(got.as_deref(), Ok(text.as_str()), "{:?}", keys);
}
}
}
}