Skip to content

Commit 69e0d79

Browse files
authored
tests(smokehouse): convert to ES modules (#13046)
1 parent 298ec1a commit 69e0d79

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+384
-244
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"type": "module",
3+
"//": "Any directory that uses `import ... from` or `export ...` must be type module. Temporary file until root package.json is type: module"
4+
}

lighthouse-cli/test/static-server-test.js renamed to lighthouse-cli/test/fixtures/static-server-test.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
*/
66
'use strict';
77

8-
const fs = require('fs');
9-
const fetch = require('node-fetch');
10-
const {server} = require('./fixtures/static-server.js');
8+
import fs from 'fs';
9+
10+
import fetch from 'node-fetch';
11+
12+
import {server} from './static-server.js';
1113

1214
/* eslint-env jest */
1315

@@ -27,7 +29,7 @@ describe('Server', () => {
2729
it('fetches fixture', async () => {
2830
const res = await fetch(`http://localhost:${server.getPort()}/dobetterweb/dbw_tester.html`);
2931
const data = await res.text();
30-
const expected = fs.readFileSync(`${__dirname}/fixtures/dobetterweb/dbw_tester.html`, 'utf-8');
32+
const expected = fs.readFileSync(`${server.baseDir}/dobetterweb/dbw_tester.html`, 'utf-8');
3133
expect(data).toEqual(expected);
3234
});
3335

lighthouse-cli/test/fixtures/static-server.js

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,24 @@
88

99
/* eslint-disable no-console */
1010

11-
const http = require('http');
12-
const zlib = require('zlib');
13-
const path = require('path');
14-
const fs = require('fs');
15-
const glob = require('glob');
16-
const mime = require('mime-types');
17-
const parseQueryString = require('querystring').parse;
18-
const parseURL = require('url').parse;
19-
const URLSearchParams = require('url').URLSearchParams;
20-
const {LH_ROOT} = require('../../../root.js');
11+
import http from 'http';
12+
import zlib from 'zlib';
13+
import path from 'path';
14+
import fs from 'fs';
15+
import {parse as parseQueryString} from 'querystring';
16+
import {parse as parseURL} from 'url';
17+
import {URLSearchParams} from 'url';
18+
19+
import mime from 'mime-types';
20+
import glob from 'glob';
21+
import esMain from 'es-main';
22+
23+
import {LH_ROOT} from '../../../root.js';
2124

2225
const HEADER_SAFELIST = new Set(['x-robots-tag', 'link', 'content-security-policy']);
2326

2427
class Server {
25-
baseDir = __dirname;
28+
baseDir = `${LH_ROOT}/lighthouse-cli/test/fixtures`;
2629

2730
constructor() {
2831
this._server = http.createServer(this._requestHandler.bind(this));
@@ -172,7 +175,7 @@ class Server {
172175

173176
// Create an index page that lists the available test pages.
174177
if (filePath === '/') {
175-
const fixturePaths = glob.sync('**/*.html', {cwd: __dirname});
178+
const fixturePaths = glob.sync('**/*.html', {cwd: this.baseDir});
176179
const html = `
177180
<html>
178181
<h1>Smoke test fixtures</h1>
@@ -187,7 +190,7 @@ class Server {
187190

188191
if (filePath.startsWith('/dist/gh-pages')) {
189192
// Rewrite lighthouse-viewer paths to point to that location.
190-
absoluteFilePath = path.join(__dirname, '/../../../', filePath);
193+
absoluteFilePath = path.join(this.baseDir, '/../../../', filePath);
191194
}
192195

193196
// Disallow file requests outside of LH folder
@@ -244,18 +247,18 @@ serverForOnline._server.on('error', e => console.error(e.code, e));
244247
serverForOffline._server.on('error', e => console.error(e.code, e));
245248

246249
// If called via `node static-server.js` then start listening, otherwise, just expose the servers
247-
if (require.main === module) {
250+
if (esMain(import.meta)) {
248251
// Start listening
249252
const onlinePort = 10200;
250253
const offlinePort = 10503;
251254
serverForOnline.listen(onlinePort, 'localhost');
252255
serverForOffline.listen(offlinePort, 'localhost');
253256
console.log(`online: listening on http://localhost:${onlinePort}`);
254257
console.log(`offline: listening on http://localhost:${offlinePort}`);
255-
} else {
256-
module.exports = {
257-
Server,
258-
server: serverForOnline,
259-
serverForOffline,
260-
};
261258
}
259+
260+
export {
261+
Server,
262+
serverForOnline as server,
263+
serverForOffline
264+
};

lighthouse-cli/test/smokehouse/frontends/back-compat-util.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,6 @@ function updateTestDefnFormat(allTestDefns) {
3737
return expandedTestDefns.flat();
3838
}
3939

40-
module.exports = {
41-
updateTestDefnFormat,
40+
export {
41+
updateTestDefnFormat
4242
};

lighthouse-cli/test/smokehouse/frontends/lib.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@
1313

1414
/* eslint-disable no-console */
1515

16-
const cloneDeep = require('lodash.clonedeep');
17-
const smokeTests = require('../test-definitions/core-tests.js');
18-
const {runSmokehouse} = require('../smokehouse.js');
16+
import cloneDeep from 'lodash.clonedeep';
17+
18+
import smokeTests from '../test-definitions/core-tests.js';
19+
import {runSmokehouse} from '../smokehouse.js';
1920

2021
/**
2122
* @param {Smokehouse.SmokehouseLibOptions} options
@@ -43,4 +44,4 @@ async function smokehouse(options) {
4344
return runSmokehouse(modifiedTests, smokehouseOptions);
4445
}
4546

46-
module.exports = smokehouse;
47+
export {smokehouse};

lighthouse-cli/test/smokehouse/frontends/node.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@
1010
*/
1111

1212
// Smokehouse is runnable from within node, so just a no-op for now.
13-
module.exports = require('../smokehouse.js');
13+
export * from '../smokehouse.js';

lighthouse-cli/test/smokehouse/frontends/smokehouse-bin.js

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,18 @@
1313

1414
/* eslint-disable no-console */
1515

16-
const fs = require('fs');
17-
const path = require('path');
18-
const cloneDeep = require('lodash.clonedeep');
19-
const yargs = require('yargs');
20-
const log = require('lighthouse-logger');
21-
const {runSmokehouse} = require('../smokehouse.js');
22-
const {updateTestDefnFormat} = require('./back-compat-util.js');
23-
const {LH_ROOT} = require('../../../../root.js');
16+
import path from 'path';
17+
import fs from 'fs';
18+
import url from 'url';
19+
20+
import cloneDeep from 'lodash.clonedeep';
21+
import yargs from 'yargs';
22+
import * as yargsHelpers from 'yargs/helpers';
23+
import log from 'lighthouse-logger';
24+
25+
import {runSmokehouse} from '../smokehouse.js';
26+
import {updateTestDefnFormat} from './back-compat-util.js';
27+
import {LH_ROOT} from '../../../../root.js';
2428

2529
const coreTestDefnsPath =
2630
path.join(LH_ROOT, 'lighthouse-cli/test/smokehouse/test-definitions/core-tests.js');
@@ -115,7 +119,8 @@ function pruneExpectedNetworkRequests(testDefns, takeNetworkRequestUrls) {
115119
* CLI entry point.
116120
*/
117121
async function begin() {
118-
const rawArgv = yargs
122+
const y = yargs(yargsHelpers.hideBin(process.argv));
123+
const rawArgv = y
119124
.help('help')
120125
.usage('node $0 [<options>] <test-ids>')
121126
.example('node $0 -j=1 pwa seo', 'run pwa and seo tests serially')
@@ -159,7 +164,7 @@ async function begin() {
159164
describe: 'Run all available tests except the ones provided',
160165
},
161166
})
162-
.wrap(yargs.terminalWidth())
167+
.wrap(y.terminalWidth())
163168
.argv;
164169

165170
// Augmenting yargs type with auto-camelCasing breaks in [email protected] and @types/[email protected],
@@ -173,13 +178,13 @@ async function begin() {
173178
if (argv.runner === 'bundle') {
174179
console.log('\n✨ Be sure to have recently run this: yarn build-all');
175180
}
176-
const lighthouseRunner = require(runnerPath).runLighthouse;
181+
const {runLighthouse} = await import(runnerPath);
177182

178183
// Find test definition file and filter by requestedTestIds.
179184
let testDefnPath = argv.testsPath || coreTestDefnsPath;
180185
testDefnPath = path.resolve(process.cwd(), testDefnPath);
181186
const requestedTestIds = argv._;
182-
const rawTestDefns = require(testDefnPath);
187+
const {default: rawTestDefns} = await import(url.pathToFileURL(testDefnPath).href);
183188
const allTestDefns = updateTestDefnFormat(rawTestDefns);
184189
const invertMatch = argv.invertMatch;
185190
const testDefns = getDefinitionsToRun(allTestDefns, requestedTestIds, {invertMatch});
@@ -192,7 +197,7 @@ async function begin() {
192197
try {
193198
// If running the core tests, spin up the test server.
194199
if (testDefnPath === coreTestDefnsPath) {
195-
({server, serverForOffline} = require('../../fixtures/static-server.js'));
200+
({server, serverForOffline} = await import('../../fixtures/static-server.js'));
196201
server.listen(10200, 'localhost');
197202
serverForOffline.listen(10503, 'localhost');
198203
takeNetworkRequestUrls = server.takeRequestUrls.bind(server);
@@ -204,7 +209,7 @@ async function begin() {
204209
retries,
205210
isDebug: argv.debug,
206211
useFraggleRock: argv.fraggleRock,
207-
lighthouseRunner,
212+
lighthouseRunner: runLighthouse,
208213
takeNetworkRequestUrls,
209214
};
210215

lighthouse-cli/test/smokehouse/lib/child-process-error.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,4 @@ class ChildProcessError extends Error {
2323
}
2424
}
2525

26-
module.exports = ChildProcessError;
26+
export {ChildProcessError};

lighthouse-cli/test/smokehouse/lib/concurrent-mapper.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,4 +123,4 @@ class ConcurrentMapper {
123123
}
124124
}
125125

126-
module.exports = ConcurrentMapper;
126+
export {ConcurrentMapper};

lighthouse-cli/test/smokehouse/lib/local-console.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,4 @@ class LocalConsole {
4848
}
4949
}
5050

51-
module.exports = LocalConsole;
51+
export {LocalConsole};

lighthouse-cli/test/smokehouse/lighthouse-runners/bundle.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111
* Currently uses `lighthouse-dt-bundle.js`.
1212
*/
1313

14-
const ChromeLauncher = require('chrome-launcher');
15-
const ChromeProtocol = require('../../../../lighthouse-core/gather/connections/cri.js');
14+
import ChromeLauncher from 'chrome-launcher';
15+
16+
import ChromeProtocol from '../../../../lighthouse-core/gather/connections/cri.js';
1617

1718
const originalRequire = global.require;
1819
if (typeof globalThis === 'undefined') {
@@ -22,7 +23,7 @@ if (typeof globalThis === 'undefined') {
2223

2324
// Load bundle, which creates a `global.runBundledLighthouse`.
2425
// @ts-ignore - file exists if `yarn build-all` is run, but not used for types anyways.
25-
require('../../../../dist/lighthouse-dt-bundle.js'); // eslint-disable-line
26+
import '../../../../dist/lighthouse-dt-bundle.js'; // eslint-disable-line
2627

2728
global.require = originalRequire;
2829

@@ -60,6 +61,6 @@ async function runLighthouse(url, configJson, testRunnerOptions = {}) {
6061
}
6162
}
6263

63-
module.exports = {
64-
runLighthouse,
64+
export {
65+
runLighthouse
6566
};

lighthouse-cli/test/smokehouse/lighthouse-runners/cli.js

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,18 @@
1212
* them.
1313
*/
1414

15-
const fs = require('fs').promises;
16-
const {promisify} = require('util');
17-
const execFileAsync = promisify(require('child_process').execFile);
15+
import {promises as fs} from 'fs';
16+
import {promisify} from 'util';
17+
import {execFile} from 'child_process';
1818

19-
const log = require('lighthouse-logger');
19+
import log from 'lighthouse-logger';
2020

21-
const assetSaver = require('../../../../lighthouse-core/lib/asset-saver.js');
22-
const LocalConsole = require('../lib/local-console.js');
23-
const ChildProcessError = require('../lib/child-process-error.js');
24-
const {LH_ROOT} = require('../../../../root.js');
21+
import assetSaver from '../../../../lighthouse-core/lib/asset-saver.js';
22+
import {LocalConsole} from '../lib/local-console.js';
23+
import {ChildProcessError} from '../lib/child-process-error.js';
24+
import {LH_ROOT} from '../../../../root.js';
25+
26+
const execFileAsync = promisify(execFile);
2527

2628
/**
2729
* Launch Chrome and do a full Lighthouse run via the Lighthouse CLI.
@@ -70,7 +72,7 @@ async function internalRun(url, tmpPath, configJson, options) {
7072
const artifactsDirectory = `${tmpPath}/artifacts/`;
7173

7274
const args = [
73-
`${__dirname}/../../../index.js`, // 'lighthouse-cli/index.js'
75+
`${LH_ROOT}/lighthouse-cli/index.js`,
7476
`${url}`,
7577
`--output-path=${outputPath}`,
7678
'--output=json',
@@ -143,6 +145,6 @@ async function internalRun(url, tmpPath, configJson, options) {
143145
};
144146
}
145147

146-
module.exports = {
147-
runLighthouse,
148+
export {
149+
runLighthouse
148150
};
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"type": "module",
3+
"//": "Any directory that uses `import ... from` or `export ...` must be type module. Temporary file until root package.json is type: module"
4+
}

lighthouse-cli/test/smokehouse/report-assert.js

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,10 @@
1010
* against the results actually collected from Lighthouse.
1111
*/
1212

13-
const cloneDeep = require('lodash.clonedeep');
14-
const log = require('lighthouse-logger');
15-
const LocalConsole = require('./lib/local-console.js');
13+
import cloneDeep from 'lodash.clonedeep';
14+
import log from 'lighthouse-logger';
1615

17-
const NUMBER_REGEXP = /(?:\d|\.)+/.source;
18-
const OPS_REGEXP = /<=?|>=?|\+\/-|±/.source;
19-
// An optional number, optional whitespace, an operator, optional whitespace, a number.
20-
const NUMERICAL_EXPECTATION_REGEXP =
21-
new RegExp(`^(${NUMBER_REGEXP})?\\s*(${OPS_REGEXP})\\s*(${NUMBER_REGEXP})$`);
16+
import {LocalConsole} from './lib/local-console.js';
2217

2318
/**
2419
* @typedef Difference
@@ -36,6 +31,12 @@ const NUMERICAL_EXPECTATION_REGEXP =
3631
* @property {Difference|null} [diff]
3732
*/
3833

34+
const NUMBER_REGEXP = /(?:\d|\.)+/.source;
35+
const OPS_REGEXP = /<=?|>=?|\+\/-|±/.source;
36+
// An optional number, optional whitespace, an operator, optional whitespace, a number.
37+
const NUMERICAL_EXPECTATION_REGEXP =
38+
new RegExp(`^(${NUMBER_REGEXP})?\\s*(${OPS_REGEXP})\\s*(${NUMBER_REGEXP})$`);
39+
3940
/**
4041
* Checks if the actual value matches the expectation. Does not recursively search. This supports
4142
* - Greater than/less than operators, e.g. "<100", ">90"
@@ -370,7 +371,7 @@ function reportAssertion(localConsole, assertion) {
370371
* @param {{isDebug?: boolean, isBundled?: boolean}=} reportOptions
371372
* @return {{passed: number, failed: number, log: string}}
372373
*/
373-
function report(actual, expected, reportOptions = {}) {
374+
function getAssertionReport(actual, expected, reportOptions = {}) {
374375
const localConsole = new LocalConsole();
375376

376377
expected = pruneExpectations(localConsole, actual.lhr, expected, reportOptions);
@@ -398,4 +399,4 @@ function report(actual, expected, reportOptions = {}) {
398399
};
399400
}
400401

401-
module.exports = report;
402+
export {getAssertionReport};

0 commit comments

Comments
 (0)