Debian Codegraph @

mypyc/test/test_run.py

raw ◀ ▶
1 Debian patch touch this file
1 """Test cases for building an C extension and running it."""
2
3 from __future__ import annotations
4
5 import ast
6 import contextlib
7 import glob
8 import os.path
9 import re
10 import shutil
11 import subprocess
12 import sys
13 import time
14 from collections.abc import Iterator
15 from typing import Any
16
17 import pytest
18
19 from mypy import build
20 from mypy.errors import CompileError
21 from mypy.options import Options
22 from mypy.test.config import mypyc_output_dir, test_temp_dir
23 from mypy.test.data import DataDrivenTestCase
24 from mypy.test.helpers import assert_module_equivalence, perform_file_operations
25 from mypyc.build import construct_groups
26 from mypyc.codegen import emitmodule
27 from mypyc.codegen.emitmodule import collect_source_dependencies
28 from mypyc.errors import Errors
29 from mypyc.options import CompilerOptions
30 from mypyc.test.config import test_data_prefix
31 from mypyc.test.librt_cache import get_librt_path
32 from mypyc.test.test_serialization import check_serialization_roundtrip
33 from mypyc.test.testutil import (
34 ICODE_GEN_BUILTINS,
35 TESTUTIL_PATH,
36 MypycDataSuite,
37 assert_test_output,
38 fudge_dir_mtimes,
39 has_test_name_tag,
40 show_c,
41 use_custom_builtins,
42 )
43
44 files = [
45 "run-async.test",
46 "run-misc.test",
47 "run-functions.test",
48 "run-integers.test",
49 "run-i64.test",
50 "run-i32.test",
51 "run-i16.test",
52 "run-u8.test",
53 "run-floats.test",
54 "run-math.test",
55 "run-bools.test",
56 "run-strings.test",
57 "run-bytes.test",
58 "run-tuples.test",
59 "run-lists.test",
60 "run-dicts.test",
61 "run-sets.test",
62 "run-primitives.test",
63 "run-loops.test",
64 "run-exceptions.test",
65 "run-imports.test",
66 "run-classes.test",
67 "run-traits.test",
68 "run-generators.test",
69 "run-generics.test",
70 "run-multimodule.test",
71 "run-bench.test",
72 "run-mypy-sim.test",
73 "run-dunders.test",
74 "run-dunders-special.test",
75 "run-singledispatch.test",
76 "run-attrs.test",
77 "run-signatures.test",
78 "run-weakref.test",
79 "run-python37.test",
80 "run-python38.test",
81 "run-librt-strings.test",
82 "run-base64.test",
83 "run-librt-time.test",
84 "run-librt-random.test",
85 "run-threading.test",
86 "run-match.test",
87 "run-vecs-i64-interp.test",
88 "run-vecs-misc-interp.test",
89 "run-vecs-t-interp.test",
90 "run-vecs-nested-interp.test",
91 "run-vecs-i64.test",
92 "run-vecs-misc.test",
93 "run-vecs-t.test",
94 "run-vecs-nested.test",
95 ]
96
97 if sys.version_info >= (3, 12):
98 files.append("run-python312.test")
99
100 setup_format = """\
101 from setuptools import setup
102 from mypyc.build import mypycify
103
104 setup(name='test_run_output',
105 ext_modules=mypycify({}, separate={}, skip_cgen_input={!r}, strip_asserts=False,
106 multi_file={}, opt_level='{}', install_librt={},
107 experimental_features={}, depends_on_librt_internal={}),
108 )
109 """
110
111 WORKDIR = "build"
112
113
114 def run_setup(script_name: str, script_args: list[str]) -> bool:
115 """Run a setup script in a somewhat controlled environment.
116
117 This is adapted from code in distutils and our goal here is that is
118 faster to not need to spin up a python interpreter to run it.
119
120 We had to fork it because the real run_setup swallows errors
121 and KeyboardInterrupt with no way to recover them (!).
122 The real version has some extra features that we removed since
123 we weren't using them.
124
125 Returns whether the setup succeeded.
126 """
127 save_argv = sys.argv.copy()
128 g = {"__file__": script_name}
129 try:
130 try:
131 sys.argv[0] = script_name
132 sys.argv[1:] = script_args
133 with open(script_name, "rb") as f:
134 exec(f.read(), g)
135 finally:
136 sys.argv = save_argv
137 except SystemExit as e:
138 # distutils converts KeyboardInterrupt into a SystemExit with
139 # "interrupted" as the argument. Convert it back so that
140 # pytest will exit instead of just failing the test.
141 if e.code == "interrupted":
142 raise KeyboardInterrupt from e
143
144 return e.code == 0 or e.code is None
145
146 return True
147
148
149 @contextlib.contextmanager
150 def chdir_manager(target: str) -> Iterator[None]:
151 dir = os.getcwd()
152 os.chdir(target)
153 try:
154 yield
155 finally:
156 os.chdir(dir)
157
158
159 class TestRun(MypycDataSuite):
160 """Test cases that build a C extension and run code."""
161
162 files = files
163 base_path = test_temp_dir
164 optional_out = True
165 multi_file = False
166 separate = False # If True, using separate (incremental) compilation
167 strict_dunder_typing = False
168
169 def run_case(self, testcase: DataDrivenTestCase) -> None:
170 with pytest.MonkeyPatch.context() as mp:
171 mp.delenv("CFLAGS", raising=False)
172 # setup.py wants to be run from the root directory of the package, which we accommodate
173 # by chdiring into tmp/
174 with (
175 use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase),
176 chdir_manager("tmp"),
177 ):
178 self.run_case_inner(testcase)
179
180 def run_case_inner(self, testcase: DataDrivenTestCase) -> None:
181 if not os.path.isdir(WORKDIR): # (one test puts something in build...)
182 os.mkdir(WORKDIR)
183
184 text = "\n".join(testcase.input)
185
186 with open("native.py", "w", encoding="utf-8") as f:
187 f.write(text)
188 with open("interpreted.py", "w", encoding="utf-8") as f:
189 f.write(text)
190
191 shutil.copyfile(TESTUTIL_PATH, "testutil.py")
192
193 step = 1
194 self.run_case_step(testcase, step)
195
196 steps = testcase.find_steps()
197 if steps == [[]]:
198 steps = []
199
200 for operations in steps:
201 # To make sure that any new changes get picked up as being
202 # new by distutils, shift the mtime of all of the
203 # generated artifacts back by a second.
204 fudge_dir_mtimes(WORKDIR, -1)
205 # On some OS, changing the mtime doesn't work reliably. As
206 # a workaround, sleep.
207 # TODO: Figure out a better approach, since this slows down tests.
208 time.sleep(1.0)
209
210 step += 1
211 with chdir_manager(".."):
212 perform_file_operations(operations)
213 self.run_case_step(testcase, step)
214
215 def run_case_step(self, testcase: DataDrivenTestCase, incremental_step: int) -> None:
216 benchmark_build = has_test_name_tag(testcase.name, "benchmark")
217 bench = testcase.config.getoption("--bench", False) and (
218 benchmark_build or "Benchmark" in testcase.name
219 )
220
221 options = Options()
222 options.use_builtins_fixtures = True
223 options.show_traceback = True
224 options.strict_optional = True
225 options.strict_bytes = True
226 options.disable_bytearray_promotion = True
227 options.disable_memoryview_promotion = True
228 options.python_version = sys.version_info[:2]
229 options.export_types = True
230 options.preserve_asts = True
231 options.allow_empty_bodies = True
232 options.incremental = self.separate
233 options.check_untyped_defs = True
234
235 # Avoid checking modules/packages named 'unchecked', to provide a way
236 # to test interacting with code we don't have types for.
237 options.per_module_options["unchecked.*"] = {"follow_imports": "error"}
238 # Avoid checking modules/packages named 'skipped', to provide a way
239 # to test interacting with code ignored by follow_imports=skip.
240 options.per_module_options["skipped"] = {"follow_imports": "skip"}
241 options.per_module_options["skipped.*"] = {"follow_imports": "skip"}
242
243 source = build.BuildSource("native.py", "native", None)
244 sources = [source]
245 module_names = ["native"]
246 module_paths = ["native.py"]
247
248 # Hard code another module name to compile in the same compilation unit.
249 to_delete = []
250 for fn, text in testcase.files:
251 fn = os.path.relpath(fn, test_temp_dir)
252
253 if os.path.basename(fn).startswith("other") and fn.endswith(".py"):
254 name = fn.split(".")[0].replace(os.sep, ".")
255 module_names.append(name)
256 sources.append(build.BuildSource(fn, name, None))
257 to_delete.append(fn)
258 module_paths.append(fn)
259
260 shutil.copyfile(fn, os.path.join(os.path.dirname(fn), name + "_interpreted.py"))
261 elif fn.endswith("__init__.py"):
262 pkg_dir = os.path.dirname(fn)
263 if os.path.basename(pkg_dir).startswith("other"):
264 name = pkg_dir.replace(os.sep, ".")
265 module_names.append(name)
266 sources.append(build.BuildSource(fn, name, None))
267 to_delete.append(fn)
268 module_paths.append(fn)
269
270 for source in sources:
271 options.per_module_options.setdefault(source.module, {})["mypyc"] = True
272
273 separate = (
274 self.get_separate("\n".join(testcase.input), incremental_step)
275 if self.separate
276 else False
277 )
278
279 groups = construct_groups(sources, separate, len(module_names) > 1, None)
280
281 # Use _librt_internal to test mypy-specific parts of librt (they have
282 # some special-casing in mypyc), for everything else use _librt suffix.
283 librt_internal = has_test_name_tag(testcase.name, "librt_internal")
284 librt = has_test_name_tag(testcase.name, "librt")
285 # Enable experimental features (local librt build also includes experimental features)
286 experimental_features = has_test_name_tag(testcase.name, "experimental")
287 result = None
288 try:
289 compiler_options = CompilerOptions(
290 multi_file=self.multi_file,
291 separate=self.separate,
292 strict_dunder_typing=self.strict_dunder_typing,
293 depends_on_librt_internal=librt_internal,
294 experimental_features=experimental_features,
295 strict_traceback_checks=True,
296 )
297 result = emitmodule.parse_and_typecheck(
298 sources=sources,
299 options=options,
300 compiler_options=compiler_options,
301 groups=groups,
302 alt_lib_path=".",
303 )
304 errors = Errors(options)
305 ir, cfiles, _ = emitmodule.compile_modules_to_c(
306 result, compiler_options=compiler_options, errors=errors, groups=groups
307 )
308 deps = sorted(
309 (
310 (dep.path, dep.include_dirs, dep.internal)
311 for dep in collect_source_dependencies(ir)
312 ),
313 key=lambda tup: tup[0],
314 )
315 if errors.num_errors:
316 errors.flush_errors()
317 assert False, "Compile error"
318 except CompileError as e:
319 for line in e.messages:
320 print(fix_native_line_number(line, testcase.file, testcase.line))
321 assert False, "Compile error"
322 finally:
323 if result is not None:
324 result.manager.metastore.close()
325
326 # Check that serialization works on this IR. (Only on the first
327 # step because the returned ir only includes updated code.)
328 if incremental_step == 1:
329 check_serialization_roundtrip(ir)
330
331 opt_level = 3 if benchmark_build else int(os.environ.get("MYPYC_OPT_LEVEL", 0))
332
333 setup_file = os.path.abspath(os.path.join(WORKDIR, "setup.py"))
334 # We pass the C file information to the build script via setup.py unfortunately
335 # Note: install_librt is always False since we use cached librt from librt_cache
336 with open(setup_file, "w", encoding="utf-8") as f:
337 f.write(
338 setup_format.format(
339 module_paths,
340 separate,
341 (cfiles, deps),
342 self.multi_file,
343 opt_level,
344 False, # install_librt - use cached version instead
345 experimental_features,
346 librt_internal,
347 )
348 )
349
350 if librt:
351 # Use cached pre-built librt instead of rebuilding for each test
352 cached_librt = get_librt_path(experimental_features, opt_level=str(opt_level))
353 shutil.copytree(os.path.join(cached_librt, "librt"), "librt")
354
355 if not run_setup(setup_file, ["build_ext", "--inplace"]):
356 if testcase.config.getoption("--mypyc-showc"):
357 show_c(cfiles)
358 copy_output_files(mypyc_output_dir)
359 assert False, "Compilation failed"
360
361 # Assert that an output file got created
362 suffix = "pyd" if sys.platform == "win32" else "so"
363 assert glob.glob(f"native.*.{suffix}") or glob.glob(f"native.{suffix}")
364
365 driver_path = "driver.py"
366 if not os.path.isfile(driver_path):
367 # No driver.py provided by test case. Use the default one
368 # (mypyc/test-data/driver/driver.py) that calls each
369 # function named test_*.
370 default_driver = os.path.join(test_data_prefix, "driver", "driver.py")
371 shutil.copy(default_driver, driver_path)
372 env = os.environ.copy()
373 env["MYPYC_RUN_BENCH"] = "1" if bench else "0"
374
375 debugger = testcase.config.getoption("debugger")
376 if debugger:
377 if debugger == "lldb":
378 subprocess.check_call(["lldb", "--", sys.executable, driver_path], env=env)
379 elif debugger == "gdb":
380 subprocess.check_call(["gdb", "--args", sys.executable, driver_path], env=env)
381 else:
382 assert False, "Unsupported debugger"
383 # TODO: find a way to automatically disable capturing
384 # stdin/stdout when in debugging mode
385 assert False, (
386 "Test can't pass in debugging mode. "
387 "(Make sure to pass -s to pytest to interact with the debugger)"
388 )
389 proc = subprocess.Popen(
390 [sys.executable, driver_path],
391 stdout=subprocess.PIPE,
392 stderr=subprocess.STDOUT,
393 env=env,
394 )
•395 if sys.version_info >= (3, 12) and sys.version_info < (3, 13):
396 # TODO: testDecorators1 hangs on 3.12, remove this once fixed
397 proc.wait(timeout=30)
398 output = proc.communicate()[0].decode("utf8")
399 output = output.replace(f' File "{os.getcwd()}{os.sep}', ' File "')
400 outlines = output.splitlines()
401
402 if testcase.config.getoption("--mypyc-showc"):
403 show_c(cfiles)
404 if proc.returncode != 0:
405 print()
406 signal = proc.returncode == -11
407 extra = ""
408 if signal:
409 extra = " (likely segmentation fault)"
410 print(f"*** Exit status: {proc.returncode}{extra}")
411 if signal and not sys.platform.startswith("win"):
412 print()
413 if sys.platform == "darwin":
414 debugger = "lldb"
415 else:
416 debugger = "gdb"
417 print(
418 f'hint: Use "pytest -n0 -s --mypyc-debug={debugger} -k <name-substring>" to run test in debugger'
419 )
420 print("hint: You may need to build a debug version of Python first and use it")
421 print('hint: See also "Debugging Segfaults" in mypyc/doc/dev-intro.md')
422 copy_output_files(mypyc_output_dir)
423
424 # Verify output.
425 if bench:
426 print("Test output:")
427 print(output)
428 else:
429 if incremental_step == 1:
430 msg = "Invalid output"
431 expected = testcase.output
432 else:
433 msg = f"Invalid output (step {incremental_step})"
434 expected = testcase.output2.get(incremental_step, [])
435
436 if not expected:
437 # Tweak some line numbers, but only if the expected output is empty,
438 # as tweaked output might not match expected output.
439 outlines = [
440 fix_native_line_number(line, testcase.file, testcase.line) for line in outlines
441 ]
442 assert_test_output(testcase, outlines, msg, expected)
443
444 if incremental_step > 1 and options.incremental:
445 suffix = "" if incremental_step == 2 else str(incremental_step - 1)
446 expected_rechecked = testcase.expected_rechecked_modules.get(incremental_step - 1)
447 if expected_rechecked is not None:
448 assert_module_equivalence(
449 "rechecked" + suffix, expected_rechecked, result.manager.rechecked_modules
450 )
451 expected_stale = testcase.expected_stale_modules.get(incremental_step - 1)
452 if expected_stale is not None:
453 assert_module_equivalence(
454 "stale" + suffix, expected_stale, result.manager.stale_modules
455 )
456
457 assert proc.returncode == 0
458
459 def get_separate(self, program_text: str, incremental_step: int) -> Any:
460 template = r"# separate{}: (\[.*\])$"
461 m = re.search(template.format(incremental_step), program_text, flags=re.MULTILINE)
462 if not m:
463 m = re.search(template.format(""), program_text, flags=re.MULTILINE)
464 if m:
465 return ast.literal_eval(m.group(1))
466 else:
467 return True
468
469
470 class TestRunMultiFile(TestRun):
471 """Run the main multi-module tests in multi-file compilation mode.
472
473 In multi-file mode each module gets compiled into a separate C file,
474 but all modules (C files) are compiled together.
475 """
476
477 multi_file = True
478 test_name_suffix = "_multi"
479 files = ["run-multimodule.test", "run-mypy-sim.test"]
480
481
482 class TestRunSeparate(TestRun):
483 """Run the main multi-module tests in separate compilation mode.
484
485 In this mode there are multiple compilation groups, which are compiled
486 incrementally. Each group is compiled to a separate C file, and these C
487 files are compiled separately.
488
489 Each compiled module is placed into a separate compilation group, unless
490 overridden by a special comment. Consider this example:
491
492 # separate: [(["other.py", "other_b.py"], "stuff")]
493
494 This puts other.py and other_b.py into a compilation group named "stuff".
495 Any files not mentioned in the comment will get single-file groups.
496 """
497
498 separate = True
499 test_name_suffix = "_separate"
500 files = ["run-multimodule.test", "run-mypy-sim.test"]
501
502
503 class TestRunStrictDunderTyping(TestRun):
504 """Run the tests with strict dunder typing."""
505
506 strict_dunder_typing = True
507 test_name_suffix = "_dunder_typing"
508 files = ["run-dunders.test", "run-floats.test"]
509
510
511 def fix_native_line_number(message: str, fnam: str, delta: int) -> str:
512 """Update code locations in test case output to point to the .test file.
513
514 The description of the test case is written to native.py, and line numbers
515 in test case output often are relative to native.py. This translates the
516 line numbers to be relative to the .test file that contains the test case
517 description, and also updates the file name to the .test file name.
518
519 Args:
520 message: message to update
521 fnam: path of the .test file
522 delta: line number of the beginning of the test case in the .test file
523
524 Returns updated message (or original message if we couldn't find anything).
525 """
526 fnam = os.path.basename(fnam)
527 message = re.sub(
528 r"native\.py:([0-9]+):", lambda m: "%s:%d:" % (fnam, int(m.group(1)) + delta), message
529 )
530 message = re.sub(
531 r'"native.py", line ([0-9]+),',
532 lambda m: '"%s", line %d,' % (fnam, int(m.group(1)) + delta),
533 message,
534 )
535 return message
536
537
538 def copy_output_files(target_dir: str) -> None:
539 try:
540 os.mkdir(target_dir)
541 except OSError:
542 # Only copy data for the first failure, to avoid excessive output in case
543 # many tests fail
544 return
545
546 for fnam in glob.glob("build/*.[ch]"):
547 shutil.copy(fnam, target_dir)
548
549 sys.stderr.write(f"\nGenerated files: {target_dir} (for first failure only)\n\n")