1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
|
"""HTML reporting for Coverage."""
import os, re, shutil
from coverage import __url__, __version__ # pylint: disable-msg=W0611
from coverage.misc import CoverageException
from coverage.phystokens import source_token_lines
from coverage.report import Reporter
from coverage.templite import Templite
# Disable pylint msg W0612, because a bunch of variables look unused, but
# they're accessed in a Templite context via locals().
# pylint: disable-msg=W0612
def data_filename(fname):
"""Return the path to a data file of ours."""
return os.path.join(os.path.split(__file__)[0], fname)
def data(fname):
"""Return the contents of a data file of ours."""
data_file = open(data_filename(fname))
try:
return data_file.read()
finally:
data_file.close()
class HtmlReporter(Reporter):
"""HTML reporting."""
# These files will be copied from the htmlfiles dir to the output dir.
STATIC_FILES = [
"style.css",
"jquery-1.4.3.min.js",
"jquery.tablesorter.min.js",
"jquery.hotkeys.js",
"coverage_html.js",
]
def __init__(self, coverage, ignore_errors=False):
super(HtmlReporter, self).__init__(coverage, ignore_errors)
self.directory = None
self.source_tmpl = Templite(data("htmlfiles/pyfile.html"), globals())
self.files = []
self.arcs = coverage.data.has_arcs()
def report(self, morfs, config=None):
"""Generate an HTML report for `morfs`.
`morfs` is a list of modules or filenames. `config` is a
CoverageConfig instance.
"""
assert config.html_dir, "must provide a directory for html reporting"
# Process all the files.
self.report_files(self.html_file, morfs, config, config.html_dir)
if not self.files:
raise CoverageException("No data to report.")
# Write the index file.
self.index_file()
# Create the once-per-directory files.
for static in self.STATIC_FILES:
shutil.copyfile(
data_filename("htmlfiles/" + static),
os.path.join(self.directory, static)
)
def html_file(self, cu, analysis):
"""Generate an HTML file for one source file."""
source_file = cu.source_file()
try:
source = source_file.read()
finally:
source_file.close()
nums = analysis.numbers
missing_branch_arcs = analysis.missing_branch_arcs()
n_par = 0 # accumulated below.
arcs = self.arcs
# These classes determine which lines are highlighted by default.
c_run = "run hide_run"
c_exc = "exc"
c_mis = "mis"
c_par = "par " + c_run
lines = []
for lineno, line in enumerate(source_token_lines(source)):
lineno += 1 # 1-based line numbers.
# Figure out how to mark this line.
line_class = []
annotate_html = ""
annotate_title = ""
if lineno in analysis.statements:
line_class.append("stm")
if lineno in analysis.excluded:
line_class.append(c_exc)
elif lineno in analysis.missing:
line_class.append(c_mis)
elif self.arcs and lineno in missing_branch_arcs:
line_class.append(c_par)
n_par += 1
annlines = []
for b in missing_branch_arcs[lineno]:
if b < 0:
annlines.append("exit")
else:
annlines.append(str(b))
annotate_html = " ".join(annlines)
if len(annlines) > 1:
annotate_title = "no jumps to these line numbers"
elif len(annlines) == 1:
annotate_title = "no jump to this line number"
elif lineno in analysis.statements:
line_class.append(c_run)
# Build the HTML for the line
html = []
for tok_type, tok_text in line:
if tok_type == "ws":
html.append(escape(tok_text))
else:
tok_html = escape(tok_text) or ' '
html.append(
"<span class='%s'>%s</span>" % (tok_type, tok_html)
)
lines.append({
'html': ''.join(html),
'number': lineno,
'class': ' '.join(line_class) or "pln",
'annotate': annotate_html,
'annotate_title': annotate_title,
})
# Write the HTML page for this file.
html_filename = cu.flat_rootname() + ".html"
html_path = os.path.join(self.directory, html_filename)
html = spaceless(self.source_tmpl.render(locals()))
fhtml = open(html_path, 'w')
fhtml.write(html)
fhtml.close()
# Save this file's information for the index file.
self.files.append({
'nums': nums,
'par': n_par,
'html_filename': html_filename,
'cu': cu,
})
def index_file(self):
"""Write the index.html file for this report."""
index_tmpl = Templite(data("htmlfiles/index.html"), globals())
files = self.files
arcs = self.arcs
totals = sum([f['nums'] for f in files])
fhtml = open(os.path.join(self.directory, "index.html"), "w")
fhtml.write(index_tmpl.render(locals()))
fhtml.close()
# Helpers for templates and generating HTML
def escape(t):
"""HTML-escape the text in `t`."""
return (t
# Convert HTML special chars into HTML entities.
.replace("&", "&").replace("<", "<").replace(">", ">")
.replace("'", "'").replace('"', """)
# Convert runs of spaces: "......" -> " . . ."
.replace(" ", " ")
# To deal with odd-length runs, convert the final pair of spaces
# so that "....." -> " . ."
.replace(" ", " ")
)
def spaceless(html):
"""Squeeze out some annoying extra space from an HTML string.
Nicely-formatted templates mean lots of extra space in the result.
Get rid of some.
"""
html = re.sub(">\s+<p ", ">\n<p ", html)
return html
|