use std::cell::{Cell, RefCell};
use std::collections::BTreeSet;
use std::fmt;
use std::ops::{Bound, RangeBounds};
use std::rc::Rc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Match {
Contains,
Exact,
Similar,
}
impl Match {
pub(super) const fn wanted(self) -> &'static str {
match self {
Self::Contains => "contain",
Self::Exact => "be exactly",
Self::Similar => "be, with lists in any order,",
}
}
}
pub(super) fn difference(actual: &Value, expected: &Value, path: &str, matching: Match) -> Option<String> {
let at = |key: &dyn fmt::Display| join(path, &key.to_string());
let exact = matching != Match::Contains;
match (actual, expected) {
(Value::Object(actual), Value::Object(expected)) => expected
.iter()
.find_map(|(key, expected)| match actual.get(key) {
Some(actual) => difference(actual, expected, &at(key), matching),
None => Some(format!("`{}` is missing", at(key))),
})
.or_else(|| {
let extra = actual.keys().find(|key| exact && !expected.contains_key(*key))?;
Some(format!("it has `{}` too", at(extra)))
}),
(Value::Array(items), Value::Array(expected)) => expected
.iter()
.enumerate()
.find_map(|(index, expected)| match items.get(index) {
Some(actual) => difference(actual, expected, &at(&index), matching),
None => Some(format!("`{}` is missing", at(&index))),
})
.or_else(|| {
(exact && items.len() > expected.len()).then(|| {
format!(
"{} has {} item{}, not {}",
subject(path),
items.len(),
if items.len() == 1 { "" } else { "s" },
expected.len()
)
})
}),
_ if actual == expected => None,
_ => Some(format!("{} is {actual}", subject(path))),
}
}
pub(super) fn find_fragment(actual: &Value, fragment: &Value, path: &str) -> Option<String> {
if difference(actual, fragment, "", Match::Contains).is_none() {
return Some(path.to_owned());
}
let at = |key: &dyn fmt::Display| join(path, &key.to_string());
match actual {
Value::Object(object) => object
.iter()
.find_map(|(key, value)| find_fragment(value, fragment, &at(key))),
Value::Array(items) => items
.iter()
.enumerate()
.find_map(|(index, item)| find_fragment(item, fragment, &at(&index))),
_ => None,
}
}
pub(super) fn structure_difference(actual: &Value, structure: &Value, path: &str, exact: bool) -> Option<String> {
let at = |key: &dyn fmt::Display| join(path, &key.to_string());
let mut named: Vec<(&str, Option<&Value>)> = Vec::new();
match structure {
Value::Null => return None,
Value::Array(items) => {
for item in items {
match item {
Value::String(key) => named.push((key, None)),
Value::Object(keys) => named.extend(keys.iter().map(|(key, nested)| (key.as_str(), Some(nested)))),
other => panic!("a JSON structure lists keys and objects of keys, not {other}"),
}
}
}
Value::Object(keys) => named.extend(keys.iter().map(|(key, nested)| (key.as_str(), Some(nested)))),
other => panic!("a JSON structure is a list or an object of keys, not {other}"),
}
for (key, nested) in &named {
if *key == "*" {
let Some(items) = entries(actual) else {
return Some(format!("{} is {actual}, not a list or object", subject(path)));
};
let difference = items.into_iter().find_map(|(index, item)| {
structure_difference(item, nested.unwrap_or(&Value::Null), &at(&index), exact)
});
if difference.is_some() {
return difference;
}
continue;
}
let Value::Object(object) = actual else {
return Some(format!("{} is {actual}, not an object with `{key}`", subject(path)));
};
let Some(value) = object.get(*key) else {
return Some(format!("`{}` is missing", at(key)));
};
if let Some(difference) = nested.and_then(|nested| structure_difference(value, nested, &at(key), exact)) {
return Some(difference);
}
}
let Value::Object(object) = actual else {
return None;
};
if !exact || named.iter().any(|(key, _)| *key == "*") {
return None;
}
let extra = object.keys().find(|key| named.iter().all(|(named, _)| named != key))?;
Some(format!("it has `{}` too", at(extra)))
}
fn join(path: &str, key: &str) -> String {
match (path.is_empty(), key.is_empty()) {
(true, _) => key.to_owned(),
(_, true) => path.to_owned(),
_ => format!("{path}.{key}"),
}
}
pub(super) fn subject(path: &str) -> String {
if path.is_empty() {
"the JSON".to_owned()
} else {
format!("`{path}`")
}
}
pub(super) fn entries(value: &Value) -> Option<Vec<(String, &Value)>> {
match value {
Value::Array(items) => Some(
items
.iter()
.enumerate()
.map(|(index, item)| (index.to_string(), item))
.collect(),
),
Value::Object(object) => Some(object.iter().map(|(key, item)| (key.clone(), item)).collect()),
_ => None,
}
}
pub(super) fn rejection<T: DeserializeOwned>(value: &Value, check: impl FnOnce(T) -> bool) -> Option<String> {
match serde_json::from_value(value.clone()) {
Ok(read) => (!check(read)).then(|| format!("pass the check, but it's {value}")),
Err(error) => Some(format!(
"read as `{}`, but it's {value}: {error}",
std::any::type_name::<T>()
)),
}
}
#[track_caller]
pub(super) fn to_json(expected: impl Serialize) -> Value {
serde_json::to_value(expected).expect("the expected value should serialize")
}
#[track_caller]
pub(super) fn fail(json: &Value, outline: &str, message: fmt::Arguments<'_>) -> ! {
panic!("{message}:\n{}\n\n{outline}", pretty(json))
}
pub(super) fn sorted(value: &Value) -> Value {
match value {
Value::Array(items) => {
let mut items: Vec<Value> = items.iter().map(sorted).collect();
items.sort_by_cached_key(Value::to_string);
Value::Array(items)
}
Value::Object(object) => {
let mut entries: Vec<(&String, &Value)> = object.iter().collect();
entries.sort_by_key(|(key, _)| *key);
Value::Object(
entries
.into_iter()
.map(|(key, value)| (key.clone(), sorted(value)))
.collect(),
)
}
_ => value.clone(),
}
}
pub(super) fn descend<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
if path.is_empty() {
return Some(value);
}
path.split('.').try_fold(value, |value, segment| match value {
Value::Object(object) => object.get(segment),
Value::Array(items) => segment.parse::<usize>().ok().and_then(|index| items.get(index)),
_ => None,
})
}
pub(super) fn pretty(value: &impl Serialize) -> String {
serde_json::to_string_pretty(value).unwrap_or_default()
}
pub struct AssertableJson {
json: Rc<Value>,
outline: Rc<str>,
scope: Scope,
}
struct Scope {
path: String,
interacted: RefCell<BTreeSet<String>>,
etc: Cell<bool>,
}
impl AssertableJson {
#[track_caller]
pub(super) fn assert_root(json: Value, outline: String, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) {
let root = Self {
json: Rc::new(json),
outline: outline.into(),
scope: Scope::at(String::new()),
};
assertions(&root);
root.assert_interacted();
}
pub fn prop(&self, path: &str) -> Option<&Value> {
if let Some(key) = path.split('.').next().filter(|key| !key.is_empty()) {
self.scope.interacted.borrow_mut().insert(key.to_owned());
}
descend(&self.json, &self.full_path(path))
}
#[track_caller]
fn expect_prop(&self, path: &str) -> &Value {
match self.prop(path) {
Some(value) => value,
None => self.fail(format_args!("expected the JSON to have `{}`", self.full_path(path))),
}
}
fn full_path(&self, path: &str) -> String {
join(&self.scope.path, path)
}
fn subject(&self, path: &str) -> String {
subject(&self.full_path(path))
}
#[track_caller]
fn fail(&self, message: fmt::Arguments<'_>) -> ! {
fail(&self.json, &self.outline, message)
}
#[track_caller]
pub fn has(&self, path: &str) -> &Self {
self.expect_prop(path);
self
}
#[track_caller]
pub fn has_any(&self, paths: &[&str]) -> &Self {
let found: Vec<bool> = paths.iter().map(|path| self.prop(path).is_some()).collect();
if !found.contains(&true) {
let paths: Vec<String> = paths.iter().map(|path| format!("`{}`", self.full_path(path))).collect();
self.fail(format_args!("expected the JSON to have one of {}", paths.join(", ")));
}
self
}
#[track_caller]
pub fn has_count(&self, path: &str, count: usize) -> &Self {
self.has_count_in(path, count..=count)
}
#[track_caller]
pub fn has_count_in(&self, path: &str, counts: impl RangeBounds<usize> + fmt::Debug) -> &Self {
let actual = self.items(path).len();
if !counts.contains(&actual) {
let expected = match (counts.start_bound(), counts.end_bound()) {
(Bound::Included(start), Bound::Included(end)) if start == end => start.to_string(),
_ => format!("{counts:?}"),
};
self.fail(format_args!(
"expected {} to have {expected} items, but it has {actual}",
self.subject(path)
));
}
self
}
#[track_caller]
fn items(&self, path: &str) -> Vec<String> {
let value = self.expect_prop(path);
match entries(value) {
Some(entries) => entries.into_iter().map(|(key, _)| key).collect(),
None => self.fail(format_args!(
"expected {} to be a list or object, but it's {value}",
self.subject(path)
)),
}
}
#[track_caller]
pub fn missing(&self, path: &str) -> &Self {
if let Some(value) = self.prop(path) {
self.fail(format_args!(
"expected the JSON to have no `{}`, but it's {value}",
self.full_path(path)
));
}
self
}
#[track_caller]
pub fn equals(&self, path: &str, expected: impl Serialize) -> &Self {
let expected = to_json(expected);
let actual = self.expect_prop(path);
if actual != &expected {
self.fail(format_args!(
"expected {} to be {expected}, but it's {actual}",
self.subject(path)
));
}
self
}
#[track_caller]
pub fn satisfies<T: DeserializeOwned>(&self, path: &str, check: impl FnOnce(T) -> bool) -> &Self {
if let Some(rejection) = rejection(self.expect_prop(path), check) {
self.fail(format_args!("expected {} to {rejection}", self.subject(path)));
}
self
}
#[track_caller]
pub fn contains(&self, path: &str, item: impl Serialize) -> &Self {
let item = to_json(item);
let found = match self.expect_prop(path) {
Value::Array(items) => items.contains(&item),
Value::Object(object) => object.values().any(|value| value == &item),
other => self.fail(format_args!(
"expected {} to be a list or object, but it's {other}",
self.subject(path)
)),
};
if !found {
self.fail(format_args!("expected {} to contain {item}", self.subject(path)));
}
self
}
#[track_caller]
pub fn scope(&self, path: &str, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) -> &Self {
self.assert_scoped(path, assertions);
self
}
#[track_caller]
pub fn first(&self, path: &str, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) -> &Self {
let Some(first) = self.items(path).into_iter().next() else {
self.fail(format_args!("expected {} to have an item", self.subject(path)));
};
self.assert_scoped(&join(path, &first), assertions);
self
}
#[track_caller]
pub fn each(&self, path: &str, mut assertions: impl for<'a> FnMut(&'a Self) -> &'a Self) -> &Self {
let items = self.items(path);
if items.is_empty() {
self.fail(format_args!("expected {} to have an item", self.subject(path)));
}
for item in items {
self.assert_scoped(&join(path, &item), &mut assertions);
}
self
}
pub fn etc(&self) -> &Self {
self.scope.etc.set(true);
self
}
#[track_caller]
fn assert_scoped(&self, path: &str, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) {
self.items(path);
let scoped = Self {
json: Rc::clone(&self.json),
outline: Rc::clone(&self.outline),
scope: Scope::at(self.full_path(path)),
};
assertions(&scoped);
scoped.assert_interacted();
}
#[track_caller]
fn assert_interacted(&self) {
if self.scope.etc.get() {
return;
}
let entries = descend(&self.json, &self.scope.path).and_then(entries);
let interacted = self.scope.interacted.borrow();
let unexpected: Vec<String> = entries
.unwrap_or_default()
.into_iter()
.filter(|(key, _)| !interacted.contains(key))
.map(|(key, _)| format!("`{}`", join(&self.scope.path, &key)))
.collect();
if !unexpected.is_empty() {
self.fail(format_args!(
"unexpected keys in {}: {}. Assert on them, or call `etc()` to allow them",
self.subject(""),
unexpected.join(", ")
));
}
}
}
impl Scope {
fn at(path: String) -> Self {
Self {
path,
interacted: RefCell::default(),
etc: Cell::new(false),
}
}
}
impl fmt::Debug for AssertableJson {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AssertableJson")
.field("path", &self.scope.path)
.field("json", &descend(&self.json, &self.scope.path))
.finish()
}
}