use bson::{Binary, Bson, doc, spec::BinarySubtype};
use super::{MongoExtract, field};
use crate::{
BeI128, BeU64, BeU128, Count, Score,
comparison::mongo::MongoCarrier,
query::mongo::{MongoExtractionError, MongoTypeError},
};
fn round_trip<T>(value: T)
where
T: MongoCarrier + MongoExtract + core::fmt::Debug + PartialEq,
{
let written = value.to_bson();
assert_eq!(T::extract(Some(&written)), Ok(value), "wrote {written:?}");
}
#[test]
fn every_storage_type_round_trips_through_its_own_bson() {
round_trip(true);
round_trip(false);
round_trip(-1i8);
round_trip(-300i16);
round_trip(i32::MIN);
round_trip(i64::MIN);
round_trip(255u8);
round_trip(u16::MAX);
round_trip(u32::MAX);
round_trip(0.5f32);
round_trip(f64::MIN);
round_trip("a red car".to_owned());
round_trip(vec![1u8, 2, 3]);
round_trip(Score::new(0.25).expect("in range"));
round_trip(BeU64(u64::MAX));
round_trip(BeU128(u128::MAX));
round_trip(BeI128(i128::MIN));
round_trip(Count::new(0));
round_trip(Count::new(7));
round_trip(Count::new(i64::MAX.unsigned_abs()));
round_trip(crate::Timestamp::MIN);
round_trip(crate::Timestamp::MAX);
round_trip(crate::Timestamp::UNIX_EPOCH);
round_trip::<crate::Timestamp>("2026-08-09T21:14:03.123456789Z".parse().unwrap());
round_trip::<crate::Timestamp>("1969-12-31T23:59:58.5Z".parse().unwrap());
}
#[test]
fn a_negative_count_is_refused_rather_than_reinterpreted() {
assert_eq!(
Count::extract(Some(&Bson::Int64(-1))),
Err(MongoTypeError::Range(super::NEGATIVE))
);
assert_eq!(
Count::extract(Some(&Bson::Int64(i64::MIN))),
Err(MongoTypeError::Range(super::NEGATIVE))
);
assert_eq!(
Count::extract(Some(&Bson::Int64(i64::MAX))),
Ok(Count::new(i64::MAX.unsigned_abs()))
);
}
#[test]
fn a_small_u32_is_stored_and_read_as_a_long() {
assert_eq!(7u32.to_bson(), Bson::Int64(7));
assert_eq!(u32::extract(Some(&Bson::Int64(7))), Ok(7));
assert_eq!(
u32::extract(Some(&Bson::Int32(7))),
Err(MongoTypeError::wrong_type("long", "int"))
);
}
#[test]
fn a_missing_field_and_a_null_are_one_answer() {
assert_eq!(<Option<i64>>::extract(None), Ok(None));
assert_eq!(<Option<i64>>::extract(Some(&Bson::Null)), Ok(None));
assert_eq!(<Option<i64>>::extract(Some(&Bson::Int64(7))), Ok(Some(7)));
}
#[test]
fn a_required_field_refuses_both_absences_by_name() {
assert_eq!(i64::extract(None), Err(MongoTypeError::Absent));
assert_eq!(
i64::extract(Some(&Bson::Null)),
Err(MongoTypeError::wrong_type("long", "null"))
);
}
#[test]
fn a_type_mismatch_names_the_alias_the_query_language_uses() {
assert_eq!(
String::extract(Some(&Bson::Int32(7))),
Err(MongoTypeError::wrong_type("string", "int"))
);
assert_eq!(
i64::extract(Some(&Bson::Document(doc! {}))),
Err(MongoTypeError::wrong_type("long", "object"))
);
assert_eq!(
i64::extract(Some(&Bson::Document(doc! {})))
.expect_err("an object is not a long")
.to_string(),
"this field holds a object where a long was stored"
);
}
#[test]
fn a_narrowing_integer_is_refused_rather_than_truncated() {
assert_eq!(i8::extract(Some(&Bson::Int32(300))), Err(range()));
assert_eq!(u8::extract(Some(&Bson::Int32(-1))), Err(range()));
assert_eq!(u16::extract(Some(&Bson::Int32(-1))), Err(range()));
assert_eq!(u32::extract(Some(&Bson::Int64(-1))), Err(range()));
assert_eq!(i8::extract(Some(&Bson::Int32(127))), Ok(127));
}
#[test]
fn a_double_that_no_f32_wrote_is_refused() {
assert_eq!(f32::extract(Some(&Bson::Double(0.5))), Ok(0.5));
assert_eq!(f32::extract(Some(&Bson::Double(0.1))), Err(range()));
}
#[test]
fn a_nan_survives_the_narrowing_check() {
let written = f32::NAN.to_bson();
assert!(
f32::extract(Some(&written))
.expect("a NaN is a float")
.is_nan()
);
}
#[test]
fn a_score_outside_its_range_is_refused() {
assert_eq!(
Score::extract(Some(&Bson::Double(2.0))),
Err(MongoTypeError::Range(super::DOMAIN))
);
}
#[test]
fn a_blob_of_the_wrong_width_is_refused() {
let short = Bson::Binary(Binary {
subtype: BinarySubtype::Generic,
bytes: vec![1, 2, 3],
});
assert_eq!(
BeU64::extract(Some(&short)),
Err(MongoTypeError::Range(super::WIDTH))
);
}
#[test]
fn a_blob_of_another_subtype_is_not_this_column() {
let uuid = Bson::Binary(Binary {
subtype: BinarySubtype::Uuid,
bytes: vec![0; 16],
});
assert_eq!(
BeU128::extract(Some(&uuid)),
Err(MongoTypeError::wrong_type("binData", "binData"))
);
}
#[test]
fn the_field_wrapper_names_the_key_on_every_failure() {
let document = doc! { "title": "a red car" };
assert_eq!(
field::<i64>(&document, "title"),
Err(MongoExtractionError::new(
"title",
MongoTypeError::wrong_type("long", "string")
))
);
assert_eq!(
field::<i64>(&document, "score"),
Err(MongoExtractionError::new("score", MongoTypeError::Absent))
);
assert_eq!(
field::<String>(&document, "title"),
Ok("a red car".to_owned())
);
}
fn range() -> MongoTypeError {
MongoTypeError::Range(super::NARROW)
}
#[test]
fn an_instant_refuses_a_sub_document_that_is_not_a_pair() {
use crate::Timestamp;
let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
assert_eq!(
Timestamp::extract(Some(
&doc! { "secs": 1_786_310_043i64, "nanos": 123_456_789i32 }.into()
)),
Ok(at)
);
assert_eq!(
Timestamp::extract(Some(&Bson::Int64(1_786_310_043))),
Err(MongoTypeError::wrong_type("object", "long"))
);
assert!(matches!(
Timestamp::extract(Some(&doc! { "secs": 1i64, "nanos": 1i64 }.into())),
Err(MongoTypeError::Range(_))
));
assert!(matches!(
Timestamp::extract(Some(&doc! { "secs": 1i64 }.into())),
Err(MongoTypeError::Range(_))
));
assert!(matches!(
Timestamp::extract(Some(
&doc! { "secs": 2i64, "nanos": -999_999_999i32 }.into()
)),
Err(MongoTypeError::Range(_))
));
assert_eq!(Timestamp::extract(None), Err(MongoTypeError::Absent));
assert_eq!(Option::<Timestamp>::extract(None), Ok(None));
}
#[test]
fn an_instants_refusal_names_its_field() {
use crate::Timestamp;
let document = doc! { "at": { "secs": 2i64, "nanos": -999_999_999i32 } };
let refused = field::<Timestamp>(&document, "at").expect_err("the pair is not an instant");
assert_eq!(refused.field(), "at");
}