Debian Codegraph @

mypyc/test/test_run.py

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