test_run.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. """Test cases for building an C extension and running it."""
  2. from __future__ import annotations
  3. import ast
  4. import contextlib
  5. import glob
  6. import os.path
  7. import re
  8. import shutil
  9. import subprocess
  10. import sys
  11. import time
  12. from typing import Any, Iterator
  13. from mypy import build
  14. from mypy.errors import CompileError
  15. from mypy.options import TYPE_VAR_TUPLE, UNPACK, Options
  16. from mypy.test.config import test_temp_dir
  17. from mypy.test.data import DataDrivenTestCase
  18. from mypy.test.helpers import assert_module_equivalence, perform_file_operations
  19. from mypyc.build import construct_groups
  20. from mypyc.codegen import emitmodule
  21. from mypyc.errors import Errors
  22. from mypyc.options import CompilerOptions
  23. from mypyc.test.test_serialization import check_serialization_roundtrip
  24. from mypyc.test.testutil import (
  25. ICODE_GEN_BUILTINS,
  26. TESTUTIL_PATH,
  27. MypycDataSuite,
  28. assert_test_output,
  29. fudge_dir_mtimes,
  30. show_c,
  31. use_custom_builtins,
  32. )
  33. files = [
  34. "run-async.test",
  35. "run-misc.test",
  36. "run-functions.test",
  37. "run-integers.test",
  38. "run-i64.test",
  39. "run-i32.test",
  40. "run-floats.test",
  41. "run-math.test",
  42. "run-bools.test",
  43. "run-strings.test",
  44. "run-bytes.test",
  45. "run-tuples.test",
  46. "run-lists.test",
  47. "run-dicts.test",
  48. "run-sets.test",
  49. "run-primitives.test",
  50. "run-loops.test",
  51. "run-exceptions.test",
  52. "run-imports.test",
  53. "run-classes.test",
  54. "run-traits.test",
  55. "run-generators.test",
  56. "run-multimodule.test",
  57. "run-bench.test",
  58. "run-mypy-sim.test",
  59. "run-dunders.test",
  60. "run-singledispatch.test",
  61. "run-attrs.test",
  62. ]
  63. files.append("run-python37.test")
  64. if sys.version_info >= (3, 8):
  65. files.append("run-python38.test")
  66. if sys.version_info >= (3, 10):
  67. files.append("run-match.test")
  68. setup_format = """\
  69. from setuptools import setup
  70. from mypyc.build import mypycify
  71. setup(name='test_run_output',
  72. ext_modules=mypycify({}, separate={}, skip_cgen_input={!r}, strip_asserts=False,
  73. multi_file={}, opt_level='{}'),
  74. )
  75. """
  76. WORKDIR = "build"
  77. def run_setup(script_name: str, script_args: list[str]) -> bool:
  78. """Run a setup script in a somewhat controlled environment.
  79. This is adapted from code in distutils and our goal here is that is
  80. faster to not need to spin up a python interpreter to run it.
  81. We had to fork it because the real run_setup swallows errors
  82. and KeyboardInterrupt with no way to recover them (!).
  83. The real version has some extra features that we removed since
  84. we weren't using them.
  85. Returns whether the setup succeeded.
  86. """
  87. save_argv = sys.argv.copy()
  88. g = {"__file__": script_name}
  89. try:
  90. try:
  91. sys.argv[0] = script_name
  92. sys.argv[1:] = script_args
  93. with open(script_name, "rb") as f:
  94. exec(f.read(), g)
  95. finally:
  96. sys.argv = save_argv
  97. except SystemExit as e:
  98. # distutils converts KeyboardInterrupt into a SystemExit with
  99. # "interrupted" as the argument. Convert it back so that
  100. # pytest will exit instead of just failing the test.
  101. if e.code == "interrupted":
  102. raise KeyboardInterrupt from e
  103. return e.code == 0 or e.code is None
  104. return True
  105. @contextlib.contextmanager
  106. def chdir_manager(target: str) -> Iterator[None]:
  107. dir = os.getcwd()
  108. os.chdir(target)
  109. try:
  110. yield
  111. finally:
  112. os.chdir(dir)
  113. class TestRun(MypycDataSuite):
  114. """Test cases that build a C extension and run code."""
  115. files = files
  116. base_path = test_temp_dir
  117. optional_out = True
  118. multi_file = False
  119. separate = False # If True, using separate (incremental) compilation
  120. def run_case(self, testcase: DataDrivenTestCase) -> None:
  121. # setup.py wants to be run from the root directory of the package, which we accommodate
  122. # by chdiring into tmp/
  123. with use_custom_builtins(
  124. os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase
  125. ), chdir_manager("tmp"):
  126. self.run_case_inner(testcase)
  127. def run_case_inner(self, testcase: DataDrivenTestCase) -> None:
  128. if not os.path.isdir(WORKDIR): # (one test puts something in build...)
  129. os.mkdir(WORKDIR)
  130. text = "\n".join(testcase.input)
  131. with open("native.py", "w", encoding="utf-8") as f:
  132. f.write(text)
  133. with open("interpreted.py", "w", encoding="utf-8") as f:
  134. f.write(text)
  135. shutil.copyfile(TESTUTIL_PATH, "testutil.py")
  136. step = 1
  137. self.run_case_step(testcase, step)
  138. steps = testcase.find_steps()
  139. if steps == [[]]:
  140. steps = []
  141. for operations in steps:
  142. # To make sure that any new changes get picked up as being
  143. # new by distutils, shift the mtime of all of the
  144. # generated artifacts back by a second.
  145. fudge_dir_mtimes(WORKDIR, -1)
  146. # On Ubuntu, changing the mtime doesn't work reliably. As
  147. # a workaround, sleep.
  148. #
  149. # TODO: Figure out a better approach, since this slows down tests.
  150. if sys.platform == "linux":
  151. time.sleep(1.0)
  152. step += 1
  153. with chdir_manager(".."):
  154. perform_file_operations(operations)
  155. self.run_case_step(testcase, step)
  156. def run_case_step(self, testcase: DataDrivenTestCase, incremental_step: int) -> None:
  157. bench = testcase.config.getoption("--bench", False) and "Benchmark" in testcase.name
  158. options = Options()
  159. options.use_builtins_fixtures = True
  160. options.show_traceback = True
  161. options.strict_optional = True
  162. options.python_version = sys.version_info[:2]
  163. options.export_types = True
  164. options.preserve_asts = True
  165. options.allow_empty_bodies = True
  166. options.incremental = self.separate
  167. options.enable_incomplete_feature = [TYPE_VAR_TUPLE, UNPACK]
  168. # Avoid checking modules/packages named 'unchecked', to provide a way
  169. # to test interacting with code we don't have types for.
  170. options.per_module_options["unchecked.*"] = {"follow_imports": "error"}
  171. source = build.BuildSource("native.py", "native", None)
  172. sources = [source]
  173. module_names = ["native"]
  174. module_paths = ["native.py"]
  175. # Hard code another module name to compile in the same compilation unit.
  176. to_delete = []
  177. for fn, text in testcase.files:
  178. fn = os.path.relpath(fn, test_temp_dir)
  179. if os.path.basename(fn).startswith("other") and fn.endswith(".py"):
  180. name = fn.split(".")[0].replace(os.sep, ".")
  181. module_names.append(name)
  182. sources.append(build.BuildSource(fn, name, None))
  183. to_delete.append(fn)
  184. module_paths.append(fn)
  185. shutil.copyfile(fn, os.path.join(os.path.dirname(fn), name + "_interpreted.py"))
  186. for source in sources:
  187. options.per_module_options.setdefault(source.module, {})["mypyc"] = True
  188. separate = (
  189. self.get_separate("\n".join(testcase.input), incremental_step)
  190. if self.separate
  191. else False
  192. )
  193. groups = construct_groups(sources, separate, len(module_names) > 1)
  194. try:
  195. compiler_options = CompilerOptions(multi_file=self.multi_file, separate=self.separate)
  196. result = emitmodule.parse_and_typecheck(
  197. sources=sources,
  198. options=options,
  199. compiler_options=compiler_options,
  200. groups=groups,
  201. alt_lib_path=".",
  202. )
  203. errors = Errors(options)
  204. ir, cfiles = emitmodule.compile_modules_to_c(
  205. result, compiler_options=compiler_options, errors=errors, groups=groups
  206. )
  207. if errors.num_errors:
  208. errors.flush_errors()
  209. assert False, "Compile error"
  210. except CompileError as e:
  211. for line in e.messages:
  212. print(fix_native_line_number(line, testcase.file, testcase.line))
  213. assert False, "Compile error"
  214. # Check that serialization works on this IR. (Only on the first
  215. # step because the returned ir only includes updated code.)
  216. if incremental_step == 1:
  217. check_serialization_roundtrip(ir)
  218. opt_level = int(os.environ.get("MYPYC_OPT_LEVEL", 0))
  219. debug_level = int(os.environ.get("MYPYC_DEBUG_LEVEL", 0))
  220. setup_file = os.path.abspath(os.path.join(WORKDIR, "setup.py"))
  221. # We pass the C file information to the build script via setup.py unfortunately
  222. with open(setup_file, "w", encoding="utf-8") as f:
  223. f.write(
  224. setup_format.format(
  225. module_paths, separate, cfiles, self.multi_file, opt_level, debug_level
  226. )
  227. )
  228. if not run_setup(setup_file, ["build_ext", "--inplace"]):
  229. if testcase.config.getoption("--mypyc-showc"):
  230. show_c(cfiles)
  231. assert False, "Compilation failed"
  232. # Assert that an output file got created
  233. suffix = "pyd" if sys.platform == "win32" else "so"
  234. assert glob.glob(f"native.*.{suffix}") or glob.glob(f"native.{suffix}")
  235. driver_path = "driver.py"
  236. if not os.path.isfile(driver_path):
  237. # No driver.py provided by test case. Use the default one
  238. # (mypyc/test-data/driver/driver.py) that calls each
  239. # function named test_*.
  240. default_driver = os.path.join(
  241. os.path.dirname(__file__), "..", "test-data", "driver", "driver.py"
  242. )
  243. shutil.copy(default_driver, driver_path)
  244. env = os.environ.copy()
  245. env["MYPYC_RUN_BENCH"] = "1" if bench else "0"
  246. debugger = testcase.config.getoption("debugger")
  247. if debugger:
  248. if debugger == "lldb":
  249. subprocess.check_call(["lldb", "--", sys.executable, driver_path], env=env)
  250. elif debugger == "gdb":
  251. subprocess.check_call(["gdb", "--args", sys.executable, driver_path], env=env)
  252. else:
  253. assert False, "Unsupported debugger"
  254. # TODO: find a way to automatically disable capturing
  255. # stdin/stdout when in debugging mode
  256. assert False, (
  257. "Test can't pass in debugging mode. "
  258. "(Make sure to pass -s to pytest to interact with the debugger)"
  259. )
  260. proc = subprocess.Popen(
  261. [sys.executable, driver_path],
  262. stdout=subprocess.PIPE,
  263. stderr=subprocess.STDOUT,
  264. env=env,
  265. )
  266. if sys.version_info >= (3, 12):
  267. # TODO: testDecorators1 hangs on 3.12, remove this once fixed
  268. proc.wait(timeout=30)
  269. output = proc.communicate()[0].decode("utf8")
  270. outlines = output.splitlines()
  271. if testcase.config.getoption("--mypyc-showc"):
  272. show_c(cfiles)
  273. if proc.returncode != 0:
  274. print()
  275. print("*** Exit status: %d" % proc.returncode)
  276. # Verify output.
  277. if bench:
  278. print("Test output:")
  279. print(output)
  280. else:
  281. if incremental_step == 1:
  282. msg = "Invalid output"
  283. expected = testcase.output
  284. else:
  285. msg = f"Invalid output (step {incremental_step})"
  286. expected = testcase.output2.get(incremental_step, [])
  287. if not expected:
  288. # Tweak some line numbers, but only if the expected output is empty,
  289. # as tweaked output might not match expected output.
  290. outlines = [
  291. fix_native_line_number(line, testcase.file, testcase.line) for line in outlines
  292. ]
  293. assert_test_output(testcase, outlines, msg, expected)
  294. if incremental_step > 1 and options.incremental:
  295. suffix = "" if incremental_step == 2 else str(incremental_step - 1)
  296. expected_rechecked = testcase.expected_rechecked_modules.get(incremental_step - 1)
  297. if expected_rechecked is not None:
  298. assert_module_equivalence(
  299. "rechecked" + suffix, expected_rechecked, result.manager.rechecked_modules
  300. )
  301. expected_stale = testcase.expected_stale_modules.get(incremental_step - 1)
  302. if expected_stale is not None:
  303. assert_module_equivalence(
  304. "stale" + suffix, expected_stale, result.manager.stale_modules
  305. )
  306. assert proc.returncode == 0
  307. def get_separate(self, program_text: str, incremental_step: int) -> Any:
  308. template = r"# separate{}: (\[.*\])$"
  309. m = re.search(template.format(incremental_step), program_text, flags=re.MULTILINE)
  310. if not m:
  311. m = re.search(template.format(""), program_text, flags=re.MULTILINE)
  312. if m:
  313. return ast.literal_eval(m.group(1))
  314. else:
  315. return True
  316. class TestRunMultiFile(TestRun):
  317. """Run the main multi-module tests in multi-file compilation mode.
  318. In multi-file mode each module gets compiled into a separate C file,
  319. but all modules (C files) are compiled together.
  320. """
  321. multi_file = True
  322. test_name_suffix = "_multi"
  323. files = ["run-multimodule.test", "run-mypy-sim.test"]
  324. class TestRunSeparate(TestRun):
  325. """Run the main multi-module tests in separate compilation mode.
  326. In this mode there are multiple compilation groups, which are compiled
  327. incrementally. Each group is compiled to a separate C file, and these C
  328. files are compiled separately.
  329. Each compiled module is placed into a separate compilation group, unless
  330. overridden by a special comment. Consider this example:
  331. # separate: [(["other.py", "other_b.py"], "stuff")]
  332. This puts other.py and other_b.py into a compilation group named "stuff".
  333. Any files not mentioned in the comment will get single-file groups.
  334. """
  335. separate = True
  336. test_name_suffix = "_separate"
  337. files = ["run-multimodule.test", "run-mypy-sim.test"]
  338. def fix_native_line_number(message: str, fnam: str, delta: int) -> str:
  339. """Update code locations in test case output to point to the .test file.
  340. The description of the test case is written to native.py, and line numbers
  341. in test case output often are relative to native.py. This translates the
  342. line numbers to be relative to the .test file that contains the test case
  343. description, and also updates the file name to the .test file name.
  344. Args:
  345. message: message to update
  346. fnam: path of the .test file
  347. delta: line number of the beginning of the test case in the .test file
  348. Returns updated message (or original message if we couldn't find anything).
  349. """
  350. fnam = os.path.basename(fnam)
  351. message = re.sub(
  352. r"native\.py:([0-9]+):", lambda m: "%s:%d:" % (fnam, int(m.group(1)) + delta), message
  353. )
  354. message = re.sub(
  355. r'"native.py", line ([0-9]+),',
  356. lambda m: '"%s", line %d,' % (fnam, int(m.group(1)) + delta),
  357. message,
  358. )
  359. return message