Debian Codegraph @

mypyc/test/test_emitmodule.py

raw
1 from __future__ import annotations
2
3 import tempfile
4 import unittest
5 from pathlib import Path
6
7 import pytest
8
9 from mypy import build
10 from mypy.options import Options
11 from mypyc.build import construct_groups
12 from mypyc.codegen import emitmodule
13 from mypyc.errors import Errors
14 from mypyc.irbuild.mapper import Mapper
15 from mypyc.options import CompilerOptions
16
17
18 class FakeSCC:
19 def __init__(self, mod_ids: list[str]) -> None:
20 self.mod_ids = mod_ids
21
22
23 class TestEmitModule(unittest.TestCase):
24 def test_compile_modules_to_ir_orders_scc_members_deterministically(self) -> None:
25 with tempfile.TemporaryDirectory() as tmp_dir, pytest.MonkeyPatch.context() as monkeypatch:
26 tmp_path = Path(tmp_dir)
27 a_py = tmp_path / "a.py"
28 b_py = tmp_path / "b.py"
29 a_py.write_text("import b\n\nclass A: pass\nclass C(A): pass\n", encoding="utf-8")
30 b_py.write_text(
31 "import a\n\nclass B(a.A): pass\nclass D(a.A): pass\n", encoding="utf-8"
32 )
33
34 sources = [
35 build.BuildSource(str(a_py), "a", None),
36 build.BuildSource(str(b_py), "b", None),
37 ]
38 options = Options()
39 options.preserve_asts = True
40 options.mypy_path = [str(tmp_path)]
41 options.cache_dir = str(tmp_path / ".mypy_cache")
42 for source in sources:
43 options.per_module_options.setdefault(source.module, {})["mypyc"] = True
44
45 compiler_options = CompilerOptions(strict_traceback_checks=True)
46 groups = construct_groups(
47 sources, False, use_shared_lib=True, group_name_override=None
48 )
49 result = emitmodule.parse_and_typecheck(sources, options, compiler_options, groups)
50 try:
51 group_map = {
52 source.module: lib_name for group, lib_name in groups for source in group
53 }
54 children_by_order = []
55 for order in (["a", "b"], ["b", "a"]):
56 monkeypatch.setattr(
57 emitmodule,
58 "sorted_components",
59 lambda graph, order=order: [FakeSCC(order)],
60 )
61 mapper = Mapper(group_map)
62 errors = Errors(options)
63 modules = emitmodule.compile_modules_to_ir(
64 result, mapper, compiler_options, errors
65 )
66 assert errors.num_errors == 0, errors.new_messages()
67 classes = {
68 cl.fullname: cl for module in modules.values() for cl in module.classes
69 }
70 children = classes["a.A"].children
71 assert children is not None
72 children_by_order.append([child.fullname for child in children])
73
74 assert children_by_order[1] == children_by_order[0]
75 finally:
76 result.manager.metastore.close()