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