Debian Codegraph @

mypyc/test/test_exceptions.py

raw
1 """Test runner for exception handling transform test cases.
2
3 The transform inserts exception handling branch operations to IR.
4 """
5
6 from __future__ import annotations
7
8 import os.path
9
10 from mypy.errors import CompileError
11 from mypy.test.config import test_temp_dir
12 from mypy.test.data import DataDrivenTestCase
13 from mypyc.analysis.blockfreq import frequently_executed_blocks
14 from mypyc.common import IS_FREE_THREADED, TOP_LEVEL_NAME
15 from mypyc.ir.pprint import format_func
16 from mypyc.test.testutil import (
17 ICODE_GEN_BUILTINS,
18 MypycDataSuite,
19 assert_test_output,
20 build_ir_for_single_file,
21 remove_comment_lines,
22 use_custom_builtins,
23 )
24 from mypyc.transform.exceptions import insert_exception_handling
25 from mypyc.transform.refcount import insert_ref_count_opcodes
26 from mypyc.transform.uninit import insert_uninit_checks
27
28 files = ["exceptions.test", "exceptions-freq.test"]
29
30
31 class TestExceptionTransform(MypycDataSuite):
32 files = files
33 base_path = test_temp_dir
34
35 def run_case(self, testcase: DataDrivenTestCase) -> None:
36 """Perform a runtime checking transformation test case."""
37
38 if "_withgil" in testcase.name and IS_FREE_THREADED:
39 # Test case should only run on a non-free-threaded build.
40 return
41 if "_nogil" in testcase.name and not IS_FREE_THREADED:
42 # Test case should only run on a free-threaded build.
43 return
44
45 with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):
46 expected_output = remove_comment_lines(testcase.output)
47 try:
48 ir = build_ir_for_single_file(testcase.input)
49 except CompileError as e:
50 actual = e.messages
51 else:
52 actual = []
53 for fn in ir:
54 if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith("_toplevel"):
55 continue
56 insert_uninit_checks(fn, True)
57 insert_exception_handling(fn, True)
58 insert_ref_count_opcodes(fn)
59 actual.extend(format_func(fn))
60 if testcase.name.endswith("_freq"):
61 common = frequently_executed_blocks(fn.blocks[0])
62 actual.append("hot blocks: %s" % sorted(b.label for b in common))
63
64 assert_test_output(testcase, actual, "Invalid source code output", expected_output)