use std::{cell::RefCell, rc::Rc};
use crate::{
call_range::CallRange,
expectation::{DynExpectation, Expectation},
matcher::Matcher,
};
#[derive(Clone)]
pub struct Sequence(Rc<RefCell<SequenceState>>);
struct SequenceState {
steps: Vec<Box<dyn DynExpectation>>,
current_step: usize,
strict: bool,
}
impl Sequence {
pub fn new() -> Self {
Self(Rc::new(RefCell::new(SequenceState {
steps: Vec::new(),
current_step: 0,
strict: false,
})))
}
pub fn new_strict() -> Self {
Self(Rc::new(RefCell::new(SequenceState {
steps: Vec::new(),
current_step: 0,
strict: true,
})))
}
pub fn id(&self) -> *const () {
Rc::as_ptr(&self.0).cast::<()>()
}
pub fn append_expectation<M: Matcher>(&mut self, expectation: Expectation<M>) {
self.0.borrow_mut().steps.push(Box::new(expectation));
}
pub fn record_call<M: Matcher>(&self, params: &M::Params<'_>) {
let mut state = self.0.borrow_mut();
let Some(offset) = state.steps[state.current_step..]
.iter()
.position(|expectation| {
if let Some(expectation) = expectation.as_any().downcast_ref::<Expectation<M>>() {
expectation.matches(params)
} else {
false
}
})
else {
return;
};
let matched_step = state.current_step + offset;
let blocked_steps: Vec<usize> = state.steps[state.current_step..matched_step]
.iter()
.enumerate()
.filter_map(|(i, step)| {
if !step.is_advancable() {
Some(state.current_step + i)
} else {
None
}
})
.collect();
if !blocked_steps.is_empty() {
if state.strict {
let details = blocked_steps
.iter()
.map(|&idx| {
let step = &state.steps[idx];
format!(
"{} ({} of {} calls)",
step.describe(),
step.call_count(),
step.call_range()
)
})
.collect::<Vec<_>>()
.join("; ");
panic!(
"Call out of sequence: the call matched {}, but {} not reached its minimum yet: {}",
state.steps[matched_step].describe(),
if blocked_steps.len() == 1 {
"an earlier step has"
} else {
"earlier steps have"
},
details
);
}
return;
}
state.current_step = matched_step;
state.steps[matched_step].record_match();
}
pub fn unfulfilled_steps<M: Matcher>(&self) -> Vec<(String, usize, CallRange)> {
self.0
.borrow()
.steps
.iter()
.filter_map(|step| step.as_any().downcast_ref::<Expectation<M>>())
.filter(|expectation| !expectation.is_fulfilled())
.map(|expectation| {
(
expectation.describe(),
expectation.call_count(),
expectation.call_range(),
)
})
.collect()
}
}
impl Default for Sequence {
fn default() -> Self {
Self::new()
}
}