Debian Codegraph @

test/lib/ansible_test/_internal/coverage_util.py

raw
1 """Utility code for facilitating collection of code coverage when running tests."""
2
3 from __future__ import annotations
4
5 import dataclasses
6 import os
7 import sqlite3
8 import tempfile
9 import textwrap
10 import typing as t
11
12 from .config import (
13 TestConfig,
14 )
15
16 from .io import (
17 write_text_file,
18 make_dirs,
19 open_binary_file,
20 )
21
22 from .util import (
23 ApplicationError,
24 InternalError,
25 COVERAGE_CONFIG_NAME,
26 remove_tree,
27 sanitize_host_name,
28 str_to_version,
29 )
30
31 from .data import (
32 data_context,
33 )
34
35 from .util_common import (
36 ExitHandler,
37 intercept_python,
38 ResultType,
39 )
40
41 from .host_configs import (
42 DockerConfig,
43 HostConfig,
44 OriginConfig,
45 PosixRemoteConfig,
46 PosixSshConfig,
47 PythonConfig,
48 )
49
50 from .constants import (
51 SUPPORTED_PYTHON_VERSIONS,
52 CONTROLLER_PYTHON_VERSIONS,
53 )
54
55 from .thread import (
56 mutex,
57 )
58
59
60 @dataclasses.dataclass(frozen=True)
61 class CoverageVersion:
62 """Details about a coverage version and its supported Python versions."""
63
64 coverage_version: str
65 schema_version: int
66 min_python: tuple[int, int]
67 max_python: tuple[int, int]
68
69
70 COVERAGE_VERSIONS = (
71 # IMPORTANT: Keep this in sync with the ansible-test.txt requirements file.
72 CoverageVersion('7.15.4', 7, (3, 10), (3, 15)),
73 CoverageVersion('7.10.7', 7, (3, 9), (3, 9)),
74 )
75 """
76 This tuple specifies the coverage version to use for Python version ranges.
77 """
78
79 CONTROLLER_COVERAGE_VERSION = COVERAGE_VERSIONS[0]
80 """The coverage version supported on the controller."""
81
82
83 class CoverageError(ApplicationError):
84 """Exception caused while attempting to read a coverage file."""
85
86 def __init__(self, path: str, message: str) -> None:
87 self.path = path
88 self.message = message
89
90 super().__init__(f'Error reading coverage file "{os.path.relpath(path)}": {message}')
91
92
93 def get_coverage_version(version: str) -> CoverageVersion:
94 """Return the coverage version to use with the specified Python version."""
95 python_version = str_to_version(version)
96 supported_versions = [entry for entry in COVERAGE_VERSIONS if entry.min_python <= python_version <= entry.max_python]
97
98 if not supported_versions:
99 raise InternalError(f'Python {version} has no matching entry in COVERAGE_VERSIONS.')
100
101 if len(supported_versions) > 1:
102 raise InternalError(f'Python {version} has multiple matching entries in COVERAGE_VERSIONS.')
103
104 coverage_version = supported_versions[0]
105
106 return coverage_version
107
108
109 def get_coverage_file_schema_version(path: str) -> int:
110 """
111 Return the schema version from the specified coverage file.
112 SQLite based files report schema version 1 or later.
113 JSON based files are reported as schema version 0.
114 An exception is raised if the file is not recognized or the schema version cannot be determined.
115 """
116 with open_binary_file(path) as file_obj:
117 header = file_obj.read(16)
118
119 if header.startswith(b'!coverage.py: '):
120 return 0
121
122 if header.startswith(b'SQLite'):
123 return get_sqlite_schema_version(path)
124
125 raise CoverageError(path, f'Unknown header: {header!r}')
126
127
128 def get_sqlite_schema_version(path: str) -> int:
129 """Return the schema version from a SQLite based coverage file."""
130 try:
131 with sqlite3.connect(path) as connection:
132 cursor = connection.cursor()
133 cursor.execute('select version from coverage_schema')
134 schema_version = cursor.fetchmany(1)[0][0]
135 except Exception as ex:
136 raise CoverageError(path, f'SQLite error: {ex}') from ex
137
138 if not isinstance(schema_version, int):
139 raise CoverageError(path, f'Schema version is {type(schema_version)} instead of {int}: {schema_version}')
140
141 if schema_version < 1:
142 raise CoverageError(path, f'Schema version is out-of-range: {schema_version}')
143
144 return schema_version
145
146
147 def cover_python(
148 args: TestConfig,
149 python: PythonConfig,
150 cmd: list[str],
151 target_name: str,
152 env: dict[str, str],
153 capture: bool,
154 data: t.Optional[str] = None,
155 cwd: t.Optional[str] = None,
156 ) -> tuple[t.Optional[str], t.Optional[str]]:
157 """Run a command while collecting Python code coverage."""
158 if args.coverage:
159 env.update(get_coverage_environment(args, target_name, python.version))
160
161 return intercept_python(args, python, cmd, env, capture, data, cwd)
162
163
164 def get_coverage_platform(config: HostConfig) -> str:
165 """Return the platform label for the given host config."""
166 if isinstance(config, PosixRemoteConfig):
167 platform = f'remote-{sanitize_host_name(config.name)}'
168 elif isinstance(config, DockerConfig):
169 platform = f'docker-{sanitize_host_name(config.name)}'
170 elif isinstance(config, PosixSshConfig):
171 platform = f'ssh-{sanitize_host_name(config.host)}'
172 elif isinstance(config, OriginConfig):
173 platform = 'origin' # previous versions of ansible-test used "local-{python_version}"
174 else:
175 raise NotImplementedError(f'Coverage platform label not defined for type: {type(config)}')
176
177 return platform
178
179
180 def get_coverage_environment(
181 args: TestConfig,
182 target_name: str,
183 version: str,
184 ) -> dict[str, str]:
185 """Return environment variables needed to collect code coverage."""
186 # unit tests, sanity tests and other special cases (localhost only)
187 # config is in a temporary directory
188 # results are in the source tree
189 config_file = get_coverage_config(args)
190 coverage_name = '='.join((args.command, target_name, get_coverage_platform(args.controller), f'python-{version}', 'coverage'))
191 coverage_dir = os.path.join(data_context().content.root, data_context().content.results_path, ResultType.COVERAGE.name)
192 coverage_file = os.path.join(coverage_dir, coverage_name)
193
194 make_dirs(coverage_dir)
195
196 if args.coverage_check:
197 # cause the 'coverage' module to be found, but not imported or enabled
198 coverage_file = ''
199
200 # Enable code coverage collection on local Python programs (this does not include Ansible modules).
201 # Used by the injectors to support code coverage.
202 # Used by the pytest unit test plugin to support code coverage.
203 # The COVERAGE_FILE variable is also used directly by the 'coverage' module.
204 env = dict(
205 COVERAGE_CONF=config_file,
206 COVERAGE_FILE=coverage_file,
207 )
208
209 return env
210
211
212 @mutex
213 def get_coverage_config(args: TestConfig) -> str:
214 """Return the path to the coverage config, creating the config if it does not already exist."""
215 try:
216 return get_coverage_config.path # type: ignore[attr-defined]
217 except AttributeError:
218 pass
219
220 coverage_config = generate_coverage_config()
221
222 if args.explain:
223 temp_dir = '/tmp/coverage-temp-dir'
224 else:
225 temp_dir = tempfile.mkdtemp()
226 ExitHandler.register(lambda: remove_tree(temp_dir))
227
228 path = os.path.join(temp_dir, COVERAGE_CONFIG_NAME)
229
230 if not args.explain:
231 write_text_file(path, coverage_config)
232
233 get_coverage_config.path = path # type: ignore[attr-defined]
234
235 return path
236
237
238 def generate_coverage_config() -> str:
239 """Generate code coverage configuration for tests."""
240 if data_context().content.collection:
241 coverage_config = generate_collection_coverage_config()
242 else:
243 coverage_config = generate_ansible_coverage_config()
244
245 return coverage_config
246
247
248 def generate_ansible_coverage_config() -> str:
249 """Generate code coverage configuration for Ansible tests."""
250 coverage_config = """
251 [run]
252 core = ctrace
253 branch = True
254 concurrency =
255 multiprocessing
256 thread
257 parallel = True
258
259 omit =
260 */python*/dist-packages/*
261 */python*/site-packages/*
262 */python*/distutils/*
263 */pyshared/*
264 */pytest
265 */AnsiballZ_*.py
266 */test/results/.tmp/delegation/*
267 """
268
269 coverage_config = coverage_config.lstrip()
270
271 return coverage_config
272
273
274 def generate_collection_coverage_config() -> str:
275 """Generate code coverage configuration for Ansible Collection tests."""
276 include_patterns = [
277 # {base}/ansible_collections/{ns}/{col}/*
278 os.path.join(data_context().content.root, '*'),
279 # */ansible_collections/{ns}/{col}/* (required to pick up AnsiballZ coverage)
280 os.path.join('*', data_context().content.collection.directory, '*'),
281 ]
282
283 omit_patterns = [
284 # {base}/ansible_collections/{ns}/{col}/tests/output/.tmp/delegation/*
285 os.path.join(data_context().content.root, data_context().content.results_path, '.tmp/delegation/*'),
286 ]
287
288 include = textwrap.indent('\n'.join(include_patterns), ' ' * 4)
289 omit = textwrap.indent('\n'.join(omit_patterns), ' ' * 4)
290
291 coverage_config = f"""
292 [run]
293 core = ctrace
294 branch = True
295 concurrency =
296 multiprocessing
297 thread
298 parallel = True
299 disable_warnings =
300 no-data-collected
301
302 include =
303 {include}
304
305 omit =
306 {omit}
307 """
308
309 coverage_config = coverage_config.lstrip()
310
311 return coverage_config
312
313
314 def self_check() -> None:
315 """Check for internal errors due to incorrect code changes."""
316 # Verify all supported Python versions have a coverage version.
317 for version in SUPPORTED_PYTHON_VERSIONS:
318 get_coverage_version(version)
319
320 # Verify all controller Python versions are mapped to the latest coverage version.
321 for version in CONTROLLER_PYTHON_VERSIONS:
322 if get_coverage_version(version) != CONTROLLER_COVERAGE_VERSION:
323 raise InternalError(f'Controller Python version {version} is not mapped to the latest coverage version.')
324
325
326 self_check()