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

misc: puppeteer script to test a page from devtools #12145

Merged
merged 27 commits into from
Apr 13, 2021
Merged
Show file tree
Hide file tree
Changes from 20 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
168 changes: 168 additions & 0 deletions lighthouse-core/scripts/pptr-run-devtools.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/**
* @license Copyright 2021 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';
adamraine marked this conversation as resolved.
Show resolved Hide resolved

/**
* USAGE:
* Make sure CHROME_PATH is set to a modern version of Chrome.
* This script won't work on older versions that use the "Audits" panel.
*
* URL list file: yarn run-devtools < path/to/urls.txt
* Single URL: yarn run-devtools "https://example.com"
*/

const puppeteer = require('puppeteer');
const fs = require('fs');
const readline = require('readline');
const glob = require('glob');

/** @typedef {{result?: {value?: string, objectId?: number}, exceptionDetails?: object}} RuntimeEvaluateResponse */

const OUTPUT_DIR = 'latest-run/devtools-lhrs';

const urlArg = process.argv[2];

/**
* https://source.chromium.org/chromium/chromium/src/+/master:third_party/devtools-frontend/src/front_end/test_runner/TestRunner.js;l=170;drc=f59e6de269f4f50bca824f8ca678d5906c7d3dc8
* @param {Record<string, function>} receiver
* @param {string} methodName
* @param {function} override
*/
function addSniffer(receiver, methodName, override) {
const original = receiver[methodName];
if (typeof original !== 'function') {
throw new Error('Cannot find method to override: ' + methodName);
}

/**
* @param {...any} args
*/
receiver[methodName] = function(...args) {
let result;
try {
result = original.apply(this, args);
} finally {
receiver[methodName] = original;
}
// In case of exception the override won't be called.
try {
Array.prototype.push.call(args, result);
override.apply(this, args);
} catch (e) {
throw new Error('Exception in overriden method \'' + methodName + '\': ' + e);
}
return result;
};
}

const sniffLhr = `
new Promise(resolve => {
(${addSniffer.toString()})(
UI.panels.lighthouse.__proto__,
adamraine marked this conversation as resolved.
Show resolved Hide resolved
'_buildReportUI',
(lhr, artifacts) => resolve(lhr)
);
});
`;

const startLighthouse = `
(() => {
UI.ViewManager.instance().showView('lighthouse');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this working for you locally still? When I run it it seems like this line isn't succeeding (it's stuck on the elements panel)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's working fine for me on the latest Canary, but I was having issues earlier with a custom DT frontend.

Can you try opening DT on DT and running this line manually?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you do const ViewManager = UI.ViewManager.ViewManager || UI.ViewManager; ... so it works in stable and canary?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: The issue here was that CHROME_PATH wasn't set, so puppeteer defaulted to M78 which uses the "Audits" panel instead of the "Lighthouse" panel.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've upgraded our puppeteer dep: #12284

const button = UI.panels.lighthouse.contentElement.querySelector('button');
if (button.disabled) throw new Error('Start button disabled');
button.click();
})()
`;

/**
* @param {import('puppeteer').Browser} browser
* @param {string} url
* @return {Promise<string>}
*/
async function testPage(browser, url) {
const page = await browser.newPage();

const targets = await browser.targets();
const inspectorTarget = targets.filter(t => t.url().includes('devtools'))[1];
if (!inspectorTarget) throw new Error('No inspector found.');

const session = await inspectorTarget.createCDPSession();
await session.send('Runtime.enable');

// Navigate to page and wait for initial HTML to be parsed before trying to start LH.
await new Promise(async resolve => {
const pageSession = await page.target().createCDPSession();
await pageSession.send('Page.enable');
pageSession.once('Page.domContentEventFired', resolve);
page.goto(url).catch(err => err);
});

/** @type {RuntimeEvaluateResponse|undefined} */
let startLHResponse;
while (!startLHResponse || startLHResponse.exceptionDetails) {
startLHResponse = await session.send('Runtime.evaluate', {expression: startLighthouse})
.catch(err => err);
}

/** @type {RuntimeEvaluateResponse} */
const remoteLhrResponse = await session.send('Runtime.evaluate', {
expression: sniffLhr,
awaitPromise: true,
returnByValue: true,
}).catch(err => err);

if (!remoteLhrResponse.result || !remoteLhrResponse.result.value) {
throw new Error('Problem sniffing LHR.');
}

await page.close();

return JSON.stringify(remoteLhrResponse.result.value);
}

/**
* @return {Promise<string[]>}
*/
async function readUrlList() {
if (urlArg) return [urlArg];

/** @type {string[]} */
const urlList = [];
const rl = readline.createInterface(process.stdin, process.stdout);

rl.on('line', async line => {
if (line.startsWith('#')) return;
urlList.push(line);
});

return new Promise(resolve => rl.on('close', () => resolve(urlList)));
}

async function run() {
// Create output directory.
if (fs.existsSync(OUTPUT_DIR)) {
const files = new glob.GlobSync(`${OUTPUT_DIR}/*`).found;
for (const file of files) {
fs.unlinkSync(file);
}
} else {
fs.mkdirSync(OUTPUT_DIR, {recursive: true});
}

const browser = await puppeteer.launch({
executablePath: process.env.CHROME_PATH,
devtools: true,
});

const urlList = await readUrlList();
for (let i = 0; i < urlList.length; ++i) {
const lhr = await testPage(browser, urlList[i]);
fs.writeFileSync(`${OUTPUT_DIR}/lhr-${i}.json`, lhr);
}

await browser.close();
}
run();
87 changes: 0 additions & 87 deletions lighthouse-core/test/chromium-web-tests/test-page-devtools.sh

This file was deleted.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
"update:test-devtools": "bash lighthouse-core/test/chromium-web-tests/test-locally.sh --reset-results",
"test-devtools": "bash lighthouse-core/test/chromium-web-tests/test-locally.sh",
"open-devtools": "bash lighthouse-core/scripts/open-devtools.sh",
"run-devtools": "bash lighthouse-core/test/chromium-web-tests/test-page-devtools.sh",
"run-devtools": "node lighthouse-core/scripts/pptr-run-devtools.js",
adamraine marked this conversation as resolved.
Show resolved Hide resolved
"diff:sample-json": "yarn i18n:checks && bash lighthouse-core/scripts/assert-golden-lhr-unchanged.sh",
"computeBenchmarkIndex": "./lighthouse-core/scripts/benchmark.js",
"minify-latest-run": "./lighthouse-core/scripts/lantern/minify-trace.js ./latest-run/defaultPass.trace.json ./latest-run/defaultPass.trace.min.json && ./lighthouse-core/scripts/lantern/minify-devtoolslog.js ./latest-run/defaultPass.devtoolslog.json ./latest-run/defaultPass.devtoolslog.min.json",
Expand Down