Debian Codegraph @

mypyc/test/testutil.py

raw
1 """Helpers for writing tests"""
2
3 from __future__ import annotations
4
5 import contextlib
6 import os
7 import os.path
8 import re
9 import shutil
10 from collections.abc import Callable, Iterator
11
12 from mypy import build
13 from mypy.errors import CompileError
14 from mypy.nodes import Expression, MypyFile
15 from mypy.options import Options
16 from mypy.test.config import test_temp_dir
17 from mypy.test.data import DataDrivenTestCase, DataSuite
18 from mypy.test.helpers import assert_string_arrays_equal
19 from mypy.types import Type
20 from mypyc.analysis.ircheck import assert_func_ir_valid
21 from mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE
22 from mypyc.errors import Errors
23 from mypyc.ir.func_ir import FuncIR
24 from mypyc.ir.module_ir import ModuleIR
25 from mypyc.irbuild.main import build_ir
26 from mypyc.irbuild.mapper import Mapper
27 from mypyc.options import CompilerOptions
28 from mypyc.test.config import test_data_prefix
29
30 # The builtins stub used during icode generation test cases.
31 ICODE_GEN_BUILTINS = os.path.join(test_data_prefix, "fixtures/ir.py")
32 # The testutil support library
33 TESTUTIL_PATH = os.path.join(test_data_prefix, "fixtures/testutil.py")
34
35
36 class MypycDataSuite(DataSuite):
37 # Need to list no files, since this will be picked up as a suite of tests
38 files: list[str] = []
39 data_prefix = test_data_prefix
40
41
42 def builtins_wrapper(
43 func: Callable[[DataDrivenTestCase], None], path: str
44 ) -> Callable[[DataDrivenTestCase], None]:
45 """Decorate a function that implements a data-driven test case to copy an
46 alternative builtins module implementation in place before performing the
47 test case. Clean up after executing the test case.
48 """
49 return lambda testcase: perform_test(func, path, testcase)
50
51
52 @contextlib.contextmanager
53 def use_custom_builtins(builtins_path: str, testcase: DataDrivenTestCase) -> Iterator[None]:
54 for path, _ in testcase.files:
55 if os.path.basename(path) == "builtins.pyi":
56 default_builtins = False
57 break
58 else:
59 # Use default builtins.
60 builtins = os.path.abspath(os.path.join(test_temp_dir, "builtins.pyi"))
61 shutil.copyfile(builtins_path, builtins)
62 default_builtins = True
63
64 # Actually perform the test case.
65 try:
66 yield None
67 finally:
68 if default_builtins:
69 # Clean up.
70 os.remove(builtins)
71
72
73 def perform_test(
74 func: Callable[[DataDrivenTestCase], None], builtins_path: str, testcase: DataDrivenTestCase
75 ) -> None:
76 for path, _ in testcase.files:
77 if os.path.basename(path) == "builtins.py":
78 default_builtins = False
79 break
80 else:
81 # Use default builtins.
82 builtins = os.path.join(test_temp_dir, "builtins.py")
83 shutil.copyfile(builtins_path, builtins)
84 default_builtins = True
85
86 # Actually perform the test case.
87 func(testcase)
88
89 if default_builtins:
90 # Clean up.
91 os.remove(builtins)
92
93
94 def build_ir_for_single_file(
95 input_lines: list[str], compiler_options: CompilerOptions | None = None
96 ) -> list[FuncIR]:
97 return build_ir_for_single_file2(input_lines, compiler_options)[0].functions
98
99
100 def build_ir_for_single_file2(
101 input_lines: list[str], compiler_options: CompilerOptions | None = None
102 ) -> tuple[ModuleIR, MypyFile, dict[Expression, Type], Mapper]:
103 program_text = "\n".join(input_lines)
104
105 # By default generate IR compatible with the earliest supported Python C API.
106 # If a test needs more recent API features, this should be overridden.
107 compiler_options = compiler_options or CompilerOptions(capi_version=(3, 10))
108 options = Options()
109 options.show_traceback = True
110 options.hide_error_codes = True
111 options.use_builtins_fixtures = True
112 options.strict_optional = True
113 options.python_version = compiler_options.python_version or (3, 10)
114 options.export_types = True
115 options.preserve_asts = True
116 options.allow_empty_bodies = True
117 options.strict_bytes = True
118 options.disable_bytearray_promotion = True
119 options.disable_memoryview_promotion = True
120 options.per_module_options["__main__"] = {"mypyc": True}
121
122 source = build.BuildSource("main", "__main__", program_text)
123 # Construct input as a single single.
124 # Parse and type check the input program.
125 result = build.build(sources=[source], options=options, alt_lib_path=test_temp_dir)
126 result.manager.metastore.close()
127 if result.errors:
128 raise CompileError(result.errors)
129
130 errors = Errors(options)
131 mapper = Mapper({"__main__": None})
132 modules = build_ir(
133 [result.files["__main__"]], result.graph, result.types, mapper, compiler_options, errors
134 )
135 if errors.num_errors:
136 raise CompileError(errors.new_messages())
137
138 module = list(modules.values())[0]
139 for fn in module.functions:
140 assert_func_ir_valid(fn)
141 tree = result.graph[module.fullname].tree
142 assert tree is not None
143 return module, tree, result.types, mapper
144
145
146 def update_testcase_output(testcase: DataDrivenTestCase, output: list[str]) -> None:
147 # TODO: backport this to mypy
148 assert testcase.old_cwd is not None, "test was not properly set up"
149 testcase_path = os.path.join(testcase.old_cwd, testcase.file)
150 with open(testcase_path) as f:
151 data_lines = f.read().splitlines()
152
153 # We can't rely on the test line numbers to *find* the test, since
154 # we might fix multiple tests in a run. So find it by the case
155 # header. Give up if there are multiple tests with the same name.
156 test_slug = f"[case {testcase.name}]"
157 if data_lines.count(test_slug) != 1:
158 return
159 start_idx = data_lines.index(test_slug)
160 stop_idx = start_idx + 11
161 while stop_idx < len(data_lines) and not data_lines[stop_idx].startswith("[case "):
162 stop_idx += 1
163
164 test = data_lines[start_idx:stop_idx]
165 out_start = test.index("[out]")
166 test[out_start + 1 :] = output
167 data_lines[start_idx:stop_idx] = test + [""]
168 data = "\n".join(data_lines)
169
170 with open(testcase_path, "w") as f:
171 print(data, file=f)
172
173
174 def assert_test_output(
175 testcase: DataDrivenTestCase,
176 actual: list[str],
177 message: str,
178 expected: list[str] | None = None,
179 formatted: list[str] | None = None,
180 ) -> None:
181 __tracebackhide__ = True
182
183 expected_output = expected if expected is not None else testcase.output
184 if expected_output != actual and testcase.config.getoption("--update-data", False):
185 update_testcase_output(testcase, actual)
186
187 assert_string_arrays_equal(
188 expected_output, actual, f"{message} ({testcase.file}, line {testcase.line})"
189 )
190
191
192 def get_func_names(expected: list[str]) -> list[str]:
193 res = []
194 for s in expected:
195 m = re.match(r"def ([_a-zA-Z0-9.*$]+)\(", s)
196 if m:
197 res.append(m.group(1))
198 return res
199
200
201 def remove_comment_lines(a: list[str]) -> list[str]:
202 """Return a copy of array with comments removed.
203
204 Lines starting with '--' (but not with '---') are removed.
205 """
206 r = []
207 for s in a:
208 if s.strip().startswith("--") and not s.strip().startswith("---"):
209 pass
210 else:
211 r.append(s)
212 return r
213
214
215 def print_with_line_numbers(s: str) -> None:
216 lines = s.splitlines()
217 for i, line in enumerate(lines):
218 print("%-4d %s" % (i + 1, line))
219
220
221 def heading(text: str) -> None:
222 print("=" * 20 + " " + text + " " + "=" * 20)
223
224
225 def show_c(cfiles: list[list[tuple[str, str]]]) -> None:
226 heading("Generated C")
227 for group in cfiles:
228 for cfile, ctext in group:
229 print(f"== {cfile} ==")
230 print_with_line_numbers(ctext)
231 heading("End C")
232
233
234 def fudge_dir_mtimes(dir: str, delta: int) -> None:
235 # Skip linker outputs. Pushing them back combines with write_file's
236 # +1 sec bump on .c files to make .c always newer than .so, forcing
237 # an unconditional rebuild that would mask Extension.depends bugs.
238 # See setuptools/_distutils/command/build_ext.py:`build_extension`.
239 for dirpath, _, filenames in os.walk(dir):
240 for name in filenames:
241 if name.endswith((".so", ".pyd", ".o", ".obj")):
242 continue
243 path = os.path.join(dirpath, name)
244 new_mtime = os.stat(path).st_mtime + delta
245 os.utime(path, times=(new_mtime, new_mtime))
246
247
248 def replace_word_size(text: list[str]) -> list[str]:
249 """Replace WORDSIZE with platform specific word sizes"""
250 result = []
251 for line in text:
252 index = line.find("WORD_SIZE")
253 if index != -1:
254 # get 'WORDSIZE*n' token
255 word_size_token = line[index:].split()[0]
256 n = int(word_size_token[10:])
257 replace_str = str(PLATFORM_SIZE * n)
258 result.append(line.replace(word_size_token, replace_str))
259 else:
260 result.append(line)
261 return result
262
263
264 def infer_ir_build_options_from_test_name(name: str) -> CompilerOptions | None:
265 """Look for magic substrings in test case name to set compiler options.
266
267 Return None if the test case should be skipped (always pass).
268
269 Supported naming conventions:
270
271 *_64bit*:
272 Run test case only on 64-bit platforms
273 *_32bit*:
274 Run test caseonly on 32-bit platforms
275 *_python3_10* (or for any Python version):
276 Use Python 3.10+ C API features (default: lowest supported version)
277 *StripAssert*:
278 Don't generate code for assert statements
279 """
280 # If this is specific to some bit width, always pass if platform doesn't match.
281 if "_64bit" in name and IS_32_BIT_PLATFORM:
282 return None
283 if "_32bit" in name and not IS_32_BIT_PLATFORM:
284 return None
285 options = CompilerOptions(
286 strip_asserts="StripAssert" in name, capi_version=(3, 10), strict_traceback_checks=True
287 )
288 # A suffix like _python3_10 is used to set the target C API version.
289 m = re.search(r"_python([0-9]+)_([0-9]+)(_|\b)", name)
290 if m:
291 version = (int(m.group(1)), int(m.group(2)))
292 assert version >= (3, 10), f"Unsupported _python* suffix: {name}"
293 options.capi_version = version
294 options.python_version = options.capi_version
295 elif "_py" in name or "_Python" in name:
296 assert False, f"Invalid _py* suffix (should be _pythonX_Y): {name}"
297 if has_test_name_tag(name, "experimental"):
298 options.experimental_features = True
299 return options
300
301
302 def has_test_name_tag(name: str, tag: str) -> bool:
303 """Check if a test case name contains a tag token like ``_experimental``.
304
305 A tag matches if it appears as a full underscore-delimited token:
306 ``foo_tag_bar`` or ``foo_tag``.
307 """
308 return re.search(rf"(?:^|_){re.escape(tag)}(?:_|$)", name) is not None