1use std::any::{Any, TypeId, type_name};
22use std::collections::HashMap;
23use std::future::Future;
24use std::sync::{Mutex, PoisonError};
25
26use crate::backend::{Backend, Command, Execute};
27use crate::error::{Error, Result};
28use crate::options::GlobalOptions;
29
30type Handler = Box<dyn Fn(&GlobalOptions, &dyn Any) -> Option<Box<dyn Any + Send>> + Send + Sync>;
31
32#[derive(Default)]
35pub struct Mock {
36 handlers: HashMap<TypeId, Handler>,
37 calls: Mutex<Vec<(TypeId, Box<dyn Any + Send>)>>,
38}
39
40impl Mock {
41 #[must_use]
43 pub fn new() -> Self {
44 Self::default()
45 }
46
47 #[must_use]
49 pub fn on<C: Command>(
50 mut self,
51 handler: impl Fn(&GlobalOptions, &C) -> Result<C::Output> + Send + Sync + 'static,
52 ) -> Self {
53 let erased: Handler = Box::new(move |options, command| {
54 let command = command.downcast_ref::<C>()?;
55
56 Some(Box::new(handler(options, command)))
57 });
58
59 self.handlers.insert(TypeId::of::<C>(), erased);
60
61 self
62 }
63
64 pub fn calls<C: Command>(&self) -> Vec<C> {
66 let calls = self.calls.lock().unwrap_or_else(PoisonError::into_inner);
67
68 calls
69 .iter()
70 .filter_map(|(_, command)| command.downcast_ref::<C>().cloned())
71 .collect()
72 }
73}
74
75impl Backend for Mock {}
76
77impl<C: Command> Execute<C> for Mock {
78 fn execute(
79 &self,
80 options: &GlobalOptions,
81 command: &C,
82 ) -> impl Future<Output = Result<C::Output>> + Send {
83 self.calls
84 .lock()
85 .unwrap_or_else(PoisonError::into_inner)
86 .push((TypeId::of::<C>(), Box::new(command.clone())));
87
88 let result = self
89 .handlers
90 .get(&TypeId::of::<C>())
91 .and_then(|handler| handler(options, command))
92 .and_then(|output| output.downcast::<Result<C::Output>>().ok())
93 .map_or_else(|| Err(Error::Unsupported(type_name::<C>())), |boxed| *boxed);
94
95 std::future::ready(result)
96 }
97}
98
99#[cfg(test)]
100mod tests;