-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcel_env_test.py
More file actions
500 lines (470 loc) · 14.3 KB
/
Copy pathcel_env_test.py
File metadata and controls
500 lines (470 loc) · 14.3 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
# Copyright 2026 Google 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
#
# https://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.
"""Tests for Env/Config.
This module contains tests for the `cel.EnvConfig` class, focusing on its
ability to be created from and serialized to YAML format.
"""
import textwrap
from typing import Any
from absl.testing import absltest
from cel_expr_python import cel
from cel_expr_python.ext import ext_bindings
from cel_expr_python.ext import ext_math
from cel_expr_python.ext import ext_optional
from cel_expr_python.ext import ext_strings
from cel.expr.conformance.proto2 import test_all_types_pb2 as test_all_types_pb
class CelEnvTest(absltest.TestCase):
def test_env_config_from_and_to_yaml(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
name: foo
container: test.container
stdlib:
exclude_macros:
- map
- filter
exclude_functions:
- name: "_+_"
extensions:
- name: math
variables:
- name: one
type_name: int
value: 1
functions:
- name: add
overloads:
- id: "add_int_int"
args:
- type_name: int
- type_name: int
return:
type_name: int
""")
yaml: str = config.to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
name: "foo"
container: "test.container"
extensions:
- name: "math"
stdlib:
exclude_macros:
- "filter"
- "map"
exclude_functions:
- name: "_+_"
variables:
- name: "one"
type_name: "int"
value: 1
functions:
- name: "add"
overloads:
- id: "add_int_int"
args:
- type_name: "int"
- type_name: "int"
return:
type_name: "int"
"""),
)
def test_invalid_yaml(self):
with self.assertRaises(Exception) as e:
cel.NewEnvConfigFromYaml(" invalid yaml")
self.assertIn(
"1:2: Invalid CEL environment config YAML\n"
+ "| invalid yaml\n"
+ "| ^",
str(e.exception),
)
def test_config_export_container(self):
env: cel.Env = cel.NewEnv(container="test.container")
yaml: str = env.config().to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
container: "test.container"
"""),
)
def test_config_export_variables(self):
config: cel.Env = cel.NewEnv(
variables={
"var_bool": cel.Type.BOOL,
"var_int": cel.Type.INT,
"var_uint": cel.Type.UINT,
"var_double": cel.Type.DOUBLE,
"var_str": cel.Type.STRING,
"var_bytes": cel.Type.BYTES,
"var_msg": cel.Type("cel.expr.conformance.proto2.TestAllTypes"),
"var_string_list": cel.Type.List(cel.Type.STRING),
"var_timestamp": cel.Type.TIMESTAMP,
"var_duration": cel.Type.DURATION,
"var_dyn_list": cel.Type.LIST,
"var_int_map": cel.Type.Map(cel.Type.INT, cel.Type.STRING),
"var_string_map": cel.Type.Map(cel.Type.STRING, cel.Type.BOOL),
"var_dyn_map": cel.Type.MAP,
"var_dyn": cel.Type.DYN,
}
)
yaml: str = config.config().to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
variables:
- name: "var_bool"
type_name: "bool"
- name: "var_bytes"
type_name: "bytes"
- name: "var_double"
type_name: "double"
- name: "var_duration"
type_name: "duration"
- name: "var_dyn"
type_name: "dyn"
- name: "var_dyn_list"
type_name: "list"
params:
- type_name: "dyn"
- name: "var_dyn_map"
type_name: "map"
params:
- type_name: "dyn"
- type_name: "dyn"
- name: "var_int"
type_name: "int"
- name: "var_int_map"
type_name: "map"
params:
- type_name: "int"
- type_name: "string"
- name: "var_msg"
type_name: "cel.expr.conformance.proto2.TestAllTypes"
- name: "var_str"
type_name: "string"
- name: "var_string_list"
type_name: "list"
params:
- type_name: "string"
- name: "var_string_map"
type_name: "map"
params:
- type_name: "string"
- type_name: "bool"
- name: "var_timestamp"
type_name: "timestamp"
- name: "var_uint"
type_name: "uint"
"""),
)
def test_config_augmented_variables(self):
config = cel.NewEnvConfigFromYaml("""
variables:
- name: "var_bool"
type_name: "bool"
""")
env: cel.Env = cel.NewEnv(
config=config,
variables={
"var_msg": cel.Type("cel.expr.conformance.proto2.TestAllTypes"),
},
)
yaml: str = env.config().to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
variables:
- name: "var_bool"
type_name: "bool"
- name: "var_msg"
type_name: "cel.expr.conformance.proto2.TestAllTypes"
"""),
)
def test_config_variable_override(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
variables:
- name: "var_bool"
type_name: "bool"
""")
with self.assertRaises(Exception) as e:
cel.NewEnv(
config=config,
variables={
"var_bool": cel.Type.INT,
},
)
self.assertIn(
"Variable 'var_bool' is already included",
str(e.exception),
)
def test_config_variable_types(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
variables:
- name: "var_bool"
type_name: "bool"
- name: "var_int"
type_name: "int"
value: 42
""")
env: cel.Env = cel.NewEnv(
config=config,
variables={
"var_msg": cel.Type("cel.expr.conformance.proto2.TestAllTypes"),
},
)
data: dict[str, Any] = {
"var_bool": True,
"var_msg": test_all_types_pb.TestAllTypes(single_string="hello"),
}
res: cel.Value = env.compile("var_bool").eval(data=data)
self.assertEqual(res.type(), cel.Type.BOOL)
self.assertTrue(res.value())
res = env.compile("var_msg.single_string").eval(data=data)
self.assertEqual(res.type(), cel.Type.STRING)
self.assertEqual(res.value(), "hello")
res = env.compile("var_int").eval(data=data)
self.assertEqual(res.type(), cel.Type.INT)
self.assertEqual(res.value(), 42)
def test_config_export_extension_version(self):
env: cel.Env = cel.NewEnv(
extensions=[
ext_math.ExtMath(0),
ext_optional.ExtOptional(1),
ext_strings.ExtStrings(2),
ext_bindings.ExtBindings(),
],
)
yaml: str = env.config().to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
extensions:
- name: "bindings"
- name: "math"
version: 0
- name: "optional"
version: 1
- name: "strings"
version: 2
"""),
)
def test_config_extension_version_out_of_range(self):
cases = [
[
lambda: ext_math.ExtMath(42),
r"'math' extension version: 42 not in range \[0, \d+\]",
],
[
lambda: ext_optional.ExtOptional(6),
r"'optional' extension version: 6 not in range \[0, \d+\]",
],
[
lambda: ext_strings.ExtStrings(18),
r"'strings' extension version: 18 not in range \[0, \d+\]",
],
]
for test_case in cases:
with self.assertRaises(Exception) as e:
cel.NewEnv(
extensions=[test_case[0]()],
)
self.assertRegex(str(e.exception), test_case[1])
def test_config_extensions(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
extensions:
- name: math
- name: strings
""")
env: cel.Env = cel.NewEnv(
config=config,
extensions=[TestCelExtension()],
)
yaml: str = env.config().to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
extensions:
- name: "math"
- name: "strings"
- name: "test_cel_extension"
"""),
)
res: cel.Value = env.compile("'%.4f'.format([math.sqrt(2)])").eval()
self.assertEqual(res.value(), "1.4142")
res = env.compile("hello('World')").eval()
self.assertEqual(res.value(), "Hello, World!")
def test_config_extension_override_same_version(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
extensions:
- name: cel.lib.ext.math
version: 1
- name: strings
version: 2
""")
env: cel.Env = cel.NewEnv(
config=config,
extensions=[ext_math.ExtMath(1), ext_strings.ExtStrings(2)],
)
res = env.compile("'%.3f'.format([math.floor(3.14)])").eval()
self.assertEqual(res.value(), "3.000")
def test_config_extension_override_different_version(self):
config = cel.NewEnvConfigFromYaml("""
extensions:
- name: math
version: 0
- name: cel.lib.ext.strings
version: 2
""")
with self.assertRaises(Exception) as e:
cel.NewEnv(
config=config,
extensions=[ext_math.ExtMath()],
)
self.assertIn(
"Extension 'math' version 0 is already included. Cannot"
" also include version 2",
str(e.exception),
)
with self.assertRaises(Exception) as e:
cel.NewEnv(
config=config,
extensions=[ext_strings.ExtStrings(1)],
)
self.assertIn(
"Extension 'cel.lib.ext.strings' version 2 is already included. Cannot"
" also include version 1",
str(e.exception),
)
def test_config_functions(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
functions:
- name: is_ok
overloads:
- id: "is_ok_string"
target:
type_name: string
return:
type_name: bool
""")
env: cel.Env = cel.NewEnv(
config=config,
functions=[
cel.FunctionDecl(
"hello",
[
cel.Overload(
"good_time_of_day",
return_type=cel.Type.STRING,
parameters=[
cel.Type.STRING,
cel.Type.STRING,
],
impl=lambda ampm, arg: (
"Good"
f" {'morning' if ampm == 'am' else 'afternoon'},"
f" {arg}!"
),
)
],
)
],
function_impls={
"is_ok_string": lambda arg: arg in ["excellent", "good", "fair"],
},
)
yaml = env.config().to_yaml()
self.assertEqual(
normalize_yaml(yaml),
normalize_yaml("""
functions:
- name: "hello"
overloads:
- id: "good_time_of_day"
args:
- type_name: "string"
- type_name: "string"
return:
type_name: "string"
- name: "is_ok"
overloads:
- id: "is_ok_string"
target:
type_name: "string"
return:
type_name: "bool"
"""),
)
res: cel.Value = env.compile("hello('am', 'Sunshine')").eval()
self.assertEqual(res.value(), "Good morning, Sunshine!")
res = env.compile("hello('pm', 'tea is served')").eval()
self.assertEqual(res.value(), "Good afternoon, tea is served!")
res = env.compile("'good'.is_ok()").eval()
self.assertTrue(res.value())
res = env.compile("'bad'.is_ok()").eval()
self.assertFalse(res.value())
def test_config_function_override(self):
config: cel.EnvConfig = cel.NewEnvConfigFromYaml("""
functions:
- name: foo
overloads:
- id: "unique_id"
""")
with self.assertRaises(Exception) as e:
cel.NewEnv(
config=config,
functions=[
cel.FunctionDecl(
"bar",
[
cel.Overload(
"unique_id",
impl=lambda: "hello",
)
],
)
],
function_impls={
"unique_id": lambda: "goodbye",
},
)
self.assertIn(
"An implementation for function overload id 'unique_id' already"
" exists.",
str(e.exception),
)
class TestCelExtension(cel.CelExtension):
"""An example CEL extension for testing."""
def __init__(self):
super().__init__(
"test_cel_extension",
functions=[
cel.FunctionDecl(
"hello",
[
cel.Overload(
"hello(string)",
return_type=cel.Type.STRING,
parameters=[
cel.Type.STRING,
],
impl=lambda arg: f"Hello, {arg}!",
)
],
),
],
)
def normalize_yaml(yaml: str) -> str:
return textwrap.dedent(yaml).strip()
if __name__ == "__main__":
absltest.main()