Skip to content

Commit

Permalink
feat: adds messages to rules engine and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
nf1s committed Feb 1, 2024
1 parent 7322e77 commit 43435fc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 13 deletions.
26 changes: 17 additions & 9 deletions src/rules_engine/__init__.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,28 @@
from typing import Any, Callable, TypeVar
from typing import Any, Callable, TypeVar, Optional

T = TypeVar('T')


class Rule:
def __init__(self, condition: Callable[..., bool], action: Callable[..., Any]) -> None:
def __init__(
self,
condition: Callable[..., bool],
action: Callable[..., Any],
message: Optional[str] = None,
) -> None:
self.condition = condition
self.action = action
self.message = message


class Otherwise(Rule):
def __init__(self, action):
super().__init__(when(True), action)
def __init__(self, action, message=None) -> None:
super().__init__(when(True), action, message)


class NoAction(Rule):
def __init__(self, condition):
super().__init__(condition, then(None))
def __init__(self, condition, message=None):
super().__init__(condition, then(None), message)


class RulesEngine:
Expand All @@ -25,12 +31,14 @@ def __init__(self, *rules: Rule) -> None:

def run(self, *args: Any, **kwargs: Any) -> Any:
for rule in self.rules:
if rule.condition(*args, **kwargs):
return rule.action(*args, **kwargs)
if rule.condition(*args, **kwargs, message=rule.message):
return rule.action(*args, **kwargs, message=rule.message)

def run_all(self, *args: Any, **kwargs: Any) -> list:
return [
rule.action(*args, **kwargs) for rule in self.rules if rule.condition(*args, **kwargs)
rule.action(*args, **kwargs, message=rule.message)
for rule in self.rules
if rule.condition(*args, **kwargs, message=rule.message)
]


Expand Down
6 changes: 3 additions & 3 deletions tests/test_article_completed_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@
Article = namedtuple("Article", "title price image_url stock")


def article_stock_missing(article):
def article_stock_missing(article, message):
return not article.stock


def article_price_missing(article):
def article_price_missing(article, message):
return not article.price


def article_image_missing(article):
def article_image_missing(article, message):
return not article.image_url


Expand Down
2 changes: 1 addition & 1 deletion tests/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from src.rules_engine import Rule, RulesEngine, all_, any_, not_, then, when


def raise_cannot_be_none_error(obj):
def raise_cannot_be_none_error(obj, **kwargs):
raise ValueError("cannot be None error")


Expand Down

0 comments on commit 43435fc

Please sign in to comment.