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 7 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
110 changes: 110 additions & 0 deletions lighthouse-core/scripts/pptr-run-devtools.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
'use strict';
adamraine marked this conversation as resolved.
Show resolved Hide resolved

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

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

/**
* 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);
}

receiver[methodName] = function() {
adamraine marked this conversation as resolved.
Show resolved Hide resolved
let result;
try {
// eslint-disable-next-line prefer-rest-params
result = original.apply(this, arguments);
} finally {
receiver[methodName] = original;
}
// In case of exception the override won't be called.
try {
// eslint-disable-next-line prefer-rest-params
Array.prototype.push.call(arguments, result);
// eslint-disable-next-line prefer-rest-params
override.apply(this, arguments);
} 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(JSON.stringify(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

UI.panels.lighthouse.contentElement.querySelector('button').click();
})()
`;

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

// Cut off JS for initial page navigation.
// This step is unnecessary for every page I tried except https://cnn.com.
Copy link
Collaborator

Choose a reason for hiding this comment

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

What happens when you allow JS? This is rather surprising to me.

Copy link
Member Author

Choose a reason for hiding this comment

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

LH never starts because cnn takes too long to load. I believe the page's scripts are hogging the main thread so much that startLighthouse never runs successfully.

Every other page I tested didn't need this step, but disabling JS still decreased the startup time for those pages.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Yikes. I don't love doing this because if we can't run Lighthouse because a page is so busy, it might be indicative of our users not being able to run Lighthouse because a page is too busy.

Finding the "Lighthouse doesn't work in scenario X" is actually the point of creating a DevTools repro script, so perhaps we've already found our first bug :)

Copy link
Member Author

Choose a reason for hiding this comment

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

Good point, I took another look and it turns out I was overthinking the problem. The script just blocks on await page.goto(...) and never gets to the part where it tries to start LH.

Instead of disabling javascript to get the page to load faster, I just took out the await on page.goto(...).

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: Trying to start LH immediately after navigation starts sometimes causes DT to hang on "Lighthouse is warming up..." forever.

Changed this to wait for DOMContentLoaded before trying to start LH.

await page.setJavaScriptEnabled(false);

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

// Enable JS for actual LH test.
await page.setJavaScriptEnabled(true);

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

/** @type {ProtocolResponse|undefined} */
adamraine marked this conversation as resolved.
Show resolved Hide resolved
let startLHResponse;
while (!startLHResponse || startLHResponse.exceptionDetails) {
startLHResponse = await session.send('Runtime.evaluate', {expression: startLighthouse})
.catch(err => err);
if (startLHResponse && !startLHResponse.exceptionDetails) break;
}

/** @type {ProtocolResponse} */
const snifferAddedResponse = await session.send('Runtime.evaluate', {expression: sniffLhr})
.catch(err => err);
if (!snifferAddedResponse.result || !snifferAddedResponse.result.objectId) {
throw new Error('Problem creating LHR sniffer.');
}

/** @type {ProtocolResponse} */
const remoteLhrResponse = await session.send('Runtime.awaitPromise', {
adamraine marked this conversation as resolved.
Show resolved Hide resolved
promiseObjectId: snifferAddedResponse.result.objectId,
}).catch(err => err);
if (!remoteLhrResponse.result || !remoteLhrResponse.result.value) {
throw new Error('Problem sniffing LHR.');
}

fs.writeFileSync('latest-run/lhr.json', remoteLhrResponse.result.value);

await session.send('Runtime.disable');
Copy link
Collaborator

Choose a reason for hiding this comment

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

does this have a particular effect you noticed? fine to leave in, I just wouldn't expect it to do anything if we're shutting down the entire browser immediately after :)

Copy link
Member Author

Choose a reason for hiding this comment

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

No effect that I noticed.

FWIW I plan to update this script to test multiple urls. Script would open a new page for each test and close the page after, but browser remains open the entire time. Do you think this line would have an effect then?

Copy link
Collaborator

Choose a reason for hiding this comment

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

If you're still closing the page I wouldn't expect it to have an effect. I suppose it's slightly more plausible there's some memory leak in Chromium browser process no one has discovered before, but still seems unlikely to affect us.


await page.close();
await browser.close();
}
run();
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