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 · 14.8 KB · at 90f493059be5 · raw

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