| 1 | """Smoke tests for the feel-py bindings (mirrors the feel-wasm/feel-pg behaviour). |
| 2 | |
| 3 | Run after `maturin develop`: pytest crates/feel-py/tests |
| 4 | """ |
| 5 | |
| 6 | import datetime |
| 7 | |
| 8 | import pytest |
| 9 | from dateutil.relativedelta import relativedelta |
| 10 | |
| 11 | import feel |
| 12 | |
| 13 | |
| 14 | # --- scalars, lists, contexts --------------------------------------------- # |
| 15 | |
| 16 | def test_integer_stays_int(): |
| 17 | result = feel.evaluate("1 + 1") |
| 18 | assert result == 2 |
| 19 | assert isinstance(result, int) # not 2.0 |
| 20 | |
| 21 | |
| 22 | def test_path_access_reads_nested_context(): |
| 23 | assert feel.evaluate("p.age", {"p": {"age": 42}}) == 42 |
| 24 | |
| 25 | |
| 26 | def test_for_loop_returns_list(): |
| 27 | assert feel.evaluate("for i in [1,2,3] return i + 1") == [2, 3, 4] |
| 28 | |
| 29 | |
| 30 | def test_context_literal_returns_dict(): |
| 31 | assert feel.evaluate("{a: 1, b: a + 1}") == {"a": 1, "b": 2} |
| 32 | |
| 33 | |
| 34 | # --- lenient / strict null (ADR-14) --------------------------------------- # |
| 35 | |
| 36 | def test_type_error_is_lenient_none(): |
| 37 | assert feel.evaluate("1 + true") is None |
| 38 | |
| 39 | |
| 40 | def test_strict_raises_on_error_null(): |
| 41 | with pytest.raises(feel.FeelError): |
| 42 | feel.evaluate_strict("1 + true") |
| 43 | |
| 44 | |
| 45 | def test_strict_passes_plain_null(): |
| 46 | assert feel.evaluate_strict("null") is None |
| 47 | |
| 48 | |
| 49 | def test_parse_error_raises(): |
| 50 | with pytest.raises(feel.FeelError): |
| 51 | feel.compile("1 +") |
| 52 | |
| 53 | |
| 54 | # --- temporal mapping (ADR-18) -------------------------------------------- # |
| 55 | |
| 56 | def test_date_maps_to_date(): |
| 57 | assert feel.evaluate("date(2017, 8, 3)") == datetime.date(2017, 8, 3) |
| 58 | |
| 59 | |
| 60 | def test_days_time_duration_maps_to_timedelta(): |
| 61 | assert feel.evaluate('duration("P3D")') == datetime.timedelta(days=3) |
| 62 | |
| 63 | |
| 64 | def test_years_months_duration_maps_to_relativedelta(): |
| 65 | assert feel.evaluate('duration("P1Y2M")') == relativedelta(years=1, months=2) |
| 66 | |
| 67 | |
| 68 | def test_datetime_roundtrips_through_context(): |
| 69 | # A native datetime in the context comes back out as a datetime. |
| 70 | dt = datetime.datetime(2017, 8, 10, 12, 30, 0) |
| 71 | assert feel.evaluate("x", {"x": dt}) == dt |
| 72 | |
| 73 | |
| 74 | # --- regex dialect = Python `re` (ADR-16) --------------------------------- # |
| 75 | |
| 76 | def test_regex_backreference_is_python_dialect(): |
| 77 | # Backreferences exist in Python `re` but not in the Rust regex engine, so a |
| 78 | # true result proves the Python dialect is active. |
| 79 | assert feel.evaluate(r'matches("abab", "(ab)\1")') is True |
| 80 | |
| 81 | |
| 82 | def test_regex_flag_argument(): |
| 83 | assert feel.evaluate('matches("ABC", "abc", "i")') is True |
| 84 | |
| 85 | |
| 86 | def test_regex_inline_flag(): |
| 87 | assert feel.evaluate('matches("ABC", "(?i)abc")') is True |
| 88 | |
| 89 | |
| 90 | def test_regex_replace_group_reference(): |
| 91 | assert feel.evaluate('replace("abc", "(a)(b)", "$2$1")') == "bac" |
| 92 | |
| 93 | |
| 94 | # --- object context: lazy attribute access (ADR-21) ----------------------- # |
| 95 | |
| 96 | def test_dataclass_context_reads_instance_data(): |
| 97 | from dataclasses import dataclass |
| 98 | |
| 99 | @dataclass |
| 100 | class Order: |
| 101 | total: int |
| 102 | |
| 103 | assert feel.evaluate("o.total", {"o": Order(99)}) == 99 |
| 104 | |
| 105 | |
| 106 | def test_nested_object_path(): |
| 107 | from dataclasses import dataclass |
| 108 | |
| 109 | @dataclass |
| 110 | class Customer: |
| 111 | name: str |
| 112 | |
| 113 | @dataclass |
| 114 | class Order: |
| 115 | customer: Customer |
| 116 | |
| 117 | assert feel.evaluate("o.customer.name", {"o": Order(Customer("Ada"))}) == "Ada" |
| 118 | |
| 119 | |
| 120 | def test_property_fires_when_path_names_it(): |
| 121 | # Lazy access is `getattr`, so naming a property in the path evaluates it — |
| 122 | # exactly once, on access. This is the ORM lazy-load use case. |
| 123 | fired = [] |
| 124 | |
| 125 | class Row: |
| 126 | @property |
| 127 | def computed(self): |
| 128 | fired.append(True) |
| 129 | return 7 |
| 130 | |
| 131 | assert feel.evaluate("r.computed", {"r": Row()}) == 7 |
| 132 | assert fired == [True] |
| 133 | |
| 134 | |
| 135 | def test_untouched_property_is_not_fired(): |
| 136 | # Attribute-level laziness: reading one member never fires a *sibling* |
| 137 | # property — only the attributes the expression actually names are touched. |
| 138 | fired = [] |
| 139 | |
| 140 | class Row: |
| 141 | def __init__(self): |
| 142 | self.total = 5 |
| 143 | |
| 144 | @property |
| 145 | def side_effect(self): |
| 146 | fired.append(True) |
| 147 | return 1 |
| 148 | |
| 149 | assert feel.evaluate("r.total", {"r": Row()}) == 5 |
| 150 | assert fired == [] |
| 151 | |
| 152 | |
| 153 | def test_lazy_relation_loads_only_when_navigated(): |
| 154 | loads = [] |
| 155 | |
| 156 | class Address: |
| 157 | def __init__(self): |
| 158 | self.city = "Berlin" |
| 159 | |
| 160 | class Customer: |
| 161 | @property |
| 162 | def address(self): # a lazily-loaded relation (a DB hit, in real life) |
| 163 | loads.append(True) |
| 164 | return Address() |
| 165 | |
| 166 | class Order: |
| 167 | def __init__(self): |
| 168 | self.customer = Customer() |
| 169 | |
| 170 | # Navigating into the relation triggers exactly one load. |
| 171 | assert feel.evaluate("o.customer.address.city", {"o": Order()}) == "Berlin" |
| 172 | assert loads == [True] |
| 173 | # Not naming the relation triggers no load. |
| 174 | loads.clear() |
| 175 | assert feel.evaluate("o.customer", {"o": Order()}) is not None |
| 176 | assert loads == [] |
| 177 | |
| 178 | |
| 179 | # --- output pass-through (ADR-21) ----------------------------------------- # |
| 180 | |
| 181 | def test_foreign_object_result_passes_through_by_identity(): |
| 182 | # A host object that reaches the result comes back as the *same* object, not a |
| 183 | # snapshot dict — no re-traversal. |
| 184 | class Customer: |
| 185 | def __init__(self): |
| 186 | self.name = "Ada" |
| 187 | |
| 188 | c = Customer() |
| 189 | assert feel.evaluate("o", {"o": c}) is c |
| 190 | assert feel.evaluate("o.self", {"o": {"self": c}}) is c |
| 191 | |
| 192 | |
| 193 | # --- cyclic graphs need no guard in lazy mode (ADR-21) -------------------- # |
| 194 | |
| 195 | def test_self_referential_dict_terminates_via_finite_path(): |
| 196 | d = {"a": 1} |
| 197 | d["self"] = d |
| 198 | # A finite expression names a finite path, so this terminates with no guard. |
| 199 | assert feel.evaluate("x.self.self.self.a", {"x": d}) == 1 |
| 200 | # And the cyclic object passes through by identity. |
| 201 | assert feel.evaluate("x.self", {"x": d}) is d |
| 202 | |
| 203 | |
| 204 | # --- descendant `e ... name` (DMN 10.3.2.7, grammar rule 68) -------------- # |
| 205 | # |
| 206 | # Descendant recursively collects every value bound to `name` in `e` and all nested |
| 207 | # contexts. Unlike the lazy `.`, it is an *unbounded* traversal, so a cyclic Python |
| 208 | # object would loop forever without the `identity()` override (which keys on the |
| 209 | # Python object pointer, i.e. `id()`). |
| 210 | |
| 211 | def test_descendant_spec_example(): |
| 212 | assert feel.evaluate("{a: {b: {b: 1}}} ... b") == [{"b": 1}, 1] |
| 213 | |
| 214 | |
| 215 | def test_descendant_collects_across_list_of_dicts(): |
| 216 | assert feel.evaluate("[{x:1},{x:2}] ... x") == [1, 2] |
| 217 | |
| 218 | |
| 219 | def test_descendant_no_match_is_empty_list(): |
| 220 | assert feel.evaluate("{a:1} ... z") == [] |
| 221 | |
| 222 | |
| 223 | def test_descendant_descends_into_nested_object(): |
| 224 | from dataclasses import dataclass |
| 225 | |
| 226 | @dataclass |
| 227 | class Customer: |
| 228 | name: str |
| 229 | |
| 230 | @dataclass |
| 231 | class Order: |
| 232 | customer: Customer |
| 233 | |
| 234 | assert feel.evaluate("o ... name", {"o": Order(Customer("Ada"))}) == ["Ada"] |
| 235 | |
| 236 | |
| 237 | def test_descendant_terminates_on_cyclic_dict(): |
| 238 | # A self-referential dict: `next` points back to the same object (same `id()`). |
| 239 | # The visited-set (keyed on the Python pointer) breaks the back-edge after the |
| 240 | # first re-entry, so this terminates and yields a finite, non-empty list. |
| 241 | d = {"value": 42} |
| 242 | d["next"] = d |
| 243 | result = feel.evaluate("c ... value", {"c": d}) |
| 244 | assert result == [42, 42] |
| 245 | |
| 246 | |
| 247 | def test_descendant_terminates_on_cyclic_instance(): |
| 248 | # Same cycle, but via a class instance with a self-referential attribute |
| 249 | # (the realistic ORM/object-graph shape). Distinct fresh `Arc`s per access are |
| 250 | # bridged by the `id()`-based identity. |
| 251 | class Node: |
| 252 | pass |
| 253 | |
| 254 | n = Node() |
| 255 | n.value = 7 |
| 256 | n.next = n |
| 257 | assert feel.evaluate("n ... value", {"n": n}) == [7, 7] |
| 258 | |
| 259 | |
| 260 | |
| 261 | # --- compile reuse -------------------------------------------------------- # |
| 262 | |
| 263 | def test_compile_reused_across_contexts(): |
| 264 | prog = feel.compile("a + 1") |
| 265 | assert prog.evaluate({"a": 1}) == 2 |
| 266 | assert prog.evaluate({"a": 41}) == 42 |
| 267 | |
| 268 | |
| 269 | # --- special-character names (§10.3.1.6, ADR-47) --------------------------- # |
| 270 | |
| 271 | def test_special_char_name_resolves_against_scope(): |
| 272 | # `a-b` is the in-scope NAME when the dict binds it, subtraction otherwise; |
| 273 | # `a - b` is the same candidate (spaces are not part of the name). |
| 274 | assert feel.evaluate("a-b", {"a-b": 5}) == 5 |
| 275 | assert feel.evaluate("a - b", {"a-b": 5}) == 5 |
| 276 | assert feel.evaluate("a-b", {"a": 7, "b": 3}) == 4 |
| 277 | # `(a)-(b)` is the escape hatch: subtraction even when `a-b` is the name. |
| 278 | assert feel.evaluate("(a)-(b)", {"a": 7, "b": 3, "a-b": 100}) == 4 |
| 279 | # A hyphen name as a path base: `x-y.hour` fuses `x-y`, `.hour` stays a member. |
| 280 | assert feel.evaluate("x-y.hour", {"x-y": {"hour": 3}}) == 3 |
| 281 | # A member word never fuses against the root scope: `x.y-z` is (x.y) - z. |
| 282 | assert feel.evaluate("x.y-z", {"x": {"y": 10}, "z": 3, "y-z": 1}) == 7 |
| 283 | |
| 284 | |
| 285 | def test_special_char_name_resolves_host_function_from_registry(): |
| 286 | # The ambient `functions` registry is part of the parse-time scope: a call |
| 287 | # head resolves against it (third, after context and built-ins), so a |
| 288 | # hyphen-named host function is callable (ADR-47). |
| 289 | assert feel.evaluate("my-fn(2)", {}, functions={"my-fn": lambda x: x * 10}) == 20 |
| 290 | # Without the registry entry the run stays arithmetic (`my - fn(2)` -> null). |
| 291 | assert feel.evaluate("my-fn(2)", {}) is None |
| 292 | |
| 293 | |
| 294 | def test_compile_class_is_probe_free(): |
| 295 | # A compiled program pins no scope (ADR-47): `a-b` stays arithmetic, whatever |
| 296 | # the later contexts bind. Use the one-shot `evaluate` for scope resolution. |
| 297 | prog = feel.compile("a-b") |
| 298 | assert prog.evaluate({"a-b": 5}) is None |
| 299 | assert prog.evaluate({"a": 7, "b": 3}) == 4 |
| 300 | |
| 301 | |
| 302 | # --- host callables: Python functions invoked from FEEL (ADR-23) ---------- # |
| 303 | |
| 304 | def test_callable_in_context_is_invoked(): |
| 305 | # A Python callable bound in the context is invoked by name from FEEL. |
| 306 | assert feel.evaluate("f(2, 3)", {"f": lambda a, b: a + b}) == 5 |
| 307 | |
| 308 | |
| 309 | def test_named_args_become_kwargs(): |
| 310 | # FEEL named arguments map to Python keyword arguments. |
| 311 | assert feel.evaluate("f(b: 3, a: 2)", {"f": lambda a, b: a - b}) == -1 |
| 312 | |
| 313 | |
| 314 | def test_mixed_positional_and_named(): |
| 315 | # Mixed positional + named (a tolerant superset of FEEL spec rule 39): 2 - 3. |
| 316 | assert feel.evaluate("f(2, b: 3)", {"f": lambda a, b: a - b}) == -1 |
| 317 | |
| 318 | |
| 319 | def test_host_default_applies_when_arg_omitted(): |
| 320 | # feel-core does no arity check for host callables, so the host's default fills in. |
| 321 | assert feel.evaluate("f(2)", {"f": lambda a, b=10: a + b}) == 12 |
| 322 | |
| 323 | |
| 324 | def test_keyword_only_parameter(): |
| 325 | # A keyword-only parameter is reachable via the named form. |
| 326 | def f(a, *, b): |
| 327 | return a - b |
| 328 | |
| 329 | assert feel.evaluate("f(2, b: 3)", {"f": f}) == -1 |
| 330 | |
| 331 | |
| 332 | def test_host_function_receives_object_argument(): |
| 333 | # A host object passed as an argument round-trips: the function sees the |
| 334 | # original object (identity), not a snapshot. |
| 335 | class Order: |
| 336 | def __init__(self): |
| 337 | self.total = 99 |
| 338 | |
| 339 | seen = {} |
| 340 | |
| 341 | def grab(o): |
| 342 | seen["o"] = o |
| 343 | return o.total |
| 344 | |
| 345 | order = Order() |
| 346 | assert feel.evaluate("grab(o)", {"grab": grab, "o": order}) == 99 |
| 347 | assert seen["o"] is order |
| 348 | |
| 349 | |
| 350 | def test_host_function_via_registry(): |
| 351 | # The second injection path: an ambient `functions=` registry, separate from data. |
| 352 | assert feel.evaluate("add(2, 3)", functions={"add": lambda a, b: a + b}) == 5 |
| 353 | # Combined with a data context. |
| 354 | assert ( |
| 355 | feel.evaluate("add(x, 3)", {"x": 2}, functions={"add": lambda a, b: a + b}) == 5 |
| 356 | ) |
| 357 | |
| 358 | |
| 359 | def test_host_exception_is_lenient_none(): |
| 360 | # A raised exception inside the host callable becomes an error-null (-> None). |
| 361 | def boom(a): |
| 362 | raise ValueError("nope") |
| 363 | |
| 364 | assert feel.evaluate("f(1)", {"f": boom}) is None |
| 365 | |
| 366 | |
| 367 | def test_returned_callable_passes_through_by_identity(): |
| 368 | # A host callable that reaches the result is handed back as the same object. |
| 369 | f = lambda a: a |
| 370 | assert feel.evaluate("f", {"f": f}) is f |
| 371 | |
| 372 | |
| 373 | def test_context_binding_shadows_builtin(): |
| 374 | # A function-valued context binding takes precedence over a built-in of the |
| 375 | # same name (host override; ADR-23). |
| 376 | assert feel.evaluate("count(1, 2)", {"count": lambda a, b: a * b}) == 2 |
| 377 | |
| 378 | |
| 379 | # --- `instance of`: structural shape checks over Python objects (ADR-26) -- # |
| 380 | # |
| 381 | # FEEL is *structurally* typed (like TypeScript): `value instance of context<…>` |
| 382 | # asserts the value has *at least* the named fields with conforming types — it does |
| 383 | # NOT consult the Python class name (that would be `isinstance`, which is nominal and |
| 384 | # non-portable). So `instance of` is a host-agnostic "duck-typed shape" assertion. |
| 385 | |
| 386 | def test_instance_of_builtin_types(): |
| 387 | # Over native values, against the built-in types. |
| 388 | assert feel.evaluate('"foo" instance of string') is True |
| 389 | assert feel.evaluate("42 instance of number") is True |
| 390 | assert feel.evaluate("42 instance of string") is False |
| 391 | # A null is an instance only of `Null`; a type that can't be mapped -> null. |
| 392 | assert feel.evaluate("null instance of Null") is True |
| 393 | assert feel.evaluate("null instance of string") is False |
| 394 | assert feel.evaluate("42 instance of list") is None # bare `list` needs a parameter |
| 395 | |
| 396 | |
| 397 | def test_instance_of_checks_dict_shape(): |
| 398 | # The common case: a JSON-like dict. Width subtyping — extra keys are fine. |
| 399 | order = {"id": 7, "customer": "Ada"} |
| 400 | assert feel.evaluate("o instance of context<customer: string>", {"o": order}) is True |
| 401 | assert feel.evaluate( |
| 402 | "o instance of context<id: number, customer: string>", {"o": order} |
| 403 | ) is True |
| 404 | assert feel.evaluate("o instance of context<customer: number>", {"o": order}) is False |
| 405 | assert feel.evaluate("o instance of context<missing: string>", {"o": order}) is False |
| 406 | |
| 407 | |
| 408 | def test_instance_of_checks_object_shape(): |
| 409 | # A class instance is materialised from its instance ``__dict__`` for the check, |
| 410 | # so a plain dataclass works exactly like the dict above. |
| 411 | from dataclasses import dataclass |
| 412 | |
| 413 | @dataclass |
| 414 | class Person: |
| 415 | name: str |
| 416 | age: int |
| 417 | |
| 418 | p = Person("Ada", 36) |
| 419 | assert feel.evaluate("p instance of context<name: string>", {"p": p}) is True |
| 420 | assert feel.evaluate( |
| 421 | "p instance of context<name: string, age: number>", {"p": p} |
| 422 | ) is True |
| 423 | assert feel.evaluate("p instance of context<age: number>", {"p": p}) is True |
| 424 | assert feel.evaluate("p instance of context<name: number>", {"p": p}) is False |
| 425 | |
| 426 | |
| 427 | def test_instance_of_sees_instance_data_not_properties(): |
| 428 | # CAVEAT: the shape check materialises the instance ``__dict__`` (real data |
| 429 | # attributes). A computed ``@property`` is *not* part of that view — even though |
| 430 | # the FEEL dot (``r.doubled``) *does* fire it. The two paths differ on purpose: |
| 431 | # bulk materialisation for `instance of` vs. lazy attribute access for the dot. |
| 432 | class Row: |
| 433 | def __init__(self): |
| 434 | self.total = 10 |
| 435 | |
| 436 | @property |
| 437 | def doubled(self): |
| 438 | return self.total * 2 |
| 439 | |
| 440 | r = Row() |
| 441 | assert feel.evaluate("r.doubled", {"r": r}) == 20 # the dot fires the property |
| 442 | assert feel.evaluate("r instance of context<total: number>", {"r": r}) is True |
| 443 | # The property is invisible to the structural check: |
| 444 | assert feel.evaluate("r instance of context<doubled: number>", {"r": r}) is False |
| 445 | |
| 446 | |
| 447 | def test_instance_of_slots_object_is_not_introspectable(): |
| 448 | # CAVEAT: a ``__slots__`` object has no ``__dict__``, so it cannot be materialised |
| 449 | # into a context — the predicate is False (not an error). Lazy dot access still |
| 450 | # works. |
| 451 | class Point: |
| 452 | __slots__ = ("x", "y") |
| 453 | |
| 454 | def __init__(self, x, y): |
| 455 | self.x = x |
| 456 | self.y = y |
| 457 | |
| 458 | pt = Point(1, 2) |
| 459 | assert feel.evaluate("pt.x", {"pt": pt}) == 1 # the dot still works |
| 460 | assert feel.evaluate("pt instance of context<x: number>", {"pt": pt}) is False |
| 461 | |
| 462 | |
| 463 | def test_instance_of_field_may_be_null(): |
| 464 | # A *missing* field fails the check, but a field that is present and ``None`` |
| 465 | # conforms to any type — in the FEEL lattice ``Null`` is a subtype of every type. |
| 466 | # So this asserts "has a ``name`` slot (possibly null) that, when non-null, is a |
| 467 | # string", not "has a non-null string name". |
| 468 | class Person: |
| 469 | def __init__(self, name): |
| 470 | self.name = name |
| 471 | |
| 472 | assert feel.evaluate("p instance of context<name: string>", {"p": Person(None)}) is True |
| 473 | assert feel.evaluate("p instance of context<name: string>", {"p": Person("Ada")}) is True |
| 474 | |
| 475 | |
| 476 | def test_instance_of_nested_and_list_shapes(): |
| 477 | # Generics compose: ``list<…>`` over elements and nested ``context<…>``. |
| 478 | people = [{"name": "Ada"}, {"name": "Grace"}] |
| 479 | assert feel.evaluate( |
| 480 | "ps instance of list<context<name: string>>", {"ps": people} |
| 481 | ) is True |
| 482 | # One element of the wrong shape fails the whole list. |
| 483 | assert feel.evaluate( |
| 484 | "ps instance of list<context<name: number>>", {"ps": people} |
| 485 | ) is False |
| 486 | nested = {"owner": {"name": "Ada"}} |
| 487 | assert feel.evaluate( |
| 488 | "c instance of context<owner: context<name: string>>", {"c": nested} |
| 489 | ) is True |
| 490 | assert feel.evaluate( |
| 491 | "c instance of context<owner: context<name: number>>", {"c": nested} |
| 492 | ) is False |