use std::{any::Any, fmt::Display};
use crate::spy::{call_range::CallRange, matcher::Matcher};
#[derive(Clone)]
pub struct Expectation<M: Matcher> {
name: Option<String>,
function_name: String,
matcher: M,
call_range: CallRange,
call_count: usize,
}
impl<M: Matcher> Expectation<M> {
pub fn new(matcher: M, function_name: impl Into<String>) -> Self {
Self {
name: None,
function_name: function_name.into(),
matcher,
call_range: (1..).into(),
call_count: 0,
}
}
pub fn matches(&self, params: &M::Params<'_>) -> bool {
self.matcher.matches(params)
}
pub fn call(&mut self, params: &M::Params<'_>) {
if self.matches(params) {
self.record_match();
}
}
fn record_match(&mut self) {
self.call_count += 1;
assert!(
!self.call_range.max_exceeded(&self.call_count),
"Too many calls of the spied function '{}': expectation '{}' got {}, expected {}.",
self.function_name,
self,
self.call_count,
self.call_range
);
}
pub fn is_fulfilled(&self) -> bool {
self.call_range.contains(&self.call_count)
}
pub fn call_count(&self) -> usize {
self.call_count
}
fn is_advancable(&self) -> bool {
self.call_range.min_reached(&self.call_count)
}
pub fn call_range(&self) -> CallRange {
self.call_range
}
pub fn set_call_range(&mut self, call_range: CallRange) {
self.call_range = call_range;
}
pub fn set_name(&mut self, name: String) {
self.name = Some(name);
}
pub fn describe(&self) -> String {
format!(
"expectation '{}' of the spied function '{}'",
self, self.function_name
)
}
}
impl<M: Matcher> Display for Expectation<M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(ref name) = self.name {
write!(f, "{}", name)?;
} else {
write!(f, "{}", self.matcher)?;
}
Ok(())
}
}
pub trait DynExpectation: Any {
fn call_count(&self) -> usize;
fn call_range(&self) -> CallRange;
fn is_advancable(&self) -> bool;
fn record_match(&mut self);
fn as_any(&self) -> &dyn Any;
fn describe(&self) -> String;
}
impl<M: Matcher> DynExpectation for Expectation<M> {
fn call_count(&self) -> usize {
self.call_count()
}
fn call_range(&self) -> CallRange {
self.call_range()
}
fn is_advancable(&self) -> bool {
self.is_advancable()
}
fn record_match(&mut self) {
self.record_match();
}
fn as_any(&self) -> &dyn Any {
self
}
fn describe(&self) -> String {
Expectation::describe(self)
}
}