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.backward import iitems
15from coverage.misc import isolate_module
16from coverage.report import Reporter
17
18os = isolate_module(os)
19
20
21DTD_URL = (
22    'https://raw.githubusercontent.com/cobertura/web/'
23    'f0366e5e2cf18f111cbd61fc34ef720a6584ba02'
24    '/htdocs/xml/coverage-03.dtd'
25)
26
27
28def rate(hit, num):
29    """Return the fraction of `hit`/`num`, as a string."""
30    if num == 0:
31        return "1"
32    else:
33        return "%.4g" % (float(hit) / num)
34
35
36class XmlReporter(Reporter):
37    """A reporter for writing Cobertura-style XML coverage results."""
38
39    def __init__(self, coverage, config):
40        super(XmlReporter, self).__init__(coverage, config)
41
42        self.source_paths = set()
43        if config.source:
44            for src in config.source:
45                if os.path.exists(src):
46                    self.source_paths.add(files.canonical_filename(src))
47        self.packages = {}
48        self.xml_out = None
49        self.has_arcs = coverage.data.has_arcs()
50
51    def report(self, morfs, outfile=None):
52        """Generate a Cobertura-compatible XML report for `morfs`.
53
54        `morfs` is a list of modules or file names.
55
56        `outfile` is a file object to write the XML to.
57
58        """
59        # Initial setup.
60        outfile = outfile or sys.stdout
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        self.report_files(self.xml_file, morfs)
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 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 sorted(iitems(self.packages)):
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 sorted(iitems(class_elts)):
102                xclasses.appendChild(class_elt)
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.filename.replace("\\", "/")
144        for source_path in self.source_paths:
145            if filename.startswith(source_path.replace("\\", "/") + "/"):
146                rel_name = filename[len(source_path)+1:]
147                break
148        else:
149            rel_name = fr.relative_filename()
150
151        dirname = os.path.dirname(rel_name) or "."
152        dirname = "/".join(dirname.split("/")[:self.config.xml_package_depth])
153        package_name = dirname.replace("/", ".")
154
155        if rel_name != fr.filename:
156            self.source_paths.add(fr.filename[:-len(rel_name)].rstrip(r"\/"))
157        package = self.packages.setdefault(package_name, [{}, 0, 0, 0, 0])
158
159        xclass = self.xml_out.createElement("class")
160
161        xclass.appendChild(self.xml_out.createElement("methods"))
162
163        xlines = self.xml_out.createElement("lines")
164        xclass.appendChild(xlines)
165
166        xclass.setAttribute("name", os.path.relpath(rel_name, dirname))
167        xclass.setAttribute("filename", fr.relative_filename().replace("\\", "/"))
168        xclass.setAttribute("complexity", "0")
169
170        branch_stats = analysis.branch_stats()
171        missing_branch_arcs = analysis.missing_branch_arcs()
172
173        # For each statement, create an XML 'line' element.
174        for line in sorted(analysis.statements):
175            xline = self.xml_out.createElement("line")
176            xline.setAttribute("number", str(line))
177
178            # Q: can we get info about the number of times a statement is
179            # executed?  If so, that should be recorded here.
180            xline.setAttribute("hits", str(int(line not in analysis.missing)))
181
182            if self.has_arcs:
183                if line in branch_stats:
184                    total, taken = branch_stats[line]
185                    xline.setAttribute("branch", "true")
186                    xline.setAttribute(
187                        "condition-coverage",
188                        "%d%% (%d/%d)" % (100*taken/total, taken, total)
189                        )
190                if line in missing_branch_arcs:
191                    annlines = ["exit" if b < 0 else str(b) for b in missing_branch_arcs[line]]
192                    xline.setAttribute("missing-branches", ",".join(annlines))
193            xlines.appendChild(xline)
194
195        class_lines = len(analysis.statements)
196        class_hits = class_lines - len(analysis.missing)
197
198        if self.has_arcs:
199            class_branches = sum(t for t, k in branch_stats.values())
200            missing_branches = sum(t - k for t, k in branch_stats.values())
201            class_br_hits = class_branches - missing_branches
202        else:
203            class_branches = 0.0
204            class_br_hits = 0.0
205
206        # Finalize the statistics that are collected in the XML DOM.
207        xclass.setAttribute("line-rate", rate(class_hits, class_lines))
208        if self.has_arcs:
209            branch_rate = rate(class_br_hits, class_branches)
210        else:
211            branch_rate = "0"
212        xclass.setAttribute("branch-rate", branch_rate)
213
214        package[0][rel_name] = xclass
215        package[1] += class_hits
216        package[2] += class_lines
217        package[3] += class_br_hits
218        package[4] += class_branches
219