Public repository: timo / feel

Reader

An interpreter of FEEL, written in Rust, with integrations for PostgreSQL, WASM, Lua, and Python.

feel / crates / feel-py / tests / test_feel.py · 17.8 KB · at da382279c66c · raw

Outline: 84 definitions
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}, names="symbols") == 5
275
    assert feel.evaluate("a - b", {"a-b": 5}, names="symbols") == 5
276
    assert feel.evaluate("a-b", {"a": 7, "b": 3}, names="symbols") == 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}, names="symbols") == 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}}, names="symbols") == 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}, names="symbols") == 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}, names="symbols") == 20
290
    # Without the registry entry the run stays arithmetic (`my - fn(2)` -> null).
291
    assert feel.evaluate("my-fn(2)", {}, names="symbols") is None
292
293
294
def test_compile_class_is_scope_adaptive():
295
    # ADR-48: one compiled program, both readings — it follows each context.
296
    prog = feel.compile("a-b", names="symbols")
297
    assert prog.evaluate({"a-b": 5}) == 5
298
    assert prog.evaluate({"a": 7, "b": 3}) == 4
299
    # The registry is part of the compiled path's scope too.
300
    call = feel.compile("my-fn(2)", names="symbols")
301
    assert call.evaluate({}, functions={"my-fn": lambda x: x * 10}) == 20
302
    assert call.evaluate({}) is None
303
304
305
def test_names_levels_and_backticks():
306
    ctx = {"a": 7, "b": 3, "a-b": 100}
307
    assert feel.evaluate("a-b", ctx, names="symbols") == 100
308
    assert feel.evaluate("a-b", ctx) == 4  # default: quoted (ADR-48)
309
    assert feel.evaluate("a-b", ctx, names="quoted") == 4
310
    assert feel.compile("a-b", names="quoted").evaluate(ctx) == 4
311
    assert feel.evaluate("`a-b`", ctx, names="quoted") == 100
312
    assert feel.evaluate("`Profit and loss`", {"Profit and loss": 1}) == 1
313
    with pytest.raises(feel.FeelError):
314
        feel.evaluate("1", {}, names="full")
315
316
317
def test_nested_hyphen_members():
318
    # The member probe navigates lazy host objects (ADR-48).
319
    assert feel.evaluate("applicant.first-name", {"applicant": {"first-name": "Ada"}}, names="symbols") == "Ada"
320
    assert feel.evaluate("orders.unit-price", {"orders": [{"unit-price": 2}, {"unit-price": 3}]}, names="symbols") == [2, 3]
321
    assert feel.evaluate("o.items.x", {"o": {"items": [{"x": 1}, {"x": 2}]}}, names="symbols") == [1, 2]
322
323
324
# --- host callables: Python functions invoked from FEEL (ADR-23) ---------- #
325
326
def test_callable_in_context_is_invoked():
327
    # A Python callable bound in the context is invoked by name from FEEL.
328
    assert feel.evaluate("f(2, 3)", {"f": lambda a, b: a + b}) == 5
329
330
331
def test_named_args_become_kwargs():
332
    # FEEL named arguments map to Python keyword arguments.
333
    assert feel.evaluate("f(b: 3, a: 2)", {"f": lambda a, b: a - b}) == -1
334
335
336
def test_mixed_positional_and_named():
337
    # Mixed positional + named (a tolerant superset of FEEL spec rule 39): 2 - 3.
338
    assert feel.evaluate("f(2, b: 3)", {"f": lambda a, b: a - b}) == -1
339
340
341
def test_host_default_applies_when_arg_omitted():
342
    # feel-core does no arity check for host callables, so the host's default fills in.
343
    assert feel.evaluate("f(2)", {"f": lambda a, b=10: a + b}) == 12
344
345
346
def test_keyword_only_parameter():
347
    # A keyword-only parameter is reachable via the named form.
348
    def f(a, *, b):
349
        return a - b
350
351
    assert feel.evaluate("f(2, b: 3)", {"f": f}) == -1
352
353
354
def test_host_function_receives_object_argument():
355
    # A host object passed as an argument round-trips: the function sees the
356
    # original object (identity), not a snapshot.
357
    class Order:
358
        def __init__(self):
359
            self.total = 99
360
361
    seen = {}
362
363
    def grab(o):
364
        seen["o"] = o
365
        return o.total
366
367
    order = Order()
368
    assert feel.evaluate("grab(o)", {"grab": grab, "o": order}) == 99
369
    assert seen["o"] is order
370
371
372
def test_host_function_via_registry():
373
    # The second injection path: an ambient `functions=` registry, separate from data.
374
    assert feel.evaluate("add(2, 3)", functions={"add": lambda a, b: a + b}) == 5
375
    # Combined with a data context.
376
    assert (
377
        feel.evaluate("add(x, 3)", {"x": 2}, functions={"add": lambda a, b: a + b}) == 5
378
    )
379
380
381
def test_host_exception_is_lenient_none():
382
    # A raised exception inside the host callable becomes an error-null (-> None).
383
    def boom(a):
384
        raise ValueError("nope")
385
386
    assert feel.evaluate("f(1)", {"f": boom}) is None
387
388
389
def test_returned_callable_passes_through_by_identity():
390
    # A host callable that reaches the result is handed back as the same object.
391
    f = lambda a: a
392
    assert feel.evaluate("f", {"f": f}) is f
393
394
395
def test_context_binding_shadows_builtin():
396
    # A function-valued context binding takes precedence over a built-in of the
