Debian Codegraph @

src/trio/_tests/tools/test_gen_exports.py

raw
1 import ast
2 import sys
3 from pathlib import Path
4
5 import pytest
6
7 from trio._tests.pytest_plugin import skip_if_optional_else_raise
8
9 # imports in gen_exports that are not in `install_requires` in setup.py
10 try:
11 import astor # noqa: F401
12 import isort # noqa: F401
13 except ImportError as error:
14 skip_if_optional_else_raise(error)
15
16
17 from trio._tools.gen_exports import (
18 File,
19 create_passthrough_args,
20 get_public_methods,
21 process,
22 run_linters,
23 run_ruff,
24 )
25
26 from ..._core._tests.tutil import slow
27
28 SOURCE = '''from _run import _public
29 from collections import Counter
30
31 class Test:
32 @_public
33 def public_func(self):
34 """With doc string"""
35
36 @ignore_this
37 @_public
38 @another_decorator
39 async def public_async_func(self) -> Counter:
40 pass # no doc string
41
42 def not_public(self):
43 pass
44
45 async def not_public_async(self):
46 pass
47 '''
48
49 IMPORT_1 = """\
50 from collections import Counter
51 """
52
53 IMPORT_2 = """\
54 from collections import Counter
55 import os
56 """
57
58 IMPORT_3 = """\
59 from typing import TYPE_CHECKING
60 if TYPE_CHECKING:
61 from collections import Counter
62 """
63
64
65 def test_get_public_methods() -> None:
66 methods = list(get_public_methods(ast.parse(SOURCE)))
67 assert {m.name for m in methods} == {"public_func", "public_async_func"}
68
69
70 def test_create_pass_through_args() -> None:
71 testcases = [
72 ("def f()", "()"),
73 ("def f(one)", "(one)"),
74 ("def f(one, two)", "(one, two)"),
75 ("def f(one, *args)", "(one, *args)"),
76 (
77 "def f(one, *args, kw1, kw2=None, **kwargs)",
78 "(one, *args, kw1=kw1, kw2=kw2, **kwargs)",
79 ),
80 ]
81
82 for funcdef, expected in testcases:
83 func_node = ast.parse(funcdef + ":\n pass").body[0]
84 assert isinstance(func_node, ast.FunctionDef)
85 assert create_passthrough_args(func_node) == expected
86
87
88 skip_lints = pytest.mark.skipif(
89 sys.implementation.name != "cpython",
90 reason="gen_exports is internal, black/isort only runs on CPython",
91 )
92
93
94 @slow
95 @skip_lints
96 @pytest.mark.parametrize("imports", [IMPORT_1, IMPORT_2, IMPORT_3])
97 def test_process(
98 tmp_path: Path,
99 imports: str,
100 capsys: pytest.CaptureFixture[str],
101 ) -> None:
102 try:
103 import black # noqa: F401
104 # there's no dedicated CI run that has astor+isort, but lacks black.
105 except ImportError as error: # pragma: no cover
106 skip_if_optional_else_raise(error)
107
108 modpath = tmp_path / "_module.py"
109 genpath = tmp_path / "_generated_module.py"
110 modpath.write_text(SOURCE, encoding="utf-8")
111 file = File(modpath, "runner", platform="linux", imports=imports)
112 assert not genpath.exists()
113 with pytest.raises(SystemExit) as excinfo:
114 process([file], do_test=True)
115 assert excinfo.value.code == 1
116 captured = capsys.readouterr()
117 assert "Generated sources are outdated. Please regenerate." in captured.out
118 with pytest.raises(SystemExit) as excinfo:
119 process([file], do_test=False)
120 assert excinfo.value.code == 1
121 captured = capsys.readouterr()
122 assert "Regenerated sources successfully." in captured.out
123 assert genpath.exists()
124 process([file], do_test=True)
125 # But if we change the lookup path it notices
126 with pytest.raises(SystemExit) as excinfo:
127 process(
128 [File(modpath, "runner.io_manager", platform="linux", imports=imports)],
129 do_test=True,
130 )
131 assert excinfo.value.code == 1
132 # Also if the platform is changed.
133 with pytest.raises(SystemExit) as excinfo:
134 process([File(modpath, "runner", imports=imports)], do_test=True)
135 assert excinfo.value.code == 1
136
137
138 @skip_lints
139 def test_run_ruff(tmp_path: Path) -> None:
140 """Test that processing properly fails if ruff does."""
141 try:
142 import ruff # noqa: F401
143 except ImportError as error: # pragma: no cover
144 skip_if_optional_else_raise(error)
145
146 file = File(tmp_path / "module.py", "module")
147
148 success, _ = run_ruff(file, "class not valid code ><")
149 assert not success
150
151 test_function = '''def combine_and(data: list[str]) -> str:
152 """Join values of text, and have 'and' with the last one properly."""
153 if len(data) >= 2:
154 data[-1] = 'and ' + data[-1]
155 if len(data) > 2:
156 return ', '.join(data)
157 return ' '.join(data)'''
158
159 success, response = run_ruff(file, test_function)
160 assert success
161 assert response == test_function
162
163
164 @skip_lints
165 def test_lint_failure(tmp_path: Path) -> None:
166 """Test that processing properly fails if black or ruff does."""
167 try:
168 import black # noqa: F401
169 import ruff # noqa: F401
170 except ImportError as error: # pragma: no cover
171 skip_if_optional_else_raise(error)
172
173 file = File(tmp_path / "module.py", "module")
174
175 with pytest.raises(SystemExit):
176 run_linters(file, "class not valid code ><")
177
178 with pytest.raises(SystemExit):
179 run_linters(file, "import waffle\n;import trio")