Repository navigation
Expand file tree
/
Copy pathtest_evaluation.py
More file actions
2486 lines (2098 loc) · 78.4 KB
/
Copy pathtest_evaluation.py
File metadata and controls
2486 lines (2098 loc) · 78.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-Copyright: Copyright (c) Capital One Services, LLC
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
"""
Test all the evaluation methods.
A large number of tests exercise :py:meth:`Evaluator.evaluate`.
The approach used here may not be ideal from a unit testing perspective.
This approach tends to test the superclass :py:meth:`lark.visitors.Interpreter.visit`,
which involves re-testing a fair amount of Lark code.
The alternative is to test methods in detail. For example,
using :py:meth:`Evaluator.expr` directly with a :py:class:`lark.Tree` object and
a patch for :py:meth:`Evaluator.visit_children` to emit answers directly.
For member, primary, and literal, we take this approach of invoking the
visitor method directly.
"""
from unittest.mock import Mock, call, sentinel
import os
import lark
import pytest
# IMPORTANT: Enables the `@trace` decorator.
# Must be set prior to import.
os.environ["CEL_TRACE"] = "true"
import celpy.evaluation # Expose the name for monkeypatching
from celpy import celparser, celtypes
from celpy.evaluation import *
def test_exception_syntax_error():
with pytest.raises(CELSyntaxError) as exc_info_1:
raise CELSyntaxError(
sentinel.syntax_message, sentinel.syntax_line, sentinel.syntax_col
)
assert exc_info_1.value.args == (sentinel.syntax_message,)
assert exc_info_1.value.line == sentinel.syntax_line
assert exc_info_1.value.column == sentinel.syntax_col
def test_exception_unsupported_error():
with pytest.raises(CELUnsupportedError) as exc_info_2:
raise CELUnsupportedError(
sentinel.unsup_message, sentinel.unsup_line, sentinel.unsup_col
)
assert exc_info_2.value.args == (sentinel.unsup_message,)
assert exc_info_2.value.line == sentinel.unsup_line
assert exc_info_2.value.column == sentinel.unsup_col
def test_exception_eval_error():
mock_tree = Mock(
meta=Mock(
line=sentinel.src_line,
column=sentinel.src_col,
),
data=sentinel.data,
children=[],
)
with pytest.raises(CELEvalError) as exc_info_3:
raise CELEvalError(sentinel.eval_message, tree=mock_tree)
assert exc_info_3.value.args == (sentinel.eval_message,)
assert exc_info_3.value.line == sentinel.src_line
assert exc_info_3.value.column == sentinel.src_col
mock_token = Mock(
value=sentinel.token,
line=sentinel.src_line,
column=sentinel.src_col,
)
with pytest.raises(CELEvalError) as exc_info_4:
raise CELEvalError(sentinel.eval_message, token=mock_token)
assert exc_info_4.value.args == (sentinel.eval_message,)
assert exc_info_4.value.line == sentinel.src_line
assert exc_info_4.value.column == sentinel.src_col
ex = exc_info_4.value
assert -ex == ex
assert ex + 1 == ex
assert ex - 1 == ex
assert ex * 1 == ex
assert ex / 1 == ex
assert ex // 1 == ex
assert ex % 1 == ex
assert ex**1 == ex
assert 1 + ex == ex
assert 1 - ex == ex
assert 1 * ex == ex
assert 1 / ex == ex
assert 1 // ex == ex
assert 1 % ex == ex
assert 1**ex == ex
assert not 1 == ex
assert not ex == 1
assert ex() == ex
def test_eval_error_decorator():
@eval_error(sentinel.eval_message, TypeError)
def mock_operation(a, b):
if a == sentinel.TypeError:
raise TypeError(sentinel.type_error_message)
elif a == sentinel.OtherError:
raise ValueError(sentinel.value_error_message)
else:
return sentinel.A_OP_B
result_1 = mock_operation(sentinel.TypeError, sentinel.VALUE)
assert isinstance(result_1, CELEvalError)
assert result_1.args == (
sentinel.eval_message,
TypeError,
(sentinel.type_error_message,),
)
assert result_1.__cause__.__class__ == TypeError
with pytest.raises(ValueError) as exc_info:
result_2 = mock_operation(sentinel.OtherError, sentinel.VALUE)
assert not isinstance(exc_info.value, CELEvalError)
assert exc_info.value.args == (sentinel.value_error_message,)
result_3 = mock_operation(sentinel.A, sentinel.B)
assert result_3 == sentinel.A_OP_B
def test_boolean_decorator():
@boolean
def mock_operation(a, b):
if a == sentinel.not_implemented:
return NotImplemented
else:
return a
result_1 = mock_operation(True, sentinel.b)
assert result_1 == celtypes.BoolType(True)
result_2 = mock_operation(False, sentinel.b)
assert result_2 == celtypes.BoolType(False)
result_3 = mock_operation(sentinel.not_implemented, sentinel.b)
assert result_3 == NotImplemented
def test_operator_in():
"""
Was a separate function.
Revised with 0.4.0 release to be method of String,Type ListType, and MapType.
"""
container_1 = celtypes.ListType(
[
celtypes.IntType(42),
celtypes.IntType(6),
celtypes.IntType(7),
]
)
assert operator_in(celtypes.IntType(42), container_1)
assert not operator_in(celtypes.IntType(-1), container_1)
container_2 = celtypes.ListType(
[
celtypes.IntType(42),
celtypes.StringType("six"),
celtypes.IntType(7),
]
)
assert operator_in(celtypes.IntType(42), container_2)
assert isinstance(operator_in(celtypes.IntType(-1), container_2), CELEvalError)
@pytest.mark.skipif(
"re2" not in celpy.evaluation.function_matches.__globals__, reason="Not using RE2"
)
def test_function_matches_re2():
empty_string = celtypes.StringType("")
# re-specific patterns which behave differently than re2
assert function_matches(empty_string, "^\\z")
assert isinstance(function_matches(empty_string, "^\\Z"), CELEvalError)
@pytest.mark.skipif(
"re2" in celpy.evaluation.function_matches.__globals__, reason="Using RE2"
)
def test_function_matches_re():
empty_string = celtypes.StringType("")
# re2-specific patterns which behave differently than standard re
assert isinstance(function_matches(empty_string, "^\\z"), CELEvalError)
assert function_matches(empty_string, "^\\Z")
def test_function_matches():
empty_string = celtypes.StringType("")
assert function_matches(empty_string, "^$")
def test_function_size():
container_1 = celtypes.ListType(
[
celtypes.IntType(42),
celtypes.IntType(6),
celtypes.IntType(7),
]
)
assert function_size(container_1) == celtypes.IntType(3)
with pytest.raises(TypeError):
function_size(celtypes.DoubleType("3.14"))
assert function_size(None) == 0
def test_referent():
r_0 = Referent()
assert r_0.annotation is None
assert r_0.container is None
assert r_0.value is None
r_1 = Referent(celtypes.IntType)
assert r_1.annotation is celtypes.IntType
assert r_1.container is None
assert r_1.value is celtypes.IntType
assert r_0 != r_1
r_1.value = celtypes.IntType(42)
assert r_1.annotation is celtypes.IntType
assert r_1.container is None
assert r_1.value == celtypes.IntType(42)
nc = NameContainer()
r_1.container = nc
assert (
repr(r_1)
== f"Referent(annotation={celtypes.IntType!r}, container={nc!r}, _value={celtypes.IntType(42)!r})"
)
assert r_1.annotation is celtypes.IntType
assert r_1.container is nc
assert r_1.value == nc # preferred over the assigned value.
r_c = r_1.clone()
assert r_c == r_1
assert r_c.container == r_1.container
assert r_c.value == r_1.value
def test_name_container():
"""See fields.feature acceptance test cases for more of these."""
nc = NameContainer()
nc.load_annotations({"a.b": celtypes.MapType, "a.b.c": celtypes.StringType})
nc.load_values(
{
"a.b": celtypes.MapType({"c": celtypes.StringType("oops")}),
"a.b.c": celtypes.StringType("yeah"),
}
)
assert nc.find_name([]).value == nc
assert nc.find_name(["a", "b", "c"]).value == celtypes.StringType("yeah")
member_dot = (
nc.resolve_name("", "a")
.container.resolve_name("", "b")
.container.resolve_name("", "c")
)
assert member_dot.value == celtypes.StringType("yeah")
nc2 = NameContainer()
nc2.load_values({"answer": celtypes.IntType(42)})
with pytest.raises(TypeError):
nc2.find_name(["answer", "nope"]).value
def test_name_container_init():
nc = NameContainer("a", celtypes.MapType)
assert nc["a"] == celtypes.MapType
def test_name_container_errors():
nc = NameContainer("a", celtypes.MapType)
assert nc["a"] == celtypes.MapType
with pytest.raises(ValueError):
nc.load_annotations({"123 456": celtypes.MapType})
with pytest.raises(ValueError):
nc.load_values({"123 456": celtypes.StringType("Invalid")})
def test_activation_no_package_no_vars():
a = Activation()
with pytest.raises(KeyError):
a.resolve_variable("x")
assert a.identifiers == {}
a_n = a.nested_activation(
annotations={"x": celtypes.IntType}, vars={"x": celtypes.IntType(42)}
)
assert a_n.resolve_variable("x") == celtypes.IntType(42)
def test_activation_annotation_no_vars():
a = Activation(annotations={"answer": celtypes.IntType})
with pytest.raises(KeyError) as exc_info:
print(f"Found {a.undefined=}")
assert exc_info.value.args == ("undefined",)
def test_activation_jq_package_vars():
"""
This test pushes the envelope a on what CEL should be able to do.
The package construct is *intended* to support protobuf packages, not JSON objects.
"""
a = Activation(
annotations={"jq": celtypes.MapType},
package="jq",
vars={"jq": {celtypes.StringType("json"): celtypes.StringType("document")}},
)
# The JQ-like ``.json`` expression is resolved inside the "jq" package.
assert a.resolve_variable(celtypes.StringType("json")) == celtypes.StringType(
"document"
)
# A nested activation (inside a macro, for example)
a_n = a.nested_activation(
annotations={"x": celtypes.IntType}, vars={"x": celtypes.IntType(42)}
)
assert a_n.resolve_variable("x") == celtypes.IntType(42)
# We should see globals (in the outer context)
assert a_n.resolve_variable(celtypes.StringType("json")) == celtypes.StringType(
"document"
)
def test_activation_activation():
b = Activation(vars={celtypes.StringType("param"): celtypes.DoubleType(42.0)})
c = b.clone()
assert c.resolve_variable(celtypes.StringType("param")) == celtypes.DoubleType(42.0)
def test_activation_dot_names():
a = Activation(package="x", vars={"x.y": celtypes.DoubleType(42.0)})
assert a.resolve_variable(celtypes.StringType("y")) == celtypes.DoubleType(42.0)
with pytest.raises(KeyError):
a.resolve_variable(celtypes.StringType("z"))
def test_activation_overlapping_dot_names():
a = Activation(
annotations={
"A.B": celtypes.DoubleType,
"A.C": celtypes.BoolType,
}
)
assert isinstance(a.resolve_variable("A"), NameContainer)
print(f"{a.resolve_variable('A')!r}")
assert a.resolve_variable("A")["B"].value == celtypes.DoubleType
assert a.resolve_variable("A")["C"].value == celtypes.BoolType
def test_activation_multi_package_name():
a = Activation(
annotations={
"A.B.a": celtypes.DoubleType,
"A.B.C.a": celtypes.BoolType,
"A.B.C": celtypes.IntType, # This is ambiguous and is ignored when finding "a".
},
package="A.B.C",
)
assert a.resolve_variable("a") == celtypes.BoolType
def test_activation_bad_dot_name_syntax():
with pytest.raises(ValueError):
a = Activation(package="x", vars={"x.y+z": celtypes.DoubleType(42.0)})
@pytest.fixture
def mock_tree():
tree = Mock(name="mock_tree", data="ident", children=[Mock(value=sentinel.ident)])
return tree
def test_trace_decorator(mock_tree):
class Mock_Eval:
def __init__(self):
self.logger = Mock()
self.level = 1
@trace
def method(self, tree):
return sentinel.result
e = Mock_Eval()
result = e.method(mock_tree)
assert result == sentinel.result
assert e.logger.debug.mock_calls == [
call("%s%r", "| ", mock_tree),
call("%s%s -> %r", "| ", "ident", sentinel.result),
]
def test_set_activation():
tree = lark.Tree(data="literal", children=[])
activation = Activation(vars={"name": sentinel.value})
e_0 = Evaluator(tree, activation)
assert e_0.ident_value("name") == sentinel.value
assert e_0.ident_value("int") == celtypes.IntType
e_1 = Evaluator(ast=e_0.tree, activation=e_0.activation)
e_1.set_activation({"name": sentinel.local_value})
assert e_1.ident_value("name") == sentinel.local_value
assert e_1.ident_value("int") == celtypes.IntType
assert e_0.ident_value("name") == sentinel.value
assert e_0.ident_value("int") == celtypes.IntType
def test_function_eval_0(monkeypatch):
tree = lark.Tree(data="primary", children=[])
activation = Mock(spec=Activation, resolve_function=Mock(side_effect=KeyError))
evaluator = Evaluator(tree, activation)
unknown_function_result = evaluator.function_eval(lark.Token("IDENT", "nope"))
print(f"{unknown_function_result=}")
assert isinstance(unknown_function_result, CELEvalError)
def test_function_eval_1(monkeypatch):
tree = lark.Tree(data="primary", children=[])
activation = Mock(
spec=Activation, resolve_function=Mock(return_value=function_size)
)
evaluator = Evaluator(tree, activation)
error = CELEvalError(sentinel.message)
function_of_error_result = evaluator.function_eval(
lark.Token("IDENT", "size"), error
)
print(f"{function_of_error_result=}")
assert function_of_error_result == error
def test_function_eval_2(monkeypatch):
mock_size = Mock(side_effect=ValueError(sentinel.value))
tree = lark.Tree(data="primary", children=[])
activation = Mock(spec=Activation, resolve_function=Mock(return_value=mock_size))
evaluator = Evaluator(tree, activation)
value = evaluator.function_eval(lark.Token("IDENT", "size"))
assert isinstance(value, CELEvalError)
assert value.args[1] == ValueError, f"{value.args} != (..., ValueError, ...)"
assert value.args[2] == (sentinel.value,), (
f"{value.args} != (..., ..., (sentinel.value,))"
)
def test_function_eval_3(monkeypatch):
mock_size = Mock(side_effect=TypeError(sentinel.type))
tree = lark.Tree(data="primary", children=[])
activation = Mock(spec=Activation, resolve_function=Mock(return_value=mock_size))
evaluator = Evaluator(tree, activation)
value = evaluator.function_eval(lark.Token("IDENT", "size"))
assert isinstance(value, CELEvalError)
assert value.args[1] == TypeError, f"{value.args} != (..., TypeError, ...)"
assert value.args[2] == (sentinel.type,), (
f"{value.args} != (..., ..., (sentinel.type,))"
)
def test_method_eval_0(monkeypatch):
tree = lark.Tree(data="primary", children=[])
activation = Mock(
spec=Activation,
functions=sentinel.FUNCTIONS,
resolve_function=Mock(side_effect=KeyError),
)
evaluator = Evaluator(tree, activation)
unknown_method_result = evaluator.method_eval(None, lark.Token("IDENT", "nope"))
print(f"{unknown_method_result=}")
assert isinstance(unknown_method_result, CELEvalError)
def test_method_eval_1(monkeypatch):
tree = lark.Tree(data="primary", children=[])
activation = Mock(
spec=Activation, resolve_function=Mock(return_value=function_size)
)
evaluator = Evaluator(tree, activation)
error = CELEvalError(sentinel.message)
assert evaluator.method_eval(error, lark.Token("IDENT", "size"), None) == error
assert evaluator.method_eval(None, lark.Token("IDENT", "size"), error) == error
def test_method_eval_2(monkeypatch):
mock_function = Mock(side_effect=ValueError(sentinel.value))
tree = lark.Tree(data="primary", children=[])
activation = Mock(
spec=Activation, resolve_function=Mock(return_value=mock_function)
)
evaluator = Evaluator(tree, activation)
value = evaluator.method_eval(None, lark.Token("IDENT", "size"))
assert isinstance(value, CELEvalError)
assert value.args[1] == ValueError, f"{value.args} != (..., ValueError, ...)"
assert value.args[2] == (sentinel.value,), (
f"{value.args} != (..., ..., (sentinel.value,))"
)
def test_method_eval_3(monkeypatch):
mock_function = Mock(side_effect=TypeError(sentinel.type))
tree = lark.Tree(data="primary", children=[])
activation = Mock(
spec=Activation, resolve_function=Mock(return_value=mock_function)
)
evaluator = Evaluator(tree, activation)
value = evaluator.method_eval(None, lark.Token("IDENT", "size"))
assert isinstance(value, CELEvalError)
assert value.args[1] == TypeError, f"{value.args} != (..., TypeError, ...)"
assert value.args[2] == (sentinel.type,), (
f"{value.args} != (..., ..., (sentinel.type,))"
)
def test_macro_has_eval(monkeypatch):
visit_children = Mock(return_value=[sentinel.values])
monkeypatch.setattr(Evaluator, "visit_children", visit_children)
tree = lark.Tree(data="exprlist", children=[], meta=Mock(line=1, column=1))
evaluator_0 = Evaluator(tree, activation=Mock())
assert evaluator_0.macro_has_eval(sentinel.exprlist) == celpy.celtypes.BoolType(
True
)
# Many of the following tests all use :py:meth:`Evaluator.evaluate`.
# These will involve evaluating visit_children to evaluate "literal"
# :py:class:`lark.Tree` objects.
def test_eval_expr_1():
"""
::
expr : conditionalor ["?" conditionalor ":" expr]
"""
tree = lark.Tree(
data="expr",
children=[
lark.Tree(
data="literal",
children=[
lark.Token(type_="INT_LIT", value="42"),
],
),
],
)
activation = Mock()
evaluator = Evaluator(tree, activation)
assert evaluator.evaluate() == celtypes.IntType(42)
@pytest.fixture
def mock_left_expr_tree():
tree = lark.Tree(
data="expr",
children=[
lark.Tree(
data="literal",
children=[
lark.Token(type_="BOOL_LIT", value="true"),
],
),
lark.Tree(
data="literal",
children=[
lark.Token(type_="INT_LIT", value="6"),
],
),
sentinel.DO_NOT_EVALUATE, # Test will crash if this is evaluated
],
meta=Mock(line=1, column=1),
)
return tree
def test_eval_expr_3_left_good(mock_left_expr_tree):
"""Assert ``true ? 6 : invalid`` does not execute the invalid expression."""
activation = Mock(
resolve_function=Mock(return_value=celpy.celtypes.logical_condition)
)
evaluator = Evaluator(mock_left_expr_tree, activation)
assert evaluator.evaluate() == celtypes.IntType(6)
# assert did not crash; therefore, invalid node not touched
def test_eval_expr_3_bad_override(mock_left_expr_tree):
def bad_condition(a, b, c):
raise TypeError
activation = Mock(resolve_function=Mock(return_value=bad_condition))
evaluator = Evaluator(
mock_left_expr_tree,
activation,
)
with pytest.raises(celpy.evaluation.CELEvalError) as exc_info:
evaluator.evaluate()
assert exc_info.value.args == (
"found no matching overload for _?_:_ applied to '(<class 'celpy.celtypes.BoolType'>, <class 'celpy.celtypes.IntType'>, <class 'celpy.celtypes.BoolType'>)'",
TypeError,
(),
)
def test_eval_expr_3_bad_cond_value(mock_left_expr_tree):
def bad_condition(a, b, c):
raise celpy.evaluation.CELEvalError("Baseline Error")
activation = Mock(resolve_function=Mock(return_value=bad_condition))
evaluator = Evaluator(
mock_left_expr_tree,
activation,
)
with pytest.raises(celpy.evaluation.CELEvalError) as exc_info:
evaluator.evaluate()
print(repr(exc_info.value.args))
assert exc_info.value.args == ("Baseline Error",)
@pytest.fixture
def mock_right_expr_tree():
tree = lark.Tree(
data="expr",
children=[
lark.Tree(
data="literal",
children=[
lark.Token(type_="BOOL_LIT", value="false"),
],
),
sentinel.DO_NOT_EVALUATE, # Test will crash if this is evaluated
lark.Tree(
data="literal",
children=[
lark.Token(type_="INT_LIT", value="7"),
],
),
],
meta=Mock(line=1, column=1),
)
return tree
def test_eval_expr_3_right_good(mock_right_expr_tree):
"""Assert ``false ? invalid : 7`` does not execute the invalid expression."""
activation = Mock(resolve_function=Mock(return_value=celtypes.logical_condition))
evaluator = Evaluator(mock_right_expr_tree, activation)
assert evaluator.evaluate() == celtypes.IntType(7)
# assert did not crash; therefore, invalid node not touched
def test_eval_expr_0():
tree = lark.Tree(data="expr", children=[], meta=Mock(line=1, column=1))
activation = Mock()
evaluator = Evaluator(tree, activation)
with pytest.raises(celpy.evaluation.CELSyntaxError):
evaluator.evaluate()
def binop_1_tree(data, lit_type, lit_value):
tree = lark.Tree(
data=data,
children=[
lark.Tree(
data="literal",
children=[
lark.Token(type_=lit_type, value=lit_value),
],
),
],
)
return tree
def test_eval_conditionalor_1():
tree = binop_1_tree("conditionalor", "INT_LIT", "42")
activation = Mock()
evaluator = Evaluator(tree, activation)
assert evaluator.evaluate() == celtypes.IntType(42)
def binop_2_tree(data, lit_type, lit_value_1, lit_value_2):
tree = lark.Tree(
data=data,
children=[
lark.Tree(
data="literal",
children=[
lark.Token(type_=lit_type, value=lit_value_1),
],
),
lark.Tree(
data="literal",
children=[
lark.Token(type_=lit_type, value=lit_value_2),
],
),
],
meta=Mock(line=1, column=1),
)
return tree
def test_eval_conditionalor_2_good():
tree = binop_2_tree("conditionalor", "BOOL_LIT", "false", "true")
activation = Mock(resolve_function=Mock(return_value=celtypes.logical_or))
evaluator = Evaluator(tree, activation)
assert evaluator.evaluate() == celtypes.BoolType(True)
def test_eval_conditionalor_2_bad_override():
def bad_logical_or(a, b):
raise TypeError
tree = binop_2_tree("conditionalor", "BOOL_LIT", "false", "true")
activation = Mock(resolve_function=Mock(return_value=bad_logical_or))
evaluator = Evaluator(
tree,
activation,
# functions={"_||_": bad_logical_or}
)
with pytest.raises(celpy.evaluation.CELEvalError):
evaluator.evaluate()
def binop_broken_tree(data):
tree = lark.Tree(data=data, children=[], meta=Mock(line=1, column=1))
return tree
def test_eval_conditionalor_0():
tree = binop_broken_tree("conditionalor")
activation = Mock()
evaluator = Evaluator(tree, activation)
with pytest.raises(celpy.evaluation.CELSyntaxError):
evaluator.evaluate()
def test_eval_conditionaland_1():
tree = binop_1_tree("conditionaland", "INT_LIT", "42")
activation = Mock()
evaluator = Evaluator(tree, activation)
assert evaluator.evaluate() == celtypes.IntType(42)
def test_eval_conditionaland_2_good():
tree = binop_2_tree("conditionaland", "BOOL_LIT", "false", "true")
activation = Mock(resolve_function=Mock(return_value=celtypes.logical_and))
evaluator = Evaluator(tree, activation)
assert evaluator.evaluate() == celtypes.BoolType(False)
def test_eval_conditionaland_2_bad_override():
def bad_logical_and(a, b):
raise TypeError
tree = binop_2_tree("conditionaland", "BOOL_LIT", "false", "true")
activation = Mock(resolve_function=Mock(return_value=bad_logical_and))
evaluator = Evaluator(
tree,
activation,
)
with pytest.raises(celpy.evaluation.CELEvalError):
evaluator.evaluate()
def test_eval_conditionaland_0():
tree = binop_broken_tree("conditionaland")
activation = Mock()
evaluator = Evaluator(tree, activation)
with pytest.raises(celpy.evaluation.CELSyntaxError):
evaluator.evaluate()
# This is used to generate a number of similar binop_trees fixture values
# parent_tree_data, tree_data, lit_type, lit_value_1, lit_value_2, expected, function
binary_operator_params = [
("relation", "relation_lt", "INT_LIT", "6", "7", celtypes.BoolType(True), "_<_"),
("relation", "relation_le", "INT_LIT", "6", "7", celtypes.BoolType(True), "_<=_"),
("relation", "relation_gt", "INT_LIT", "6", "7", celtypes.BoolType(False), "_>_"),
("relation", "relation_ge", "INT_LIT", "6", "7", celtypes.BoolType(False), "_>=_"),
("relation", "relation_eq", "INT_LIT", "42", "42", celtypes.BoolType(True), "_==_"),
(
"relation",
"relation_ne",
"INT_LIT",
"42",
"42",
celtypes.BoolType(False),
"_!=_",
),
(
"relation",
"relation_in",
"STRING_LIT",
"b",
["a", "b", "c"],
celtypes.BoolType(True),
"_in_",
),
("addition", "addition_add", "INT_LIT", "40", "2", celtypes.IntType(42), "_+_"),
("addition", "addition_sub", "INT_LIT", "44", "2", celtypes.IntType(42), "_-_"),
(
"addition",
"addition_add",
"INT_LIT",
"9223372036854775807",
"1",
CELEvalError,
"_+_",
),
(
"multiplication",
"multiplication_mul",
"INT_LIT",
"6",
"7",
celtypes.IntType(42),
"_*_",
),
(
"multiplication",
"multiplication_div",
"INT_LIT",
"84",
"2",
celtypes.IntType(42),
"_/_",
),
(
"multiplication",
"multiplication_mod",
"INT_LIT",
"85",
"43",
celtypes.IntType(42),
"_%_",
),
(
"multiplication",
"multiplication_mul",
"INT_LIT",
"9223372036854775807",
"2",
CELEvalError,
"_*_",
),
("multiplication", "multiplication_div", "INT_LIT", "84", "0", CELEvalError, "_/_"),
]
@pytest.fixture(params=binary_operator_params, ids=lambda f: f[6])
def binop_trees(request):
"""Creates three binary operator trees:
- t_0 is the broken tree with no children.
This can be tested to be sure it raises a syntax error.
These should not occur normally, but the exception is provided as a debugging aid.
- t_1 is the degenerate tree with no operator and a single operand.
In the long run, an optimizer should remove these nodes.
The value is always 42.
- t_2 is the tree with two operands. The right-hand operand may be an expression list.
The expected values can be a simple value or the CELEvalError type. A test will generally
check the ``t_2`` tree against the expected value. It can also check the tree against the
exception.
The function name is used to exercise the ``t_2`` tree with a bad function binding that
raises an expected TypeError.
"""
(
parent_tree_data,
tree_data,
lit_type,
lit_value_1,
lit_value_2,
expected,
function,
) = request.param
# Broken tree.
t_0 = lark.Tree(data=parent_tree_data, children=[], meta=Mock(line=1, column=1))
# No operand tree.
t_1 = binop_1_tree(parent_tree_data, "INT_LIT", "42")
# A two-operand treee with either a simple or complex right-hand-side.
if isinstance(lit_value_2, list):
right_hand_side = lark.Tree(
data="exprlist",
children=[
lark.Tree(
data="literal", children=[lark.Token(type_=lit_type, value=expr)]
)
for expr in lit_value_2
],
)
else:
right_hand_side = lark.Tree(
data="literal",
children=[
lark.Token(type_=lit_type, value=lit_value_2),
],
)
t_2 = lark.Tree(
data=parent_tree_data,
children=[
lark.Tree(
data=tree_data,
children=[
lark.Tree(
data="literal",
children=[
lark.Token(type_=lit_type, value=lit_value_1),
],
),
lark.Token(type_="relop", value="not used"),
],
),
right_hand_side,
],
meta=Mock(line=1, column=1),
)
return t_0, t_1, t_2, expected, function
def test_binops(binop_trees):
"""
The binop_trees fixture provides three trees, an expected value, and a function name
to provide an override for.
"""
t_0, t_1, t_2, expected, function = binop_trees
activation = Mock(resolve_function=Mock(return_value=base_functions[function]))
evaluator_0 = Evaluator(t_0, activation)
with pytest.raises(celpy.evaluation.CELSyntaxError):
evaluator_0.evaluate()
evaluator_1 = Evaluator(t_1, activation)
assert evaluator_1.evaluate() == celtypes.IntType(42)
evaluator_2_g = Evaluator(t_2, activation)
if isinstance(expected, type):
with pytest.raises(expected):
evaluator_2_g.evaluate()
else:
assert evaluator_2_g.evaluate() == expected
def bad_function(a, b):
raise TypeError
activation = Mock(resolve_function=Mock(return_value=bad_function))
evaluator_2_b = Evaluator(
t_2,
activation,
)
with pytest.raises(celpy.evaluation.CELEvalError):
evaluator_2_b.evaluate()
# This is used to generate a number of similar unop_trees fixture values
# parent_tree_data, tree_data, lit_type, lit_value, ignored, expected, function
unary_operator_params = [
("unary", "unary_not", "BOOL_LIT", "true", None, celtypes.BoolType(False), "!_"),
("unary", "unary_neg", "INT_LIT", "42", None, celtypes.IntType(-42), "-_"),
("unary", "unary_neg", "INT_LIT", "-9223372036854775808", None, CELEvalError, "-_"),
]
@pytest.fixture(params=unary_operator_params, ids=lambda f: f[6])
def unop_trees(request):
"""Creates three unary operator trees:
- t_0 is the broken tree with no children.
This can be tested to be sure it raises a syntax error.
These should not occur normally, but the exception is provided as a debugging aid.
- t_1 is the degenerate tree with no operator and a single operand.
In the long run, an optimizer should remove these nodes.