#![allow(
clippy::indexing_slicing,
clippy::unwrap_used,
reason = "test code with known-structure parsed data"
)]
use std::collections::BTreeSet;
use super::{Document, ElemId, Field, parse};
fn parsed(s: &str) -> Document<'_> {
parse(s.into()).unwrap()
}
fn root_values(doc: &Document<'_>) -> Vec<ElemId> {
let fields = doc.root().as_object_fields().unwrap();
fields.iter().map(|field| field.element().id()).collect()
}
#[test]
fn only_the_last_occurrence_of_a_repeated_key_counts() {
let doc = parsed(r#"{"a": 1, "b": 2, "a": 3, "a": 4}"#);
let values = root_values(&doc);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::from([values[3]]));
}
#[test]
fn a_key_in_a_sibling_object_is_not_a_repeat() {
let doc = parsed(r#"{"x": {"k": 1}, "y": {"k": 2}}"#);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::new());
}
#[test]
fn each_object_has_its_own_last_occurrence() {
let doc = parsed(r#"{"x": {"k": 1, "k": 2}, "y": {"k": 3, "k": 4}}"#);
let values = root_values(&doc);
let last_in = |object: ElemId| {
let fields = doc.element(object).unwrap().as_object_fields().unwrap();
fields.last().map(Field::element).unwrap().id()
};
assert_eq!(
doc.last_of_repeated_keys(),
BTreeSet::from([last_in(values[0]), last_in(values[1])])
);
}
#[test]
fn a_key_nested_under_an_earlier_sibling_is_not_a_repeat() {
let doc = parsed(r#"{"x": {"k": 1}, "k": 2}"#);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::new());
}
#[test]
fn a_repeat_after_an_earlier_subtree_is_found() {
let doc = parsed(r#"{"k": {"a": [1, 2]}, "b": 3, "k": {}}"#);
let values = root_values(&doc);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::from([values[2]]));
}
#[test]
fn a_key_nested_under_a_later_sibling_does_not_count() {
let doc = parsed(r#"{"k": 1, "k": 2, "x": {"k": 3}}"#);
let values = root_values(&doc);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::from([values[1]]));
}
#[test]
fn an_array_item_never_repeats_a_key() {
let doc = parsed(r#"{"list": [1, 1]}"#);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::new());
}
#[test]
fn an_escaped_spelling_of_a_key_is_a_repeat() {
let doc = parsed(r#"{"k": 1, "\u006b": 2}"#);
let values = root_values(&doc);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::from([values[1]]));
}
#[test]
fn a_malformed_name_does_not_repeat_a_decoded_one() {
let doc = parsed(r#"{"a\\q": 1, "a\q": 2}"#);
assert_eq!(doc.last_of_repeated_keys(), BTreeSet::new());
}