src/eric7/DebugClients/Python/coverage/xmlreport.py

branch
eric7
changeset 9209
b99e7fd55fd3
parent 9099
0e511e0e94a3
equal deleted inserted replaced
9208:3fc8dfeb6ebe 9209:b99e7fd55fd3
1 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2 # For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
3
4 """XML reporting for coverage.py"""
5
6 import os
7 import os.path
8 import sys
9 import time
10 import xml.dom.minidom
11
12 from coverage import __url__, __version__, files
13 from coverage.misc import isolate_module, human_sorted, human_sorted_items
14 from coverage.report import get_analysis_to_report
15
16 os = isolate_module(os)
17
18
19 DTD_URL = 'https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd'
20
21
22 def rate(hit, num):
23 """Return the fraction of `hit`/`num`, as a string."""
24 if num == 0:
25 return "1"
26 else:
27 return "%.4g" % (float(hit) / num)
28
29
30 class XmlReporter:
31 """A reporter for writing Cobertura-style XML coverage results."""
32
33 report_type = "XML report"
34
35 def __init__(self, coverage):
36 self.coverage = coverage
37 self.config = self.coverage.config
38
39 self.source_paths = set()
40 if self.config.source:
41 for src in self.config.source:
42 if os.path.exists(src):
43 if not self.config.relative_files:
44 src = files.canonical_filename(src)
45 self.source_paths.add(src)
46 self.packages = {}
47 self.xml_out = None
48
49 def report(self, morfs, outfile=None):
50 """Generate a Cobertura-compatible XML report for `morfs`.
51
52 `morfs` is a list of modules or file names.
53
54 `outfile` is a file object to write the XML to.
55
56 """
57 # Initial setup.
58 outfile = outfile or sys.stdout
59 has_arcs = self.coverage.get_data().has_arcs()
60
61 # Create the DOM that will store the data.
62 impl = xml.dom.minidom.getDOMImplementation()
63 self.xml_out = impl.createDocument(None, "coverage", None)
64
65 # Write header stuff.
66 xcoverage = self.xml_out.documentElement
67 xcoverage.setAttribute("version", __version__)
68 xcoverage.setAttribute("timestamp", str(int(time.time()*1000)))
69 xcoverage.appendChild(self.xml_out.createComment(
70 f" Generated by coverage.py: {__url__} "
71 ))
72 xcoverage.appendChild(self.xml_out.createComment(f" Based on {DTD_URL} "))
73
74 # Call xml_file for each file in the data.
75 for fr, analysis in get_analysis_to_report(self.coverage, morfs):
76 self.xml_file(fr, analysis, has_arcs)
77
78 xsources = self.xml_out.createElement("sources")
79 xcoverage.appendChild(xsources)
80
81 # Populate the XML DOM with the source info.
82 for path in human_sorted(self.source_paths):
83 xsource = self.xml_out.createElement("source")
84 xsources.appendChild(xsource)
85 txt = self.xml_out.createTextNode(path)
86 xsource.appendChild(txt)
87
88 lnum_tot, lhits_tot = 0, 0
89 bnum_tot, bhits_tot = 0, 0
90
91 xpackages = self.xml_out.createElement("packages")
92 xcoverage.appendChild(xpackages)
93
94 # Populate the XML DOM with the package info.
95 for pkg_name, pkg_data in human_sorted_items(self.packages.items()):
96 class_elts, lhits, lnum, bhits, bnum = pkg_data
97 xpackage = self.xml_out.createElement("package")
98 xpackages.appendChild(xpackage)
99 xclasses = self.xml_out.createElement("classes")
100 xpackage.appendChild(xclasses)
101 for _, class_elt in human_sorted_items(class_elts.items()):
102 xclasses.appendChild(class_elt)
103 xpackage.setAttribute("name", pkg_name.replace(os.sep, '.'))
104 xpackage.setAttribute("line-rate", rate(lhits, lnum))
105 if has_arcs:
106 branch_rate = rate(bhits, bnum)
107 else:
108 branch_rate = "0"
109 xpackage.setAttribute("branch-rate", branch_rate)
110 xpackage.setAttribute("complexity", "0")
111
112 lnum_tot += lnum
113 lhits_tot += lhits
114 bnum_tot += bnum
115 bhits_tot += bhits
116
117 xcoverage.setAttribute("lines-valid", str(lnum_tot))
118 xcoverage.setAttribute("lines-covered", str(lhits_tot))
119 xcoverage.setAttribute("line-rate", rate(lhits_tot, lnum_tot))
120 if has_arcs:
121 xcoverage.setAttribute("branches-valid", str(bnum_tot))
122 xcoverage.setAttribute("branches-covered", str(bhits_tot))
123 xcoverage.setAttribute("branch-rate", rate(bhits_tot, bnum_tot))
124 else:
125 xcoverage.setAttribute("branches-covered", "0")
126 xcoverage.setAttribute("branches-valid", "0")
127 xcoverage.setAttribute("branch-rate", "0")
128 xcoverage.setAttribute("complexity", "0")
129
130 # Write the output file.
131 outfile.write(serialize_xml(self.xml_out))
132
133 # Return the total percentage.
134 denom = lnum_tot + bnum_tot
135 if denom == 0:
136 pct = 0.0
137 else:
138 pct = 100.0 * (lhits_tot + bhits_tot) / denom
139 return pct
140
141 def xml_file(self, fr, analysis, has_arcs):
142 """Add to the XML report for a single file."""
143
144 if self.config.skip_empty:
145 if analysis.numbers.n_statements == 0:
146 return
147
148 # Create the 'lines' and 'package' XML elements, which
149 # are populated later. Note that a package == a directory.
150 filename = fr.filename.replace("\\", "/")
151 for source_path in self.source_paths:
152 source_path = files.canonical_filename(source_path)
153 if filename.startswith(source_path.replace("\\", "/") + "/"):
154 rel_name = filename[len(source_path)+1:]
155 break
156 else:
157 rel_name = fr.relative_filename()
158 self.source_paths.add(fr.filename[:-len(rel_name)].rstrip(r"\/"))
159
160 dirname = os.path.dirname(rel_name) or "."
161 dirname = "/".join(dirname.split("/")[:self.config.xml_package_depth])
162 package_name = dirname.replace("/", ".")
163
164 package = self.packages.setdefault(package_name, [{}, 0, 0, 0, 0])
165
166 xclass = self.xml_out.createElement("class")
167
168 xclass.appendChild(self.xml_out.createElement("methods"))
169
170 xlines = self.xml_out.createElement("lines")
171 xclass.appendChild(xlines)
172
173 xclass.setAttribute("name", os.path.relpath(rel_name, dirname))
174 xclass.setAttribute("filename", rel_name.replace("\\", "/"))
175 xclass.setAttribute("complexity", "0")
176
177 branch_stats = analysis.branch_stats()
178 missing_branch_arcs = analysis.missing_branch_arcs()
179
180 # For each statement, create an XML 'line' element.
181 for line in sorted(analysis.statements):
182 xline = self.xml_out.createElement("line")
183 xline.setAttribute("number", str(line))
184
185 # Q: can we get info about the number of times a statement is
186 # executed? If so, that should be recorded here.
187 xline.setAttribute("hits", str(int(line not in analysis.missing)))
188
189 if has_arcs:
190 if line in branch_stats:
191 total, taken = branch_stats[line]
192 xline.setAttribute("branch", "true")
193 xline.setAttribute(
194 "condition-coverage",
195 "%d%% (%d/%d)" % (100*taken//total, taken, total)
196 )
197 if line in missing_branch_arcs:
198 annlines = ["exit" if b < 0 else str(b) for b in missing_branch_arcs[line]]
199 xline.setAttribute("missing-branches", ",".join(annlines))
200 xlines.appendChild(xline)
201
202 class_lines = len(analysis.statements)
203 class_hits = class_lines - len(analysis.missing)
204
205 if has_arcs:
206 class_branches = sum(t for t, k in branch_stats.values())
207 missing_branches = sum(t - k for t, k in branch_stats.values())
208 class_br_hits = class_branches - missing_branches
209 else:
210 class_branches = 0.0
211 class_br_hits = 0.0
212
213 # Finalize the statistics that are collected in the XML DOM.
214 xclass.setAttribute("line-rate", rate(class_hits, class_lines))
215 if has_arcs:
216 branch_rate = rate(class_br_hits, class_branches)
217 else:
218 branch_rate = "0"
219 xclass.setAttribute("branch-rate", branch_rate)
220
221 package[0][rel_name] = xclass
222 package[1] += class_hits
223 package[2] += class_lines
224 package[3] += class_br_hits
225 package[4] += class_branches
226
227
228 def serialize_xml(dom):
229 """Serialize a minidom node to XML."""
230 return dom.toprettyxml()

eric ide

mercurial