-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathx-test-frame.js
More file actions
386 lines (356 loc) · 11.3 KB
/
x-test-frame.js
File metadata and controls
386 lines (356 loc) · 11.3 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import { XTestCommon } from './x-test-common.js';
export class XTestFrame {
/**
* @param {any} context
* @param {any} frameId
* @param {any} href
*/
static async initialize(context, frameId, href) {
Object.assign(context.state, { frameId, href });
context.publish('x-test-frame-initialize', { frameId });
context.state.parents.push({ type: 'frame', frameId });
context.subscribe(async (/** @type {any} */ event) => {
switch (event.data.type) {
case 'x-test-frame-bail':
XTestFrame.onBail(context);
break;
case 'x-test-root-run':
XTestFrame.onRun(context, event);
break;
default:
// Ignore — this message isn't for us.
}
});
// Setup global error / rejection handlers.
/* x-test:coverage disable */ // Cannot test top-level error handlers.
context.addErrorListener((/** @type {any} */ event) => {
event.preventDefault();
XTestFrame.bail(context, event.error);
});
context.addUnhandledrejectionListener((/** @type {any} */ event) => {
event.preventDefault();
XTestFrame.bail(context, event.reason);
});
/* x-test:coverage enable */
// The registration window stays open until "DOMContentLoaded", which allows
// folks to import fixtures via JSON Modules and register tests before
// registration ends. Note that this does _NOT_ support top-level awaits.
await context.domContentLoadedPromise;
if (!context.state.bailed) {
context.state.ready = true;
context.publish('x-test-frame-ready', { frameId: context.state.frameId });
}
}
/**
* @param {any} context
*/
static onBail(context/*, event*/) {
if (!context.state.bailed) {
context.state.bailed = true;
}
}
/**
* @param {any} context
* @param {any} event
*/
static async onRun(context, event) {
if (
!context.state.bailed &&
context.state.callbacks[event.data.data.testId]
) {
const { testId, directive, interval } = event.data.data;
try {
if (directive !== 'SKIP') {
const callback = context.state.callbacks[testId];
const resolvedInterval = interval ?? 30_000;
// Create a new stack to remove some internal noise from stack trace on error.
const timeout = await Promise.race([Promise.resolve().then(() => callback()), context.timeout(resolvedInterval)]);
if (timeout === XTestCommon.TIMEOUT) {
throw new Error(`timeout after ${resolvedInterval.toLocaleString()}ms`);
}
}
context.publish('x-test-frame-result', { testId, ok: true, error: null });
} catch (error) {
error = XTestFrame.createError(error); // eslint-disable-line no-ex-assign
context.publish('x-test-frame-result', { testId, ok: false, error });
}
}
}
/**
* @param {any} context
* @param {any} error
*/
static bail(context, error) {
if (!context.state.bailed) {
context.state.bailed = true;
context.publish(
'x-test-frame-bail',
{ frameId: context.state.frameId, error: XTestFrame.createError(error) }
);
}
}
/**
* @param {any} originalError
* @returns {{message: string, stack?: string}}
*/
static createError(originalError) {
const error = {};
if (originalError instanceof Error) {
Object.assign(error, { message: originalError.message, stack: originalError.stack });
} else {
error.message = String(originalError);
}
return error;
}
/**
* @param {any} context
* @param {any} caller
* @param {any} value
* @param {any} [message]
*/
static assert(context, caller, value, message) {
if (context && !context.state.bailed) {
if (!value) {
const error = new Error(message ?? 'not ok');
/** @type {any} */ (Error).captureStackTrace?.(error, caller);
throw error;
}
}
}
/**
* @param {any} context
* @param {any} caller
* @param {any} fn
* @param {any} error
* @param {any} [message]
*/
static throws(context, caller, fn, error, message) {
let threw = false;
let thrownValue;
try {
fn();
} catch (e) {
threw = true;
thrownValue = e;
}
if (!threw) {
XTestFrame.assert(context, caller, false, message ?? 'expected function to throw');
} else {
XTestFrame.assert(context, caller, error.test(String(thrownValue)), message ?? `expected thrown value to match "${error}"`);
}
}
/**
* @param {any} context
* @param {any} caller
* @param {any} fn
* @param {any} error
* @param {any} [message]
*/
static async rejects(context, caller, fn, error, message) {
let rejected = false;
let rejectionValue;
try {
await fn();
} catch (e) {
rejected = true;
rejectionValue = e;
}
if (!rejected) {
XTestFrame.assert(context, caller, false, message ?? 'expected function to reject');
} else {
XTestFrame.assert(context, caller, error.test(String(rejectionValue)), message ?? `expected rejection value to match "${error}"`);
}
}
/**
* Strict deep-equality check. Only supports primitives, plain objects, and
* arrays. Throws a non-assertion error for unsupported types (Map, Set, Date,
* class instances, functions, etc.) so the behavior can safely be expanded
* later. This is meant to be a _strict_ subset of what is provided by
* node:assert/strict#deepEqual (https://nodejs.org/api/assert.html).
* @param {any} context
* @param {any} caller
* @param {any} actual
* @param {any} expected
* @param {any} [message]
*/
static deepEqual(context, caller, actual, expected, message) {
XTestFrame.assert(context, caller, XTestFrame.#deepEqual(actual, expected), message ?? 'not deep equal');
}
/**
* @param {any} a
* @param {any} b
* @returns {boolean}
*/
static #deepEqual(a, b) {
if (Object.is(a, b)) {
// If the objects are equal, we exit early.
// Note: Object.is(NaN, NaN) === true, Object.is(+0, -0) === false;
return true;
} else if (
(a === null || (typeof a !== 'object' && typeof a !== 'function')) ||
(b === null || (typeof b !== 'object' && typeof b !== 'function'))
) {
// If not equal, and one is a primitive value, we exit early.
return false;
}
// Fail for mixed array/object.
if (Array.isArray(a) !== Array.isArray(b)) {
return false;
}
// Throw if object is not a plain object or array (Map, Set, Date, RegExp, etc).
for (const value of [a, b]) {
const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null && prototype !== Array.prototype) {
throw new Error(`deepEqual only supports primitives, plain objects, and arrays (got ${value?.constructor?.name})`);
}
}
// Fail if prototypes differ (e.g. Object.create(null) vs {}).
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) {
return false;
}
// Throw if either object has symbol-keyed properties.
if (Object.getOwnPropertySymbols(a).length > 0 || Object.getOwnPropertySymbols(b).length > 0) {
throw new Error('deepEqual does not support symbol-keyed properties.');
}
// Exit early if key length doesn't match.
if (Object.keys(a).length !== Object.keys(b).length) {
return false;
}
// Compare nested values / recurse.
for (const key of Object.keys(a)) {
if (!Object.hasOwn(b, key) || !XTestFrame.#deepEqual(a[key], b[key])) {
return false;
}
}
return true;
}
/**
* @param {any} context
* @param {any} href
*/
static load(context, href) {
if (context && !context.state.bailed && !context.state.ready) {
const frameId = context.uuid();
const frameHref = new URL(href, context.state.href).href;
const initiatorFrameId = context.state.frameId;
context.publish('x-test-frame-register', { type: 'frame', frameId, initiatorFrameId, href: frameHref });
}
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
* @param {any} directive
* @param {any} only
*/
static #suiteInner(context, text, callback, directive, only) {
if (context && !context.state.bailed && !context.state.ready) {
const suiteId = context.uuid();
const parents = [...context.state.parents];
directive = directive ?? null;
only = only ?? false;
context.publish(
'x-test-frame-register',
{ type: 'suite-start', suiteId, parents, text, directive, only }
);
try {
context.state.parents.push({ type: 'suite', suiteId });
callback();
context.state.parents.pop();
context.publish('x-test-frame-register', { type: 'suite-end', suiteId });
} catch (error) {
XTestFrame.bail(context, error);
}
}
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
*/
static suite(context, text, callback) {
XTestFrame.#suiteInner(context, text, callback, null, null);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
*/
static suiteSkip(context, text, callback) {
XTestFrame.#suiteInner(context, text, callback, 'SKIP', null);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
*/
static suiteOnly(context, text, callback) {
XTestFrame.#suiteInner(context, text, callback, null, true);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
*/
static suiteTodo(context, text, callback) {
XTestFrame.#suiteInner(context, text, callback, 'TODO', null);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
* @param {any} [interval]
* @param {any} [directive]
* @param {any} [only]
*/
static #testInner(context, text, callback, interval, directive, only) {
if (context && !context.state.bailed && !context.state.ready) {
const testId = context.uuid();
const parents = [...context.state.parents];
interval = interval ?? null;
directive = directive ?? null;
only = only ?? false;
context.state.callbacks[testId] = callback;
context.publish(
'x-test-frame-register',
{ type: 'test', testId, parents, text, interval, directive, only }
);
}
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
* @param {any} [interval]
*/
static test(context, text, callback, interval) {
XTestFrame.#testInner(context, text, callback, interval, null, null);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
* @param {any} [interval]
*/
static testSkip(context, text, callback, interval) {
XTestFrame.#testInner(context, text, callback, interval, 'SKIP', null);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
* @param {any} [interval]
*/
static testOnly(context, text, callback, interval) {
XTestFrame.#testInner(context, text, callback, interval, null, true);
}
/**
* @param {any} context
* @param {any} text
* @param {any} callback
* @param {any} [interval]
*/
static testTodo(context, text, callback, interval) {
XTestFrame.#testInner(context, text, callback, interval, 'TODO', null);
}
}