reporter.js
8.85 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Coverage Reporter
// Part of this code is based on [1], which is licensed under the New BSD License.
// For more information see the See the accompanying LICENSE-istanbul file for terms.
//
// [1]: https://github.com/gotwarlost/istanbul/blob/master/lib/command/check-coverage.js
// =====================
//
// Generates the report
// Dependencies
// ------------
var path = require('path')
var istanbul = require('istanbul')
var minimatch = require('minimatch')
var _ = require('lodash')
var globalSourceCache = require('./source-cache')
var coverageMap = require('./coverage-map')
var SourceCacheStore = require('./source-cache-store')
function isAbsolute (file) {
if (path.isAbsolute) {
return path.isAbsolute(file)
}
return path.resolve(file) === path.normalize(file)
}
// TODO(vojta): inject only what required (config.basePath, config.coverageReporter)
var CoverageReporter = function (rootConfig, helper, logger, emitter) {
var log = logger.create('coverage')
// Instance variables
// ------------------
this.adapters = []
// Options
// -------
var config = rootConfig.coverageReporter || {}
var basePath = rootConfig.basePath
var reporters = config.reporters
var sourceCache = globalSourceCache.get(basePath)
var includeAllSources = config.includeAllSources === true
if (config.watermarks) {
config.watermarks = helper.merge({}, istanbul.config.defaultConfig().reporting.watermarks, config.watermarks)
}
if (!helper.isDefined(reporters)) {
reporters = [config]
}
var collectors
var pendingFileWritings = 0
var fileWritingFinished = function () {}
function writeReport (reporter, collector) {
try {
if (typeof config._onWriteReport === 'function') {
var newCollector = config._onWriteReport(collector)
if (typeof newCollector === 'object') {
collector = newCollector
}
}
reporter.writeReport(collector, true)
} catch (e) {
log.error(e)
}
--pendingFileWritings
}
function disposeCollectors () {
if (pendingFileWritings <= 0) {
_.forEach(collectors, function (collector) {
collector.dispose()
})
fileWritingFinished()
}
}
function normalize (key) {
// Exclude keys will always be relative, but covObj keys can be absolute or relative
var excludeKey = isAbsolute(key) ? path.relative(basePath, key) : key
// Also normalize for files that start with `./`, etc.
excludeKey = path.normalize(excludeKey)
return excludeKey
}
function removeFiles (covObj, patterns) {
var obj = {}
Object.keys(covObj).forEach(function (key) {
// Do any patterns match the resolved key
var found = patterns.some(function (pattern) {
return minimatch(normalize(key), pattern, {dot: true})
})
// if no patterns match, keep the key
if (!found) {
obj[key] = covObj[key]
}
})
return obj
}
function overrideThresholds (key, overrides) {
var thresholds = {}
// First match wins
Object.keys(overrides).some(function (pattern) {
if (minimatch(normalize(key), pattern, {dot: true})) {
thresholds = overrides[pattern]
return true
}
})
return thresholds
}
function checkCoverage (browser, collector) {
var defaultThresholds = {
global: {
statements: 0,
branches: 0,
lines: 0,
functions: 0,
excludes: []
},
each: {
statements: 0,
branches: 0,
lines: 0,
functions: 0,
excludes: [],
overrides: {}
}
}
var thresholds = helper.merge({}, defaultThresholds, config.check)
var rawCoverage = collector.getFinalCoverage()
var globalResults = istanbul.utils.summarizeCoverage(removeFiles(rawCoverage, thresholds.global.excludes))
var eachResults = removeFiles(rawCoverage, thresholds.each.excludes)
// Summarize per-file results and mutate original results.
Object.keys(eachResults).forEach(function (key) {
eachResults[key] = istanbul.utils.summarizeFileCoverage(eachResults[key])
})
var coverageFailed = false
function check (name, thresholds, actuals) {
var keys = [
'statements',
'branches',
'lines',
'functions'
]
keys.forEach(function (key) {
var actual = actuals[key].pct
var actualUncovered = actuals[key].total - actuals[key].covered
var threshold = thresholds[key]
if (threshold < 0) {
if (threshold * -1 < actualUncovered) {
coverageFailed = true
log.error(browser.name + ': Uncovered count for ' + key + ' (' + actualUncovered +
') exceeds ' + name + ' threshold (' + -1 * threshold + ')')
}
} else {
if (actual < threshold) {
coverageFailed = true
log.error(browser.name + ': Coverage for ' + key + ' (' + actual +
'%) does not meet ' + name + ' threshold (' + threshold + '%)')
}
}
})
}
check('global', thresholds.global, globalResults)
Object.keys(eachResults).forEach(function (key) {
var keyThreshold = helper.merge(thresholds.each, overrideThresholds(key, thresholds.each.overrides))
check('per-file' + ' (' + key + ') ', keyThreshold, eachResults[key])
})
return coverageFailed
}
// Generate the output directory from the `coverageReporter.dir` and
// `coverageReporter.subdir` options.
function generateOutputDir (browserName, dir, subdir) {
dir = dir || 'coverage'
subdir = subdir || browserName
if (_.isFunction(subdir)) {
subdir = subdir(browserName)
}
return path.join(dir, subdir)
}
this.onRunStart = function (browsers) {
collectors = Object.create(null)
// TODO(vojta): remove once we don't care about Karma 0.10
if (browsers) {
browsers.forEach(this.onBrowserStart.bind(this))
}
}
this.onBrowserStart = function (browser) {
collectors[browser.id] = new istanbul.Collector()
if (!includeAllSources) return
collectors[browser.id].add(coverageMap.get())
}
this.onBrowserComplete = function (browser, result) {
var collector = collectors[browser.id]
if (!collector) return
if (!result || !result.coverage) return
collector.add(result.coverage)
}
this.onSpecComplete = function (browser, result) {
if (!result.coverage) return
collectors[browser.id].add(result.coverage)
}
this.onRunComplete = function (browsers, results) {
var checkedCoverage = {}
reporters.forEach(function (reporterConfig) {
browsers.forEach(function (browser) {
var collector = collectors[browser.id]
if (!collector) {
return
}
// If config.check is defined, check coverage levels for each browser
if (config.hasOwnProperty('check') && !checkedCoverage[browser.id]) {
checkedCoverage[browser.id] = true
var coverageFailed = checkCoverage(browser, collector)
if (coverageFailed) {
if (results) {
results.exitCode = 1
}
}
}
pendingFileWritings++
var mainDir = reporterConfig.dir || config.dir
var subDir = reporterConfig.subdir || config.subdir
var simpleOutputDir = generateOutputDir(browser.name, mainDir, subDir)
var resolvedOutputDir = path.resolve(basePath, simpleOutputDir)
var outputDir = helper.normalizeWinPath(resolvedOutputDir)
var sourceStore = _.isEmpty(sourceCache) ? null : new SourceCacheStore({
sourceCache: sourceCache
})
var options = helper.merge({
sourceStore: sourceStore
}, config, reporterConfig, {
dir: outputDir,
browser: browser,
emitter: emitter
})
var reporter = istanbul.Report.create(reporterConfig.type || 'html', options)
// If reporting to console or in-memory skip directory creation
var toDisk = !reporterConfig.type || !reporterConfig.type.match(/^(text|text-summary|in-memory)$/)
var hasNoFile = _.isUndefined(reporterConfig.file)
if (!toDisk && hasNoFile) {
writeReport(reporter, collector)
return
}
helper.mkdirIfNotExists(outputDir, function () {
log.debug('Writing coverage to %s', outputDir)
writeReport(reporter, collector)
disposeCollectors()
})
})
})
disposeCollectors()
}
this.onExit = function (done) {
if (pendingFileWritings) {
fileWritingFinished = (
typeof config._onExit === 'function'
? (function (done) { return function () { config._onExit(done) } }(done))
: done
)
} else {
(typeof config._onExit === 'function' ? config._onExit(done) : done())
}
}
}
CoverageReporter.$inject = ['config', 'helper', 'logger', 'emitter']
// PUBLISH
module.exports = CoverageReporter