Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core(fr): add fraggle rock driver #11742

Merged
merged 4 commits into from
Dec 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions lighthouse-core/fraggle-rock/gather/driver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const ProtocolSession = require('./session.js');
const ExecutionContext = require('../../gather/driver/execution-context.js');

const throwNotConnectedFn = () => {
throw new Error('Session not connected');
};

/** @type {LH.Gatherer.FRProtocolSession} */
const defaultSession = {
hasNextProtocolTimeout: throwNotConnectedFn,
getNextProtocolTimeout: throwNotConnectedFn,
setNextProtocolTimeout: throwNotConnectedFn,
on: throwNotConnectedFn,
once: throwNotConnectedFn,
off: throwNotConnectedFn,
sendCommand: throwNotConnectedFn,
};

/** @implements {LH.Gatherer.FRTransitionalDriver} */
class Driver {
/**
* @param {import('puppeteer').Page} page
*/
constructor(page) {
this._page = page;
/** @type {LH.Gatherer.FRProtocolSession|undefined} */
this._session = undefined;
/** @type {ExecutionContext|undefined} */
this._executionContext = undefined;

this.defaultSession = defaultSession;
}

/** @return {Promise<void>} */
async connect() {
if (this._session) return;
const session = await this._page.target().createCDPSession();
this._session = this.defaultSession = new ProtocolSession(session);
this._executionContext = new ExecutionContext(this._session);
}

/**
* @param {string} expression
* @param {{useIsolation?: boolean}} [options]
* @return {Promise<*>}
*/
async evaluateAsync(expression, options) {
if (!this._executionContext) throw new Error('Driver not connected to page');
return this._executionContext.evaluateAsync(expression, options);
}
}

module.exports = Driver;
80 changes: 80 additions & 0 deletions lighthouse-core/fraggle-rock/gather/session.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

/** @implements {LH.Gatherer.FRProtocolSession} */
class ProtocolSession {
/**
* @param {import('puppeteer').CDPSession} session
*/
constructor(session) {
this._session = session;
}

/**
* @return {boolean}
*/
hasNextProtocolTimeout() {
return false;
}

/**
* @return {number}
*/
getNextProtocolTimeout() {
return Number.MAX_SAFE_INTEGER;
}

/**
* @param {number} ms
*/
setNextProtocolTimeout(ms) { // eslint-disable-line no-unused-vars
// TODO(FR-COMPAT): support protocol timeout
}

/**
* Bind listeners for protocol events.
* @template {keyof LH.CrdpEvents} E
* @param {E} eventName
* @param {(...args: LH.CrdpEvents[E]) => void} callback
*/
on(eventName, callback) {
this._session.on(eventName, /** @type {*} */ (callback));
}

/**
* Bind listeners for protocol events.
* @template {keyof LH.CrdpEvents} E
* @param {E} eventName
* @param {(...args: LH.CrdpEvents[E]) => void} callback
*/
once(eventName, callback) {
this._session.once(eventName, /** @type {*} */ (callback));
}

/**
* Bind listeners for protocol events.
* @template {keyof LH.CrdpEvents} E
* @param {E} eventName
* @param {(...args: LH.CrdpEvents[E]) => void} callback
*/
off(eventName, callback) {
this._session.off(eventName, /** @type {*} */ (callback));
}

/**
* @template {keyof LH.CrdpCommands} C
* @param {C} method
* @param {LH.CrdpCommands[C]['paramsType']} params
* @return {Promise<LH.CrdpCommands[C]['returnType']>}
*/
sendCommand(method, ...params) {
return this._session.send(method, ...params);
}
}

module.exports = ProtocolSession;

