1# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
3
4"""XML reporting for coverage.py"""
5
6import os
7import os.path
8import sys
9import time
10import xml.dom.minidom
11
12from coverage import env
13from coverage import __url__, __version__, files
14from coverage.misc import isolate_module
15from coverage.report import Reporter
16
17os = isolate_module(os)
18
19
20DTD_URL = (
21    'https://raw.githubusercontent.com/cobertura/web/'
22    'f0366e5e2cf18f111cbd61fc34ef720a6584ba02'
23    '/htdocs/xml/coverage-03.dtd'
24)
25
26
27def rate(hit, num):
28    """Return the fraction of `hit`/`num`, as a string."""
29    if num == 0:
30        return "1"
31    else:
32        return "%.4g" % (float(hit) / num)
33
34
35class XmlReporter(Reporter):
36    """A reporter for writing Cobertura-style XML coverage results."""
37
38    def __init__(self, coverage, config):
39        super(XmlReporter, self).__init__(coverage, config)
40
41        self.source_paths = set()
42        if config.source:
43            for src in config.source:
44                if os.path.exists(src):
45                    self.source_paths.add(files.canonical_filename(src))
46        self.packages = {}
47        self.xml_out = None
48        self.has_arcs = coverage.data.has_arcs()
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
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            " Generated by coverage.py: %s " % __url__
71            ))
72        xcoverage.appendChild(self.xml_out.createComment(" Based on %s " % DTD_URL))
73
74        # Call xml_file for each file in the data.
75        self.report_files(self.xml_file, morfs)
76
77        xsources = self.xml_out.createElement("sources")
78        xcoverage.appendChild(xsources)
79
80        # Populate the XML DOM with the source info.
81        for path in sorted(self.source_paths):
82            xsource = self.xml_out.createElement("source")
83            xsources.appendChild(xsource)
84            txt = self.xml_out.createTextNode(path)
85            xsource.appendChild(txt)
86
87        lnum_tot, lhits_tot = 0, 0
88        bnum_tot, bhits_tot = 0, 0
89
90        xpackages = self.xml_out.createElement("packages")
91        xcoverage.appendChild(xpackages)
92
93        # Populate the XML DOM with the package info.
94        for pkg_name in sorted(self.packages.keys()):
95            pkg_data = self.packages[pkg_name]
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_name in sorted(class_elts.keys()):
102                xclasses.appendChild(class_elts[class_name])
103            xpackage.setAttribute("name", pkg_name.replace(os.sep, '.'))
104            xpackage.setAttribute("line-rate", rate(lhits, lnum))
105            if self.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("line-rate", rate(lhits_tot, lnum_tot))
118        if self.has_arcs:
119            branch_rate = rate(bhits_tot, bnum_tot)
120        else:
121            branch_rate = "0"
122        xcoverage.setAttribute("branch-rate", branch_rate)
123
124        # Use the DOM to write the output file.
125        out = self.xml_out.toprettyxml()
126        if env.PY2:
127            out = out.encode("utf8")
128        outfile.write(out)
129
130        # Return the total percentage.
131        denom = lnum_tot + bnum_tot
132        if denom == 0:
133            pct = 0.0
134        else:
135            pct = 100.0 * (lhits_tot + bhits_tot) / denom
136        return pct
137
138    def xml_file(self, fr, analysis):
139        """Add to the XML report for a single file."""
140
141        # Create the 'lines' and 'package' XML elements, which
142        # are populated later.  Note that a package == a directory.
143        filename = fr.relative_filename()
144        filename = filename.replace("\\", "/")
145        dirname = os.path.dirname(filename) or "."
146        parts = dirname.split("/")
147        dirname = "/".join(parts[:self.config.xml_package_depth])
148        package_name = dirname.replace("/", ".")
149        rel_name = fr.relative_filename()
150
151        if rel_name != fr.filename:
152            self.source_paths.add(fr.filename[:-len(rel_name)].rstrip(r"\/"))
153        package = self.packages.setdefault(package_name, [{}, 0, 0, 0, 0])
154
155        xclass = self.xml_out.createElement("class")
156
157        xclass.appendChild(self.xml_out.createElement("methods"))
158
159        xlines = self.xml_out.createElement("lines")
160        xclass.appendChild(xlines)
161
162        xclass.setAttribute("name", os.path.relpath(filename, dirname))
163        xclass.setAttribute("filename", filename)
164        xclass.setAttribute("complexity", "0")
165
166        branch_stats = analysis.branch_stats()
167        missing_branch_arcs = analysis.missing_branch_arcs()
168
169        # For each statement, create an XML 'line' element.
170        for line in sorted(analysis.statements):
171            xline = self.xml_out.createElement("line")
172            xline.setAttribute("number", str(line))
173
174            # Q: can we get info about the number of times a statement is
175            # executed?  If so, that should be recorded here.
176            xline.setAttribute("hits", str(int(line not in analysis.missing)))
177
178            if self.has_arcs:
179                if line in branch_stats:
180                    total, taken = branch_stats[line]
181                    xline.setAttribute("branch", "true")
182                    xline.setAttribute(
183                        "condition-coverage",
184                        "%d%% (%d/%d)" % (100*taken/total, taken, total)
185                        )
186                if line in missing_branch_arcs:
187                    annlines = ["exit" if b < 0 else str(b) for b in missing_branch_arcs[line]]
188                    xline.setAttribute("missing-branches", ",".join(annlines))
189            xlines.appendChild(xline)
190
191        class_lines = len(analysis.statements)
192        class_hits = class_lines - len(analysis.missing)
193
194        if self.has_arcs:
195            class_branches = sum(t for t, k in branch_stats.values())
196            missing_branches = sum(t - k for t, k in branch_stats.values())
197            class_br_hits = class_branches - missing_branches
198        else:
199            class_branches = 0.0
200            class_br_hits = 0.0
201
202        # Finalize the statistics that are collected in the XML DOM.
203        xclass.setAttribute("line-rate", rate(class_hits, class_lines))
204        if self.has_arcs:
205            branch_rate = rate(class_br_hits, class_branches)
206        else:
207            branch_rate = "0"
208        xclass.setAttribute("branch-rate", branch_rate)
209
210        package[0][rel_name] = xclass
211        package[1] += class_hits
212        package[2] += class_lines
213        package[3] += class_br_hits
214        package[4] += class_branches
215