use std::any::{Any, TypeId, type_name};
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Mutex, PoisonError};
use crate::backend::{Backend, Command, Execute};
use crate::error::{Error, Result};
use crate::options::GlobalOptions;
type Handler = Box<dyn Fn(&GlobalOptions, &dyn Any) -> Option<Box<dyn Any + Send>> + Send + Sync>;
#[derive(Default)]
pub struct Mock {
handlers: HashMap<TypeId, Handler>,
calls: Mutex<Vec<(TypeId, Box<dyn Any + Send>)>>,
}
impl Mock {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn on<C: Command>(
mut self,
handler: impl Fn(&GlobalOptions, &C) -> Result<C::Output> + Send + Sync + 'static,
) -> Self {
let erased: Handler = Box::new(move |options, command| {
let command = command.downcast_ref::<C>()?;
Some(Box::new(handler(options, command)))
});
self.handlers.insert(TypeId::of::<C>(), erased);
self
}
pub fn calls<C: Command>(&self) -> Vec<C> {
let calls = self.calls.lock().unwrap_or_else(PoisonError::into_inner);
calls
.iter()
.filter_map(|(_, command)| command.downcast_ref::<C>().cloned())
.collect()
}
}
impl Backend for Mock {}
impl<C: Command> Execute<C> for Mock {
fn execute(
&self,
options: &GlobalOptions,
command: &C,
) -> impl Future<Output = Result<C::Output>> + Send {
self.calls
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push((TypeId::of::<C>(), Box::new(command.clone())));
let result = self
.handlers
.get(&TypeId::of::<C>())
.and_then(|handler| handler(options, command))
.and_then(|output| output.downcast::<Result<C::Output>>().ok())
.map_or_else(|| Err(Error::Unsupported(type_name::<C>())), |boxed| *boxed);
std::future::ready(result)
}
}
#[cfg(test)]
mod tests;