/
reporter.py
207 lines (173 loc) · 7.29 KB
/
reporter.py
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
197
198
199
200
201
202
203
204
205
206
207
import logging
import os
from coverage.files import prep_patterns
try:
# coverage v7.x
from coverage.files import GlobMatcher
except ImportError:
# coverage v5.x and v6.x
from coverage.files import FnmatchMatcher as GlobMatcher
try:
# coverage v6.x
from coverage.exceptions import NoSource
from coverage.exceptions import NotPython
except ImportError:
# coverage v5.x
from coverage.misc import NoSource
from coverage.misc import NotPython
log = logging.getLogger('coveralls.reporter')
class CoverallReporter:
"""Custom coverage.py reporter for coveralls.io."""
def __init__(self, cov, base_dir='', src_dir=''):
self.coverage = []
self.base_dir = self.sanitize_dir(base_dir)
self.src_dir = self.sanitize_dir(src_dir)
self.report(cov)
@staticmethod
def sanitize_dir(directory):
if directory:
directory = directory.replace(os.path.sep, '/')
if directory[-1] != '/':
directory += '/'
return directory
def report(self, cov):
# N.B. this method is 99% copied from the coverage source code;
# unfortunately, the coverage v5+ style of `get_analysis_to_report`
# errors out entirely if any source file has issues -- which would be a
# breaking change for us. In the interest of backwards compatibility,
# I've copied their code here so we can maintain the same `coveralls`
# API regardless of which `coverage` version is being used.
#
# TODO: deprecate the relevant APIs so we can just use the coverage
# public API directly.
#
# from coverage.report import get_analysis_to_report
# try:
# for cu, analyzed in get_analysis_to_report(cov, None):
# self.parse_file(cu, analyzed)
# except NoSource:
# # Note that this behavior must necessarily change between
# # coverage<5 and coverage>=5, as we are no longer interweaving
# # with get_analysis_to_report (a single exception breaks the
# # whole loop)
# log.warning('No source for at least one file')
# except NotPython:
# # Note that this behavior must necessarily change between
# # coverage<5 and coverage>=5, as we are no longer interweaving
# # with get_analysis_to_report (a single exception breaks the
# # whole loop)
# log.warning('A source file is not python')
# except CoverageException as e:
# if str(e) != 'No data to report.':
# raise
# get_analysis_to_report starts here; changes marked with TODOs
# TODO: in v7.5, this returns list of tuples (fr->morf)
# https://github.com/nedbat/coveragepy/commit/4e5027338b93fc893c5e6e82c8a234c48f0b95e7
file_reporters = cov._get_file_reporters(None) # pylint: disable=W0212
config = cov.config
if config.report_include:
matcher = GlobMatcher(prep_patterns(config.report_include))
file_reporters = [
fr for fr in file_reporters
if matcher.match(fr.filename)
]
if config.report_omit:
matcher = GlobMatcher(prep_patterns(config.report_omit))
file_reporters = [
fr for fr in file_reporters
if not matcher.match(fr.filename)
]
# TODO: deprecate changes
# if not file_reporters:
# raise CoverageException("No data to report.")
for fr in sorted(file_reporters):
try:
analysis = cov._analyze(fr) # pylint: disable=W0212
except NoSource:
if not config.ignore_errors:
# TODO: deprecate changes
# raise
log.warning('No source for %s', fr.filename)
except NotPython:
# Only report errors for .py files, and only if we didn't
# explicitly suppress those errors.
# NotPython is only raised by PythonFileReporter, which has a
# should_be_python() method.
if fr.should_be_python():
if config.ignore_errors:
msg = f"Couldn't parse Python file '{fr.filename}'"
cov._warn( # pylint: disable=W0212
msg, slug='couldnt-parse',
)
else:
# TODO: deprecate changes
# raise
log.warning(
'Source file is not python %s', fr.filename,
)
else:
# TODO: deprecate changes (well, this one is fine /shrug)
# yield (fr, analysis)
self.parse_file(fr, analysis)
@staticmethod
def get_hits(line_num, analysis):
"""
Source file stats for each line.
* A positive integer if the line is covered, representing the number
of times the line is hit during the test suite.
* 0 if the line is not covered by the test suite.
* null to indicate the line is not relevant to code coverage (it may
be whitespace or a comment).
"""
if line_num in analysis.missing:
return 0
if line_num not in analysis.statements:
return None
return 1
@staticmethod
def get_arcs(analysis):
"""
Hit stats for each branch.
Returns a flat list where every four values represent a branch:
1. line-number
2. block-number (not used)
3. branch-number
4. hits (we only get 1/0 from coverage.py)
"""
if not analysis.has_arcs():
return None
# N.B. switching to the public method analysis.missing_branch_arcs
# would work for half of what we need, but there doesn't seem to be an
# equivalent analysis.executed_branch_arcs
branch_lines = analysis._branch_lines() # pylint: disable=W0212
branches = []
for l1, l2 in analysis.arcs_executed():
if l1 in branch_lines:
branches.extend((l1, 0, abs(l2), 1))
for l1, l2 in analysis.arcs_missing():
if l1 in branch_lines:
branches.extend((l1, 0, abs(l2), 0))
return branches
def parse_file(self, cu, analysis):
"""Generate data for single file."""
filename = cu.relative_filename()
# ensure results are properly merged between platforms
posix_filename = filename.replace(os.path.sep, '/')
if self.base_dir and posix_filename.startswith(self.base_dir):
posix_filename = posix_filename[len(self.base_dir):]
posix_filename = self.src_dir + posix_filename
source = analysis.file_reporter.source()
token_lines = analysis.file_reporter.source_token_lines()
coverage_lines = [
self.get_hits(i, analysis)
for i, _ in enumerate(token_lines, 1)
]
results = {
'name': posix_filename,
'source': source,
'coverage': coverage_lines,
}
branches = self.get_arcs(analysis)
if branches:
results['branches'] = branches
self.coverage.append(results)