-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathassertSnapshot.js
More file actions
272 lines (244 loc) Β· 8.8 KB
/
assertSnapshot.js
File metadata and controls
272 lines (244 loc) Β· 8.8 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
'use strict';
const common = require('.');
const path = require('node:path');
const test = require('node:test');
const fs = require('node:fs/promises');
const assert = require('node:assert/strict');
const { pathToFileURL } = require('node:url');
const { hostname } = require('node:os');
const stackFramesRegexp = /(?<=\n)(\s+)((.+?)\s+\()?(?:\(?(.+?):(\d+)(?::(\d+))?)\)?(\s+\{)?(\[\d+m)?(\n|$)/g;
const windowNewlineRegexp = /\r/g;
function replaceNodeVersion(str) {
return str.replaceAll(process.version, '*');
}
function replaceStackTrace(str, replacement = '$1*$7$8\n') {
return str.replace(stackFramesRegexp, replacement);
}
function replaceInternalStackTrace(str) {
// Replace non-internal frame `at TracingChannel.traceSync (node:diagnostics_channel:328:14)`
// as well as `at node:internal/main/run_main_module:33:47` with `*`.
return str.replaceAll(/(\W+).*[(\s]node:.*/g, '$1*');
}
function replaceWindowsLineEndings(str) {
return str.replace(windowNewlineRegexp, '');
}
function replaceWindowsPaths(str) {
return common.isWindows ? str.replaceAll(path.win32.sep, path.posix.sep) : str;
}
function transformProjectRoot(replacement = '') {
const projectRoot = path.resolve(__dirname, '../..');
const fsRoot = path.parse(projectRoot).root;
// If projectRoot is fs root, skip stripping to avoid corrupting URL separators.
if (projectRoot === fsRoot) {
return (str) => str.replaceAll('\\\'', "'");
}
// Stack output may use '/' on Windows; handle both separators.
const projectRootPosix = projectRoot.replaceAll(path.win32.sep, path.posix.sep);
const fileUrlPrefix = 'file:///';
const fileUrl = pathToFileURL(projectRoot).href;
const fileUrlRoot = fileUrl.startsWith(fileUrlPrefix) ?
fileUrl.slice(fileUrlPrefix.length) :
null;
const stripPrefixAtBoundary = (str, prefix) => {
if (!prefix) return str;
let out = '';
let index = 0;
while (true) {
const match = str.indexOf(prefix, index);
if (match === -1) return out + str.slice(index);
const after = match + prefix.length;
const nextChar = str[after];
const isBoundary = after === str.length || nextChar === '/' || nextChar === '\\';
out += str.slice(index, match);
out += isBoundary ? replacement : prefix;
index = after;
}
};
// Strip repo prefix from file:// URLs only; keep other schemes intact.
const stripFileUrlRoot = (str) => {
if (!fileUrlRoot) return str;
const needle = `${fileUrlPrefix}${fileUrlRoot}`;
let out = '';
let index = 0;
while (true) {
const match = str.indexOf(needle, index);
if (match === -1) return out + str.slice(index);
const after = match + needle.length;
const nextChar = str[after];
const isBoundary = after === str.length || nextChar === '/';
out += str.slice(index, match);
out += isBoundary ? `${fileUrlPrefix}${replacement}` : needle;
// If the next character is a '/' and the replacement is empty, skip the next character.
if (isBoundary && replacement === '' && nextChar === '/') {
index = after + 1;
} else {
index = after;
}
}
};
return (str) => {
let out = str.replaceAll('\\\'', "'");
out = stripFileUrlRoot(out);
out = stripPrefixAtBoundary(out, projectRoot);
if (projectRootPosix !== projectRoot) out = stripPrefixAtBoundary(out, projectRootPosix);
return out;
};
}
function transform(...args) {
return (str) => args.reduce((acc, fn) => fn(acc), str);
}
function getSnapshotPath(filename) {
const { name, dir } = path.parse(filename);
return path.resolve(dir, `${name}.snapshot`);
}
async function assertSnapshot(actual, filename = process.argv[1]) {
const snapshot = getSnapshotPath(filename);
if (process.env.NODE_REGENERATE_SNAPSHOTS) {
await fs.writeFile(snapshot, actual);
} else {
let expected;
try {
expected = await fs.readFile(snapshot, 'utf8');
} catch (e) {
if (e.code === 'ENOENT') {
console.log(
'Snapshot file does not exist. You can create a new one by running the test with NODE_REGENERATE_SNAPSHOTS=1',
);
}
throw e;
}
assert.strictEqual(actual, replaceWindowsLineEndings(expected));
}
}
/**
* Spawn a process and assert its output against a snapshot.
* if you want to automatically update the snapshot, run tests with NODE_REGENERATE_SNAPSHOTS=1
* transform is a function that takes the output and returns a string that will be compared against the snapshot
* this is useful for normalizing output such as stack traces
* there are some predefined transforms in this file such as replaceStackTrace and replaceWindowsLineEndings
* both of which can be used as an example for writing your own
* compose multiple transforms by passing them as arguments to the transform function:
* assertSnapshot.transform(assertSnapshot.replaceStackTrace, assertSnapshot.replaceWindowsLineEndings)
* @param {string} filename
* @param {function(string): string} [transform]
* @param {object} [options] - control how the child process is spawned
* @param {boolean} [options.tty] - whether to spawn the process in a pseudo-tty
* @returns {Promise<void>}
*/
async function spawnAndAssert(filename, transform = (x) => x, { tty = false, ...options } = {}) {
if (tty && common.isWindows) {
test({ skip: 'Skipping pseudo-tty tests, as pseudo terminals are not available on Windows.' });
return;
}
let { flags } = common.parseTestMetadata(filename);
if (options.flags) {
flags = [...options.flags, ...flags];
}
const executable = tty ? (process.env.PYTHON || 'python3') : process.execPath;
const args =
tty ?
[path.join(__dirname, '../..', 'tools/pseudo-tty.py'), process.execPath, ...flags, filename] :
[...flags, filename];
const { stdout, stderr } = await common.spawnPromisified(executable, args, options);
await assertSnapshot(transform(`${stdout}${stderr}`), filename);
}
function replaceTestDuration(str) {
return str
.replaceAll(/duration_ms: [0-9.]+/g, 'duration_ms: *')
.replaceAll(/duration_ms [0-9.]+/g, 'duration_ms *');
}
const root = path.resolve(__dirname, '..', '..');
const color = '(\\[\\d+m)';
const stackTraceBasePath = new RegExp(`${color}\\(${RegExp.escape(root)}/?${color}(.*)${color}\\)`, 'g');
function replaceSpecDuration(str) {
return str
.replaceAll(/[0-9.]+ms/g, '*ms')
.replaceAll(/duration_ms [0-9.]+/g, 'duration_ms *')
.replace(stackTraceBasePath, '$3');
}
function replaceJunitDuration(str) {
return str
.replaceAll(/time="[0-9.]+"/g, 'time="*"')
.replaceAll(/duration_ms [0-9.]+/g, 'duration_ms *')
.replaceAll(`hostname="${hostname()}"`, 'hostname="HOSTNAME"')
.replaceAll(/file="[^"]*"/g, 'file="*"')
.replace(stackTraceBasePath, '$3');
}
function removeWindowsPathEscaping(str) {
return common.isWindows ? str.replaceAll(/\\\\/g, '\\') : str;
}
function replaceTestLocationLine(str) {
return str.replaceAll(/(js:)(\d+)(:\d+)/g, '$1(LINE)$3');
}
// The Node test coverage returns results for all files called by the test. This
// will make the output file change if files like test/common/index.js change.
// This transform picks only the first line and then the lines from the test
// file.
function pickTestFileFromLcov(str) {
const lines = str.split(/\n/);
const firstLineOfTestFile = lines.findIndex(
(line) => line.startsWith('SF:') && line.trim().endsWith('output.js'),
);
const lastLineOfTestFile = lines.findIndex(
(line, index) => index > firstLineOfTestFile && line.trim() === 'end_of_record',
);
return (
lines[0] + '\n' + lines.slice(firstLineOfTestFile, lastLineOfTestFile + 1).join('\n') + '\n'
);
}
const defaultTransform = transform(
replaceWindowsLineEndings,
replaceStackTrace,
removeWindowsPathEscaping,
transformProjectRoot(),
replaceWindowsPaths,
replaceTestDuration,
replaceTestLocationLine,
);
const specTransform = transform(
replaceSpecDuration,
replaceWindowsLineEndings,
replaceStackTrace,
replaceWindowsPaths,
);
const junitTransform = transform(
replaceJunitDuration,
replaceWindowsLineEndings,
replaceStackTrace,
replaceWindowsPaths,
);
const lcovTransform = transform(
replaceWindowsLineEndings,
replaceStackTrace,
transformProjectRoot(),
replaceWindowsPaths,
pickTestFileFromLcov,
);
function ensureCwdIsProjectRoot() {
if (process.cwd() !== root) {
process.chdir(root);
}
}
function canColorize() {
// Loading it lazily to avoid breaking `NODE_REGENERATE_SNAPSHOTS`.
return require('internal/tty').getColorDepth() > 2;
}
module.exports = {
assertSnapshot,
getSnapshotPath,
replaceNodeVersion,
replaceStackTrace,
replaceInternalStackTrace,
replaceWindowsLineEndings,
replaceWindowsPaths,
spawnAndAssert,
transform,
transformProjectRoot,
replaceTestDuration,
defaultTransform,
specTransform,
junitTransform,
lcovTransform,
ensureCwdIsProjectRoot,
canColorize,
};