use std::fmt;
use std::sync::{Arc, Mutex, PoisonError};
use navree_kernel::BoxFuture;
use crate::error::Result;
use crate::exec::ExecContext;
use crate::hooks::{Flow, HookKind, ModelEvent, ModelHook};
use crate::model::{Model, PrimaryKey};
use crate::record::Record;
#[derive(Default)]
pub struct ModelEventFake {
fired: Mutex<Vec<FiredEvent>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FiredEvent {
pub model: &'static str,
pub event: ModelEvent,
pub key: String,
}
impl ModelEventFake {
pub fn new() -> Self {
ModelEventFake::default()
}
pub fn fired(&self) -> Vec<FiredEvent> {
self.lock().clone()
}
pub fn keys<M: Model>(&self, event: ModelEvent) -> Vec<String> {
self.lock()
.iter()
.filter(|fired| fired.model == M::meta().name() && fired.event == event)
.map(|fired| fired.key.clone())
.collect()
}
pub fn clear(&self) {
self.lock().clear();
}
#[track_caller]
pub fn assert_fired<M: Model>(&self, event: ModelEvent) {
if self.keys::<M>(event).is_empty() {
panic!(
"expected {} `{event}` to fire, but it did not; fired: {}",
M::meta().name(),
self.summary()
);
}
}
#[track_caller]
pub fn assert_fired_times<M: Model>(&self, event: ModelEvent, times: usize) {
let fired = self.keys::<M>(event).len();
if fired != times {
panic!(
"expected {} `{event}` to fire {times} time(s), but it fired {fired}; fired: {}",
M::meta().name(),
self.summary()
);
}
}
#[track_caller]
pub fn assert_not_fired<M: Model>(&self, event: ModelEvent) {
let keys = self.keys::<M>(event);
if !keys.is_empty() {
panic!(
"expected {} `{event}` not to fire, but it fired for {}",
M::meta().name(),
keys.join(", ")
);
}
}
#[track_caller]
pub fn assert_nothing_fired(&self) {
if !self.lock().is_empty() {
panic!(
"expected no model event, but these fired: {}",
self.summary()
);
}
}
fn record<M: Model>(&self, event: ModelEvent, record: &Record<M>) {
self.lock().push(FiredEvent {
model: M::meta().name(),
event,
key: record.key().to_key_string(),
});
}
fn summary(&self) -> String {
let fired = self.lock();
if fired.is_empty() {
return "(nothing)".to_owned();
}
fired
.iter()
.map(|fired| format!("{} `{}` ({})", fired.model, fired.event, fired.key))
.collect::<Vec<_>>()
.join(", ")
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<FiredEvent>> {
self.fired.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl fmt::Debug for ModelEventFake {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModelEventFake")
.field("fired", &self.lock().len())
.finish()
}
}
pub(crate) struct FakeListener(pub(crate) Arc<ModelEventFake>);
impl<M: Model> ModelHook<M> for FakeListener {
fn before<'a>(
&'a self,
event: ModelEvent,
_ctx: &'a ExecContext,
record: &'a mut Record<M>,
) -> BoxFuture<'a, Result<Flow>> {
self.0.record(event, record);
Box::pin(async { Ok(Flow::Continue) })
}
fn after<'a>(
&'a self,
event: ModelEvent,
_ctx: &'a ExecContext,
record: &'a mut Record<M>,
) -> BoxFuture<'a, Result<()>> {
self.0.record(event, record);
Box::pin(async { Ok(()) })
}
fn kind(&self) -> HookKind {
HookKind::Listener
}
}