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