-
Notifications
You must be signed in to change notification settings - Fork 377
Expand file tree
/
Copy pathtest_metaprogramming.py
More file actions
640 lines (520 loc) · 18.8 KB
/
test_metaprogramming.py
File metadata and controls
640 lines (520 loc) · 18.8 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
import typing as t
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from tenacity import retry, stop_after_attempt
import re
import pandas as pd # noqa: TID253
import pytest
import sqlglot
from pytest_mock.plugin import MockerFixture
from sqlglot import exp
from sqlglot import exp as expressions
from sqlglot.expressions import SQLGLOT_META, to_table
from sqlglot.optimizer.pushdown_projections import SELECT_ALL
import tests.utils.test_date as test_date
from sqlmesh.core.dialect import normalize_model_name
from sqlmesh.core import constants as c
from sqlmesh.core.macros import RuntimeStage
from sqlmesh.utils.errors import SQLMeshError
from sqlmesh.utils.metaprogramming import (
Executable,
ExecutableKind,
_dict_sort,
build_env,
func_globals,
normalize_source,
prepare_env,
print_exception,
serialize_env,
)
def test_print_exception(mocker: MockerFixture):
out_mock = mocker.Mock()
test_env = {
"test_fun": Executable(
name="test_func",
payload="""def test_fun():
raise RuntimeError("error")""",
path="/test/path.py",
),
}
env = prepare_env(test_env)
try:
eval("test_fun()", env)
except Exception as ex:
print_exception(ex, test_env, out_mock)
expected_message = r""" File ".*?.tests.utils.test_metaprogramming\.py", line 48, in test_print_exception
eval\("test_fun\(\)", env\).*
File '/test/path.py' \(or imported file\), line 2, in test_fun
def test_fun\(\):
raise RuntimeError\("error"\)
RuntimeError: error
"""
actual_message = out_mock.write.call_args_list[0][0][0]
assert isinstance(actual_message, str)
expected_message = "".join(expected_message.split())
actual_message = "".join(actual_message.split())
assert re.match(expected_message, actual_message)
X = 1
Y = 2
Z = 3
W = 0
my_lambda = lambda: print("z") # noqa: E731
KLASS_X = 1
KLASS_Y = 2
KLASS_Z = 3
@dataclass
class DataClass:
x: int
class ReferencedClass:
def __init__(self, value: int):
self.value = value
def get_value(self) -> int:
return self.value
class MyClass:
def __init__(self, x: int):
self.helper = ReferencedClass(x * 2)
@staticmethod
def foo():
return KLASS_X
@classmethod
def bar(cls):
return KLASS_Y
def baz(self):
return KLASS_Z
def use_referenced(self, value: int) -> int:
ref = ReferencedClass(value)
return ref.get_value()
def compute_with_reference(self) -> int:
return self.helper.get_value() + 10
def other_func(a: int) -> int:
import sqlglot
sqlglot.parse_one("1")
pd.DataFrame([{"x": 1}])
to_table("y")
my_lambda() # type: ignore
obj = MyClass(a)
return X + a + W + obj.compute_with_reference()
@contextmanager
def sample_context_manager():
yield
@retry(stop=stop_after_attempt(3))
def fetch_data():
return "'test data'"
def custom_decorator(_func):
def wrapper(*args, **kwargs):
return _func(*args, **kwargs)
return wrapper
@custom_decorator
def function_with_custom_decorator():
return
def main_func(y: int, foo=exp.true(), *, bar=expressions.Literal.number(1) + 2) -> int:
"""DOC STRING"""
sqlglot.parse_one("1")
MyClass(47)
DataClass(x=y)
normalize_model_name("test" + SQLGLOT_META)
fetch_data()
function_with_custom_decorator()
def closure(z: int) -> int:
return z + Z
with sample_context_manager():
pass
return closure(y) + other_func(Y)
def macro1() -> str:
print("macro1 hello there")
print(RuntimeStage.CREATING)
return "1"
def macro2() -> str:
print("macro2 hello there")
print(RuntimeStage.LOADING)
return "2"
def test_func_globals() -> None:
assert func_globals(main_func) == {
"Y": 2,
"Z": 3,
"DataClass": DataClass,
"MyClass": MyClass,
"normalize_model_name": normalize_model_name,
"other_func": other_func,
"sqlglot": sqlglot,
"exp": exp,
"expressions": exp,
"fetch_data": fetch_data,
"sample_context_manager": sample_context_manager,
"function_with_custom_decorator": function_with_custom_decorator,
"SQLGLOT_META": SQLGLOT_META,
}
assert func_globals(other_func) == {
"X": 1,
"W": 0,
"MyClass": MyClass,
"my_lambda": my_lambda,
"pd": pd,
"to_table": to_table,
}
def closure_test() -> t.Callable:
y = 1
def closure() -> int:
return main_func(y)
return closure
assert func_globals(closure_test()) == {
"main_func": main_func,
"y": 1,
}
def test_normalize_source() -> None:
assert (
normalize_source(main_func)
== """def main_func(y: int, foo=exp.true(), *, bar=expressions.Literal.number(1) + 2
):
sqlglot.parse_one('1')
MyClass(47)
DataClass(x=y)
normalize_model_name('test' + SQLGLOT_META)
fetch_data()
function_with_custom_decorator()
def closure(z: int):
return z + Z
with sample_context_manager():
pass
return closure(y) + other_func(Y)"""
)
assert (
normalize_source(other_func)
== """def other_func(a: int):
import sqlglot
sqlglot.parse_one('1')
pd.DataFrame([{'x': 1}])
to_table('y')
my_lambda()
obj = MyClass(a)
return X + a + W + obj.compute_with_reference()"""
)
def test_serialize_env_error() -> None:
with pytest.raises(SQLMeshError):
# pretend to be the module pandas
serialize_env({"test_date": (test_date, None)}, path=Path("tests/utils"))
with pytest.raises(SQLMeshError):
serialize_env({"select_all": (SELECT_ALL, None)}, path=Path("tests/utils"))
def test_serialize_env() -> None:
path = Path("tests/utils")
env: t.Dict[str, t.Tuple[t.Any, t.Optional[bool]]] = {}
build_env(main_func, env=env, name="MAIN", path=path)
serialized_env = serialize_env(env, path=path) # type: ignore
assert prepare_env(serialized_env)
expected_env = {
"MAIN": Executable(
name="main_func",
alias="MAIN",
path="test_metaprogramming.py",
payload="""def main_func(y: int, foo=exp.true(), *, bar=expressions.Literal.number(1) + 2
):
sqlglot.parse_one('1')
MyClass(47)
DataClass(x=y)
normalize_model_name('test' + SQLGLOT_META)
fetch_data()
function_with_custom_decorator()
def closure(z: int):
return z + Z
with sample_context_manager():
pass
return closure(y) + other_func(Y)""",
),
"X": Executable(payload="1", kind=ExecutableKind.VALUE),
"Y": Executable(payload="2", kind=ExecutableKind.VALUE),
"Z": Executable(payload="3", kind=ExecutableKind.VALUE),
"W": Executable(payload="0", kind=ExecutableKind.VALUE),
"_GeneratorContextManager": Executable(
payload="from contextlib import _GeneratorContextManager", kind=ExecutableKind.IMPORT
),
"contextmanager": Executable(
payload="from contextlib import contextmanager", kind=ExecutableKind.IMPORT
),
"KLASS_X": Executable(payload="1", kind=ExecutableKind.VALUE),
"KLASS_Y": Executable(payload="2", kind=ExecutableKind.VALUE),
"KLASS_Z": Executable(payload="3", kind=ExecutableKind.VALUE),
"to_table": Executable(
kind=ExecutableKind.IMPORT,
payload="from sqlglot.expressions import to_table",
),
"DataClass": Executable(
kind=ExecutableKind.DEFINITION,
name="DataClass",
path="test_metaprogramming.py",
payload="""@dataclass
class DataClass:
x: int""",
),
"MyClass": Executable(
kind=ExecutableKind.DEFINITION,
name="MyClass",
path="test_metaprogramming.py",
payload="""class MyClass:
def __init__(self, x: int):
self.helper = ReferencedClass(x * 2)
@staticmethod
def foo():
return KLASS_X
@classmethod
def bar(cls):
return KLASS_Y
def baz(self):
return KLASS_Z
def use_referenced(self, value: int):
ref = ReferencedClass(value)
return ref.get_value()
def compute_with_reference(self):
return self.helper.get_value() + 10""",
),
"ReferencedClass": Executable(
kind=ExecutableKind.DEFINITION,
name="ReferencedClass",
path="test_metaprogramming.py",
payload="""class ReferencedClass:
def __init__(self, value: int):
self.value = value
def get_value(self):
return self.value""",
),
"dataclass": Executable(
payload="from dataclasses import dataclass", kind=ExecutableKind.IMPORT
),
"pd": Executable(payload="import pandas as pd", kind=ExecutableKind.IMPORT),
"sqlglot": Executable(kind=ExecutableKind.IMPORT, payload="import sqlglot"),
"exp": Executable(kind=ExecutableKind.IMPORT, payload="import sqlglot.expressions as exp"),
"expressions": Executable(
kind=ExecutableKind.IMPORT, payload="import sqlglot.expressions as expressions"
),
"func": Executable(
payload="""@contextmanager
def sample_context_manager():
yield""",
name="sample_context_manager",
path="test_metaprogramming.py",
alias="func",
),
"my_lambda": Executable(
name="my_lambda",
path="test_metaprogramming.py",
payload="my_lambda = lambda : print('z')",
),
"normalize_model_name": Executable(
payload="from sqlmesh.core.dialect import normalize_model_name",
kind=ExecutableKind.IMPORT,
),
"other_func": Executable(
name="other_func",
path="test_metaprogramming.py",
payload="""def other_func(a: int):
import sqlglot
sqlglot.parse_one('1')
pd.DataFrame([{'x': 1}])
to_table('y')
my_lambda()
obj = MyClass(a)
return X + a + W + obj.compute_with_reference()""",
),
"sample_context_manager": Executable(
payload="""@contextmanager
def sample_context_manager():
yield""",
name="sample_context_manager",
path="test_metaprogramming.py",
),
"wraps": Executable(payload="from functools import wraps", kind=ExecutableKind.IMPORT),
"functools": Executable(payload="import functools", kind=ExecutableKind.IMPORT),
"retry": Executable(payload="from tenacity import retry", kind=ExecutableKind.IMPORT),
"stop_after_attempt": Executable(
payload="from tenacity.stop import stop_after_attempt", kind=ExecutableKind.IMPORT
),
"wrapped_f": Executable(
payload='''@retry(stop=stop_after_attempt(3))
def fetch_data():
return "'test data'"''',
name="fetch_data",
path="test_metaprogramming.py",
alias="wrapped_f",
),
"fetch_data": Executable(
payload='''@retry(stop=stop_after_attempt(3))
def fetch_data():
return "'test data'"''',
name="fetch_data",
path="test_metaprogramming.py",
),
"f": Executable(
payload='''@retry(stop=stop_after_attempt(3))
def fetch_data():
return "'test data'"''',
name="fetch_data",
path="test_metaprogramming.py",
alias="f",
),
"function_with_custom_decorator": Executable(
name="wrapper",
path="test_metaprogramming.py",
payload="""def wrapper(*args, **kwargs):
return _func(*args, **kwargs)""",
alias="function_with_custom_decorator",
),
"custom_decorator": Executable(
name="custom_decorator",
path="test_metaprogramming.py",
payload="""def custom_decorator(_func):
def wrapper(*args, **kwargs):
return _func(*args, **kwargs)
return wrapper""",
),
"_func": Executable(
name="function_with_custom_decorator",
path="test_metaprogramming.py",
payload="""@custom_decorator
def function_with_custom_decorator():
return""",
alias="_func",
),
"SQLGLOT_META": Executable.value("sqlglot.meta"),
}
assert all(not is_metadata for (_, is_metadata) in env.values())
assert serialized_env == expected_env
# Annotate the entrypoint as "metadata only" to show how it propagates
setattr(main_func, c.SQLMESH_METADATA, True)
env = {}
build_env(main_func, env=env, name="MAIN", path=path)
serialized_env = serialize_env(env, path=path) # type: ignore
assert prepare_env(serialized_env)
expected_env = {k: Executable(**v.dict(), is_metadata=True) for k, v in expected_env.items()}
# Every object is treated as "metadata only", transitively
assert all(is_metadata for (_, is_metadata) in env.values())
assert serialized_env == expected_env
# Check that class references inside init are captured
init_globals = func_globals(MyClass.__init__)
assert "ReferencedClass" in init_globals
env = {}
build_env(other_func, env=env, name="other_func_test", path=path)
serialized_env = serialize_env(env, path=path)
assert "MyClass" in serialized_env
assert "ReferencedClass" in serialized_env
prepared_env = prepare_env(serialized_env)
result = eval("other_func_test(2)", prepared_env)
assert result == 17
def test_serialize_env_with_enum_import_appearing_in_two_functions() -> None:
path = Path("tests/utils")
env: t.Dict[str, t.Tuple[t.Any, t.Optional[bool]]] = {}
build_env(macro1, env=env, name="macro1", path=path)
build_env(macro2, env=env, name="macro2", path=path)
serialized_env = serialize_env(env, path=path) # type: ignore
assert prepare_env(serialized_env)
expected_env = {
"RuntimeStage": Executable(
payload="from sqlmesh.core.macros import RuntimeStage", kind=ExecutableKind.IMPORT
),
"macro1": Executable(
payload="""def macro1():
print('macro1 hello there')
print(RuntimeStage.CREATING)
return '1'""",
name="macro1",
path="test_metaprogramming.py",
),
"macro2": Executable(
payload="""def macro2():
print('macro2 hello there')
print(RuntimeStage.LOADING)
return '2'""",
name="macro2",
path="test_metaprogramming.py",
),
}
assert serialized_env == expected_env
def test_dict_sort_basic_types():
"""Test dict_sort with basic Python types."""
# Test basic types that should use standard repr
assert _dict_sort(42) == "42"
assert _dict_sort("hello") == "'hello'"
assert _dict_sort(True) == "True"
assert _dict_sort(None) == "None"
assert _dict_sort(3.14) == "3.14"
def test_dict_sort_dict_ordering():
"""Test that dict_sort produces consistent output for dicts with different key ordering."""
# Same dict with different key ordering
dict1 = {"c": 3, "a": 1, "b": 2}
dict2 = {"a": 1, "b": 2, "c": 3}
dict3 = {"b": 2, "c": 3, "a": 1}
repr1 = _dict_sort(dict1)
repr2 = _dict_sort(dict2)
repr3 = _dict_sort(dict3)
# All should produce the same representation
assert repr1 == repr2 == repr3
assert repr1 == "{'a': 1, 'b': 2, 'c': 3}"
def test_dict_sort_mixed_key_types():
"""Test dict_sort with mixed key types (strings and numbers)."""
dict1 = {42: "number", "string": "text", 1: "one"}
dict2 = {"string": "text", 1: "one", 42: "number"}
repr1 = _dict_sort(dict1)
repr2 = _dict_sort(dict2)
# Should produce consistent ordering despite mixed key types
assert repr1 == repr2
# Numbers come before strings when sorting by string representation
assert repr1 == "{1: 'one', 42: 'number', 'string': 'text'}"
def test_dict_sort_nested_structures():
"""Test dict_sort with deeply nested dictionaries."""
nested1 = {"outer": {"z": 26, "a": 1}, "list": [3, {"y": 2, "x": 1}], "simple": "value"}
nested2 = {"simple": "value", "list": [3, {"x": 1, "y": 2}], "outer": {"a": 1, "z": 26}}
repr1 = _dict_sort(nested1)
repr2 = _dict_sort(nested2)
assert repr1 != repr2
# Verify structure is maintained with sorted keys
expected1 = "{'list': [3, {'y': 2, 'x': 1}], 'outer': {'z': 26, 'a': 1}, 'simple': 'value'}"
expected2 = "{'list': [3, {'x': 1, 'y': 2}], 'outer': {'a': 1, 'z': 26}, 'simple': 'value'}"
assert repr1 == expected1
assert repr2 == expected2
def test_dict_sort_lists_and_tuples():
"""Test dict_sort preserves order for lists/tuples and doesn't sort nested dicts."""
# Lists should be unchanged
list_with_dicts = [{"z": 26, "a": 1}, {"y": 25, "b": 2}]
list_repr = _dict_sort(list_with_dicts)
expected_list = "[{'z': 26, 'a': 1}, {'y': 25, 'b': 2}]"
assert list_repr == expected_list
# Tuples should be unchanged
tuple_with_dicts = ({"z": 26, "a": 1}, {"y": 25, "b": 2})
tuple_repr = _dict_sort(tuple_with_dicts)
expected_tuple = "({'z': 26, 'a': 1}, {'y': 25, 'b': 2})"
assert tuple_repr == expected_tuple
def test_dict_sort_empty_containers():
"""Test dict_sort with empty containers."""
assert _dict_sort({}) == "{}"
assert _dict_sort([]) == "[]"
assert _dict_sort(()) == "()"
def test_dict_sort_special_characters():
"""Test dict_sort handles special characters correctly."""
special_dict = {
"quotes": "text with 'single' and \"double\" quotes",
"unicode": "unicode: ñáéíóú",
"newlines": "text\nwith\nnewlines",
"backslashes": "path\\to\\file",
}
result = _dict_sort(special_dict)
# Should be valid Python that can be evaluated
reconstructed = eval(result)
assert reconstructed == special_dict
# Should be deterministic - same input produces same output
result2 = _dict_sort(special_dict)
assert result == result2
def test_dict_sort_executable_integration():
"""Test that dict_sort works correctly with Executable.value()."""
# Test the integration with Executable.value which is the main use case
variables1 = {"env": "dev", "debug": True, "timeout": 30}
variables2 = {"timeout": 30, "debug": True, "env": "dev"}
exec1 = Executable.value(variables1, sort_root_dict=True)
exec2 = Executable.value(variables2, sort_root_dict=True)
# Should produce identical payloads despite different input ordering
assert exec1.payload == exec2.payload
assert exec1.payload == "{'debug': True, 'env': 'dev', 'timeout': 30}"
# Should be valid Python
reconstructed = eval(exec1.payload)
assert reconstructed == variables1
# non-deterministic repr should not change the payload
exec3 = Executable.value(variables1)
assert exec3.payload == "{'env': 'dev', 'debug': True, 'timeout': 30}"