397
    # same name (host override; ADR-23).
398
    assert feel.evaluate("count(1, 2)", {"count": lambda a, b: a * b}) == 2
399
400
401
# --- `instance of`: structural shape checks over Python objects (ADR-26) -- #
402
#
403
# FEEL is *structurally* typed (like TypeScript): `value instance of context<…>`
404
# asserts the value has *at least* the named fields with conforming types — it does
405
# NOT consult the Python class name (that would be `isinstance`, which is nominal and
406
# non-portable). So `instance of` is a host-agnostic "duck-typed shape" assertion.
407
408
def test_instance_of_builtin_types():
409
    # Over native values, against the built-in types.
410
    assert feel.evaluate('"foo" instance of string') is True
411
    assert feel.evaluate("42 instance of number") is True
412
    assert feel.evaluate("42 instance of string") is False
413
    # A null is an instance only of `Null`; a type that can't be mapped -> null.
414
    assert feel.evaluate("null instance of Null") is True
415
    assert feel.evaluate("null instance of string") is False
416
    assert feel.evaluate("42 instance of list") is None  # bare `list` needs a parameter
417
418
419
def test_instance_of_checks_dict_shape():
420
    # The common case: a JSON-like dict. Width subtyping — extra keys are fine.
421
    order = {"id": 7, "customer": "Ada"}
422
    assert feel.evaluate("o instance of context<customer: string>", {"o": order}) is True
423
    assert feel.evaluate(
424
        "o instance of context<id: number, customer: string>", {"o": order}
425
    ) is True
426
    assert feel.evaluate("o instance of context<customer: number>", {"o": order}) is False
427
    assert feel.evaluate("o instance of context<missing: string>", {"o": order}) is False
428
429
430
def test_instance_of_checks_object_shape():
431
    # A class instance is materialised from its instance ``__dict__`` for the check,
432
    # so a plain dataclass works exactly like the dict above.
433
    from dataclasses import dataclass
434
435
    @dataclass
436
    class Person:
437
        name: str
438
        age: int
439
440
    p = Person("Ada", 36)
441
    assert feel.evaluate("p instance of context<name: string>", {"p": p}) is True
442
    assert feel.evaluate(
443
        "p instance of context<name: string, age: number>", {"p": p}
444
    ) is True
445
    assert feel.evaluate("p instance of context<age: number>", {"p": p}) is True
446
    assert feel.evaluate("p instance of context<name: number>", {"p": p}) is False
447
448
449
def test_instance_of_sees_instance_data_not_properties():
450
    # CAVEAT: the shape check materialises the instance ``__dict__`` (real data
451
    # attributes). A computed ``@property`` is *not* part of that view — even though
452
    # the FEEL dot (``r.doubled``) *does* fire it. The two paths differ on purpose:
453
    # bulk materialisation for `instance of` vs. lazy attribute access for the dot.
454
    class Row:
455
        def __init__(self):
456
            self.total = 10
457
458
        @property
459
        def doubled(self):
460
            return self.total * 2
461
462
    r = Row()
463
    assert feel.evaluate("r.doubled", {"r": r}) == 20  # the dot fires the property
464
    assert feel.evaluate("r instance of context<total: number>", {"r": r}) is True
465
    # The property is invisible to the structural check:
466
    assert feel.evaluate("r instance of context<doubled: number>", {"r": r}) is False
467
468
469
def test_instance_of_slots_object_is_not_introspectable():
470
    # CAVEAT: a ``__slots__`` object has no ``__dict__``, so it cannot be materialised
471
    # into a context — the predicate is False (not an error). Lazy dot access still
472
    # works.
473
    class Point:
474
        __slots__ = ("x", "y")
475
476
        def __init__(self, x, y):
477
            self.x = x
478
            self.y = y
479
480
    pt = Point(1, 2)
481
    assert feel.evaluate("pt.x", {"pt": pt}) == 1  # the dot still works
482
    assert feel.evaluate("pt instance of context<x: number>", {"pt": pt}) is False
483
484
485
def test_instance_of_field_may_be_null():
486
    # A *missing* field fails the check, but a field that is present and ``None``
487
    # conforms to any type — in the FEEL lattice ``Null`` is a subtype of every type.
488
    # So this asserts "has a ``name`` slot (possibly null) that, when non-null, is a
489
    # string", not "has a non-null string name".
490
    class Person:
491
        def __init__(self, name):
492
            self.name = name
493
494
    assert feel.evaluate("p instance of context<name: string>", {"p": Person(None)}) is True
495
    assert feel.evaluate("p instance of context<name: string>", {"p": Person("Ada")}) is True
496
497
498
def test_instance_of_nested_and_list_shapes():
499
    # Generics compose: ``list<…>`` over elements and nested ``context<…>``.
500
    people = [{"name": "Ada"}, {"name": "Grace"}]
501
    assert feel.evaluate(
502
        "ps instance of list<context<name: string>>", {"ps": people}
503
    ) is True
504
    # One element of the wrong shape fails the whole list.
505
    assert feel.evaluate(
506
        "ps instance of list<context<name: number>>", {"ps": people}
507
    ) is False
508
    nested = {"owner": {"name": "Ada"}}
509
    assert feel.evaluate(
510
        "c instance of context<owner: context<name: string>>", {"c": nested}
511
    ) is True
512
    assert feel.evaluate(
513
        "c instance of context<owner: context<name: number>>", {"c": nested}
514
    ) is False