use bson::{Bson, doc};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct Counted {
#[serde(with = "super")]
hits: i64,
}
#[cfg(feature = "regex")]
#[derive(Debug, Serialize, Deserialize)]
struct Watch {
#[serde(with = "super")]
root: String,
#[serde(with = "super")]
include: Option<regex::Regex>,
}
#[test]
fn a_field_with_a_serde_row_writes_the_bson_its_carrier_writes() {
let document = bson::serialize_to_document(&Counted { hits: 7 }).expect("the row writes");
assert_eq!(document, doc! { "hits": 7i64 });
let read: Counted = bson::deserialize_from_document(document).expect("the row reads");
assert_eq!(read.hits, 7);
}
#[cfg(feature = "regex")]
#[test]
fn a_pattern_field_round_trips_as_its_text_with_no_serde_row_anywhere() {
let watch = Watch {
root: "/media".to_owned(),
include: Some(regex::Regex::new(r"\.mp4$").expect("a pattern")),
};
let document = bson::serialize_to_document(&watch).expect("the row writes");
assert_eq!(document, doc! { "root": "/media", "include": r"\.mp4$" });
let read: Watch = bson::deserialize_from_document(document).expect("the row reads");
assert_eq!(read.root, "/media");
assert_eq!(
read.include.as_ref().map(regex::Regex::as_str),
Some(r"\.mp4$")
);
}
#[cfg(feature = "regex")]
#[test]
fn an_absent_pattern_is_a_null_in_both_directions() {
let watch = Watch {
root: "/media".to_owned(),
include: None,
};
let document = bson::serialize_to_document(&watch).expect("the row writes");
assert_eq!(document.get("include"), Some(&Bson::Null));
let read: Watch = bson::deserialize_from_document(document).expect("the row reads");
assert!(read.include.is_none());
}
#[cfg(feature = "regex")]
#[test]
fn a_stored_pattern_that_no_longer_compiles_is_refused_by_name() {
let forged = doc! { "root": "/media", "include": "a(b" };
let refused =
bson::deserialize_from_document::<Watch>(forged).expect_err("the text is not a pattern");
assert!(
refused.to_string().contains("no longer a pattern"),
"the refusal names the situation: {refused}"
);
}
#[cfg(feature = "regex")]
#[test]
fn a_pattern_key_holding_another_bson_type_names_both_aliases() {
let forged = doc! { "root": "/media", "include": 7i64 };
let refused =
bson::deserialize_from_document::<Watch>(forged).expect_err("a long is not a pattern");
let said = refused.to_string();
assert!(said.contains("long"), "it names what was found: {said}");
assert!(said.contains("string"), "it names what was stored: {said}");
}