Debian Codegraph @

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

raw
1 """Generate XML code coverage reports."""
2
3 from __future__ import annotations
4
5 import os
6 import time
7
8 from xml.etree.ElementTree import (
9 Comment,
10 Element,
11 SubElement,
12 tostring,
13 )
14
15 from xml.dom import (
16 minidom,
17 )
18
19 from ...io import (
20 make_dirs,
21 read_json_file,
22 )
23
24 from ...util_common import (
25 ResultType,
26 write_text_test_results,
27 )
28
29 from ...util import (
30 get_ansible_version,
31 )
32
33 from ...data import (
34 data_context,
35 )
36
37 from ...provisioning import (
38 prepare_profiles,
39 )
40
41 from .combine import (
42 combine_coverage_files,
43 CoverageCombineConfig,
44 )
45
46 from . import (
47 run_coverage,
48 )
49
50
51 def command_coverage_xml(args: CoverageXmlConfig) -> None:
52 """Generate an XML coverage report."""
53 host_state = prepare_profiles(args) # coverage xml
54 output_files = combine_coverage_files(args, host_state)
55
56 for output_file in output_files:
57 xml_name = '%s.xml' % os.path.basename(output_file)
58 if output_file.endswith('-powershell'):
59 report = _generate_powershell_xml(output_file)
60
61 rough_string = tostring(report, 'utf-8')
62 reparsed = minidom.parseString(rough_string)
63 pretty = reparsed.toprettyxml(indent=' ')
64
65 write_text_test_results(ResultType.REPORTS, xml_name, pretty)
66 else:
67 xml_path = os.path.join(ResultType.REPORTS.path, xml_name)
68 make_dirs(ResultType.REPORTS.path)
69 run_coverage(args, host_state, output_file, 'xml', ['-i', '-o', xml_path])
70
71
72 def _generate_powershell_xml(coverage_file: str) -> Element:
73 """Generate a PowerShell coverage report XML element from the specified coverage file and return it."""
74 coverage_info = read_json_file(coverage_file)
75
76 content_root = data_context().content.root
77 is_ansible = data_context().content.is_ansible
78
79 packages: dict[str, dict[str, dict[str, int]]] = {}
80 for path, results in coverage_info.items():
81 filename = os.path.splitext(os.path.basename(path))[0]
82
83 if filename.startswith('Ansible.ModuleUtils'):
84 package = 'ansible.module_utils'
85 elif is_ansible:
86 package = 'ansible.modules'
87 else:
88 rel_path = path[len(content_root) + 1:]
89 plugin_type = "modules" if rel_path.startswith("plugins/modules") else "module_utils"
90 package = 'ansible_collections.%splugins.%s' % (data_context().content.collection.prefix, plugin_type)
91
92 if package not in packages:
93 packages[package] = {}
94
95 packages[package][path] = results
96
97 elem_coverage = Element('coverage')
98 elem_coverage.append(
99 Comment(' Generated by ansible-test from the Ansible project: https://www.ansible.com/ '))
100 elem_coverage.append(
101 Comment(' Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd '))
102
103 elem_sources = SubElement(elem_coverage, 'sources')
104
105 elem_source = SubElement(elem_sources, 'source')
106 elem_source.text = data_context().content.root
107
108 elem_packages = SubElement(elem_coverage, 'packages')
109
110 total_lines_hit = 0
111 total_line_count = 0
112
113 for package_name, package_data in packages.items():
114 lines_hit, line_count = _add_cobertura_package(elem_packages, package_name, package_data)
115
116 total_lines_hit += lines_hit
117 total_line_count += line_count
118
119 elem_coverage.attrib.update({
120 'branch-rate': '0',
121 'branches-covered': '0',
122 'branches-valid': '0',
123 'complexity': '0',
124 'line-rate': str(round(total_lines_hit / total_line_count, 4)) if total_line_count else "0",
125 'lines-covered': str(total_line_count),
126 'lines-valid': str(total_lines_hit),
127 'timestamp': str(int(time.time())),
128 'version': get_ansible_version(),
129 })
130
131 return elem_coverage
132
133
134 def _add_cobertura_package(packages: Element, package_name: str, package_data: dict[str, dict[str, int]]) -> tuple[int, int]:
135 """Add a package element to the given packages element."""
136 elem_package = SubElement(packages, 'package')
137 elem_classes = SubElement(elem_package, 'classes')
138
139 total_lines_hit = 0
140 total_line_count = 0
141
142 for path, results in package_data.items():
143 lines_hit = len([True for hits in results.values() if hits])
144 line_count = len(results)
145
146 total_lines_hit += lines_hit
147 total_line_count += line_count
148
149 elem_class = SubElement(elem_classes, 'class')
150
151 class_name = os.path.splitext(os.path.basename(path))[0]
152 if class_name.startswith("Ansible.ModuleUtils"):
153 class_name = class_name[20:]
154
155 content_root = data_context().content.root
156 filename = path
157 if filename.startswith(content_root):
158 filename = filename[len(content_root) + 1:]
159
160 elem_class.attrib.update({
161 'branch-rate': '0',
162 'complexity': '0',
163 'filename': filename,
164 'line-rate': str(round(lines_hit / line_count, 4)) if line_count else "0",
165 'name': class_name,
166 })
167
168 SubElement(elem_class, 'methods')
169
170 elem_lines = SubElement(elem_class, 'lines')
171
172 for number, hits in results.items():
173 elem_line = SubElement(elem_lines, 'line')
174 elem_line.attrib.update(
175 hits=str(hits),
176 number=str(number),
177 )
178
179 elem_package.attrib.update({
180 'branch-rate': '0',
181 'complexity': '0',
182 'line-rate': str(round(total_lines_hit / total_line_count, 4)) if total_line_count else "0",
183 'name': package_name,
184 })
185
186 return total_lines_hit, total_line_count
187
188
189 class CoverageXmlConfig(CoverageCombineConfig):
190 """Configuration for the coverage xml command."""