/
provider.ts
298 lines (249 loc) · 9.75 KB
/
provider.ts
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
/* eslint-disable no-restricted-imports */
import { existsSync, promises as fs } from 'node:fs'
import { relative, resolve } from 'pathe'
import type { TransformPluginContext } from 'rollup'
import type { AfterSuiteRunMeta, CoverageIstanbulOptions, CoverageProvider, ReportContext, ResolvedCoverageOptions, Vitest } from 'vitest'
import { coverageConfigDefaults, defaultExclude, defaultInclude } from 'vitest/config'
import { BaseCoverageProvider } from 'vitest/coverage'
import libReport from 'istanbul-lib-report'
import reports from 'istanbul-reports'
import type { CoverageMap } from 'istanbul-lib-coverage'
import libCoverage from 'istanbul-lib-coverage'
import libSourceMaps from 'istanbul-lib-source-maps'
import { type Instrumenter, createInstrumenter } from 'istanbul-lib-instrument'
// @ts-expect-error missing types
import _TestExclude from 'test-exclude'
import { COVERAGE_STORE_KEY } from './constants'
type Options = ResolvedCoverageOptions<'istanbul'>
type Threshold = 'lines' | 'functions' | 'statements' | 'branches'
interface TestExclude {
new(opts: {
cwd?: string | string[]
include?: string | string[]
exclude?: string | string[]
extension?: string | string[]
excludeNodeModules?: boolean
}): {
shouldInstrument(filePath: string): boolean
glob(cwd: string): Promise<string[]>
}
}
export class IstanbulCoverageProvider extends BaseCoverageProvider implements CoverageProvider {
name = 'istanbul'
ctx!: Vitest
options!: Options
instrumenter!: Instrumenter
testExclude!: InstanceType<TestExclude>
/**
* Coverage objects collected from workers.
* Some istanbul utilizers write these into file system instead of storing in memory.
* If storing in memory causes issues, we can simply write these into fs in `onAfterSuiteRun`
* and read them back when merging coverage objects in `onAfterAllFilesRun`.
*/
coverages: any[] = []
initialize(ctx: Vitest) {
const config: CoverageIstanbulOptions = ctx.config.coverage
this.ctx = ctx
this.options = {
...coverageConfigDefaults,
// User's options
...config,
// Resolved fields
provider: 'istanbul',
reportsDirectory: resolve(ctx.config.root, config.reportsDirectory || coverageConfigDefaults.reportsDirectory),
reporter: this.resolveReporters(config.reporter || coverageConfigDefaults.reporter),
}
this.instrumenter = createInstrumenter({
produceSourceMap: true,
autoWrap: false,
esModules: true,
compact: false,
coverageVariable: COVERAGE_STORE_KEY,
// @ts-expect-error missing type
coverageGlobalScope: 'globalThis',
coverageGlobalScopeFunc: false,
ignoreClassMethods: this.options.ignoreClassMethods,
})
this.testExclude = new _TestExclude({
cwd: ctx.config.root,
include: typeof this.options.include === 'undefined' ? undefined : [...this.options.include],
exclude: [...defaultExclude, ...defaultInclude, ...this.options.exclude],
excludeNodeModules: true,
extension: this.options.extension,
})
}
resolveOptions() {
return this.options
}
onFileTransform(sourceCode: string, id: string, pluginCtx: TransformPluginContext) {
if (!this.testExclude.shouldInstrument(id))
return
const sourceMap = pluginCtx.getCombinedSourcemap()
sourceMap.sources = sourceMap.sources.map(removeQueryParameters)
const code = this.instrumenter.instrumentSync(sourceCode, id, sourceMap as any)
const map = this.instrumenter.lastSourceMap() as any
return { code, map }
}
onAfterSuiteRun({ coverage }: AfterSuiteRunMeta) {
this.coverages.push(coverage)
}
async clean(clean = true) {
if (clean && existsSync(this.options.reportsDirectory))
await fs.rm(this.options.reportsDirectory, { recursive: true, force: true, maxRetries: 10 })
this.coverages = []
}
async reportCoverage({ allTestsRun }: ReportContext = {}) {
const mergedCoverage: CoverageMap = this.coverages.reduce((coverage, previousCoverageMap) => {
const map = libCoverage.createCoverageMap(coverage)
map.merge(previousCoverageMap)
return map
}, libCoverage.createCoverageMap({}))
if (this.options.all && allTestsRun)
await this.includeUntestedFiles(mergedCoverage)
includeImplicitElseBranches(mergedCoverage)
const sourceMapStore = libSourceMaps.createSourceMapStore()
const coverageMap: CoverageMap = await sourceMapStore.transformCoverage(mergedCoverage)
const context = libReport.createContext({
dir: this.options.reportsDirectory,
coverageMap,
sourceFinder: sourceMapStore.sourceFinder,
watermarks: this.options.watermarks,
})
for (const reporter of this.options.reporter) {
reports.create(reporter[0], {
skipFull: this.options.skipFull,
projectRoot: this.ctx.config.root,
...reporter[1],
}).execute(context)
}
if (this.options.branches
|| this.options.functions
|| this.options.lines
|| this.options.statements) {
this.checkThresholds(coverageMap, {
branches: this.options.branches,
functions: this.options.functions,
lines: this.options.lines,
statements: this.options.statements,
})
}
if (this.options.thresholdAutoUpdate && allTestsRun) {
this.updateThresholds({
coverageMap,
thresholds: {
branches: this.options.branches,
functions: this.options.functions,
lines: this.options.lines,
statements: this.options.statements,
},
perFile: this.options.perFile,
configurationFile: this.ctx.server.config.configFile,
})
}
}
checkThresholds(coverageMap: CoverageMap, thresholds: Record<Threshold, number | undefined>) {
// Construct list of coverage summaries where thresholds are compared against
const summaries = this.options.perFile
? coverageMap.files()
.map((file: string) => ({
file,
summary: coverageMap.fileCoverageFor(file).toSummary(),
}))
: [{
file: null,
summary: coverageMap.getCoverageSummary(),
}]
// Check thresholds of each summary
for (const { summary, file } of summaries) {
for (const thresholdKey of ['lines', 'functions', 'statements', 'branches'] as const) {
const threshold = thresholds[thresholdKey]
if (threshold !== undefined) {
const coverage = summary.data[thresholdKey].pct
if (coverage < threshold) {
process.exitCode = 1
/*
* Generate error message based on perFile flag:
* - ERROR: Coverage for statements (33.33%) does not meet threshold (85%) for src/math.ts
* - ERROR: Coverage for statements (50%) does not meet global threshold (85%)
*/
let errorMessage = `ERROR: Coverage for ${thresholdKey} (${coverage}%) does not meet`
if (!this.options.perFile)
errorMessage += ' global'
errorMessage += ` threshold (${threshold}%)`
if (this.options.perFile && file)
errorMessage += ` for ${relative('./', file).replace(/\\/g, '/')}`
console.error(errorMessage)
}
}
}
}
}
async includeUntestedFiles(coverageMap: CoverageMap) {
// Load, instrument and collect empty coverages from all files which
// are not already in the coverage map
const includedFiles = await this.testExclude.glob(this.ctx.config.root)
const uncoveredFiles = includedFiles
.map(file => resolve(this.ctx.config.root, file))
.filter(file => !coverageMap.data[file])
const transformResults = await Promise.all(uncoveredFiles.map(async (filename) => {
const transformResult = await this.ctx.vitenode.transformRequest(filename)
return { transformResult, filename }
}))
for (const { transformResult, filename } of transformResults) {
const sourceMap = transformResult?.map
if (sourceMap) {
this.instrumenter.instrumentSync(
transformResult.code,
filename,
sourceMap as any,
)
const lastCoverage = this.instrumenter.lastFileCoverage()
if (lastCoverage)
coverageMap.addFileCoverage(lastCoverage)
}
}
}
}
/**
* Remove possible query parameters from filenames
* - From `/src/components/Header.component.ts?vue&type=script&src=true&lang.ts`
* - To `/src/components/Header.component.ts`
*/
function removeQueryParameters(filename: string) {
return filename.split('?')[0]
}
/**
* Work-around for #1887 and #2239 while waiting for https://github.com/istanbuljs/istanbuljs/pull/706
*
* Goes through all files in the coverage map and checks if branchMap's have
* if-statements with implicit else. When finds one, copies source location of
* the if-statement into the else statement.
*/
function includeImplicitElseBranches(coverageMap: CoverageMap) {
for (const file of coverageMap.files()) {
const fileCoverage = coverageMap.fileCoverageFor(file)
for (const branchMap of Object.values(fileCoverage.branchMap)) {
if (branchMap.type === 'if') {
const lastIndex = branchMap.locations.length - 1
if (lastIndex > 0) {
const elseLocation = branchMap.locations[lastIndex]
if (elseLocation && isEmptyCoverageRange(elseLocation)) {
const ifLocation = branchMap.locations[0]
elseLocation.start = { ...ifLocation.start }
elseLocation.end = { ...ifLocation.end }
}
}
}
}
}
}
function isEmptyCoverageRange(range: libCoverage.Range) {
return (
range.start === undefined
|| range.start.line === undefined
|| range.start.column === undefined
|| range.end === undefined
|| range.end.line === undefined
|| range.end.column === undefined
)
}