Debian Codegraph @

test/lib/ansible_test/_internal/commands/coverage/combine.py

raw
1 """Combine code coverage files."""
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import os
7 import json
8 import typing as t
9
10 from ...target import (
11 walk_compile_targets,
12 walk_powershell_targets,
13 )
14
15 from ...io import (
16 read_text_file,
17 )
18
19 from ...util import (
20 ANSIBLE_TEST_TOOLS_ROOT,
21 display,
22 ApplicationError,
23 raw_command,
24 common_environment,
25 )
26
27 from ...util_common import (
28 ResultType,
29 write_json_file,
30 write_json_test_results,
31 get_powershell_injector_env,
32 )
33
34 from ...executor import (
35 Delegate,
36 )
37
38 from ...data import (
39 data_context,
40 PayloadConfig,
41 )
42
43 from ...host_configs import (
44 DockerConfig,
45 RemoteConfig,
46 )
47
48 from ...provisioning import (
49 HostState,
50 prepare_profiles,
51 )
52
53 from . import (
54 enumerate_python_arcs,
55 enumerate_powershell_lines,
56 get_collection_path_regexes,
57 get_all_coverage_files,
58 get_python_coverage_files,
59 get_python_modules,
60 get_powershell_coverage_files,
61 initialize_coverage,
62 COVERAGE_OUTPUT_FILE_NAME,
63 COVERAGE_GROUPS,
64 CoverageConfig,
65 PathChecker,
66 )
67
68
69 def command_coverage_combine(args: CoverageCombineConfig) -> None:
70 """Patch paths in coverage files and merge into a single file."""
71 host_state = prepare_profiles(args) # coverage combine
72 combine_coverage_files(args, host_state)
73
74
75 def combine_coverage_files(args: CoverageCombineConfig, host_state: HostState) -> list[str]:
76 """Combine coverage and return a list of the resulting files."""
77 if args.delegate:
78 if isinstance(args.controller, (DockerConfig, RemoteConfig)):
79 paths = get_all_coverage_files()
80 exported_paths = [path for path in paths if os.path.basename(path).split('=')[-1].split('.')[:2] == ['coverage', 'combined']]
81
82 if not exported_paths:
83 raise ExportedCoverageDataNotFound()
84
85 pairs = [(path, os.path.relpath(path, data_context().content.root)) for path in exported_paths]
86
87 def coverage_callback(payload_config: PayloadConfig) -> None:
88 """Add the coverage files to the payload file list."""
89 display.info('Including %d exported coverage file(s) in payload.' % len(pairs), verbosity=1)
90 files = payload_config.files
91 files.extend(pairs)
92
93 data_context().register_payload_callback(coverage_callback)
94
95 raise Delegate(host_state=host_state)
96
97 paths = _command_coverage_combine_powershell(args) + _command_coverage_combine_python(args, host_state)
98
99 for path in paths:
100 display.info('Generated combined output: %s' % path, verbosity=1)
101
102 return paths
103
104
105 class ExportedCoverageDataNotFound(ApplicationError):
106 """Exception when no combined coverage data is present yet is required."""
107
108 def __init__(self) -> None:
109 super().__init__(
110 'Coverage data must be exported before processing with the `--docker` or `--remote` option.\n'
111 'Export coverage with `ansible-test coverage combine` using the `--export` option.\n'
112 'The exported files must be in the directory: %s/' % ResultType.COVERAGE.relative_path
113 )
114
115
116 def _command_coverage_combine_python(args: CoverageCombineConfig, host_state: HostState) -> list[str]:
117 """Combine Python coverage files and return a list of the output files."""
118 coverage = initialize_coverage(args, host_state)
119
120 modules = get_python_modules()
121
122 coverage_files = get_python_coverage_files()
123
124 def _default_stub_value(source_paths: list[str]) -> dict[str, set[tuple[int, int]]]:
125 return {path: {(0, 0)} for path in source_paths}
126
127 counter = 0
128 sources = _get_coverage_targets(args, walk_compile_targets)
129 groups = _build_stub_groups(args, sources, _default_stub_value)
130
131 collection_search_re, collection_sub_re = get_collection_path_regexes()
132
133 for coverage_file in coverage_files:
134 counter += 1
135 display.info('[%4d/%4d] %s' % (counter, len(coverage_files), coverage_file), verbosity=2)
136
137 group = get_coverage_group(args, coverage_file)
138
139 if group is None:
140 display.warning('Unexpected name for coverage file: %s' % coverage_file)
141 continue
142
143 for filename, arcs in enumerate_python_arcs(coverage_file, coverage, modules, collection_search_re, collection_sub_re):
144 if args.export:
145 filename = os.path.relpath(filename) # exported paths must be relative since absolute paths may differ between systems
146
147 if group not in groups:
148 groups[group] = {}
149
150 arc_data = groups[group]
151
152 if filename not in arc_data:
153 arc_data[filename] = set()
154
155 arc_data[filename].update(arcs)
156
157 output_files = []
158
159 if args.export:
160 coverage_file = os.path.join(args.export, '')
161 suffix = '=coverage.combined'
162 else:
163 coverage_file = os.path.join(ResultType.COVERAGE.path, COVERAGE_OUTPUT_FILE_NAME)
164 suffix = ''
165
166 path_checker = PathChecker(args, collection_search_re)
167
168 for group in sorted(groups):
169 arc_data = groups[group]
170 output_file = coverage_file + group + suffix
171
172 if args.explain:
173 continue
174
175 updated = coverage.CoverageData(output_file)
176
177 for filename in arc_data:
178 if not path_checker.check_path(filename):
179 continue
180
181 updated.add_arcs({filename: list(arc_data[filename])})
182
183 if args.all:
184 updated.add_arcs(dict((source[0], []) for source in sources))
185
186 updated.write() # always write files to make sure stale files do not exist
187
188 if updated:
189 # only report files which are non-empty to prevent coverage from reporting errors
190 output_files.append(output_file)
191
192 path_checker.report()
193
194 return sorted(output_files)
195
196
197 def _command_coverage_combine_powershell(args: CoverageCombineConfig) -> list[str]:
198 """Combine PowerShell coverage files and return a list of the output files."""
199 coverage_files = get_powershell_coverage_files()
200
201 def _default_stub_value(source_paths: list[str]) -> dict[str, dict[int, int]]:
202 env = common_environment()
203 env.update(get_powershell_injector_env(args.controller_powershell, env))
204
205 cmd = ['pwsh', os.path.join(ANSIBLE_TEST_TOOLS_ROOT, 'coverage_stub.ps1')]
206 cmd.extend(source_paths)
207
208 stubs = json.loads(raw_command(cmd, env=env, capture=True)[0])
209
210 return dict((d['Path'], dict((line, 0) for line in d['Lines'])) for d in stubs)
211
212 counter = 0
213 sources = _get_coverage_targets(args, walk_powershell_targets)
214 groups = _build_stub_groups(args, sources, _default_stub_value)
215
216 collection_search_re, collection_sub_re = get_collection_path_regexes()
217
218 for coverage_file in coverage_files:
219 counter += 1
220 display.info('[%4d/%4d] %s' % (counter, len(coverage_files), coverage_file), verbosity=2)
221
222 group = get_coverage_group(args, coverage_file)
223
224 if group is None:
225 display.warning('Unexpected name for coverage file: %s' % coverage_file)
226 continue
227
228 for filename, hits in enumerate_powershell_lines(coverage_file, collection_search_re, collection_sub_re):
229 if args.export:
230 filename = os.path.relpath(filename) # exported paths must be relative since absolute paths may differ between systems
231
232 if group not in groups:
233 groups[group] = {}
234
235 coverage_data = groups[group]
236
237 if filename not in coverage_data:
238 coverage_data[filename] = {}
239
240 file_coverage = coverage_data[filename]
241
242 for line_no, hit_count in hits.items():
243 file_coverage[line_no] = file_coverage.get(line_no, 0) + hit_count
244
245 output_files = []
246
247 path_checker = PathChecker(args)
248
249 for group in sorted(groups):
250 coverage_data = dict((filename, data) for filename, data in groups[group].items() if path_checker.check_path(filename))
251
252 if args.all:
253 missing_sources = [source for source, _source_line_count in sources if source not in coverage_data]
254 coverage_data.update(_default_stub_value(missing_sources))
255
256 if not args.explain:
257 if args.export:
258 output_file = os.path.join(args.export, group + '=coverage.combined')
259 write_json_file(output_file, coverage_data, formatted=False)
260 output_files.append(output_file)
261 continue
262
263 output_file = COVERAGE_OUTPUT_FILE_NAME + group + '-powershell'
264
265 write_json_test_results(ResultType.COVERAGE, output_file, coverage_data, formatted=False)
266
267 output_files.append(os.path.join(ResultType.COVERAGE.path, output_file))
268
269 path_checker.report()
270
271 return sorted(output_files)
272
273
274 def _get_coverage_targets(args: CoverageCombineConfig, walk_func: c.Callable) -> list[tuple[str, int]]:
275 """Return a list of files to cover and the number of lines in each file, using the given function as the source of the files."""
276 sources = []
277
278 if args.all or args.stub:
279 # excludes symlinks of regular files to avoid reporting on the same file multiple times
280 # in the future it would be nice to merge any coverage for symlinks into the real files
281 for target in walk_func(include_symlinks=False):
282 target_path = os.path.abspath(target.path)
283
284 target_lines = len(read_text_file(target_path).splitlines())
285
286 sources.append((target_path, target_lines))
287
288 sources.sort()
289
290 return sources
291
292
293 def _build_stub_groups[TValue](
294 args: CoverageCombineConfig,
295 sources: list[tuple[str, int]],
296 default_stub_value: c.Callable[[list[str]], dict[str, TValue]],
297 ) -> dict[str, dict[str, TValue]]:
298 """
299 Split the given list of sources with line counts into groups, maintaining a maximum line count for each group.
300 Each group consists of a dictionary of sources and default coverage stubs generated by the provided default_stub_value function.
301 """
302 groups = {}
303
304 if args.stub:
305 stub_group: list[str] = []
306 stub_groups = [stub_group]
307 stub_line_limit = 500000
308 stub_line_count = 0
309
310 for source, source_line_count in sources:
311 stub_group.append(source)
312 stub_line_count += source_line_count
313
314 if stub_line_count > stub_line_limit:
315 stub_line_count = 0
316 stub_group = []
317 stub_groups.append(stub_group)
318
319 for stub_index, stub_group in enumerate(stub_groups):
320 if not stub_group:
321 continue
322
323 groups['=stub-%02d' % (stub_index + 1)] = default_stub_value(stub_group)
324
325 return groups
326
327
328 def get_coverage_group(args: CoverageCombineConfig, coverage_file: str) -> t.Optional[str]:
329 """Return the name of the coverage group for the specified coverage file, or None if no group was found."""
330 parts = os.path.basename(coverage_file).split('=', 4)
331
332 if len(parts) != 5 or not parts[4].startswith('coverage.'):
333 return None
334
335 names = dict(
336 command=parts[0],
337 target=parts[1],
338 environment=parts[2],
339 version=parts[3],
340 )
341
342 export_names = dict(
343 version=parts[3],
344 )
345
346 group = ''
347
348 for part in COVERAGE_GROUPS:
349 if part in args.group_by:
350 group += '=%s' % names[part]
351 elif args.export:
352 group += '=%s' % export_names.get(part, 'various')
353
354 if args.export:
355 group = group.lstrip('=')
356
357 return group
358
359
360 class CoverageCombineConfig(CoverageConfig):
361 """Configuration for the coverage combine command."""
362
363 def __init__(self, args: t.Any) -> None:
364 super().__init__(args)
365
366 self.group_by: frozenset[str] = frozenset(args.group_by) if args.group_by else frozenset()
367 self.all: bool = args.all
368 self.stub: bool = args.stub
369
370 # only available to coverage combine
371 self.export: str | None = args.export if 'export' in args else None