helm-rs 0.1.0

Typed Rust API for Helm 4: swappable backends, native chart, values and release reading
Documentation
//! A scriptable backend for tests of code built on helm-rs.
//!
//! ```
//! use helm_rs::{Helm, command::Env, mock::Mock};
//!
//! # #[tokio::main(flavor = "current_thread")]
//! # async fn main() {
//! let mock = Mock::new().on::<Env>(|options, _| {
//!     let namespace = options.namespace.clone().unwrap_or_default();
//!
//!     Ok([("HELM_NAMESPACE".to_owned(), namespace)].into())
//! });
//! let helm = Helm::new(mock).with_namespace("prod");
//! let env = helm.run(Env).await.expect("mock env");
//!
//! assert_eq!(env["HELM_NAMESPACE"], "prod");
//! assert_eq!(helm.backend().calls::<Env>().len(), 1);
//! # }
//! ```

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>;

/// A backend whose behaviour is registered per command type with [`Mock::on`]. It records every
/// command it receives; commands without a handler fail with [`Error::Unsupported`].
#[derive(Default)]
pub struct Mock {
    handlers: HashMap<TypeId, Handler>,
    calls: Mutex<Vec<(TypeId, Box<dyn Any + Send>)>>,
}

impl Mock {
    /// An empty mock.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers the handler for command type `C`, replacing an earlier one.
    #[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
    }

    /// The commands of type `C` received so far, in order.
    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;