refactor(docs-infra): slightly improve log output of `test-pwa-score` (#31414)

This commit slightly improves the log outout of the `test-pwa-score`
script (e.g. by showing the total duration, indenting messages to group
them together, etc.). It, also, includes various minor refactorings.

These changes are in preparation of augmenting the script to support
checking the scores on all available categories (such as a11y,
performance, seo, etc.) in a subsequent commit.

PR Close #31414
This commit is contained in:
George Kalpakas 2019-07-04 00:05:43 +03:00 committed by Matias Niemelä
parent 8b7a4d7550
commit 3d9ba19ff8
1 changed files with 36 additions and 29 deletions

View File

@ -1,4 +1,5 @@
#!/bin/env node #!/bin/env node
'use strict';
/** /**
* Usage: * Usage:
@ -9,7 +10,7 @@
* Fails if the score is below `<min-score>`. * Fails if the score is below `<min-score>`.
* If `<log-file>` is defined, the full results will be logged there. * If `<log-file>` is defined, the full results will be logged there.
* *
* (Skips HTTPS-related audits, when run for HTTP URL.) * (Skips HTTPS-related audits, when run for an HTTP URL.)
*/ */
// Imports // Imports
@ -20,16 +21,11 @@ const logger = require('lighthouse-logger');
// Constants // Constants
const CHROME_LAUNCH_OPTS = {chromeFlags: ['--headless']}; const CHROME_LAUNCH_OPTS = {chromeFlags: ['--headless']};
const LIGHTHOUSE_FLAGS = {logLevel: 'info'}; const LIGHTHOUSE_FLAGS = {logLevel: process.env.CI ? 'error' : 'info'}; // Be less verbose on CI.
const SKIPPED_HTTPS_AUDITS = ['redirects-http', 'uses-http2']; const SKIPPED_HTTPS_AUDITS = ['redirects-http', 'uses-http2'];
const VIEWER_URL = 'https://googlechrome.github.io/lighthouse/viewer/'; const VIEWER_URL = 'https://googlechrome.github.io/lighthouse/viewer';
const WAIT_FOR_SW_DELAY = 5000; const WAIT_FOR_SW_DELAY = 5000;
// Be less verbose on CI.
if (process.env.CI) {
LIGHTHOUSE_FLAGS.logLevel = 'error';
}
// Run // Run
_main(process.argv.slice(2)); _main(process.argv.slice(2));
@ -42,7 +38,7 @@ async function _main(args) {
// Since the Angular ServiceWorker waits for the app to stabilize before registering, // Since the Angular ServiceWorker waits for the app to stabilize before registering,
// wait a few seconds after load to allow Lighthouse to reliably detect it. // wait a few seconds after load to allow Lighthouse to reliably detect it.
passes: [{passName: 'defaultPass', pauseAfterLoadMs: WAIT_FOR_SW_DELAY}], passes: [{passName: 'defaultPass', pauseAfterLoadMs: WAIT_FOR_SW_DELAY}],
} };
console.log(`Running PWA audit for '${url}'...`); console.log(`Running PWA audit for '${url}'...`);
@ -53,9 +49,12 @@ async function _main(args) {
logger.setLevel(LIGHTHOUSE_FLAGS.logLevel); logger.setLevel(LIGHTHOUSE_FLAGS.logLevel);
try { try {
console.log('');
const startTime = Date.now();
const results = await launchChromeAndRunLighthouse(url, LIGHTHOUSE_FLAGS, config); const results = await launchChromeAndRunLighthouse(url, LIGHTHOUSE_FLAGS, config);
const score = await processResults(results, logFile); const score = await processResults(results, logFile);
evaluateScore(minScore, score); evaluateScore(minScore, score);
console.log(`\n(Completed in ${((Date.now() - startTime) / 1000).toFixed(1)}s.)\n`);
} catch (err) { } catch (err) {
onError(err); onError(err);
} }
@ -63,14 +62,18 @@ async function _main(args) {
function evaluateScore(expectedScore, actualScore) { function evaluateScore(expectedScore, actualScore) {
console.log('\nLighthouse PWA score:'); console.log('\nLighthouse PWA score:');
console.log(` - Expected: ${expectedScore.toFixed(0).padStart(3)} / 100 (or higher)`); console.log(` - Expected: ${formatScore(expectedScore)} (or higher)`);
console.log(` - Actual: ${actualScore.toFixed(0).padStart(3)} / 100\n`); console.log(` - Actual: ${formatScore(actualScore)}`);
if (isNaN(actualScore) || (actualScore < expectedScore)) { if (isNaN(actualScore) || (actualScore < expectedScore)) {
throw new Error(`PWA score is too low. (${actualScore} < ${expectedScore})`); throw new Error(`PWA score is too low. (${actualScore} < ${expectedScore})`);
} }
} }
function formatScore(score) {
return `${(score * 100).toFixed(0).padStart(3)}`;
}
async function launchChromeAndRunLighthouse(url, flags, config) { async function launchChromeAndRunLighthouse(url, flags, config) {
const chrome = await chromeLauncher.launch(CHROME_LAUNCH_OPTS); const chrome = await chromeLauncher.launch(CHROME_LAUNCH_OPTS);
flags.port = chrome.port; flags.port = chrome.port;
@ -84,18 +87,24 @@ async function launchChromeAndRunLighthouse(url, flags, config) {
function onError(err) { function onError(err) {
console.error(err); console.error(err);
console.error('');
process.exit(1); process.exit(1);
} }
function parseInput(args) { function parseInput(args) {
const url = args[0]; const [url, minScoreRaw, logFile] = args;
const minScore = Number(args[1]);
const logFile = args[2];
if (!url) { if (!url) {
onError('Invalid arguments: <URL> not specified.'); onError('Invalid arguments: <url> not specified.');
} else if (isNaN(minScore)) { } else if (!minScoreRaw) {
onError('Invalid arguments: <MIN_SCORE> not specified or not a number.'); onError('Invalid arguments: <min-score> not specified.');
}
const minScore = Number(minScoreRaw) / 100;
const isValid = (0 <= minScore) && (minScore <= 1);
if (!isValid) {
onError(`Invalid arguments: <min-score> has non-numeric or out-of-range values: ${minScoreRaw}`);
} }
return {url, minScore, logFile}; return {url, minScore, logFile};
@ -108,28 +117,26 @@ async function processResults(results, logFile) {
if (logFile) { if (logFile) {
console.log(`\nSaving results in '${logFile}'...`); console.log(`\nSaving results in '${logFile}'...`);
console.log(`(LightHouse viewer: ${VIEWER_URL})`); console.log(` LightHouse viewer: ${VIEWER_URL}`);
await printer.write(report, printer.OutputMode.json, logFile); await printer.write(report, printer.OutputMode.json, logFile);
} }
const categoryData = Object.keys(categories).map(name => categories[name]);
const maxTitleLen = Math.max(...categoryData.map(({title}) => title.length));
console.log(`\nLighthouse version: ${lhVersion}`); console.log(`\nLighthouse version: ${lhVersion}`);
console.log('\nAudit scores:'); console.log('\nAudit scores:');
categoryData.forEach(({title, score}) => {
const maxTitleLen = Math.max(...Object.values(categories).map(({title}) => title.length));
Object.keys(categories).sort().forEach(cat => {
const {title, score} = categories[cat];
const paddedTitle = `${title}:`.padEnd(maxTitleLen + 1); const paddedTitle = `${title}:`.padEnd(maxTitleLen + 1);
const paddedScore = (score * 100).toFixed(0).padStart(3);
console.log(` - ${paddedTitle} ${paddedScore} / 100`); console.log(` - ${paddedTitle} ${formatScore(score)}`);
}); });
return categories.pwa.score * 100; return categories.pwa.score;
} }
function skipHttpsAudits(config) { function skipHttpsAudits(config) {
console.info(`Skipping HTTPS-related audits (${SKIPPED_HTTPS_AUDITS.join(', ')})...`); console.log(` Skipping HTTPS-related audits: ${SKIPPED_HTTPS_AUDITS.join(', ')}`);
const settings = config.settings || (config.settings = {}); config.settings = {...config.settings, skipAudits: SKIPPED_HTTPS_AUDITS};
settings.skipAudits = SKIPPED_HTTPS_AUDITS;
} }