From 17e4c7ebdc091c8681e6e6549274fde68cf48c3e Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 17 May 2021 15:22:57 +0100 Subject: [PATCH] adds response checking and error handling --- calrules/rules.py | 88 +++++++++++++++++++++++++---------------------- 1 file changed, 47 insertions(+), 41 deletions(-) diff --git a/calrules/rules.py b/calrules/rules.py index 823f60f..ac96223 100644 --- a/calrules/rules.py +++ b/calrules/rules.py @@ -4,58 +4,64 @@ import rule_engine class Response(Enum): - ACCEPT = 1 - MAYBE = 2 - DECLINE = 3 - DELETE = 4 + ACCEPT = 1 + MAYBE = 2 + DECLINE = 3 + DELETE = 4 + NOOP = 5 -class Rule: - def __init__(self, pattern: str, description: str, response: Response = Response.DECLINE, *message: str): - self.pattern = pattern - self.description = description - self.response = response - self.message = message + @staticmethod + def from_str(response): + return Response[response.upper()] + +class RuleRuntimeError(Exception): + pass - self.rule = rule_engine.Rule( - pattern, - rule_engine.Context(default_value=None, regex_flags=re.IGNORECASE | re.MULTILINE) - ) +class Rule: + def __init__(self, pattern: str, description: str, response: Response = Response.DECLINE, *message: str): + self.pattern = pattern + self.description = description + self.response = response + self.message = message - def matches(self, thing: dict) -> bool: - return self.rule.matches(thing) + self.rule = rule_engine.Rule( + pattern, + rule_engine.Context(default_value=None, regex_flags=re.IGNORECASE | re.MULTILINE) + ) + def matches(self, thing: dict) -> bool: + try: + return self.rule.matches(thing) + except TypeError as e: + raise RuleRuntimeError(e) class Rules: - @classmethod - def load(rules: list[Rule]) -> None: - return Rules(rules) + def __init__(self, rules: list[dict]): + self.load(rules) - def __init__(self, rules: list[Rule]): - self.load(rules) + def __iter__(self): + return iter(self.rules) - def __iter__(self): - return iter(self.rules) + def __next__(self): + return next(self.rules) - def __next__(self): - return next(self.rules) + def __len__(self): + return len(self.rules) - def __len__(self): - return len(self.rules) + def load(self, rules: list[dict]): + _rules = [] - def load(self, rules: list[Rule]): - _rules = [] + for r in rules: + rule = Rule( + pattern=r['pattern'], + description=r['description'] + ) - for r in rules: - rule = Rule( - pattern=r['pattern'], - description=r['description'] - ) + if 'message' in r: + rule.message = r['message'] - if 'response' in r: - rule.decline = r['response'] - - if 'message' in r: - rule.decline = r['message'] + if 'response' in r: + rule.response = Response.from_str(r['response']) - _rules.append(rule) + _rules.append(rule) - self.rules = _rules \ No newline at end of file + self.rules = _rules \ No newline at end of file