chkware / cli

Low-code API quality testing, and automation toolbox
https://chkware.com/docs/quick-start
Mozilla Public License 2.0
16 stars 4 forks source link

YAML dot-param handler and parser #325

Open 0hsn opened 3 weeks ago

0hsn commented 3 weeks ago

Create a dot-param string parser and handler for yaml keys

FX:

auth .scm=bearer: <-- parser for this
    token: <JWT>
0hsn commented 3 weeks ago

Here is a reference implementation

import abc
from typing import Any

from icecream import ic
from pydantic import BaseModel, Field, validate_call

class DotParamHandler(BaseModel, abc.ABC):    
    parameters: dict[str, Any] = Field(default_factory=dict)

    @abc.abstractmethod
    def function(self, **kwargs) -> Any:
        pass

    def execute(self) -> Any:
        return self.function(**self.parameters)

    @validate_call
    def add_param(self, name: str, value: Any) -> None:
        self.parameters[name] = value

class DotParamParser(BaseModel):
    triggers: dict[str, DotParamHandler] = Field(default_factory=dict)

    def handle(self, string: str) -> Any:
        if " ." not in string:
            raise ValueError("Not a dot-param string found.")

        parsed_string: list = string.split()
        trigger = parsed_string.pop(0)

        if trigger not in self.triggers.keys():
            raise ValueError(f"No associated function found for {trigger}.")

        for item in parsed_string:
            key, val = item.replace(".", "").split("=")

            self.triggers[trigger].add_param(key, val)

        return self.triggers[trigger].execute()

    @validate_call
    def add_trigger(self, trigger: str, handler: DotParamHandler) -> None:
        self.triggers[trigger] = handler

class VarnameHandler(DotParamHandler):

    def function(self, attr1, attr2) -> dict:
        return {"attr1": attr1, "attr2": attr2}

prs = DotParamParser()
prs.add_trigger("varname", VarnameHandler())

var1 = "varname .attr1=val1 .attr2=2"
ret = prs.handle(var1)
ic(ret)