3 changes: 3 additions & 0 deletions lighthouse-core/gather/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ class Driver {
// eslint-disable-next-line no-invalid-this
_executionContext = new ExecutionContext(this);

// eslint-disable-next-line no-invalid-this
defaultSession = this;

/**
* @param {Connection} connection
*/
Expand Down
80 changes: 80 additions & 0 deletions lighthouse-core/test/fraggle-rock/gather/driver-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const Driver = require('../../../fraggle-rock/gather/driver.js');

/* eslint-env jest */

/** @type {Array<keyof LH.Gatherer.FRProtocolSession>} */
const DELEGATED_FUNCTIONS = [
'hasNextProtocolTimeout',
'getNextProtocolTimeout',
'setNextProtocolTimeout',
'on',
'off',
'sendCommand',
];

/** @type {import('puppeteer').Page} */
let page;
/** @type {import('puppeteer').Target} */
let pageTarget;
/** @type {import('puppeteer').CDPSession} */
let puppeteerSession;
/** @type {Driver} */
let driver;

beforeEach(() => {
// @ts-expect-error - Individual mock functions are applied as necessary.
page = {target: () => pageTarget};
// @ts-expect-error - Individual mock functions are applied as necessary.
pageTarget = {createCDPSession: () => puppeteerSession};
// @ts-expect-error - Individual mock functions are applied as necessary.
puppeteerSession = {on: jest.fn(), off: jest.fn(), send: jest.fn()};
driver = new Driver(page);
});

for (const fnName of DELEGATED_FUNCTIONS) {
describe(fnName, () => {
it('should fail if called before connect', () => {
expect(driver.defaultSession[fnName]).toThrow(/not connected/);
});

it('should use connected session for default', async () => {
await driver.connect();
if (!driver._session) throw new Error('Driver did not connect');

/** @type {any} */
const args = [1, {arg: 2}];
const returnValue = {foo: 'bar'};
driver._session[fnName] = jest.fn().mockReturnValue(returnValue);
// @ts-expect-error - typescript can't handle this union type.
const actualResult = driver.defaultSession[fnName](...args);
expect(driver._session[fnName]).toHaveBeenCalledWith(...args);
expect(actualResult).toEqual(returnValue);
});
});
}

describe('.evaluateAsync', () => {
it('should fail if called before connect', async () => {
await expect(driver.evaluateAsync('1 + 1')).rejects.toBeTruthy();
});

it('should delegate to execution context', async () => {
await driver.connect();
if (!driver._executionContext) throw new Error('Runtime did not connect');

const returnValue = 2;
const evaluateAsyncMock = driver._executionContext.evaluateAsync =
jest.fn().mockReturnValue(returnValue);

const actualResult = await driver.evaluateAsync('1 + 1', {useIsolation: true});
expect(evaluateAsyncMock).toHaveBeenCalledWith('1 + 1', {useIsolation: true});
expect(actualResult).toEqual(returnValue);
});
});
47 changes: 47 additions & 0 deletions lighthouse-core/test/fraggle-rock/gather/session-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const ProtocolSession = require('../../../fraggle-rock/gather/session.js');

/* eslint-env jest */

describe('ProtocolSession', () => {
/** @type {import('puppeteer').CDPSession} */
let puppeteerSession;
/** @type {ProtocolSession} */
let session;

beforeEach(() => {
// @ts-expect-error - Individual mock functions are applied as necessary.
puppeteerSession = {};
session = new ProtocolSession(puppeteerSession);
});

/** @type {Array<'on'|'off'|'once'>} */
const delegateMethods = ['on', 'once', 'off'];
for (const method of delegateMethods) {
describe(`.${method}`, () => {
it('delegates to puppeteer', async () => {
const puppeteerFn = puppeteerSession[method] = jest.fn();
const callback = () => undefined;

session[method]('Page.frameNavigated', callback);
expect(puppeteerFn).toHaveBeenCalledWith('Page.frameNavigated', callback);
});
});
}

describe('.sendCommand', () => {
it('delegates to puppeteer', async () => {
const send = puppeteerSession.send = jest.fn().mockResolvedValue(123);

const result = await session.sendCommand('Page.navigate', {url: 'foo'});
expect(result).toEqual(123);
expect(send).toHaveBeenCalledWith('Page.navigate', {url: 'foo'});
});
});
});
2 changes: 2 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
// Opt-in to typechecking for some core tests.
"lighthouse-core/test/scripts/lantern/constants-test.js",
"lighthouse-core/test/gather/driver/execution-context-test.js",
"lighthouse-core/test/fraggle-rock/gather/session-test.js",
"lighthouse-core/test/fraggle-rock/gather/driver-test.js",
"lighthouse-core/test/gather/driver-test.js",
"lighthouse-core/test/gather/gather-runner-test.js",
"lighthouse-core/test/audits/script-treemap-data-test.js"
Expand Down
3 changes: 2 additions & 1 deletion types/gatherer.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ declare global {
}

/** The limited driver interface shared between pre and post Fraggle Rock Lighthouse. */
export interface FRTransitionalDriver extends FRProtocolSession {
export interface FRTransitionalDriver {
defaultSession: FRProtocolSession;
evaluateAsync(expression: string, options?: {useIsolation?: boolean}): Promise<any>;
}

Expand Down