| 1 |
#!/usr/bin/env python |
| 2 |
# PYTHON_ARGCOMPLETE_OK |
| 3 |
|
| 4 |
# (c) 2020 Red Hat, Inc. |
| 5 |
# |
| 6 |
# This file is part of Ansible |
| 7 |
# |
| 8 |
# Ansible is free software: you can redistribute it and/or modify |
| 9 |
# it under the terms of the GNU General Public License as published by |
| 10 |
# the Free Software Foundation, either version 3 of the License, or |
| 11 |
# (at your option) any later version. |
| 12 |
# |
| 13 |
# Ansible is distributed in the hope that it will be useful, |
| 14 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
# GNU General Public License for more details. |
| 17 |
# |
| 18 |
# You should have received a copy of the GNU General Public License |
| 19 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 20 |
"""CLI tool for reporting on incidental test coverage.""" |
| 21 |
from __future__ import annotations |
| 22 |
|
| 23 |
# noinspection PyCompatibility |
| 24 |
import argparse |
| 25 |
import glob |
| 26 |
import json |
| 27 |
import os |
| 28 |
import re |
| 29 |
import subprocess |
| 30 |
import sys |
| 31 |
import hashlib |
| 32 |
|
| 33 |
try: |
| 34 |
# noinspection PyPackageRequirements |
| 35 |
import argcomplete |
| 36 |
except ImportError: |
| 37 |
argcomplete = None |
| 38 |
|
| 39 |
# Following changes should be made to improve the overall style: |
| 40 |
# TODO use new style formatting method. |
| 41 |
# TODO type hints. |
| 42 |
# TODO pathlib. |
| 43 |
|
| 44 |
|
| 45 |
def main(): |
| 46 |
"""Main program body.""" |
| 47 |
args = parse_args() |
| 48 |
|
| 49 |
try: |
| 50 |
incidental_report(args) |
| 51 |
except ApplicationError as ex: |
| 52 |
sys.exit(ex) |
| 53 |
|
| 54 |
|
| 55 |
def parse_args(): |
| 56 |
"""Parse and return args.""" |
| 57 |
source = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 58 |
|
| 59 |
parser = argparse.ArgumentParser(description='Report on incidental test coverage downloaded from Azure Pipelines.') |
| 60 |
|
| 61 |
parser.add_argument('result', |
| 62 |
type=directory, |
| 63 |
help='path to directory containing test results downloaded from Azure Pipelines') |
| 64 |
|
| 65 |
parser.add_argument('--output', |
| 66 |
type=optional_directory, |
| 67 |
default=os.path.join(source, 'test', 'results', '.tmp', 'incidental'), |
| 68 |
help='path to directory where reports should be written') |
| 69 |
|
| 70 |
parser.add_argument('--source', |
| 71 |
type=optional_directory, |
| 72 |
default=source, |
| 73 |
help='path to git repository containing Ansible source') |
| 74 |
|
| 75 |
parser.add_argument('--skip-checks', |
| 76 |
action='store_true', |
| 77 |
help='skip integrity checks, use only for debugging') |
| 78 |
|
| 79 |
parser.add_argument('--ignore-cache', |
| 80 |
dest='use_cache', |
| 81 |
action='store_false', |
| 82 |
help='ignore cached files') |
| 83 |
|
| 84 |
parser.add_argument('-v', '--verbose', |
| 85 |
action='store_true', |
| 86 |
help='increase verbosity') |
| 87 |
|
| 88 |
parser.add_argument('--result-sha', |
| 89 |
default=None, |
| 90 |
help='Override the result sha') |
| 91 |
|
| 92 |
targets = parser.add_mutually_exclusive_group() |
| 93 |
|
| 94 |
targets.add_argument('--targets', |
| 95 |
type=regex, |
| 96 |
default='^incidental_', |
| 97 |
help='regex for targets to analyze, default: %(default)s') |
| 98 |
|
| 99 |
targets.add_argument('--plugin-path', |
| 100 |
help='path to plugin to report incidental coverage on') |
| 101 |
|
| 102 |
if argcomplete: |
| 103 |
argcomplete.autocomplete(parser) |
| 104 |
|
| 105 |
args = parser.parse_args() |
| 106 |
|
| 107 |
return args |
| 108 |
|
| 109 |
|
| 110 |
def optional_directory(value): |
| 111 |
if not os.path.exists(value): |
| 112 |
return value |
| 113 |
|
| 114 |
return directory(value) |
| 115 |
|
| 116 |
|
| 117 |
def directory(value): |
| 118 |
if not os.path.isdir(value): |
| 119 |
raise argparse.ArgumentTypeError('"%s" is not a directory' % value) |
| 120 |
|
| 121 |
return value |
| 122 |
|
| 123 |
|
| 124 |
def regex(value): |
| 125 |
try: |
| 126 |
return re.compile(value) |
| 127 |
except Exception as ex: |
| 128 |
raise argparse.ArgumentTypeError('"%s" is not a valid regex: %s' % (value, ex)) |
| 129 |
|
| 130 |
|
| 131 |
def incidental_report(args): |
| 132 |
"""Generate incidental coverage report.""" |
| 133 |
ct = CoverageTool() |
| 134 |
git = Git(os.path.abspath(args.source)) |
| 135 |
coverage_data = CoverageData(os.path.abspath(args.result)) |
| 136 |
|
| 137 |
result_sha = args.result_sha or coverage_data.result_sha |
| 138 |
|
| 139 |
try: |
| 140 |
git.show([result_sha, '--']) |
| 141 |
except subprocess.CalledProcessError: |
| 142 |
raise ApplicationError('%s: commit not found: %s\n' |
| 143 |
'make sure your source repository is up-to-date' % (git.path, result_sha)) |
| 144 |
|
| 145 |
if coverage_data.result != "succeeded": |
| 146 |
check_failed(args, 'results indicate tests did not pass (result: %s)\n' |
| 147 |
're-run until passing, then download the latest results and re-run the report using those results' % coverage_data.result) |
| 148 |
|
| 149 |
if not coverage_data.paths: |
| 150 |
raise ApplicationError('no coverage data found\n' |
| 151 |
'make sure the downloaded results are from a code coverage run on Azure Pipelines') |
| 152 |
|
| 153 |
# generate a unique subdirectory in the output directory based on the input files being used |
| 154 |
path_hash = hashlib.sha256(b'\n'.join(p.encode() for p in coverage_data.paths)).hexdigest() |
| 155 |
output_path = os.path.abspath(os.path.join(args.output, path_hash)) |
| 156 |
|
| 157 |
data_path = os.path.join(output_path, 'data') |
| 158 |
reports_path = os.path.join(output_path, 'reports') |
| 159 |
|
| 160 |
for path in [data_path, reports_path]: |
| 161 |
if not os.path.exists(path): |
| 162 |
os.makedirs(path) |
| 163 |
|
| 164 |
# combine coverage results into a single file |
| 165 |
combined_path = os.path.join(output_path, 'combined.json') |
| 166 |
cached(combined_path, args.use_cache, args.verbose, |
| 167 |
lambda: ct.combine(coverage_data.paths, combined_path)) |
| 168 |
|
| 169 |
with open(combined_path) as combined_file: |
| 170 |
combined = json.load(combined_file) |
| 171 |
|
| 172 |
if args.plugin_path: |
| 173 |
# reporting on coverage missing from the test target for the specified plugin |
| 174 |
# the report will be on a single target |
| 175 |
cache_path_format = '%s' + '-for-%s' % os.path.splitext(os.path.basename(args.plugin_path))[0] |
| 176 |
target_pattern = '^%s$' % get_target_name_from_plugin_path(args.plugin_path) |
| 177 |
include_path = args.plugin_path |
| 178 |
missing = True |
| 179 |
target_name = get_target_name_from_plugin_path(args.plugin_path) |
| 180 |
else: |
| 181 |
# reporting on coverage exclusive to the matched targets |
| 182 |
# the report can contain multiple targets |
| 183 |
cache_path_format = '%s' |
| 184 |
target_pattern = args.targets |
| 185 |
include_path = None |
| 186 |
missing = False |
| 187 |
target_name = None |
| 188 |
|
| 189 |
# identify integration test targets to analyze |
| 190 |
target_names = sorted(combined['targets']) |
| 191 |
incidental_target_names = [target for target in target_names if re.search(target_pattern, target)] |
| 192 |
|
| 193 |
if not incidental_target_names: |
| 194 |
if target_name: |
| 195 |
# if the plugin has no tests we still want to know what coverage is missing |
| 196 |
incidental_target_names = [target_name] |
| 197 |
else: |
| 198 |
raise ApplicationError('no targets to analyze') |
| 199 |
|
| 200 |
# exclude test support plugins from analysis |
| 201 |
# also exclude six, which for an unknown reason reports bogus coverage lines (indicating coverage of comments) |
| 202 |
exclude_path = '^(test/support/|lib/ansible/module_utils/six/)' |
| 203 |
|
| 204 |
# process coverage for each target and then generate a report |
| 205 |
# save sources for generating a summary report at the end |
| 206 |
summary = {} |
| 207 |
report_paths = {} |
| 208 |
|
| 209 |
for target_name in incidental_target_names: |
| 210 |
cache_name = cache_path_format % target_name |
| 211 |
|
| 212 |
only_target_path = os.path.join(data_path, 'only-%s.json' % cache_name) |
| 213 |
cached(only_target_path, args.use_cache, args.verbose, |
| 214 |
lambda: ct.filter(combined_path, only_target_path, include_targets=[target_name], include_path=include_path, exclude_path=exclude_path)) |
| 215 |
|
| 216 |
without_target_path = os.path.join(data_path, 'without-%s.json' % cache_name) |
| 217 |
cached(without_target_path, args.use_cache, args.verbose, |
| 218 |
lambda: ct.filter(combined_path, without_target_path, exclude_targets=[target_name], include_path=include_path, exclude_path=exclude_path)) |
| 219 |
|
| 220 |
if missing: |
| 221 |
source_target_path = missing_target_path = os.path.join(data_path, 'missing-%s.json' % cache_name) |
| 222 |
cached(missing_target_path, args.use_cache, args.verbose, |
| 223 |
lambda: ct.missing(without_target_path, only_target_path, missing_target_path, only_gaps=True)) |
| 224 |
else: |
| 225 |
source_target_path = exclusive_target_path = os.path.join(data_path, 'exclusive-%s.json' % cache_name) |
| 226 |
cached(exclusive_target_path, args.use_cache, args.verbose, |
| 227 |
lambda: ct.missing(only_target_path, without_target_path, exclusive_target_path, only_gaps=True)) |
| 228 |
|
| 229 |
source_expanded_target_path = os.path.join(os.path.dirname(source_target_path), 'expanded-%s' % os.path.basename(source_target_path)) |
| 230 |
cached(source_expanded_target_path, args.use_cache, args.verbose, |
| 231 |
lambda: ct.expand(source_target_path, source_expanded_target_path)) |
| 232 |
|
| 233 |
summary[target_name] = sources = collect_sources(source_expanded_target_path, git, coverage_data, result_sha) |
| 234 |
|
| 235 |
txt_report_path = os.path.join(reports_path, '%s.txt' % cache_name) |
| 236 |
cached(txt_report_path, args.use_cache, args.verbose, |
| 237 |
lambda: generate_report(sources, txt_report_path, coverage_data, target_name, missing=missing)) |
| 238 |
|
| 239 |
report_paths[target_name] = txt_report_path |
| 240 |
|
| 241 |
# provide a summary report of results |
| 242 |
for target_name in incidental_target_names: |
| 243 |
sources = summary[target_name] |
| 244 |
report_path = os.path.relpath(report_paths[target_name]) |
| 245 |
|
| 246 |
print('%s: %d arcs, %d lines, %d files - %s' % ( |
| 247 |
target_name, |
| 248 |
sum(len(s.covered_arcs) for s in sources), |
| 249 |
sum(len(s.covered_lines) for s in sources), |
| 250 |
len(sources), |
| 251 |
report_path, |
| 252 |
)) |
| 253 |
|
| 254 |
if not missing: |
| 255 |
sys.stderr.write('NOTE: This report shows only coverage exclusive to the reported targets. ' |
| 256 |
'As targets are removed, exclusive coverage on the remaining targets will increase.\n') |
| 257 |
|
| 258 |
|
| 259 |
def get_target_name_from_plugin_path(path): # type: (str) -> str |
| 260 |
"""Return the integration test target name for the given plugin path.""" |
| 261 |
parts = os.path.splitext(path)[0].split(os.path.sep) |
| 262 |
plugin_name = parts[-1] |
| 263 |
|
| 264 |
if path.startswith('lib/ansible/modules/'): |
| 265 |
plugin_type = None |
| 266 |
elif path.startswith('lib/ansible/plugins/'): |
| 267 |
plugin_type = parts[3] |
| 268 |
elif path.startswith('lib/ansible/module_utils/'): |
| 269 |
plugin_type = parts[2] |
| 270 |
elif path.startswith('plugins/'): |
| 271 |
plugin_type = parts[1] |
| 272 |
else: |
| 273 |
raise ApplicationError('Cannot determine plugin type from plugin path: %s' % path) |
| 274 |
|
| 275 |
if plugin_type is None: |
| 276 |
target_name = plugin_name |
| 277 |
else: |
| 278 |
target_name = '%s_%s' % (plugin_type, plugin_name) |
| 279 |
|
| 280 |
return target_name |
| 281 |
|
| 282 |
|
| 283 |
class CoverageData: |
| 284 |
def __init__(self, result_path): |
| 285 |
with open(os.path.join(result_path, 'run.json')) as run_file: |
| 286 |
run = json.load(run_file) |
| 287 |
|
| 288 |
self.result_sha = run["resources"]["repositories"]["self"]["version"] |
| 289 |
self.result = run['result'] |
| 290 |
|
| 291 |
self.github_base_url = 'https://github.com/ansible/ansible/blob/%s/' % self.result_sha |
| 292 |
|
| 293 |
# locate available results |
| 294 |
self.paths = sorted(glob.glob(os.path.join(result_path, '*', 'coverage-analyze-targets.json'))) |
| 295 |
|
| 296 |
|
| 297 |
class Git: |
| 298 |
def __init__(self, path): |
| 299 |
self.git = 'git' |
| 300 |
self.path = path |
| 301 |
|
| 302 |
try: |
| 303 |
self.show() |
| 304 |
except subprocess.CalledProcessError: |
| 305 |
raise ApplicationError('%s: not a git repository' % path) |
| 306 |
|
| 307 |
def show(self, args=None): |
| 308 |
return self.run(['show'] + (args or [])) |
| 309 |
|
| 310 |
def run(self, command): |
| 311 |
return subprocess.check_output([self.git] + command, cwd=self.path) |
| 312 |
|
| 313 |
|
| 314 |
class CoverageTool: |
| 315 |
def __init__(self): |
| 316 |
self.analyze_cmd = ['ansible-test', 'coverage', 'analyze', 'targets'] |
| 317 |
|
| 318 |
def combine(self, input_paths, output_path): |
| 319 |
subprocess.check_call(self.analyze_cmd + ['combine'] + input_paths + [output_path]) |
| 320 |
|
| 321 |
def filter(self, input_path, output_path, include_targets=None, exclude_targets=None, include_path=None, exclude_path=None): |
| 322 |
args = [] |
| 323 |
|
| 324 |
if include_targets: |
| 325 |
for target in include_targets: |
| 326 |
args.extend(['--include-target', target]) |
| 327 |
|
| 328 |
if exclude_targets: |
| 329 |
for target in exclude_targets: |
| 330 |
args.extend(['--exclude-target', target]) |
| 331 |
|
| 332 |
if include_path: |
| 333 |
args.extend(['--include-path', include_path]) |
| 334 |
|
| 335 |
if exclude_path: |
| 336 |
args.extend(['--exclude-path', exclude_path]) |
| 337 |
|
| 338 |
subprocess.check_call(self.analyze_cmd + ['filter', input_path, output_path] + args) |
| 339 |
|
| 340 |
def missing(self, from_path, to_path, output_path, only_gaps=False): |
| 341 |
args = [] |
| 342 |
|
| 343 |
if only_gaps: |
| 344 |
args.append('--only-gaps') |
| 345 |
|
| 346 |
subprocess.check_call(self.analyze_cmd + ['missing', from_path, to_path, output_path] + args) |
| 347 |
|
| 348 |
def expand(self, input_path, output_path): |
| 349 |
subprocess.check_call(self.analyze_cmd + ['expand', input_path, output_path]) |
| 350 |
|
| 351 |
|
| 352 |
class SourceFile: |
| 353 |
def __init__(self, path, source, coverage_data, coverage_points): |
| 354 |
self.path = path |
| 355 |
self.lines = source.decode().splitlines() |
| 356 |
self.coverage_data = coverage_data |
| 357 |
self.coverage_points = coverage_points |
| 358 |
self.github_url = coverage_data.github_base_url + path |
| 359 |
|
| 360 |
is_arcs = ':' in dict(coverage_points).popitem()[0] |
| 361 |
|
| 362 |
if is_arcs: |
| 363 |
parse = parse_arc |
| 364 |
else: |
| 365 |
parse = int |
| 366 |
|
| 367 |
self.covered_points = set(parse(v) for v in coverage_points) |
| 368 |
self.covered_arcs = self.covered_points if is_arcs else None |
| 369 |
self.covered_lines = set(abs(p[0]) for p in self.covered_points) | set(abs(p[1]) for p in self.covered_points) |
| 370 |
|
| 371 |
|
| 372 |
def collect_sources(data_path, git, coverage_data, result_sha): |
| 373 |
with open(data_path) as data_file: |
| 374 |
data = json.load(data_file) |
| 375 |
|
| 376 |
sources = [] |
| 377 |
|
| 378 |
for path_coverage in data.values(): |
| 379 |
for path, path_data in path_coverage.items(): |
| 380 |
sources.append(SourceFile(path, git.show(['%s:%s' % (result_sha, path)]), coverage_data, path_data)) |
| 381 |
|
| 382 |
return sources |
| 383 |
|
| 384 |
|
| 385 |
def generate_report(sources, report_path, coverage_data, target_name, missing): |
| 386 |
output = [ |
| 387 |
'Target: %s (%s coverage)' % (target_name, 'missing' if missing else 'exclusive'), |
| 388 |
'GitHub: %stest/integration/targets/%s' % (coverage_data.github_base_url, target_name), |
| 389 |
] |
| 390 |
|
| 391 |
for source in sources: |
| 392 |
if source.covered_arcs: |
| 393 |
output.extend([ |
| 394 |
'', |
| 395 |
'Source: %s (%d arcs, %d/%d lines):' % (source.path, len(source.covered_arcs), len(source.covered_lines), len(source.lines)), |
| 396 |
'GitHub: %s' % source.github_url, |
| 397 |
'', |
| 398 |
]) |
| 399 |
else: |
| 400 |
output.extend([ |
| 401 |
'', |
| 402 |
'Source: %s (%d/%d lines):' % (source.path, len(source.covered_lines), len(source.lines)), |
| 403 |
'GitHub: %s' % source.github_url, |
| 404 |
'', |
| 405 |
]) |
| 406 |
|
| 407 |
last_line_no = 0 |
| 408 |
|
| 409 |
for line_no, line in enumerate(source.lines, start=1): |
| 410 |
if line_no not in source.covered_lines: |
| 411 |
continue |
| 412 |
|
| 413 |
if last_line_no and last_line_no != line_no - 1: |
| 414 |
output.append('') |
| 415 |
|
| 416 |
notes = '' |
| 417 |
|
| 418 |
if source.covered_arcs: |
| 419 |
from_lines = sorted(p[0] for p in source.covered_points if abs(p[1]) == line_no) |
| 420 |
to_lines = sorted(p[1] for p in source.covered_points if abs(p[0]) == line_no) |
| 421 |
|
| 422 |
if from_lines: |
| 423 |
notes += ' ### %s -> (here)' % ', '.join(str(from_line) for from_line in from_lines) |
| 424 |
|
| 425 |
if to_lines: |
| 426 |
notes += ' ### (here) -> %s' % ', '.join(str(to_line) for to_line in to_lines) |
| 427 |
|
| 428 |
output.append('%4d %s%s' % (line_no, line, notes)) |
| 429 |
last_line_no = line_no |
| 430 |
|
| 431 |
with open(report_path, 'w') as report_file: |
| 432 |
report_file.write('\n'.join(output) + '\n') |
| 433 |
|
| 434 |
|
| 435 |
def parse_arc(value): |
| 436 |
return tuple(int(v) for v in value.split(':')) |
| 437 |
|
| 438 |
|
| 439 |
def cached(path, use_cache, show_messages, func): |
| 440 |
if os.path.exists(path) and use_cache: |
| 441 |
if show_messages: |
| 442 |
sys.stderr.write('%s: cached\n' % path) |
| 443 |
sys.stderr.flush() |
| 444 |
return |
| 445 |
|
| 446 |
if show_messages: |
| 447 |
sys.stderr.write('%s: generating ... ' % path) |
| 448 |
sys.stderr.flush() |
| 449 |
|
| 450 |
func() |
| 451 |
|
| 452 |
if show_messages: |
| 453 |
sys.stderr.write('done\n') |
| 454 |
sys.stderr.flush() |
| 455 |
|
| 456 |
|
| 457 |
def check_failed(args, message): |
| 458 |
if args.skip_checks: |
| 459 |
sys.stderr.write('WARNING: %s\n' % message) |
| 460 |
return |
| 461 |
|
| 462 |
raise ApplicationError(message) |
| 463 |
|
| 464 |
|
| 465 |
class ApplicationError(Exception): |
| 466 |
pass |
| 467 |
|
| 468 |
|
| 469 |
if __name__ == '__main__': |
| 470 |
main() |