diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2b5334e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +Git tags of this fork (`1.10.0-N`) do not follow the package version declared in `setup.py`. + +| Tag | Package version | Changes | +|---|---|---| +| `1.10.0-4` | `1.14.0` | `create_solver(parameters, strict=True)`: an undefined or `None` parameter raises a `MathJSONException` caused by `MathJSONUnresolvedParameter`. `IsDefined` implemented. `Str` and `Not` keep the `Constants` context. `extract_variables` reads the final expression of `Constants` and ignores `Str` / `Date` literals. | +| `1.10.0-3` | `1.14.0` | `Date` operator. | +| `1.10.0-2` | `1.14.0` | Comparison operators accept multiple operands. | +| `1.10.0-1` | `1.10.0` | `Rational` and `Ln` operators. | diff --git a/README.md b/README.md index 8173b50..e91acf1 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,27 @@ except MathJSONException: Left unhandled, the exception will look like `MathJSONException("Problem in Divide. ['Divide', 1, 0]. division by zero")`. +## Strict mode + +By default, a parameter that is not defined evaluates to its own name, as a string, and each operator handles that string its own way (comparisons return `False`, `Add` skips it). Use `create_solver(parameters, strict=True)` to raise instead: + +```python +from mathjson_solver import create_solver, MathJSONException + +solver = create_solver({"a": 0.7, "b": None}, strict=True) +solver(["Greater", "c", 0.6]) # MathJSONException: Parameter 'c' is not defined +solver(["Add", "a", "b"]) # MathJSONException: Parameter 'b' is None +``` + +The exception's `e` is a `MathJSONUnresolvedParameter` (a `KeyError`), and its `expr` / `construct` are the innermost expression containing the parameter. + +In strict mode: +* a parameter whose value is `None` is unresolved too; +* string values of parameters are returned as is, not resolved again as names; +* string literals must be written with `Str`: `["Str", "plasma"]` returns `"plasma"` without looking it up. Bare strings anywhere else (`Switch` cases, `In` arrays, `Strptime` formats, ...) are parameter names; +* `If`, `Map` and `HasMatchingSublist` still catch a `MathJSONException` raised by a branch or an element, as they do in the default mode. + + ## How to run tests Make sure you have `pytest` installed. Then `cd` into project directory and run: ```bash diff --git a/docs/README.md b/docs/README.md index 8049ffe..205306a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -205,6 +205,8 @@ Despite these differences, there are many cases where both `Equal` and `StrictEq _MathJSON Solver_ supports static arrays and arrays given as parameters. Arrays can contain any number of elements, including other arrays. Arrays can be used in `Max`, `Min`, `Average`, `Median`, `Length`, `Any`, `All`, `In`, `ContainsAnyOf`, `ContainsAllOf`, `ContainsNoneOf`, `NotIn`. +`Any` and `All` take a single operand, an array: `["All", ["Array", cond_a, cond_b]]`. Written as `["All", cond_a, cond_b]`, only the operands of `cond_a` are checked and `cond_b` is ignored. + A static array is defined as `["Array", 1, 2, 3]` and when evaluated, results to the same `["Array", 1, 2, 3]`. An array can also be given as a parameter. In this case, the array is defined in the parameters dictionary and referred to by its name. For example, `parameters = {"a": ["Array", 1, 2, 3]}` and then the expression `["Max", "a"]` will result in 3. diff --git a/src/mathjson_solver/__init__.py b/src/mathjson_solver/__init__.py index 97e433e..433041e 100644 --- a/src/mathjson_solver/__init__.py +++ b/src/mathjson_solver/__init__.py @@ -1,2 +1,6 @@ from .__main__ import create_mathjson_solver as create_solver -from .__main__ import MathJSONException, extract_variables +from .__main__ import ( + MathJSONException, + MathJSONUnresolvedParameter, + extract_variables, +) diff --git a/src/mathjson_solver/__main__.py b/src/mathjson_solver/__main__.py index e8ebdff..604ac21 100644 --- a/src/mathjson_solver/__main__.py +++ b/src/mathjson_solver/__main__.py @@ -29,6 +29,13 @@ def __str__(self): return f"Problem in {self.construct}. {self.expr}. {m}" +class MathJSONUnresolvedParameter(KeyError): + """A parameter is not defined, or is None, in strict mode""" + + def __str__(self): + return str(self.args[0]) + + def is_numeric(x): try: float(x) @@ -149,7 +156,17 @@ def has_sublist2( return count >= required_match_count -def create_mathjson_solver(solver_parameters): +def create_mathjson_solver(solver_parameters, strict=False): + def resolved(name, value): + if strict and value is None: + raise MathJSONUnresolvedParameter(f"Parameter '{name}' is None") + return value + + def resolve_value(value, c): + if strict and isinstance(value, str): + return value + return f(value, c) + def f(s, *args): if args: c = deepcopy(args[0]) @@ -389,7 +406,9 @@ def Contains_none_of(s): def Str(s): if len(s) < 2: raise ValueError("Wrong parameters for 'Str'") - return f"{f(s[1])}" + if strict and isinstance(s[1], str): + return s[1] + return f"{f(s[1], c)}" def Date(s): if len(s) < 2: @@ -397,7 +416,10 @@ def Date(s): return datetime.fromisoformat(s[1]) def Not(s): - return not f(s[1]) + return not f(s[1], c) + + def IsDefined(s): + return s[1] in solver_parameters or s[1] in c def Map(s): """ @@ -588,6 +610,7 @@ def safe_float(val): "Str": Str, "Date": Date, "Not": Not, + "IsDefined": IsDefined, "Map": Map, "StrictMap": StrictMap, "Filter": Filter, @@ -616,23 +639,33 @@ def safe_float(val): raise MathJSONException(e, s, mathjson_construct=s[0]) except ZeroDivisionError as e: raise MathJSONException(e, s, mathjson_construct=s[0]) + except MathJSONUnresolvedParameter as e: + raise MathJSONException(e, s, mathjson_construct=s[0]) else: # raise MathJSONException( # NotImplementedError(f"'{s[0]}' is not supported"), s # ) return s elif s in solver_parameters: + value = resolved(s, solver_parameters[s]) try: - return f(solver_parameters[s], c) + return resolve_value(value, c) except RecursionError: - return solver_parameters[s] + return value elif s in c: - return f(c[s], c) + return resolve_value(resolved(s, c[s]), c) else: - # raise KeyError(f"Parameter '{s}' is not defined") + if strict and isinstance(s, str): + raise MathJSONUnresolvedParameter(f"Parameter '{s}' is not defined") return s - return f + def solver(s, *args): + try: + return f(s, *args) + except MathJSONUnresolvedParameter as e: + raise MathJSONException(e, s, mathjson_construct="Parameter") + + return solver def extract_variables( @@ -708,7 +741,9 @@ def extract_variables( for x in s[1:-1]: ignore_list.add(x[0]) li.update(extract_variables(x[1], li, ignore_list)) - li.update(extract_variables(x[-1], li, ignore_list)) + li.update(extract_variables(s[-1], li, ignore_list)) + elif s[0] in ("Str", "Date"): + return li elif s[0] == "If": for elif_block in s[1:-1]: # s[1] is list for x in elif_block: diff --git a/tests/test_with_pytest.py b/tests/test_with_pytest.py index 4317921..cafaa99 100644 --- a/tests/test_with_pytest.py +++ b/tests/test_with_pytest.py @@ -7,7 +7,12 @@ sys.path.append(os.path.join(os.path.dirname(__file__), "../src/")) -from mathjson_solver import create_solver, MathJSONException, extract_variables +from mathjson_solver import ( + create_solver, + MathJSONException, + MathJSONUnresolvedParameter, + extract_variables, +) @pytest.mark.parametrize( @@ -646,6 +651,9 @@ def test_handle_exception(): ({"a": 5}, ["Sum", 2, "a", 3], set()), ({"a": 5, "b": 6}, ["Sum", 2, "a", "c"], set(["c"])), ({}, ["Constants", ["c", 1], ["d", ["Add", 2, "a"]], "d"], set(["a"])), + ({}, ["Constants", ["x", 5], ["Add", "x", "y"]], set(["y"])), + ({}, ["Equal", "a", ["Str", "NEEDS_REVIEW"]], set(["a"])), + ({}, ["Less", "a", ["Date", "2026-01-01"]], set(["a"])), # Now with "ugly" variables that mimic the ones used for deep referencing. ( {}, @@ -682,3 +690,86 @@ def test_extract_variables(parameters, expression, expected_result): ) == expected_result ) + + +@pytest.mark.parametrize( + "parameters, expression, expected_result", + [ + ({"a": 3000}, ["Add", "a", "b"], 3000.0), + ({}, ["Add", "a", "b"], "ab"), + ({"a": 1, "b": None}, ["Add", "a", "b"], 1.0), + ({}, ["Greater", "a", 0.6], False), + ({"a": None}, ["Greater", "a", 0.6], False), + ({"color": "green"}, ["Switch", "undefined", 0, ["blue", 10]], 0), + ({}, "a", "a"), + ], +) +def test_unresolved_parameter_is_permissive_by_default( + parameters, expression, expected_result +): + assert create_solver(parameters)(expression) == expected_result + + +@pytest.mark.parametrize( + "parameters, expression, construct, message", + [ + ({"a": 3000}, ["Add", "a", "b"], "Add", "Parameter 'b' is not defined"), + ({"a": 1, "b": None}, ["Add", "a", "b"], "Add", "Parameter 'b' is None"), + ({}, ["Greater", "a", 0.6], "Greater", "Parameter 'a' is not defined"), + ({"a": None}, ["Less", "a", 0.6], "Less", "Parameter 'a' is None"), + ({"a": 2}, ["Multiply", "a", "b"], "Multiply", "Parameter 'b' is not defined"), + ( + {"a": 0.7}, + ["All", ["Array", ["Greater", "a", 0.6], ["Less", "b", 1]]], + "Less", + "Parameter 'b' is not defined", + ), + ({}, "a", "Parameter", "Parameter 'a' is not defined"), + ], +) +def test_unresolved_parameter_raises_in_strict_mode( + parameters, expression, construct, message +): + with pytest.raises(MathJSONException) as exc_info: + create_solver(parameters, strict=True)(expression) + exception = exc_info.value + assert isinstance(exception.e, MathJSONUnresolvedParameter) + assert str(exception.e) == message + assert exception.construct == construct + + +def test_unresolved_parameter_reports_innermost_expression(): + with pytest.raises(MathJSONException) as exc_info: + create_solver({"a": 0.7}, strict=True)( + ["Add", 1, ["Multiply", "a", "b"]] + ) + assert exc_info.value.expr == ["Multiply", "a", "b"] + + +@pytest.mark.parametrize( + "parameters, expression, expected_result", + [ + ({"a": 0.7}, ["Greater", "a", 0.6], True), + ({"a": 0}, ["Add", "a", 1], 1.0), + ({"a": False}, ["Not", "a"], True), + ({"matrix": "plasma"}, ["Equal", "matrix", ["Str", "plasma"]], True), + ({"plasma": 1}, ["Str", "plasma"], "plasma"), + ({}, ["Constants", ["x", 5], ["Add", "x", 1]], 6.0), + ({}, ["Constants", ["x", 0], ["Not", "x"]], True), + ({}, ["Date", "2026-01-01"], datetime(2026, 1, 1)), + ], +) +def test_strict_mode_resolved_expressions(parameters, expression, expected_result): + assert create_solver(parameters, strict=True)(expression) == expected_result + + +@pytest.mark.parametrize( + "parameters, expected_result", + [({"a": 0.7}, True), ({"a": None}, True), ({}, False)], +) +def test_is_defined(parameters, expected_result): + assert create_solver(parameters)(["IsDefined", "a"]) == expected_result + assert ( + create_solver(parameters, strict=True)(["IsDefined", "a"]) + == expected_result + )