-
Notifications
You must be signed in to change notification settings - Fork 8
/
verifier.ts
305 lines (270 loc) · 7.85 KB
/
verifier.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
299
300
301
302
303
304
305
import { Options, transformSync } from "@swc/core";
import * as path from "path";
import { assert } from "chai";
import { readInitialCoverage } from "./read-coverage";
import { EOL } from "os";
import { FileCoverageInterop } from "../swc-coverage-instrument-wasm/pkg/swc_coverage_instrument_wasm";
const clone: typeof import("lodash.clone") = require("lodash.clone");
const pluginBinary = path.resolve(
__dirname,
"../../target/wasm32-wasi/debug/swc_plugin_coverage.wasm"
);
/// Mimic instrumenter.
const instrumentSync = (
code: string,
filename: string,
inputSourceMap?: object,
instrumentOptions?: Record<string, any>,
transformOptions?: Options
) => {
const pluginOptions = inputSourceMap
? {
...(instrumentOptions ?? {}),
inputSourceMap,
}
: instrumentOptions ?? {};
const options = {
filename: filename ?? "unknown",
jsc: {
parser: {
syntax: "ecmascript",
jsx: true,
},
target: "es2022",
preserveAllComments: true,
},
isModule: transformOptions?.isModule ?? true,
module: {
type: "commonjs",
strict: transformOptions?.isModule ?? false,
},
};
if (process.env.SWC_TRANSFORM_CUSTOM === "1") {
const { transformSync } = require("../../index");
return transformSync(
code,
true,
Buffer.from(JSON.stringify(options)),
Buffer.from(
JSON.stringify({
...pluginOptions,
debugInitialCoverageComment: true,
})
)
);
}
options.jsc.experimental = {
plugins: [
[
pluginBinary,
{
...pluginOptions,
debugInitialCoverageComment: true,
},
],
],
};
return transformSync(code, options);
};
/**
* Poorman's substitution for instrumenter::lastFileCoverage to get the coverage from instrumented codes.
* SWC's plugin transform does not allow to pass arbiatary data other than transformed AST, using trailing comment
* to grab out data from plugin.
*/
const lastFileCoverage = (code?: string) => {
const lines = (code ?? "").split(EOL);
const commentLine = lines
.find((v) => v.includes("__coverage_data_json_comment__::"))
?.split("__coverage_data_json_comment__::")[1];
const data = commentLine?.substring(0, commentLine.indexOf("*/"));
return data ? JSON.parse(data) : {};
};
type UnknownReserved = any;
class Verifier {
private result: UnknownReserved;
constructor(result: UnknownReserved) {
this.result = result;
}
async verify(args, expectedOutput, expectedCoverage) {
assert.ok(!this.result.err, (this.result.err || {}).message);
getGlobalObject()[this.result.coverageVariable] = clone(
this.result.baseline
);
const actualOutput = await this.result.fn(args);
const cov = this.getFileCoverage();
assert.ok(
cov && typeof cov === "object",
"No coverage found for [" + this.result.file + "]"
);
assert.deepEqual(actualOutput, expectedOutput, "Output mismatch");
assert.deepEqual(
Object.fromEntries(cov.getLineCoverage()),
expectedCoverage.lines || {},
"Line coverage mismatch"
);
assert.deepEqual(
Object.fromEntries(cov.f()),
expectedCoverage.functions || {},
"Function coverage mismatch"
);
assert.deepEqual(
Object.fromEntries(cov.b()),
expectedCoverage.branches || {},
"Branch coverage mismatch"
);
assert.deepEqual(
Object.fromEntries(cov.bT() || new Map()),
expectedCoverage.branchesTrue || {},
"Branch truthiness coverage mismatch"
);
assert.deepEqual(
Object.fromEntries(cov.s()),
expectedCoverage.statements || {},
"Statement coverage mismatch"
);
assert.deepEqual(
cov.inputSourceMap(),
expectedCoverage.inputSourceMap || undefined,
"Input source map mismatch"
);
const initial = readInitialCoverage(
this.getGeneratedCode(),
this.result.transformOptions
);
assert.ok(initial);
assert.deepEqual(initial.coverageData, this.result.emptyCoverage);
assert.ok(initial.path);
if (this.result.file) {
assert.equal(initial.path, this.result.file);
}
assert.equal(initial.gcv, this.result.coverageVariable);
assert.ok(initial.hash);
}
getCoverage() {
return getGlobalObject()[this.result.coverageVariable];
}
getFileCoverage() {
const cov = this.getCoverage();
const { _coverageSchema, hash, ...fileCoverage } = cov[Object.keys(cov)[0]];
return new FileCoverageInterop(fileCoverage);
}
getGeneratedCode() {
return this.result.generatedCode;
}
compileError() {
return this.result.err;
}
}
function extractTestOption(options, name, defaultValue) {
let v = defaultValue;
if (Object.prototype.hasOwnProperty.call(options, name)) {
v = options[name];
}
return v;
}
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
function pad(str, len) {
const blanks = " ";
if (str.length >= len) {
return str;
}
return blanks.substring(0, len - str.length) + str;
}
function annotatedCode(code) {
const codeArray = code.split("\n");
let line = 0;
const annotated = codeArray.map((str) => {
line += 1;
return pad(line, 6) + ": " + str;
});
return annotated.join("\n");
}
function getGlobalObject() {
return new Function("return this")();
}
const create = (code, options = {}, instrumentOptions = {}, inputSourceMap) => {
instrumentOptions.coverageVariable =
instrumentOptions.coverageVariable || "__testing_coverage__";
const debug = extractTestOption(options, "debug", process.env.DEBUG === "1");
const file = extractTestOption(options, "file", __filename);
const generateOnly = extractTestOption(options, "generateOnly", false);
const noCoverage = extractTestOption(options, "noCoverage", false);
const quiet = extractTestOption(options, "quiet", false);
const coverageVariable = instrumentOptions.coverageVariable;
const g = getGlobalObject();
let instrumenterOutput;
let wrapped;
let fn;
let verror;
if (debug) {
instrumentOptions.compact = false;
instrumentOptions.instrumentLog = {
logLevel: "trace",
enable_trace: true,
};
}
try {
let out = instrumentSync(
code,
file,
inputSourceMap,
instrumentOptions,
options.transformOptions
);
instrumenterOutput = out.code;
if (debug) {
console.log(
"================== Original ============================================"
);
console.log(annotatedCode(code));
console.log(
"================== Generated ==========================================="
);
console.log(instrumenterOutput);
console.log(
"========================================================================"
);
}
} catch (ex) {
if (!quiet) {
console.error(ex.stack);
}
verror = new Error(
"Error instrumenting:\n" + annotatedCode(String(code)) + "\n" + ex.message
);
}
if (!(verror || generateOnly)) {
wrapped = "{ var output;\n" + instrumenterOutput + "\nreturn output;\n}";
g[coverageVariable] = undefined;
try {
if (options.isAsync) {
fn = new AsyncFunction("args", wrapped);
} else {
fn = new Function("args", wrapped);
}
} catch (ex) {
console.error(ex.stack);
verror = new Error(
"Error compiling\n" + annotatedCode(code) + "\n" + ex.message
);
}
}
if (generateOnly || noCoverage) {
if (verror) {
throw verror;
}
}
return new Verifier({
err: verror,
debug,
file,
fn,
code,
generatedCode: instrumenterOutput,
coverageVariable,
baseline: clone(g[coverageVariable]),
emptyCoverage: lastFileCoverage(instrumenterOutput), //instrumenter.getLastFileCoverage()
transformOptions: options.transformOptions,
});
};
export { create, instrumentSync };