-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
Copy pathexecution-context-test.js
386 lines (326 loc) · 13.6 KB
/
execution-context-test.js
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
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {ExecutionContext} from '../../../gather/driver/execution-context.js';
import {
makePromiseInspectable,
flushAllTimersAndMicrotasks,
fnAny,
timers,
} from '../../test-utils.js';
import {createMockSession} from '../mock-driver.js';
/** @param {string} s */
function trimTrailingWhitespace(s) {
return s.split('\n').map(line => line.trimEnd()).join('\n');
}
describe('ExecutionContext', () => {
let sessionMock = createMockSession();
/** @type {(executionContext: ExecutionContext, id: number) => Promise<void>} */
let forceNewContextId;
beforeEach(() => {
sessionMock = createMockSession();
forceNewContextId = async (executionContext, executionContextId) => {
sessionMock.sendCommand
.mockResponse('Page.enable')
.mockResponse('Runtime.enable')
.mockResponse('Page.getFrameTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId})
.mockResponse('Runtime.evaluate', {result: {value: 2}});
await executionContext.evaluateAsync('1 + 1', {useIsolation: true});
};
});
it('should clear context on frame navigations', async () => {
const executionContext = new ExecutionContext(sessionMock);
const frameListener = sessionMock.on.mock.calls
.find(call => call[0] === 'Page.frameNavigated') ?? [];
expect(frameListener[1]).toBeDefined();
await forceNewContextId(executionContext, 42);
expect(executionContext.getContextId()).toEqual(42);
frameListener[1]();
expect(executionContext.getContextId()).toEqual(undefined);
});
it('should clear context on execution context destroyed', async () => {
const executionContext = new ExecutionContext(sessionMock);
const executionDestroyed = sessionMock.on.mock.calls
.find(call => call[0] === 'Runtime.executionContextDestroyed') ?? [];
expect(executionDestroyed[1]).toBeDefined();
await forceNewContextId(executionContext, 42);
expect(executionContext.getContextId()).toEqual(42);
executionDestroyed[1]({executionContextId: 51});
expect(executionContext.getContextId()).toEqual(42);
executionDestroyed[1]({executionContextId: 42});
expect(executionContext.getContextId()).toEqual(undefined);
});
// it('TODO: should cache native objects in page');
});
describe('.evaluateAsync', () => {
before(() => timers.useFakeTimers());
after(() => timers.dispose());
let sessionMock = createMockSession();
/** @type {ExecutionContext} */
let executionContext;
beforeEach(() => {
sessionMock = createMockSession();
executionContext = new ExecutionContext(sessionMock.asSession());
});
it('evaluates an expression', async () => {
const sendCommand = (sessionMock.sendCommand.mockResponse(
'Runtime.evaluate',
{result: {value: 2}}
));
const value = await executionContext.evaluateAsync('1 + 1');
expect(value).toEqual(2);
sendCommand.findInvocation('Runtime.evaluate');
});
it('uses a high default timeout', async () => {
const setNextProtocolTimeout = sessionMock.setNextProtocolTimeout = fnAny();
sessionMock.hasNextProtocolTimeout = fnAny().mockReturnValue(false);
sessionMock.sendCommand.mockRejectedValue(new Error('Timeout'));
const evaluatePromise = makePromiseInspectable(executionContext.evaluateAsync('1 + 1'));
await flushAllTimersAndMicrotasks();
expect(setNextProtocolTimeout).toHaveBeenCalledWith(60000);
expect(evaluatePromise).toBeDone();
await expect(evaluatePromise).rejects.toBeTruthy();
});
it('uses the specific timeout given', async () => {
const expectedTimeout = 5000;
const setNextProtocolTimeout = sessionMock.setNextProtocolTimeout = fnAny();
sessionMock.hasNextProtocolTimeout = fnAny().mockReturnValue(true);
sessionMock.getNextProtocolTimeout = fnAny().mockReturnValue(expectedTimeout);
sessionMock.sendCommand.mockRejectedValue(new Error('Timeout'));
const evaluatePromise = makePromiseInspectable(executionContext.evaluateAsync('1 + 1'));
await flushAllTimersAndMicrotasks();
expect(setNextProtocolTimeout).toHaveBeenCalledWith(expectedTimeout);
expect(evaluatePromise).toBeDone();
await expect(evaluatePromise).rejects.toBeTruthy();
});
it('uses the specific timeout given (isolation)', async () => {
const expectedTimeout = 5000;
const setNextProtocolTimeout = sessionMock.setNextProtocolTimeout = fnAny();
sessionMock.hasNextProtocolTimeout = fnAny().mockReturnValue(true);
sessionMock.getNextProtocolTimeout = fnAny().mockReturnValue(expectedTimeout);
sessionMock.sendCommand
.mockResponse('Page.enable')
.mockResponse('Runtime.enable')
.mockResponse('Page.getFrameTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 1});
const evaluatePromise = makePromiseInspectable(executionContext.evaluateAsync('1 + 1', {
useIsolation: true,
}));
await flushAllTimersAndMicrotasks();
expect(setNextProtocolTimeout).toHaveBeenCalledWith(expectedTimeout);
expect(evaluatePromise).toBeDone();
await expect(evaluatePromise).rejects.toBeTruthy();
});
it('evaluates an expression in isolation', async () => {
sessionMock.sendCommand
.mockResponse('Page.enable')
.mockResponse('Runtime.enable')
.mockResponse('Page.getFrameTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 1})
.mockResponse('Runtime.evaluate', {result: {value: 2}})
.mockResponse('Runtime.evaluate', {result: {value: 2}});
const value = await executionContext.evaluateAsync('1 + 1', {useIsolation: true});
expect(value).toEqual(2);
// Check that we used the correct frame when creating the isolated context
let createWorldInvocations =
sessionMock.sendCommand.findAllInvocations('Page.createIsolatedWorld');
expect(createWorldInvocations[0]).toMatchObject({frameId: '1337'});
// Check that we used the isolated context when evaluating
const evaluateArgs = sessionMock.sendCommand.findInvocation('Runtime.evaluate');
expect(evaluateArgs).toMatchObject({contextId: 1});
// Make sure we cached the isolated context from last time
createWorldInvocations = sessionMock.sendCommand.findAllInvocations('Page.createIsolatedWorld');
expect(createWorldInvocations).toHaveLength(1);
await executionContext.evaluateAsync('1 + 1', {useIsolation: true});
createWorldInvocations = sessionMock.sendCommand.findAllInvocations('Page.createIsolatedWorld');
expect(createWorldInvocations).toHaveLength(1);
});
it('recovers from isolation failures', async () => {
sessionMock.sendCommand
.mockResponse('Page.enable')
.mockResponse('Runtime.enable')
.mockResponse('Page.getFrameTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 9001})
.mockResponse('Runtime.evaluate', Promise.reject(new Error('Cannot find context')))
.mockResponse('Page.enable')
.mockResponse('Runtime.enable')
.mockResponse('Page.getFrameTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 9002})
.mockResponse('Runtime.evaluate', {result: {value: 'mocked value'}});
const value = await executionContext.evaluateAsync('"magic"', {useIsolation: true});
expect(value).toEqual('mocked value');
});
it('handles runtime evaluation exception', async () => {
/** @type {LH.Crdp.Runtime.ExceptionDetails} */
const exceptionDetails = {
exceptionId: 1,
text: 'Uncaught',
lineNumber: 7,
columnNumber: 8,
stackTrace: {description: '', callFrames: []},
exception: {
type: 'object',
subtype: 'error',
className: 'ReferenceError',
description: 'ReferenceError: Prosmise is not defined\n' +
' at wrapInNativePromise (_lighthouse-eval.js:8:9)\n' +
' at _lighthouse-eval.js:83:8',
},
};
sessionMock.sendCommand
.mockResponse('Page.enable')
.mockResponse('Runtime.enable')
.mockResponse('Page.getResourceTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.getFrameTree', {frameTree: {frame: {id: '1337'}}})
.mockResponse('Page.createIsolatedWorld', {executionContextId: 9001})
.mockResponse('Runtime.evaluate', {exceptionDetails});
const promise = executionContext.evaluateAsync('new Prosmise', {useIsolation: true});
await expect(promise).rejects.toThrow(/Expression: new Prosmise/);
await expect(promise).rejects.toThrow(/elided/);
await expect(promise).rejects.toThrow(/at wrapInNativePromise/);
});
});
describe('.evaluate', () => {
let sessionMock = createMockSession();
/** @type {ExecutionContext} */
let executionContext;
beforeEach(() => {
sessionMock = createMockSession();
executionContext = new ExecutionContext(sessionMock.asSession());
});
it('transforms parameters into an expression given to Runtime.evaluate', async () => {
const mockFn = sessionMock.sendCommand
.mockResponse('Runtime.evaluate', {result: {value: 1}});
/** @param {number} value */
function main(value) {
return value;
}
const value = await executionContext.evaluate(main, {args: [1]});
expect(value).toEqual(1);
const {expression} = mockFn.findInvocation('Runtime.evaluate');
const expected = `
(function wrapInNativePromise() {
const Promise = globalThis.__nativePromise || globalThis.Promise;
const URL = globalThis.__nativeURL || globalThis.URL;
const performance = globalThis.__nativePerformance || globalThis.performance;
const fetch = globalThis.__nativeFetch || globalThis.fetch;
globalThis.__lighthouseExecutionContextUniqueIdentifier =
undefined;
return new Promise(function (resolve) {
return Promise.resolve()
.then(_ => (() => {
return (function main(value) {
return value;
})(1);
})())
.catch(function wrapRuntimeEvalErrorInBrowser(err) {
if (!err || typeof err === 'string') {
err = new Error(err);
}
return {
__failedInBrowser: true,
name: err.name || 'Error',
message: err.message || 'unknown error',
stack: err.stack,
};
})
.then(resolve);
});
}())
//# sourceURL=_lighthouse-eval.js`.trim();
expect(trimTrailingWhitespace(expression)).toBe(trimTrailingWhitespace(expected));
expect(await eval(expression)).toBe(1);
});
it('transforms parameters into an expression (basic)', async () => {
// Mock so the argument can be intercepted, and the generated code
// can be evaluated without the error catching code.
const mockFn = executionContext._evaluateInContext = fnAny()
.mockImplementation(() => Promise.resolve());
/** @param {number} value */
function mainFn(value) {
return value;
}
/** @type {number} */
const value = await executionContext.evaluate(mainFn, {args: [1]}); // eslint-disable-line no-unused-vars
const code = mockFn.mock.calls[0][0];
expect(trimTrailingWhitespace(code)).toBe(`(() => {
return (function mainFn(value) {
return value;
})(1);
})()`);
expect(eval(code)).toEqual(1);
});
it('transforms parameters into an expression (arrows)', async () => {
// Mock so the argument can be intercepted, and the generated code
// can be evaluated without the error catching code.
const mockFn = executionContext._evaluateInContext = fnAny()
.mockImplementation(() => Promise.resolve());
/** @param {number} value */
const mainFn = (value) => {
return value;
};
/** @type {number} */
const value = await executionContext.evaluate(mainFn, {args: [1]}); // eslint-disable-line no-unused-vars
const code = mockFn.mock.calls[0][0];
expect(trimTrailingWhitespace(code)).toBe(`(() => {
return ((value) => {
return value;
})(1);
})()`);
expect(eval(code)).toEqual(1);
});
it('transforms parameters into an expression (complex)', async () => {
// Mock so the argument can be intercepted, and the generated code
// can be evaluated without the error catching code.
const mockFn = executionContext._evaluateInContext = fnAny()
.mockImplementation(() => Promise.resolve());
/**
* @param {{a: number, b: number}} _
* @param {any} passThru
*/
function mainFn({a, b}, passThru) {
return {a: abs(a), b: square(b), passThru};
}
/**
* @param {number} val
*/
function abs(val) {
return Math.abs(val);
}
/**
* @param {number} val
*/
function square(val) {
return val * val;
}
/** @type {{a: number, b: number, passThru: any}} */
const value = await executionContext.evaluate(mainFn, { // eslint-disable-line no-unused-vars
args: [{a: -5, b: 10}, 'hello'],
deps: [abs, square],
});
const code = mockFn.mock.calls[0][0];
expect(trimTrailingWhitespace(code)).toEqual(`(() => {
function abs(val) {
return Math.abs(val);
}
function square(val) {
return val * val;
}
return (function mainFn({a, b}, passThru) {
return {a: abs(a), b: square(b), passThru};
})({"a":-5,"b":10},"hello");
})()`);
expect(eval(code)).toEqual({a: 5, b: 100, passThru: 'hello'});
});
});
describe('.serializeArguments', () => {
it('should serialize a list of differently typed arguments', () => {
const args = [undefined, 1, 'foo', null, {x: {y: {z: [2]}}}];
expect(ExecutionContext.serializeArguments(args)).toEqual(
`undefined,1,"foo",null,{"x":{"y":{"z":[2]}}}`
);
});
});