use std::{any::Any, collections::HashMap};
use crate::{
common::generic_key::GenericKeyPart,
spy::{matcher::Matcher, spy_store::SpyStore},
};
pub trait DynSpyStore: Any {
fn name(&self) -> &str;
fn check_for_failures(&self) -> Vec<String>;
fn clear(&mut self);
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<M: Matcher> DynSpyStore for SpyStore<M> {
fn name(&self) -> &str {
SpyStore::name(self)
}
fn check_for_failures(&self) -> Vec<String> {
SpyStore::check_for_failures(self)
}
fn clear(&mut self) {
SpyStore::clear(self)
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub struct GenericSpyStore<const GENERIC_COUNT: usize> {
name: &'static str,
stores: HashMap<[GenericKeyPart; GENERIC_COUNT], Box<dyn DynSpyStore>>,
}
impl<const GENERIC_COUNT: usize> GenericSpyStore<GENERIC_COUNT> {
pub fn new(name: &'static str) -> Self {
Self {
name,
stores: HashMap::new(),
}
}
pub fn with_store_mut<M: Matcher, R>(
&mut self,
generic_keys: [GenericKeyPart; GENERIC_COUNT],
name: impl FnOnce() -> String,
f: impl FnOnce(&mut SpyStore<M>) -> R,
) -> R {
let store = self
.stores
.entry(generic_keys)
.or_insert_with(|| Box::new(SpyStore::<M>::new(name())));
let store = store.as_any_mut().downcast_mut::<SpyStore<M>>().unwrap_or_else(|| {
panic!(
"Generic spy '{}' holds a store whose matcher type does not match the generic arguments it is keyed by. This is a bug in fnmock; please report it.",
self.name
)
});
f(store)
}
pub fn assert_for(&self, generic_keys: &[GenericKeyPart; GENERIC_COUNT]) {
let Some(store) = self.stores.get(generic_keys) else {
return;
};
let failures = store.check_for_failures();
assert!(
failures.is_empty(),
"Expectation(s) of the spied function '{}' failed:\n{}",
store.name(),
failures.join("\n")
);
}
pub fn assert_all(&self) {
let mut failures: Vec<String> = Vec::new();
for store in self.stores.values() {
for failure in store.check_for_failures() {
failures.push(format!("{}: {}", store.name(), failure));
}
}
failures.sort();
assert!(
failures.is_empty(),
"Expectation(s) of the spied function '{}' failed:\n{}",
self.name,
failures.join("\n")
);
}
pub fn clear_for(&mut self, generic_keys: &[GenericKeyPart; GENERIC_COUNT]) {
let Some(store) = self.stores.get_mut(generic_keys) else {
return;
};
store.clear();
}
}
#[cfg(test)]
mod tests {
use std::{any::TypeId, fmt::Display, marker::PhantomData};
use crate::{common::generic_key::ConstValue, spy::expectation::Expectation};
use super::*;
struct TestMatcher<T> {
accepts: bool,
_phantom: PhantomData<fn() -> T>,
}
impl<T> Clone for TestMatcher<T> {
fn clone(&self) -> Self {
Self {
accepts: self.accepts,
_phantom: PhantomData,
}
}
}
impl<T> TestMatcher<T> {
fn new(accepts: bool) -> Self {
Self {
accepts,
_phantom: PhantomData,
}
}
}
impl<T> Display for TestMatcher<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "test matcher")
}
}
impl<T: 'static> Matcher for TestMatcher<T> {
type Params<'a> = (&'a T,);
fn matches(&self, _params: &Self::Params<'_>) -> bool {
self.accepts
}
}
fn type_key<T: 'static>() -> [GenericKeyPart; 1] {
[GenericKeyPart::Type(TypeId::of::<T>())]
}
#[test]
fn test_each_combination_of_generic_arguments_gets_its_own_store() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| "f::<i32>".into(),
|s| {
s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<i32>"));
s.record_call(&(&1,));
},
);
store.with_store_mut::<TestMatcher<String>, _>(
type_key::<String>(),
|| "f::<alloc::string::String>".into(),
|s| {
let expectation = Expectation::new(TestMatcher::new(true), "f::<String>");
s.add_expectation(expectation);
assert_eq!(s.check_for_failures().len(), 1);
},
);
store.assert_for(&type_key::<i32>());
}
#[test]
fn test_the_name_closure_only_runs_when_the_store_is_created() {
let mut store = GenericSpyStore::<1>::new("f");
let mut built = 0;
for _ in 0..3 {
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| {
built += 1;
"f::<i32>".into()
},
|s| s.record_call(&(&1,)),
);
}
assert_eq!(built, 1);
}
#[test]
fn test_const_generic_values_are_separate_instantiations() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
[GenericKeyPart::Const(ConstValue::new(5usize))],
|| "f::<5>".into(),
|s| s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<5>")),
);
store.assert_for(&[GenericKeyPart::Const(ConstValue::new(7usize))]);
}
#[test]
fn test_assert_for_passes_for_an_instantiation_that_was_never_touched() {
let store = GenericSpyStore::<1>::new("f");
store.assert_for(&type_key::<i32>());
store.assert_all();
}
#[test]
fn test_assert_for_ignores_another_instantiations_failure() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| "f::<i32>".into(),
|s| {
s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<i32>"));
},
);
store.with_store_mut::<TestMatcher<String>, _>(
type_key::<String>(),
|| "f::<String>".into(),
|s| s.record_call(&(&"a".to_string(),)),
);
store.assert_for(&type_key::<String>());
}
#[test]
#[should_panic(expected = "f::<i32>")]
fn test_assert_all_reports_a_failure_from_any_instantiation() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| "f::<i32>".into(),
|s| {
s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<i32>"));
},
);
store.assert_all();
}
#[test]
fn test_clear_for_removes_the_expectations_of_that_instantiation() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| "f::<i32>".into(),
|s| s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<i32>")),
);
store.clear_for(&type_key::<i32>());
store.assert_for(&type_key::<i32>());
}
#[test]
fn test_clear_for_leaves_other_instantiations_untouched() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| "f::<i32>".into(),
|s| s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<i32>")),
);
store.with_store_mut::<TestMatcher<String>, _>(
type_key::<String>(),
|| "f::<String>".into(),
|s| s.add_expectation(Expectation::new(TestMatcher::new(true), "f::<String>")),
);
store.clear_for(&type_key::<i32>());
store.with_store_mut::<TestMatcher<String>, _>(
type_key::<String>(),
|| unreachable!("the store already exists"),
|s| assert_eq!(s.check_for_failures().len(), 1),
);
}
#[test]
fn test_clear_for_resets_the_call_count_of_that_instantiation() {
let mut store = GenericSpyStore::<1>::new("f");
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| "f::<i32>".into(),
|s| {
s.set_total_call_range(1.into());
s.record_call(&(&1,));
},
);
store.clear_for(&type_key::<i32>());
store.with_store_mut::<TestMatcher<i32>, _>(
type_key::<i32>(),
|| unreachable!("the store already exists"),
|s| {
s.set_total_call_range(1.into());
s.record_call(&(&1,));
assert!(s.check_for_failures().is_empty());
},
);
}
}