Debian Codegraph @

test/sanity/code-smell/mypy.py

raw
1 """Sanity test which executes mypy."""
2
3 from __future__ import annotations
4
5 import dataclasses
6 import os
7 import pathlib
8 import re
9 import subprocess
10 import sys
11 import typing as t
12
13 vendored_paths = (
14 'lib/ansible/module_utils/six/__init__.py',
15 'lib/ansible/module_utils/distro/_distro.py',
16 )
17
18 config_dir = pathlib.Path(__file__).parent / 'mypy'
19
20
21 def main() -> None:
22 """Main program entry point."""
23 paths = sys.argv[1:] or sys.stdin.read().splitlines()
24 paths = [path for path in paths if path not in vendored_paths] # FUTURE: define the exclusions in config so the paths can be skipped earlier
25
26 if not paths:
27 return
28
29 python_version = os.environ['ANSIBLE_TEST_TARGET_PYTHON_VERSION']
30 controller_python_versions = os.environ['ANSIBLE_TEST_CONTROLLER_PYTHON_VERSIONS'].split(',')
31 remote_only_python_versions = os.environ['ANSIBLE_TEST_REMOTE_ONLY_PYTHON_VERSIONS'].split(',')
32
33 contexts = (
34 MyPyContext('ansible-test', ['test/lib/ansible_test/'], controller_python_versions),
35 MyPyContext('ansible-test', ['test/lib/ansible_test/_util/target/'], remote_only_python_versions),
36 MyPyContext('ansible-core', ['lib/ansible/'], controller_python_versions),
37 MyPyContext('ansible-core', ['lib/ansible/modules/', 'lib/ansible/module_utils/'], remote_only_python_versions),
38 MyPyContext('ansible-core', ['test/units/'], controller_python_versions),
39 MyPyContext('ansible-core', ['test/units/modules/', 'test/units/module_utils/'], remote_only_python_versions),
40 MyPyContext('packaging', ['packaging/'], controller_python_versions),
41 )
42
43 unfiltered_messages: list[SanityMessage] = []
44
45 for context in contexts:
46 if python_version not in context.python_versions:
47 continue
48
49 unfiltered_messages.extend(test_context(python_version, context, paths))
50
51 notices = []
52 messages = []
53
54 for message in unfiltered_messages:
55 if message.level != 'error':
56 notices.append(message)
57 continue
58
59 match = re.search(r'^(?P<message>.*) {2}\[(?P<code>.*)]$', message.message)
60
61 messages.append(
62 SanityMessage(
63 message=match.group('message'),
64 path=message.path,
65 line=message.line,
66 column=message.column,
67 level=message.level,
68 code=match.group('code'),
69 )
70 )
71
72 # FUTURE: provide a way for script based tests to report non-error messages (in this case, notices)
73
74 # The following error codes from mypy indicate that results are incomplete.
75 # That prevents the test from completing successfully, just as if mypy were to traceback or generate unexpected output.
76 fatal_error_codes = {
77 'import',
78 'syntax',
79 }
80
81 fatal_errors = [message for message in messages if message.code in fatal_error_codes]
82
83 if fatal_errors:
84 error_message = '\n'.join(error.format() for error in fatal_errors)
85 raise Exception(f'Encountered {len(fatal_errors)} fatal errors reported by mypy:\n{error_message}')
86
87 paths_set = set(paths)
88
89 # Only report messages for paths that were specified as targets.
90 # Imports in our code are followed by mypy in order to perform its analysis, which is important for accurate results.
91 # However, it will also report issues on those files, which is not the desired behavior.
92 messages = [message for message in messages if message.path in paths_set]
93
94 for message in messages:
95 print(message.format())
96
97
98 def test_context(
99 python_version: str,
100 context: MyPyContext,
101 paths: list[str],
102 ) -> list[SanityMessage]:
103 """Run mypy tests for the specified context."""
104 context_paths = [path for path in paths if any(path.startswith(match_path) for match_path in context.paths)]
105
106 if not context_paths:
107 return []
108
109 config_path = config_dir / f'{context.name}.ini'
110
111 # FUTURE: provide a way for script based tests to report progress and other diagnostic information
112 # display.info(f'Checking context "{context.name}"', verbosity=1)
113
114 env = os.environ.copy()
115 env['MYPYPATH'] = env['PYTHONPATH']
116
117 # The --no-site-packages option should not be used, as it will prevent loading of type stubs from the sanity test virtual environment.
118
119 # Enabling the --warn-unused-configs option would help keep the config files clean.
120 # However, the option can only be used when all files in tested contexts are evaluated.
121 # Unfortunately sanity tests have no way of making that determination currently.
122 # The option is also incompatible with incremental mode and caching.
123
124 cmd = [
125 # Below are arguments common to all contexts.
126 # They are kept here to avoid repetition in each config file.
127 sys.executable,
128 '-m', 'mypy',
129 '--show-column-numbers',
130 '--show-error-codes',
131 '--no-error-summary',
132 # This is a fairly common pattern in our code, so we'll allow it.
133 '--allow-redefinition',
134 # Since we specify the path(s) to test, it's important that mypy is configured to use the default behavior of following imports.
135 '--follow-imports', 'normal',
136 # Incremental results and caching do not provide significant performance benefits.
137 # It also prevents the use of the --warn-unused-configs option.
138 '--no-incremental',
139 '--cache-dir', '/dev/null',
140 # The platform is specified here so that results are consistent regardless of what platform the tests are run from.
141 # In the future, if testing of other platforms is desired, the platform should become part of the test specification, just like the Python version.
142 '--platform', 'linux',
143 # Despite what the documentation [1] states, the --python-version option does not cause mypy to search for a corresponding Python executable.
144 # It will instead use the Python executable that is used to run mypy itself.
145 # The --python-executable option can be used to specify the Python executable, with the default being the executable used to run mypy.
146 # As a precaution, that option is used in case the behavior of mypy is updated in the future to match the documentation.
147 # That should help guarantee that the Python executable providing type hints is the one used to run mypy.
148 # [1] https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-python-version
149 '--python-executable', sys.executable,
150 '--python-version', python_version,
151 # Below are context specific arguments.
152 # They are primarily useful for listing individual 'ignore_missing_imports' entries instead of using a global ignore.
153 '--config-file', config_path,
154 ] # fmt: skip
155
156 cmd.extend(context_paths)
157
158 try:
159 completed_process = subprocess.run(cmd, env=env, capture_output=True, check=True, text=True)
160 stdout, stderr = completed_process.stdout, completed_process.stderr
161
162 if stdout or stderr:
163 raise Exception(f'{stdout=} {stderr=}')
164 except subprocess.CalledProcessError as ex:
165 if ex.returncode != 1 or ex.stderr or not ex.stdout:
166 raise Exception(f'{ex.stdout=} {ex.stderr=} {ex.returncode=}') from ex
167
168 stdout = ex.stdout
169
170 pattern = re.compile(r'^(?P<path>[^:]*):(?P<line>[0-9]+):((?P<column>[0-9]+):)? (?P<level>[^:]+): (?P<message>.*)$')
171
172 parsed = parse_to_list_of_dict(pattern, stdout or '')
173
174 messages = [
175 SanityMessage(
176 level=r['level'],
177 message=r['message'],
178 path=r['path'],
179 line=int(r['line']),
180 column=int(r.get('column') or '0'),
181 code='', # extracted from error level messages later
182 )
183 for r in parsed
184 ]
185
186 return messages
187
188
189 @dataclasses.dataclass(frozen=True)
190 class MyPyContext:
191 """Context details for a single run of mypy."""
192
193 name: str
194 paths: list[str]
195 python_versions: list[str]
196
197
198 @dataclasses.dataclass(frozen=True)
199 class SanityMessage:
200 message: str
201 path: str
202 line: int
203 column: int
204 level: str
205 code: str
206
207 def format(self) -> str:
208 if self.code:
209 msg = f'{self.code}: {self.message}'
210 else:
211 msg = self.message
212
213 return f'{self.path}:{self.line}:{self.column}: {msg}'
214
215
216 def parse_to_list_of_dict(pattern: re.Pattern, value: str) -> list[dict[str, t.Any]]:
217 matched = []
218 unmatched = []
219
220 for line in value.splitlines():
221 match = re.search(pattern, line)
222
223 if match:
224 matched.append(match.groupdict())
225 else:
226 unmatched.append(line)
227
228 if unmatched:
229 raise Exception(f'Pattern {pattern!r} did not match values:\n' + '\n'.join(unmatched))
230
231 return matched
232
233
234 if __name__ == '__main__':
235 main()