Skip to main content

helm_rs/mock/
mod.rs

1//! A scriptable backend for tests of code built on helm-rs.
2//!
3//! ```
4//! use helm_rs::{Helm, command::Env, mock::Mock};
5//!
6//! # #[tokio::main(flavor = "current_thread")]
7//! # async fn main() {
8//! let mock = Mock::new().on::<Env>(|options, _| {
9//!     let namespace = options.namespace.clone().unwrap_or_default();
10//!
11//!     Ok([("HELM_NAMESPACE".to_owned(), namespace)].into())
12//! });
13//! let helm = Helm::new(mock).with_namespace("prod");
14//! let env = helm.run(Env).await.expect("mock env");
15//!
16//! assert_eq!(env["HELM_NAMESPACE"], "prod");
17//! assert_eq!(helm.backend().calls::<Env>().len(), 1);
18//! # }
19//! ```
20
21use 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/// A backend whose behaviour is registered per command type with [`Mock::on`]. It records every
33/// command it receives; commands without a handler fail with [`Error::Unsupported`].
34#[derive(Default)]
35pub struct Mock {
36    handlers: HashMap<TypeId, Handler>,
37    calls: Mutex<Vec<(TypeId, Box<dyn Any + Send>)>>,
38}
39
40impl Mock {
41    /// An empty mock.
42    #[must_use]
43    pub fn new() -> Self {
44        Self::default()
45    }
46
47    /// Registers the handler for command type `C`, replacing an earlier one.
48    #[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    /// The commands of type `C` received so far, in order.
65    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;