use super::RequestHeaders;
use super::arrays::satisfied_by_array;
use crate::util::MultiValueMap;
use serde_json::Value;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::hash::BuildHasher;
pub(crate) fn leaf_text(value: &Value) -> Cow<'_, str> {
match value {
Value::String(s) => Cow::Borrowed(s),
Value::Number(n) => Cow::Owned(rift_types::wire::js_number_string(n)),
Value::Bool(true) => Cow::Borrowed("true"),
Value::Bool(false) => Cow::Borrowed("false"),
Value::Null => Cow::Borrowed("null"),
Value::Array(_) | Value::Object(_) => Cow::Owned(value.to_string()),
}
}
pub(crate) fn truthy(value: &serde_json::Value) -> bool {
match value {
serde_json::Value::Null => false,
serde_json::Value::Bool(b) => *b,
serde_json::Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
serde_json::Value::String(s) => !s.is_empty(),
serde_json::Value::Array(_) | serde_json::Value::Object(_) => true,
}
}
struct ExistsCheck<'e> {
except: &'e dyn for<'a> Fn(&'a str) -> Cow<'a, str>,
key_case_sensitive: bool,
}
impl ExistsCheck<'_> {
fn present(&self, value: Option<&str>) -> bool {
value.is_some_and(|v| !(self.except)(v).is_empty())
}
fn expects_present(&self, expected: &serde_json::Value) -> bool {
match expected {
serde_json::Value::String(s) => self.present(Some(s)),
other => truthy(other),
}
}
fn is_container(&self, actual: &serde_json::Value) -> bool {
match actual {
serde_json::Value::String(s) => self.present(Some(s)),
other => truthy(other),
}
}
fn holds_for_values(&self, expected: &serde_json::Value, values: &[&str]) -> bool {
let wanted = self.expects_present(expected);
match values {
[] => !wanted,
[one] => self.present(Some(one)) == wanted,
many => wanted || many.iter().any(|v| !self.present(Some(v))),
}
}
fn field<'a>(&self, actual: &'a serde_json::Value, key: &str) -> Option<&'a serde_json::Value> {
let obj = actual.as_object()?;
if self.key_case_sensitive {
obj.get(key)
} else {
obj.get(key).or_else(|| {
obj.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(key))
.map(|(_, v)| v)
})
}
}
fn satisfied(
&self,
expected: &serde_json::Map<String, serde_json::Value>,
actual: &serde_json::Value,
) -> bool {
if !self.is_container(actual) {
return false;
}
if let serde_json::Value::String(text) = actual
&& let Ok(parsed) = serde_json::from_str::<serde_json::Value>(text)
{
return self.fields(expected, &parsed);
}
self.fields(expected, actual)
}
fn fields(
&self,
expected: &serde_json::Map<String, serde_json::Value>,
actual: &serde_json::Value,
) -> bool {
if let serde_json::Value::Array(elements) = actual {
return elements
.iter()
.any(|element| self.satisfied(expected, element));
}
expected.iter().all(|(key, expected_val)| {
let field = self.field(actual, key);
match (expected_val, field) {
(serde_json::Value::Object(nested), Some(serde_json::Value::Array(elements))) => {
elements
.iter()
.any(|element| self.satisfied(nested, element))
}
(serde_json::Value::Object(nested), Some(value)) => self.satisfied(nested, value),
(serde_json::Value::Object(_), None) => false,
(_, Some(serde_json::Value::Array(elements))) => {
self.expects_present(expected_val)
|| elements.iter().any(
|e| matches!(e, serde_json::Value::String(s) if !self.present(Some(s))),
)
}
(_, Some(serde_json::Value::String(text))) => {
self.present(Some(text)) == self.expects_present(expected_val)
}
(_, field) => field.is_some() == self.expects_present(expected_val),
}
})
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn check_exists_predicate<H>(
obj: &HashMap<String, serde_json::Value>,
method: &str,
path: &str,
query: &MultiValueMap,
headers: &H,
body: &str,
request_from: Option<&str>,
client_ip: Option<&str>,
form: Option<&MultiValueMap>,
key_case_sensitive: bool,
body_json: &crate::behaviors::LazyJson<'_>,
apply_except: &dyn for<'a> Fn(&'a str) -> Cow<'a, str>,
) -> bool
where
H: RequestHeaders,
{
let check = ExistsCheck {
except: apply_except,
key_case_sensitive,
};
let key_matches = |expected_key: &str, actual_key: &str| -> bool {
if key_case_sensitive {
expected_key == actual_key
} else {
expected_key.eq_ignore_ascii_case(actual_key)
}
};
for (field, value) in [
("method", Some(method)),
("path", Some(path)),
("requestFrom", request_from),
("ip", client_ip),
] {
if let Some(expected) = obj.get(field)
&& check.present(value) != check.expects_present(expected)
{
return false;
}
}
if let Some(expected) = obj.get("body") {
let holds = match expected {
serde_json::Value::Object(fields) => match body_json.get() {
Some(parsed) => check.present(Some(body)) && check.fields(fields, parsed),
None => check.satisfied(fields, &serde_json::Value::String(body.to_owned())),
},
_ => check.present(Some(body)) == check.expects_present(expected),
};
if !holds {
return false;
}
}
if let Some(expected_query) = obj.get("query").and_then(|v| v.as_object()) {
for (key, expected) in expected_query {
let values: Vec<&str> = query
.iter()
.filter(|(k, _)| key_matches(key, k))
.flat_map(|(_, v)| v.iter().map(String::as_str))
.collect();
if !check.holds_for_values(expected, &values) {
return false;
}
}
}
if let Some(expected_headers) = obj.get("headers").and_then(|v| v.as_object()) {
for (key, expected) in expected_headers {
let mut values: Vec<&str> = Vec::new();
for value in headers
.entries()
.filter(|(k, _)| key_matches(key, k))
.flat_map(|(_, values)| values.iter().map(String::as_str))
{
match values.as_mut_slice() {
[first] if first.is_empty() => *first = value,
_ => values.push(value),
}
}
if !check.holds_for_values(expected, &values) {
return false;
}
}
}
if let Some(expected_form) = obj.get("form").and_then(|v| v.as_object()) {
let Some(actual_form) = form.filter(|f| !(f.is_empty() && body.is_empty())) else {
return false;
};
for (key, expected) in expected_form {
let values: Vec<&str> = actual_form
.iter()
.filter(|(k, _)| key_matches(key, k))
.flat_map(|(_, v)| v.iter().map(String::as_str))
.collect();
if !check.holds_for_values(expected, &values) {
return false;
}
}
}
true
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NullLeaf {
Identity,
NoText,
Text,
}
pub(crate) struct Satisfy<'a> {
pub(crate) compare: &'a dyn Fn(&str, &str) -> bool,
pub(crate) except: &'a dyn for<'b> Fn(&'b str) -> Cow<'b, str>,
pub(crate) key_case_sensitive: bool,
pub(crate) case_sensitive: bool,
pub(crate) nulls: NullLeaf,
}
impl Satisfy<'_> {
pub(crate) fn text(&self, expected: &Value, text: &str, pre_parsed: Option<&Value>) -> bool {
if text.is_empty() {
return false;
}
match pre_parsed {
Some(parsed) => self.parsed(expected, parsed),
None => match serde_json::from_str::<Value>(text) {
Ok(parsed) => self.parsed(expected, &parsed),
Err(_) => self.fields(expected, &Value::String(text.to_owned())),
},
}
}
fn container(&self, expected: &Value, actual: Option<&Value>) -> bool {
match actual {
Some(Value::String(text)) => self.text(expected, text, None),
Some(actual) if truthy(actual) => self.fields(expected, actual),
_ => false,
}
}
fn parsed(&self, expected: &Value, parsed: &Value) -> bool {
!parsed.is_null() && self.fields(expected, parsed)
}
fn fields(&self, expected: &Value, actual: &Value) -> bool {
match expected {
Value::Object(fields) => fields.iter().all(|(key, expected_value)| {
let value = object_field(actual, key, self.key_case_sensitive);
self.field(expected, expected_value, value, actual)
}),
Value::Array(elements) => {
let Value::Array(actuals) = actual else {
return false;
};
self.sorted(elements)
.into_iter()
.enumerate()
.all(|(i, element)| self.field(expected, element, actuals.get(i), actual))
}
leaf => self.leaf(leaf, Some(actual)),
}
}
fn field(
&self,
whole: &Value,
expected: &Value,
actual: Option<&Value>,
parent: &Value,
) -> bool {
match (actual, parent) {
(Some(Value::Array(actuals)), _) => {
satisfied_by_array(expected, actuals, |e, a| self.test(e, Some(a)))
}
(None, Value::Array(elements)) if !expected.is_array() => elements
.iter()
.any(|element| self.test(whole, Some(element))),
_ => self.test(expected, actual),
}
}
fn test(&self, expected: &Value, actual: Option<&Value>) -> bool {
match expected {
Value::Object(_) | Value::Array(_) => self.container(expected, actual),
leaf => self.leaf(leaf, actual),
}
}
fn leaf(&self, expected: &Value, actual: Option<&Value>) -> bool {
let actual: Cow<'_, str> = match actual {
None => Cow::Borrowed(""),
Some(Value::Null) => match self.nulls {
NullLeaf::Identity => return expected.is_null(),
NullLeaf::NoText => return false,
NullLeaf::Text => Cow::Borrowed("null"),
},
Some(Value::Object(_)) if self.nulls == NullLeaf::Text => {
Cow::Borrowed("[object Object]")
}
Some(Value::Object(_) | Value::Array(_)) => return false,
Some(scalar) => leaf_text(scalar),
};
self.leaf_against_text(expected, &actual)
}
pub(crate) fn leaf_against_text(&self, expected: &Value, actual: &str) -> bool {
if expected.is_null() && self.nulls == NullLeaf::Identity {
return false;
}
(self.compare)(&leaf_text(expected), &(self.except)(actual))
}
fn sorted<'v>(&self, elements: &'v [Value]) -> Vec<&'v Value> {
let key = |v: &Value| -> String {
let text = leaf_text(v);
if self.case_sensitive {
text.into_owned()
} else {
text.to_ascii_lowercase()
}
};
let mut sorted: Vec<&Value> = elements.iter().collect();
sorted.sort_by(|a, b| match (a.as_f64(), b.as_f64()) {
(Some(x), Some(y)) => x.total_cmp(&y),
_ => key(a).cmp(&key(b)),
});
sorted
}
}
fn object_field<'a>(actual: &'a Value, key: &str, key_case_sensitive: bool) -> Option<&'a Value> {
let fields = actual.as_object()?;
if key_case_sensitive {
fields.get(key)
} else {
fields.get(key).or_else(|| {
fields
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(key))
.map(|(_, v)| v)
})
}
}
pub(crate) struct DeepEquals<'a> {
pub(crate) except: &'a dyn for<'b> Fn(&'b str) -> Cow<'b, str>,
pub(crate) case_sensitive: bool,
pub(crate) key_case_sensitive: bool,
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Canonical {
Text(String),
List(Vec<Canonical>),
Map(BTreeMap<String, Canonical>),
}
impl DeepEquals<'_> {
pub(crate) fn text(&self, expected: &Value, text: &str, pre_parsed: Option<&Value>) -> bool {
let actual = match pre_parsed {
Some(parsed) => self.canonical(parsed),
None => match serde_json::from_str::<Value>(text) {
Ok(parsed) => self.canonical(&parsed),
Err(_) => return false,
},
};
self.canonical(expected) == actual
}
fn canonical(&self, value: &Value) -> Canonical {
match value {
Value::Object(fields) => Canonical::Map(
fields
.iter()
.map(|(key, v)| (self.fold_key(key), self.canonical(v)))
.collect(),
),
Value::Array(elements) => {
let mut list: Vec<Canonical> = elements.iter().map(|v| self.canonical(v)).collect();
list.sort();
Canonical::List(list)
}
leaf => {
let text = leaf_text(leaf);
let text = (self.except)(&text);
Canonical::Text(if self.case_sensitive {
text.into_owned()
} else {
text.to_ascii_lowercase()
})
}
}
}
fn fold_key(&self, key: &str) -> String {
if self.key_case_sensitive {
key.to_owned()
} else {
key.to_ascii_lowercase()
}
}
}
fn is_jsonish_string(s: &str) -> bool {
let t = s.trim_start();
t.starts_with('{') || t.starts_with('[')
}
fn mix64(mut x: u64) -> u64 {
x ^= x >> 33;
x = x.wrapping_mul(0xff51afd7ed558ccd);
x ^= x >> 33;
x = x.wrapping_mul(0xc4ceb9fe1a85ec53);
x ^= x >> 33;
x
}
fn combine(a: u64, b: u64) -> u64 {
mix64(a ^ mix64(b).rotate_left(31))
}
fn hash_folded(s: &str) -> u64 {
foldhash::fast::FixedState::default().hash_one(s.to_ascii_lowercase())
}
const OBJ_TAG: u64 = 0x9e37_79b9_7f4a_7c15;
const ARR_TAG: u64 = 0xc2b2_ae3d_27d4_eb4f;
pub(crate) fn structural_hash(value: &Value) -> Option<u64> {
match value {
Value::Object(map) => {
let mut folded: BTreeMap<String, &Value> = BTreeMap::new();
for (k, v) in map {
folded.insert(k.to_ascii_lowercase(), v);
}
let mut acc: u64 = 0;
for (k, v) in &folded {
let entry = combine(hash_folded(k), structural_hash(v)?);
acc = acc.wrapping_add(mix64(entry));
}
Some(combine(OBJ_TAG, combine(folded.len() as u64, acc)))
}
Value::Array(arr) => {
let mut acc: u64 = 0;
for v in arr {
acc = acc.wrapping_add(mix64(structural_hash(v)?));
}
Some(combine(ARR_TAG, combine(arr.len() as u64, acc)))
}
Value::String(s) if is_jsonish_string(s) => None,
leaf => Some(hash_folded(&leaf_text(leaf))),
}
}
#[cfg(test)]
mod structural_hash_tests {
use super::*;
use serde_json::{Value, json};
fn deep_equals_default(expected: &Value, actual: &Value) -> bool {
DeepEquals {
except: &|s: &str| Cow::Borrowed(s),
case_sensitive: false,
key_case_sensitive: false, }
.text(expected, &actual.to_string(), Some(actual))
}
fn assert_sound(e: &Value, a: &Value) {
if deep_equals_default(e, a) {
let (he, ha) = (structural_hash(e), structural_hash(a));
assert!(
he.is_none() || ha.is_none() || he == ha,
"under-approximation: deep_equals holds but hashes differ\n e={e}\n a={a}\n he={he:?} ha={ha:?}"
);
}
}
#[test]
fn concrete_cross_type_equivalences_hash_equal() {
for (e, a) in [
(json!({"n": 1}), json!({"n": "1"})), (json!({"b": true}), json!({"b": "true"})), (json!({"z": null}), json!({"z": "null"})), (json!({"n": 1}), json!({"n": 1.0})), (json!({"n": 100}), json!({"n": 1e2})), (json!({"s": "ABC"}), json!({"s": "abc"})), (json!({"a": 1, "b": 2}), json!({"b": 2, "a": 1})), (json!({"Key": 1}), json!({"key": 1})), (json!([1, "2", null]), json!(["1", 2, "null"])), (json!([1, 2]), json!([2, 1])), (
json!({"i": [{"id": 1}, {"id": 2}]}),
json!({"i": [{"id": 2}, {"id": 1}]}),
),
(json!({"k": 1, "K": 1}), json!({"k": 1})), (json!({"o": {"x": 1}}), json!({"o": {"x": "1"}})), ] {
assert!(
deep_equals_default(&e, &a),
"precondition: {e} deep-equals {a}"
);
assert_eq!(
structural_hash(&e),
structural_hash(&a),
"{e} and {a} deep-equal but hash differently"
);
assert!(structural_hash(&e).is_some());
}
}
#[test]
fn distinct_values_stay_distinct() {
for (e, a) in [
(json!({"n": 1.5}), json!({"n": 1})),
(json!({"z": null}), json!({"z": ""})),
(json!(["a", "a", "b"]), json!(["a", "b", "b"])), (json!(["a"]), json!(["a", "a"])),
] {
assert!(
!deep_equals_default(&e, &a),
"precondition: {e} differs from {a}"
);
assert_ne!(
structural_hash(&e),
structural_hash(&a),
"{e} and {a} collide"
);
}
}
#[test]
fn json_in_string_leaf_bails_both_directions() {
assert_eq!(structural_hash(&json!({"a": "{\"b\":1}"})), None);
assert_eq!(structural_hash(&json!({"a": " [1,2]"})), None); assert_eq!(structural_hash(&json!(["{}"])), None);
assert!(!deep_equals_default(
&json!({"a": {"b": 1}}),
&json!({"a": "{\"b\":1}"})
));
assert!(structural_hash(&json!({"a": "x{y"})).is_some());
}
#[test]
fn empty_container_types_are_distinct() {
assert_ne!(structural_hash(&json!({})), structural_hash(&json!([])));
assert_ne!(structural_hash(&json!({})), structural_hash(&json!("")));
}
#[test]
fn array_order_is_ignored() {
for (e, a) in [
(json!([1, 2]), json!([2, 1])),
(json!({"m": [[2, 1], [3]]}), json!({"m": [[3], [1, 2]]})),
(
json!([{"a": null}, {"a": "z"}]),
json!([{"a": "z"}, {"a": "null"}]),
),
] {
assert!(
deep_equals_default(&e, &a),
"precondition: {e} deep-equals {a}"
);
assert_eq!(structural_hash(&e), structural_hash(&a), "{e} and {a}");
}
}
struct Lcg(u64);
impl Lcg {
fn next_u64(&mut self) -> u64 {
self.0 = self
.0
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
self.0
}
fn below(&mut self, n: u64) -> u64 {
(self.next_u64() >> 33) % n
}
fn coin(&mut self) -> bool {
self.next_u64() >> 63 == 1
}
}
fn gen_value(rng: &mut Lcg, depth: u32) -> Value {
let leaf = depth == 0 || rng.below(100) < 70u64.saturating_sub(u64::from(depth) * 20);
if leaf {
match rng.below(9) {
0 => Value::Null,
1 => Value::Bool(rng.coin()),
2 => json!(rng.below(4) as i64), 3 => json!(rng.below(3) as f64 + 0.5), 7 => json!(rng.below(3) as f64), 8 => Value::String("NULL".to_string()), 4 => Value::String(["a", "B", "aB", ""][rng.below(4) as usize].to_string()),
5 => Value::String(rng.below(4).to_string()), _ => Value::String("{jsonish".to_string()), }
} else if rng.coin() {
let n = rng.below(3);
let mut m = serde_json::Map::new();
for i in 0..n {
let key = ["k", "K", "other"][i as usize % 3].to_string();
m.insert(key, gen_value(rng, depth - 1));
}
Value::Object(m)
} else {
let n = rng.below(4);
Value::Array((0..n).map(|_| gen_value(rng, depth - 1)).collect())
}
}
fn preserving_variant(rng: &mut Lcg, v: &Value) -> Value {
match v {
Value::Null => {
if rng.coin() {
Value::String("null".to_string())
} else {
Value::Null
}
}
Value::Bool(b) => {
if rng.coin() {
Value::String(b.to_string())
} else {
Value::Bool(*b)
}
}
Value::Number(n) => {
if rng.coin() {
Value::String(rift_types::wire::js_number_string(n))
} else {
Value::Number(n.clone())
}
}
Value::String(s) => {
if is_jsonish_string(s) {
Value::String(s.clone())
} else if rng.coin() {
Value::String(s.to_uppercase())
} else {
Value::String(s.to_lowercase())
}
}
Value::Array(a) => {
let mut elements: Vec<Value> =
a.iter().map(|e| preserving_variant(rng, e)).collect();
if elements.len() > 1 {
let by = 1 + rng.below(elements.len() as u64 - 1);
elements.rotate_left(by as usize);
}
Value::Array(elements)
}
Value::Object(m) => {
let mut entries: Vec<(String, Value)> = m
.iter()
.map(|(k, val)| {
let key = if rng.coin() {
k.to_uppercase()
} else {
k.clone()
};
(key, preserving_variant(rng, val))
})
.collect();
entries.reverse();
Value::Object(entries.into_iter().collect())
}
}
}
#[test]
fn structural_hash_agrees_with_deep_equals_property() {
let mut rng = Lcg(0x5eed_1234_9e37_79b9);
let mut deep_equal_cases = 0u32;
let iterations = 10_000;
for _ in 0..iterations {
let a = gen_value(&mut rng, 3);
let e = if rng.coin() {
preserving_variant(&mut rng, &a)
} else {
gen_value(&mut rng, 3)
};
if deep_equals_default(&e, &a) {
deep_equal_cases += 1;
}
assert_sound(&e, &a);
assert_sound(&a, &e);
}
assert!(
deep_equal_cases > iterations / 10,
"generator too weak: only {deep_equal_cases}/{iterations} deep-equal pairs — the \
soundness assertion would be near-vacuous"
);
}
}
#[cfg(test)]
mod comparator_tests {
use super::*;
use serde_json::json;
fn no_except(s: &str) -> Cow<'_, str> {
Cow::Borrowed(s)
}
fn equals(expected: Value, body: &str) -> bool {
Satisfy {
compare: &|e: &str, a: &str| e.eq_ignore_ascii_case(a),
except: &no_except,
key_case_sensitive: false,
case_sensitive: false,
nulls: NullLeaf::Identity,
}
.text(&expected, body, None)
}
fn contains(expected: Value, body: &str) -> bool {
Satisfy {
compare: &|e: &str, a: &str| a.contains(e),
except: &no_except,
key_case_sensitive: false,
case_sensitive: false,
nulls: NullLeaf::NoText,
}
.text(&expected, body, None)
}
fn matches(expected: Value, body: &str) -> bool {
Satisfy {
compare: &|p: &str, a: &str| regex::Regex::new(p).is_ok_and(|re| re.is_match(a)),
except: &no_except,
key_case_sensitive: false,
case_sensitive: true,
nulls: NullLeaf::Text,
}
.text(&expected, body, None)
}
fn deep_equals(expected: Value, body: &str) -> bool {
DeepEquals {
except: &no_except,
case_sensitive: false,
key_case_sensitive: false,
}
.text(&expected, body, None)
}
#[test]
fn an_expected_array_is_a_subset_of_an_actual_array_in_any_order() {
assert!(equals(
json!({"tags": ["a", "c"]}),
r#"{"tags": ["a", "b", "c"]}"#
));
assert!(equals(json!({"t": ["b", "a"]}), r#"{"t": ["a", "b"]}"#));
assert!(equals(json!({"t": []}), r#"{"t": ["a"]}"#));
assert!(equals(json!({"t": [null]}), r#"{"t": [null, "a"]}"#));
assert!(equals(
json!({"i": [{"id": 2}]}),
r#"{"i": [{"id": 1, "x": 0}, {"id": 2, "x": 1}]}"#
));
assert!(!equals(json!({"t": ["a", "z"]}), r#"{"t": ["a"]}"#));
}
#[test]
fn a_scalar_or_object_expectation_holds_for_any_element() {
assert!(equals(json!({"t": "b"}), r#"{"t": ["a", "b"]}"#));
assert!(equals(
json!({"i": {"id": 2}}),
r#"{"i": [{"id": 1}, {"id": 2}]}"#
));
assert!(!equals(
json!({"i": {"id": 3}}),
r#"{"i": [{"id": 1}, {"id": 2}]}"#
));
assert!(contains(json!({"t": ["b"]}), r#"{"t": ["xa", "xbx"]}"#));
assert!(matches(json!({"t": "^b$"}), r#"{"t": ["a", "b"]}"#));
assert!(matches(
json!({"t": ["^a", "^b"]}),
r#"{"t": ["bz", "az", "c"]}"#
));
}
#[test]
fn an_object_left_off_array_syntax_matches_any_element_of_an_array_of_objects() {
assert!(equals(
json!({"name": "x"}),
r#"[{"name": "y"}, {"name": "x"}]"#
));
assert!(!equals(
json!({"a": "1", "b": "2"}),
r#"[{"a": "1"}, {"b": "2"}]"#
));
assert!(!equals(json!({"a": "1"}), r#"["x"]"#));
}
#[test]
fn a_top_level_expected_array_compares_by_position_after_sorting_the_expected_side() {
assert!(equals(json!(["a"]), r#"["a", "b"]"#)); assert!(equals(json!(["b", "a"]), r#"["a", "b"]"#)); assert!(!equals(json!(["a", "b"]), r#"["b", "a"]"#)); assert!(!equals(json!(["b"]), r#"["a", "b"]"#));
}
#[test]
fn contains_does_not_match_across_elements() {
assert!(!contains(json!({"t": "a\",\"b"}), r#"{"t": ["a", "b"]}"#));
}
#[test]
fn null_is_only_null_under_equals() {
assert!(equals(json!({"a": null}), r#"{"a": null}"#));
assert!(!equals(json!({"a": null}), r#"{"a": ""}"#));
assert!(!equals(json!({"a": null}), r#"{"a": "null"}"#));
assert!(!equals(json!({"a": null}), r#"{"b": 1}"#));
assert!(!equals(json!({"a": ""}), r#"{"a": null}"#));
assert!(!contains(json!({"a": "x"}), r#"{"a": null}"#));
assert!(matches(json!({"a": "^null$"}), r#"{"a": null}"#));
assert!(!matches(json!({"a": "^$"}), r#"{"a": null}"#));
}
#[test]
fn a_missing_field_reads_as_the_empty_string() {
assert!(equals(json!({"a": ""}), r#"{"b": 1}"#));
assert!(equals(json!({"a": ""}), "plain text"));
assert!(!equals(json!({"a": {"b": ""}}), r#"{"c": 1}"#));
assert!(!equals(json!({"a": ""}), ""));
}
#[test]
fn numbers_compare_as_javascript_prints_them() {
assert!(equals(json!({"a": 1}), r#"{"a": 1.0}"#));
assert!(equals(json!({"a": 100}), r#"{"a": 1e2}"#));
assert!(equals(json!({"a": 1}), r#"{"a": "1"}"#));
assert!(deep_equals(json!({"a": 1}), r#"{"a": 1.0}"#));
assert!(deep_equals(json!({"a": 100}), r#"{"a": 1e2}"#));
}
#[test]
fn an_expected_array_against_a_plain_string_misses() {
assert!(!equals(json!({"t": ["a"]}), r#"{"t": "a"}"#));
assert!(!equals(json!({"t": ["a"]}), r#"{"t": "abc"}"#));
assert!(equals(json!({"s": ["a"]}), r#"{"s": "[\"a\", \"b\"]"}"#));
assert!(!equals(json!({"s": ["b"]}), r#"{"s": "[\"a\", \"b\"]"}"#));
}
#[test]
fn deep_equals_compares_arrays_as_multisets() {
assert!(deep_equals(
json!({"items": [{"id": 1}, {"id": 2}]}),
r#"{"items": [{"id": 2}, {"id": 1}]}"#
));
assert!(deep_equals(
json!({"m": [[2, 1], [3]]}),
r#"{"m": [[3], [1, 2]]}"#
));
assert!(deep_equals(json!([1, 2]), "[2, 1]"));
assert!(deep_equals(
json!({"t": [{"k": 1}, "s"]}),
r#"{"t": ["s", {"k": 1}]}"#
));
assert!(deep_equals(
json!({"t": ["B", "a"]}),
r#"{"t": ["b", "A"]}"#
));
assert!(!deep_equals(
json!({"t": ["a", "a", "b"]}),
r#"{"t": ["a", "b", "b"]}"#
));
assert!(!deep_equals(json!({"t": ["a"]}), r#"{"t": ["a", "a"]}"#));
assert!(!deep_equals(
json!({"i": [{"id": 1}]}),
r#"{"i": [{"id": 1, "x": 2}]}"#
));
}
#[test]
fn deep_equals_reads_null_as_the_text_null() {
assert!(deep_equals(
json!({"a": null, "b": "1"}),
r#"{"a": "null", "b": "1"}"#
));
assert!(deep_equals(json!({"a": "null"}), r#"{"a": null}"#));
assert!(deep_equals(
json!([{"a": null}, {"a": "z"}]),
r#"[{"a": "z"}, {"a": "null"}]"#
));
assert!(!deep_equals(json!({"a": null}), r#"{"a": ""}"#));
}
#[test]
fn deep_equals_parses_the_request_once() {
assert!(!deep_equals(
json!({"a": {"b": "1"}}),
r#"{"a": "{\"b\": 1}"}"#
));
assert!(!deep_equals(json!({"a": 1}), "not json"));
}
#[test]
fn deep_equals_applies_except_and_case_to_every_leaf() {
fn strip_x(s: &str) -> Cow<'_, str> {
Cow::Owned(s.replace('x', ""))
}
let sensitive = DeepEquals {
except: &no_except,
case_sensitive: true,
key_case_sensitive: true,
};
assert!(sensitive.text(&json!({"t": ["B", "a"]}), r#"{"t": ["a", "B"]}"#, None));
assert!(!sensitive.text(&json!({"t": ["b", "a"]}), r#"{"t": ["a", "B"]}"#, None));
let except = DeepEquals {
except: &strip_x,
case_sensitive: false,
key_case_sensitive: false,
};
assert!(except.text(&json!({"t": ["b", "a"]}), r#"{"t": ["ax", "bx"]}"#, None));
}
}