quokka-command 0.3.0-beta.0

A new framework for building old-school fullstack web applications
Documentation
use crate::{CommandHandler, Commands, Error, Result};
use clap::Command;
use quokka_state::FromState;

#[tokio::test]
async fn test_ok() {
    #[derive(Clone)]
    struct TestState;

    struct TestHandler;

    impl<S> FromState<S> for TestHandler {
        fn from_state(_: &S) -> Self {
            Self
        }
    }

    impl CommandHandler for TestHandler {
        type Error = Error;

        fn args() -> clap::Command {
            Command::new("test-command")
        }

        async fn call(self, _: clap::ArgMatches) -> Result<()> {
            Ok(())
        }
    }

    let mut cmds = Commands::default();

    cmds.register_command::<TestHandler>();
    assert!(cmds.dispatch(TestState, ["", "test-command"]).await.is_ok());
}

#[tokio::test]
async fn test_err() {
    #[derive(Clone)]
    struct TestState;

    struct TestHandler;

    impl<S> FromState<S> for TestHandler {
        fn from_state(_: &S) -> Self {
            Self
        }
    }

    impl CommandHandler for TestHandler {
        type Error = Error;

        fn args() -> clap::Command {
            Command::new("test-command").arg(clap::arg!(<test> "Tests stuff"))
        }

        async fn call(self, args: clap::ArgMatches) -> Result<()> {
            let arg = args.get_one::<String>("test").unwrap();

            Err(Error::CommandCallError(arg.to_string()))
        }
    }

    let mut cmds = Commands::default();

    cmds.register_command::<TestHandler>();
    assert_eq!(
        cmds.dispatch(TestState, ["", "test-command", "Test"])
            .await
            .unwrap_err(),
        // The command responds with a quokka_command::Error for simplicity, which adds the "Unable to call client command: ", so we match for that too
        Error::CommandCallError("Unable to call client command: Test".to_string())
    );
}