use std::borrow::Cow;
use std::collections::BTreeMap;
use proptest::prelude::*;
use serde_json::Value;
use super::super::paths::tests::Style;
use super::*;
fn path(text: &str) -> Path {
Path::parse(text).unwrap()
}
fn index(rows: &[(&str, &str, Compare)]) -> LiteralIndex {
LiteralIndex::new(rows.iter().map(|&(p, l, c)| (path(p), l, c)))
}
#[test]
fn rows_match_by_text_or_string_in_declared_order() {
use Compare::{String as S, Text as T};
let rows = index(&[
("data_stream.dataset", "system.auth", T),
("f", "123", T),
("f", "123", S),
("data_stream.dataset", "system.auth", T),
("f", "1.50", T),
("ok", "true", T),
("ok", "true", S),
("n", "null", T),
("data_stream.dataset", "nginx.access", T),
]);
let cases: &[(&str, &[usize])] = &[
(r#"{"data_stream":{"dataset":"system.auth"}}"#, &[0, 3]),
(
r#"{"data_stream":{"dataset":"system.auth"},"f":123}"#,
&[0, 1, 3],
),
(r#"{"f":"123"}"#, &[1, 2]),
("{\"f\":\"\\u0031\\u00323\"}", &[1, 2]),
(r#"{"f":123.0}"#, &[]),
(r#"{"f":1.50}"#, &[4]),
(r#"{"f":1.5}"#, &[]),
(r#"{"ok":true}"#, &[5]),
(r#"{"ok":"true"}"#, &[5, 6]),
(r#"{"n":null}"#, &[]),
(r#"{"n":"null"}"#, &[7]),
(r#"{"f":[123]}"#, &[]),
(r#"{"f":{"x":123}}"#, &[]),
(r#"{"data_stream":"system.auth"}"#, &[]),
(
r#"{"data_stream":{"dataset":"nginx.access"},"f":"123"}"#,
&[1, 2, 8],
),
(
r#"{"data_stream":{"dataset":"system.auth"},"f":tru}"#,
&[0, 3],
),
(r#"{"f":12"#, &[]),
(r#"{"f":123,"f":"x"}"#, &[1]),
("[]", &[]),
("", &[]),
];
check(&rows, cases);
assert_eq!(rows.len(), 9);
assert!(!rows.is_empty());
assert!(index(&[]).is_empty());
}
fn check(rows: &LiteralIndex, cases: &[(&str, &[usize])]) {
let mut slots = Slots::new();
let mut out = Vec::new();
for &(json, want) in cases {
rows.matching(json.as_bytes(), &mut slots, &mut out);
assert_eq!(out, want, "{json}");
assert_eq!(
rows.first(json.as_bytes(), &mut slots),
want.first().copied(),
"{json}"
);
let read: Vec<Option<(Kind, Cow<'_, str>)>> = rows
.paths
.read(json.as_bytes(), &mut slots)
.iter()
.map(|slot| {
let raw = slot.found()?;
match raw.kind() {
Kind::String => raw.to_str().map(|s| (Kind::String, s)),
kind => Some((kind, Cow::Borrowed(raw.text()))),
}
})
.collect();
let values = || {
read.iter().map(|v| {
v.as_ref().and_then(|(kind, text)| match kind {
Kind::String => Some(Scalar::String(text)),
Kind::Number => Some(Scalar::Number(text)),
Kind::Bool => Some(Scalar::Bool(text == "true")),
Kind::Object | Kind::Array | Kind::Null => None,
})
})
};
rows.matching_values(values(), &mut out);
assert_eq!(out, want, "values of {json}");
let mut borrowed = Vec::new();
for (path, value) in values().enumerate() {
if let Some(value) = value {
rows.rows_with(path, value, |ids| borrowed.extend_from_slice(ids));
}
}
borrowed.sort_unstable();
assert_eq!(borrowed, want, "rows_with of {json}");
assert_eq!(rows.first_value(values()), want.first().copied(), "{json}");
}
}
#[test]
fn a_supplied_value_replaces_the_record() {
use Compare::{String as S, Text as T};
let rows = index(&[("a", "x", S), ("b", "7", T), ("a", "y", T)]);
assert_eq!(rows.paths(), [path("a"), path("b")]);
let mut out = Vec::new();
let values = [Some(Scalar::String("y")), Some(Scalar::Number("7"))];
rows.matching_values(values, &mut out);
assert_eq!(out, [1, 2]);
assert_eq!(rows.first_value([None, Some(Scalar::Bool(true))]), None);
let run = index(&[("a", "x", T), ("b", "x", T), ("a", "x", T), ("a", "y", T)]);
let mut runs: Vec<Vec<usize>> = Vec::new();
run.rows_with(0, Scalar::String("x"), |ids| runs.push(ids.to_vec()));
assert_eq!(runs, [vec![0, 2]]);
run.rows_with(9, Scalar::String("x"), |_| panic!("no such path"));
}
#[cfg(feature = "parse")]
const PRINTED: &[(&str, &str)] = &[
("42", "42"),
("1.5", "1.5"),
("1.50", "1.5"),
("1e2", "100.0"),
("-2.5E-3", "-0.0025"),
("-0", "-0.0"),
("0", "0"),
("-7", "-7"),
("123456789012345678", "123456789012345678"),
("1234567890123456789", "1234567890123456789"),
("18446744073709551615", "18446744073709551615"),
("18446744073709551616", "1.8446744073709552e+19"),
("-9223372036854775808", "-9223372036854775808"),
("1.8446744073709552e+19", "1.8446744073709552e+19"),
("100.0", "100.0"),
("15e-1", "1.5"),
];
#[cfg(feature = "parse")]
#[test]
fn a_number_prints_as_serde_json_prints_it() {
for &(text, printed) in PRINTED {
let value: Value = serde_json::from_str(text).unwrap();
assert_eq!(value.to_string(), printed, "serde_json {text}");
assert_eq!(number_form(text), printed, "{text}");
}
for not_a_number in [
"abc", "1e400", " 1.5", "1.5 ", "007", "+1", "-", "", "1.", "true",
] {
assert_eq!(number_form(not_a_number), not_a_number);
}
}
#[cfg(feature = "parse")]
#[test]
fn number_rows_read_a_number_as_serde_json_prints_it() {
use Compare::{Number as N, String as S, Text as T};
let rows = index(&[
("f", "42", N),
("f", "1.50", N),
("f", "1e2", N),
("f", "-2.5E-3", N),
("f", "-0", N),
("f", "-7", N),
("f", "18446744073709551616", N),
("f", "true", N),
("f", "1.50", T),
("f", "1.5", S),
("f", "abc", N),
("f", "1e400", N),
("f", "1234567890123456789", N),
("f", "42", T),
]);
let cases: &[(&str, &[usize])] = &[
(r#"{"f":42}"#, &[0, 13]),
(r#"{"f":"42"}"#, &[0, 13]),
(r#"{"f":42.0}"#, &[]),
(r#"{"f":1.5}"#, &[1]),
(r#"{"f":1.50}"#, &[1, 8]),
(r#"{"f":15e-1}"#, &[1]),
(r#"{"f":"1.50"}"#, &[1, 8]),
(r#"{"f":"1.5"}"#, &[9]),
(r#"{"f":100}"#, &[]),
(r#"{"f":1e2}"#, &[2]),
(r#"{"f":100.0}"#, &[2]),
(r#"{"f":1E+2}"#, &[2]),
(r#"{"f":"100.0"}"#, &[]),
(r#"{"f":-0.0025}"#, &[3]),
(r#"{"f":-2.5e-3}"#, &[3]),
(r#"{"f":-0}"#, &[4]),
(r#"{"f":-0.0}"#, &[4]),
(r#"{"f":"-0"}"#, &[4]),
(r#"{"f":0}"#, &[]),
(r#"{"f":-7}"#, &[5]),
(r#"{"f":18446744073709551616}"#, &[6]),
(r#"{"f":1.8446744073709552e19}"#, &[6]),
(r#"{"f":true}"#, &[7]),
(r#"{"f":"true"}"#, &[7]),
(r#"{"f":false}"#, &[]),
(r#"{"f":"abc"}"#, &[10]),
(r#"{"f":1e400}"#, &[11]),
(r#"{"f":1234567890123456789}"#, &[12]),
(r#"{"f":null}"#, &[]),
(r#"{"f":[42]}"#, &[]),
(r#"{"f":{"x":42}}"#, &[]),
(r#"{"f":-07}"#, &[]),
(r#"{"f":4"#, &[]),
(r#"{"g":42}"#, &[]),
];
check(&rows, cases);
}
#[test]
fn a_thousand_rows_on_one_path_are_one_lookup() {
let rows = LiteralIndex::new((0..1_008).map(|i| {
(
path("data_stream.dataset"),
format!("app{i}.log"),
Compare::Text,
)
}));
let mut slots = Slots::new();
let mut out = Vec::new();
rows.matching(
br#"{"data_stream":{"dataset":"app1007.log"}}"#,
&mut slots,
&mut out,
);
assert_eq!(out, [1_007]);
assert_eq!(rows.by_path.len(), 1);
}
#[derive(Debug, Clone)]
enum Field {
Value(Value),
Number(&'static str),
}
fn model(
rows: &[(String, String, Compare)],
fields: &BTreeMap<&str, Field>,
record: &Value,
) -> Vec<usize> {
rows.iter()
.enumerate()
.filter(
|(_, (key, literal, compare))| match (record.get(key), compare) {
(Some(Value::String(s)), _) => s == literal,
(Some(Value::Bool(b)), Compare::Text) => &b.to_string() == literal,
(Some(Value::Number(n)), Compare::Text) => match &fields[key.as_str()] {
Field::Number(text) => text == literal,
Field::Value(_) => &n.to_string() == literal,
},
#[cfg(feature = "parse")]
(Some(Value::Bool(b)), Compare::Number) => &b.to_string() == literal,
#[cfg(feature = "parse")]
(Some(Value::Number(n)), Compare::Number) => {
n.to_string()
== literal
.parse::<serde_json::Number>()
.map_or_else(|_| literal.clone(), |l| l.to_string())
}
_ => false,
},
)
.map(|(i, _)| i)
.collect()
}
const FIELDS: &[&str] = &["a", "b", "a.b", "\u{e9}"];
const LITERALS: &[&str] = &[
"1",
"-2",
"1.5",
"1.50",
"1e2",
"100.0",
"-0",
"-0.0",
"0",
"1234567890123456789",
"18446744073709551616",
"1.8446744073709552e+19",
"true",
"false",
"x",
"x y",
"\u{e9}\"\\",
"",
];
const NUMBER_TEXTS: &[&str] = &[
"1",
"1.5",
"1.50",
"15e-1",
"1e2",
"1E+2",
"100.0",
"100",
"-0",
"-0.0",
"0",
"0e0",
"123456789012345678",
"1234567890123456789",
"18446744073709551616",
"-9223372036854775809",
];
fn literal_value() -> impl Strategy<Value = Value> {
prop_oneof![
prop::sample::select(LITERALS).prop_map(|s| Value::String(s.to_owned())),
prop::sample::select(&[1_i64, -2, 7][..]).prop_map(Value::from),
Just(Value::from(1.5)),
any::<bool>().prop_map(Value::Bool),
Just(Value::Null),
Just(serde_json::json!([1])),
Just(serde_json::json!({"x": "1"})),
]
}
fn field() -> impl Strategy<Value = Field> {
prop_oneof![
3 => literal_value().prop_map(Field::Value),
1 => prop::sample::select(NUMBER_TEXTS).prop_map(Field::Number),
]
}
#[cfg(feature = "parse")]
const COMPARES: &[Compare] = &[Compare::Text, Compare::String, Compare::Number];
#[cfg(not(feature = "parse"))]
const COMPARES: &[Compare] = &[Compare::Text, Compare::String];
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
#[test]
fn matching_agrees_with_a_model_on_serde_json(
rows in prop::collection::vec(
(prop::sample::select(FIELDS), prop::sample::select(LITERALS), prop::sample::select(COMPARES)),
0..24,
),
fields in prop::collection::btree_map(prop::sample::select(FIELDS), field(), 0..4),
seed in any::<u64>(),
spaces in any::<bool>(),
escapes in any::<bool>(),
) {
let rows: Vec<(String, String, Compare)> = rows
.into_iter()
.map(|(k, l, c)| (k.to_owned(), l.to_owned(), c))
.collect();
let index = LiteralIndex::new(rows.iter().map(|(k, l, c)| {
(Path::from_keys([k.as_str()]).unwrap(), l.as_str(), *c)
}));
let mut style = Style { seed: seed | 1, spaces, escapes };
let mut json = String::from("{");
for (i, (key, field)) in fields.iter().enumerate() {
if i > 0 {
style.space(&mut json);
json.push(',');
}
style.space(&mut json);
style.string(key, &mut json);
style.space(&mut json);
json.push(':');
style.space(&mut json);
match field {
Field::Value(value) => style.write(value, &mut json),
Field::Number(text) => json.push_str(text),
}
}
style.space(&mut json);
json.push('}');
let record: Value = serde_json::from_str(&json).unwrap();
let mut slots = Slots::new();
let mut out = Vec::new();
index.matching(json.as_bytes(), &mut slots, &mut out);
let want = model(&rows, &fields, &record);
prop_assert_eq!(&out, &want, "{}", json);
prop_assert_eq!(index.first(json.as_bytes(), &mut slots), want.first().copied());
}
}