#![cfg(test)]
use serde_core::de::value::{
BoolDeserializer, BytesDeserializer, Error as ValueError, SeqDeserializer, StrDeserializer,
U64Deserializer,
};
use serde_core::de::{Deserialize, DeserializeSeed, IntoDeserializer};
use serde_core::ser::Serialize;
use super::{ByteBuf, Bytes, IdentifierSeed, accept, end, require};
#[track_caller]
pub(crate) fn assert_refusal<T, E>(outcome: Result<T, E>, fragment: &str)
where
E: std::fmt::Display,
{
match outcome {
Ok(_) => panic!("expected a refusal mentioning `{fragment}`, but the value was accepted"),
Err(error) => {
let reported = error.to_string();
assert!(
reported.contains(fragment),
"refusal `{reported}` does not mention `{fragment}`"
);
}
}
}
#[track_caller]
pub(crate) fn assert_expecting<T>(fragment: &str)
where
T: for<'de> Deserialize<'de>,
{
let deserializer: BoolDeserializer<ValueError> = true.into_deserializer();
assert_refusal(T::deserialize(deserializer), fragment);
}
#[track_caller]
pub(crate) fn round_trip<T>(value: &T) -> T
where
T: Serialize + for<'de> Deserialize<'de>,
{
let encoded = serde_json::to_string(value).expect("a fixture value serializes");
serde_json::from_str(&encoded).expect("what this crate wrote, this crate reads")
}
#[track_caller]
pub(crate) fn encode<T: Serialize>(value: &T) -> String {
serde_json::to_string(value).expect("a fixture value serializes")
}
#[test]
fn an_identifier_reads_a_name_or_a_declared_position() {
let by_name: StrDeserializer<'_, ValueError> = "beta".into_deserializer();
assert_eq!(
IdentifierSeed(&["alpha", "beta"])
.deserialize(by_name)
.expect("a name is an identifier")
.0,
"beta"
);
let by_position: U64Deserializer<ValueError> = 1_u64.into_deserializer();
assert_eq!(
IdentifierSeed(&["alpha", "beta"])
.deserialize(by_position)
.expect("a declared position resolves to the name it stands for")
.0,
"beta"
);
}
#[test]
fn an_identifier_refuses_an_undeclared_position_and_a_wrong_type() {
let past_the_end: U64Deserializer<ValueError> = 2_u64.into_deserializer();
let refused = IdentifierSeed(&["alpha", "beta"])
.deserialize(past_the_end)
.map(|identifier| identifier.0)
.expect_err("a position past the declaration is not an identifier")
.to_string();
assert!(
refused.contains("a declared field or variant position"),
"{refused}"
);
let wrong_type: BoolDeserializer<ValueError> = true.into_deserializer();
let reported = IdentifierSeed(&["alpha", "beta"])
.deserialize(wrong_type)
.map(|identifier| identifier.0)
.expect_err("a boolean is not an identifier")
.to_string();
assert!(reported.contains("a field or variant name"), "{reported}");
}
#[test]
fn a_field_is_recorded_once_and_a_repeat_is_refused() {
let mut slot = None;
accept::<u8, ValueError>(&mut slot, 1, "alpha").expect("the first occurrence is recorded");
assert_eq!(slot, Some(1));
let repeated = accept::<u8, ValueError>(&mut slot, 2, "alpha")
.expect_err("a second occurrence is a malformed record, not a later value winning")
.to_string();
assert!(repeated.contains("duplicate field `alpha`"), "{repeated}");
assert_eq!(slot, Some(1), "a refused repeat left the first value alone");
}
#[test]
fn a_missing_field_is_reported_by_name() {
assert_eq!(
require::<u8, ValueError>(Some(3), "alpha").expect("a present field is returned"),
3
);
let missing = require::<u8, ValueError>(None, "beta")
.expect_err("nothing is defaulted")
.to_string();
assert!(missing.contains("missing field `beta`"), "{missing}");
}
#[test]
fn a_struct_sequence_must_end_after_its_declared_fields() {
let mut exact = SeqDeserializer::<_, ValueError>::new(Vec::<u8>::new().into_iter());
end(&mut exact, 2).expect("no undeclared field remains");
let mut trailing = SeqDeserializer::<_, ValueError>::new([7_u8].into_iter());
let error = end(&mut trailing, 2)
.expect_err("an undeclared positional field is malformed")
.to_string();
assert!(error.contains("invalid length 3"), "{error}");
assert!(
error.contains("exactly the declared struct fields"),
"{error}"
);
assert_refusal(
serde_json::from_str::<crate::audit::Event>(r#"["kind",null,true]"#),
"invalid length 3",
);
}
#[test]
fn a_byte_string_reads_from_every_shape_a_format_offers() {
assert_eq!(
ByteBuf::deserialize(BytesDeserializer::<ValueError>::new(&[1, 2]))
.expect("a format that carries byte strings hands one over")
.0
.as_ref(),
[1, 2]
);
assert_eq!(
serde_json::from_str::<ByteBuf>("[3,4]")
.expect("a JSON writer renders a byte string as an array of integers")
.0
.as_ref(),
[3, 4]
);
assert_eq!(
serde_json::from_str::<ByteBuf>("[]")
.expect("an empty byte string is still a byte string")
.0
.as_ref(),
[] as [u8; 0]
);
assert_refusal(serde_json::from_str::<ByteBuf>("{}"), "a byte string");
}
#[test]
fn bytes_are_written_as_a_byte_string() {
assert_eq!(encode(&Bytes(&[0, 255])), "[0,255]");
}
#[test]
fn an_optional_byte_string_keeps_its_presence() {
assert_eq!(
ByteBuf::into_optional(Some(ByteBuf(Box::from([1_u8].as_slice()))))
.expect("a present byte string stays present")
.as_ref(),
[1]
);
assert!(ByteBuf::into_optional(None).is_none());
}