forked from vitest-dev/vitest
/
json.ts
197 lines (173 loc) · 6.16 KB
/
json.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
import { existsSync, promises as fs } from 'fs'
import { dirname, resolve } from 'pathe'
import type { Vitest } from '../../node'
import type { File, Reporter, Suite, TaskState, Test } from '../../types'
import { getSuites, getTests } from '../../utils'
import { getOutputFile } from '../../utils/config-helpers'
import { interpretSourcePos, parseStacktrace } from '../../utils/source-map'
// for compatibility reasons, the reporter produces a JSON similar to the one produced by the Jest JSON reporter
// the following types are extracted from the Jest repository (and simplified)
// the commented-out fields are the missing ones
type Status = 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled'
type Milliseconds = number
interface Callsite { line: number; column: number }
const StatusMap: Record<TaskState, Status> = {
fail: 'failed',
only: 'pending',
pass: 'passed',
run: 'pending',
skip: 'skipped',
todo: 'todo',
}
interface FormattedAssertionResult {
ancestorTitles: Array<string>
fullName: string
status: Status
title: string
duration?: Milliseconds | null
failureMessages: Array<string>
location?: Callsite | null
}
interface FormattedTestResult {
message: string
name: string
status: 'failed' | 'passed'
startTime: number
endTime: number
assertionResults: Array<FormattedAssertionResult>
// summary: string
// coverage: unknown
}
interface FormattedTestResults {
numFailedTests: number
numFailedTestSuites: number
numPassedTests: number
numPassedTestSuites: number
numPendingTests: number
numPendingTestSuites: number
numTodoTests: number
numTotalTests: number
numTotalTestSuites: number
startTime: number
success: boolean
testResults: Array<FormattedTestResult>
// coverageMap?: CoverageMap | null | undefined
// numRuntimeErrorTestSuites: number
// snapshot: SnapshotSummary
// wasInterrupted: boolean
}
export class JsonReporter implements Reporter {
start = 0
ctx!: Vitest
onInit(ctx: Vitest): void {
this.ctx = ctx
this.start = Date.now()
}
protected async logTasks(files: File[]) {
const suites = getSuites(files)
const numTotalTestSuites = suites.length
const tests = getTests(files)
const numTotalTests = tests.length
const numFailedTestSuites = suites.filter(s => s.result?.error).length
const numPassedTestSuites = numTotalTestSuites - numFailedTestSuites
const numPendingTestSuites = suites.filter(s => s.result?.state === 'run').length
const numFailedTests = tests.filter(t => t.result?.state === 'fail').length
const numPassedTests = numTotalTests - numFailedTests
const numPendingTests = tests.filter(t => t.result?.state === 'run').length
const numTodoTests = tests.filter(t => t.mode === 'todo').length
const testResults: Array<FormattedTestResult> = []
const success = numFailedTestSuites === 0 && numFailedTests === 0
for (const file of files) {
const tests = getTests([file])
let startTime = tests.reduce((prev, next) => Math.min(prev, next.result?.startTime ?? Infinity), Infinity)
if (startTime === Infinity)
startTime = this.start
const endTime = tests.reduce((prev, next) => Math.max(prev, (next.result?.startTime ?? 0) + (next.result?.duration ?? 0)), startTime)
const assertionResults = await Promise.all(tests.map(async (t) => {
const ancestorTitles = [] as string[]
let iter: Suite | undefined = t.suite
while (iter) {
ancestorTitles.push(iter.name)
iter = iter.suite
}
ancestorTitles.reverse()
return {
ancestorTitles,
fullName: ancestorTitles.length > 0 ? `${ancestorTitles.join(' ')} ${t.name}` : t.name,
status: StatusMap[t.result?.state || t.mode] || 'skipped',
title: t.name,
duration: t.result?.duration,
failureMessages: t.result?.error?.message == null ? [] : [t.result.error.message],
location: await this.getFailureLocation(t),
} as FormattedAssertionResult
}))
if (tests.some(t => t.result?.state === 'run')) {
this.ctx.logger.warn('WARNING: Some tests are still running when generating the JSON report.'
+ 'This is likely an internal bug in Vitest.'
+ 'Please report it to https://github.com/vitest-dev/vitest/issues')
}
testResults.push({
assertionResults,
startTime,
endTime,
status: tests.every(t =>
t.result?.state === 'pass'
|| t.result?.state === 'skip'
|| t.result?.state === 'todo')
? 'passed'
: 'failed',
message: file.result?.error?.message ?? '',
name: file.filepath,
})
}
const result: FormattedTestResults = {
numTotalTestSuites,
numPassedTestSuites,
numFailedTestSuites,
numPendingTestSuites,
numTotalTests,
numPassedTests,
numFailedTests,
numPendingTests,
numTodoTests,
startTime: this.start,
success,
testResults,
}
await this.writeReport(JSON.stringify(result, null, 2))
}
async onFinished(files = this.ctx.state.getFiles()) {
await this.logTasks(files)
}
/**
* Writes the report to an output file if specified in the config,
* or logs it to the console otherwise.
* @param report
*/
async writeReport(report: string) {
const outputFile = getOutputFile(this.ctx, 'json')
if (outputFile) {
const reportFile = resolve(this.ctx.config.root, outputFile)
const outputDirectory = dirname(reportFile)
if (!existsSync(outputDirectory))
await fs.mkdir(outputDirectory, { recursive: true })
await fs.writeFile(reportFile, report, 'utf-8')
this.ctx.logger.log(`JSON report written to ${reportFile}`)
}
else {
this.ctx.logger.log(report)
}
}
protected async getFailureLocation(test: Test): Promise<Callsite | undefined> {
const error = test.result?.error
if (!error)
return
const stack = parseStacktrace(error)
await interpretSourcePos(stack, this.ctx)
const frame = stack[stack.length - 1]
if (!frame)
return
const pos = frame.sourcePos || frame
return { line: pos.line, column: pos.column }
}
}