Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make raise_on_notset default to True with environment variable override #3

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "light-rule-engine"
version = "0.5.1"
version = "1.0.0"
description = "A simple rule engine"
authors = ["Biagio Distefano <me@biagiodistefano.io>"]
readme = "README.md"
Expand Down
9 changes: 6 additions & 3 deletions src/rule_engine/rule.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import os
import re
import typing as t
from enum import Enum
Expand Down Expand Up @@ -207,11 +208,13 @@ def __init__(self, *args: "Rule", **conditions: t.Any) -> None:
The keys should be field names and the values should be dictionaries
with operator names as keys and values as values.
- the special key `__id` can be used to set the rule ID
- the special key `__raise_on_notset` can be used to raise an exception
if a field is not set in the example data and is to be evaluated.
- the special key `__raise_on_notset` can be used to override the default behavior
of raising an exception when a field is not set in the example data
"""
self._id = self._validate_id(conditions.pop("__id", str(uuid4())))
self._raise_on_notset = conditions.pop("__raise_on_notset", False)
# Default to True unless explicitly disabled via env var or override in conditions
default_raise = os.getenv("RULE_ENGINE_RAISE_ON_NOTSET", "true").lower() in ["true", "1"]
self._raise_on_notset = conditions.pop("__raise_on_notset", default_raise)
self._conditions: list[tuple[_OP, t.Union[dict[str, t.Any], "Rule"]]] = []
for arg in args:
if isinstance(arg, Rule):
Expand Down
53 changes: 46 additions & 7 deletions src/rule_engine/tests/test_rule_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,11 +237,11 @@ def test_iin_value_error(data: dict[str, t.Any], condition_value: t.Any) -> None
@pytest.mark.parametrize(
("data", "rule", "expected_result"),
[
({}, Rule(whatever__gte=3), False),
({}, Rule(name__iin=["John", "Jane"]), False),
({}, Rule(name__notset=True), True),
({"name": "Frank"}, Rule(name__notset=True), False),
({"name": "Frank"}, Rule(name__notset=False), True),
({}, Rule(whatever__gte=3, __raise_on_notset=False), False),
({}, Rule(name__iin=["John", "Jane"], __raise_on_notset=False), False),
({}, Rule(name__notset=True, __raise_on_notset=False), True),
({"name": "Frank"}, Rule(name__notset=True, __raise_on_notset=False), False),
({"name": "Frank"}, Rule(name__notset=False, __raise_on_notset=False), True),
],
)
def test_not_set(data: dict[str, t.Any], rule: Rule, expected_result: bool) -> None:
Expand All @@ -258,7 +258,7 @@ def test_raise_on_not_set() -> None:
("input_data", "expected_value", "expected_result"),
[
({"no-field-match": "not-set"}, None, False), # NOT_SET case
({"field_match": "is-set"}, "is-set", True), # Normal case
({"field_match": "is-set"}, "is-set", True), # Normal case
],
)
def test_regression_not_set_json_serialization(
Expand All @@ -267,7 +267,7 @@ def test_regression_not_set_json_serialization(
expected_result: bool,
) -> None:
"""Test that NOT_SET is properly serialized to JSON as null."""
rule = Rule(field_match__nin=["not-set"])
rule = Rule(field_match__nin=["not-set"], __raise_on_notset=False)
result = rule.evaluate(input_data)

# Test direct JSON serialization
Expand All @@ -290,3 +290,42 @@ def test_rule_json_encoder() -> None:
# Test regular object falls back to default behavior
with pytest.raises(TypeError):
encoder.default(object())


@pytest.mark.parametrize(
("env_value", "init_value", "expected_raise"),
[
("true", None, True), # Default env var behavior
("1", None, True), # Alternative true value
("false", None, False),
("", None, False),
("invalid", None, False),
("true", False, False), # Explicit override in init
("false", True, True), # Explicit override in init
],
)
def test_raise_on_notset_behavior_env_var_settings(
env_value: str, init_value: bool | None, expected_raise: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Test that _raise_on_notset respects both environment variable and explicit settings."""
monkeypatch.setenv("RULE_ENGINE_RAISE_ON_NOTSET", env_value)

rule_kwargs = {}
if init_value is not None:
rule_kwargs["__raise_on_notset"] = init_value

rule = Rule(foo="bar", **rule_kwargs)

if expected_raise:
with pytest.raises(ValueError, match="Field 'foo' is not set in the example data"):
rule.evaluate({})
else:
result = rule.evaluate({})
assert bool(result) is False


def test_raise_on_notset_behavior_no_env_var_expected_raise() -> None:
"""Test that _raise_on_notset respects both environment variable and explicit settings."""
rule = Rule(foo="bar")
with pytest.raises(ValueError, match="Field 'foo' is not set in the example data"):
rule.evaluate({})