/
cli.test.js
454 lines (382 loc) · 16.1 KB
/
cli.test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* @license Copyright 2019 Google Inc. 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';
/* eslint-env jest */
const fs = require('fs');
const path = require('path');
const {spawn} = require('child_process');
const fetch = require('isomorphic-fetch');
const log = require('lighthouse-logger');
const puppeteer = require('puppeteer');
const {
startServer,
waitForCondition,
getSqlFilePath,
runCLI,
CLI_PATH,
} = require('./test-utils.js');
describe('Lighthouse CI CLI', () => {
const rcFile = path.join(__dirname, 'fixtures/lighthouserc.json');
const rcMatrixFile = path.join(__dirname, 'fixtures/lighthouserc-matrix.json');
const rcExtendedFile = path.join(__dirname, 'fixtures/lighthouserc-extended.json');
const budgetsFile = path.join(__dirname, 'fixtures/budgets.json');
const staticDistDir = path.join(__dirname, 'fixtures');
const tmpSqlFilePath = getSqlFilePath();
let server;
let projectToken;
let urlToCollect;
afterAll(() => {
if (server) {
server.process.kill();
if (fs.existsSync(server.sqlFile)) fs.unlinkSync(server.sqlFile);
}
if (fs.existsSync(tmpSqlFilePath)) fs.unlinkSync(tmpSqlFilePath);
});
describe('server', () => {
it('should bring up the server and accept requests', async () => {
server = await startServer();
urlToCollect = `http://localhost:${server.port}/app/`;
});
it('should accept requests', async () => {
const response = await fetch(`http://localhost:${server.port}/v1/projects`);
const projects = await response.json();
expect(projects).toEqual([]);
});
});
describe('wizard', () => {
const ENTER_KEY = '\x0D';
async function writeAllInputs(wizardProcess, inputs) {
for (const input of inputs) {
wizardProcess.stdin.write(input);
wizardProcess.stdin.write(ENTER_KEY);
// Wait for inquirer to write back our response, that's the signal we can continue.
await waitForCondition(() => wizardProcess.stdoutMemory.includes(input));
// Sometimes it still isn't ready though, give it a bit more time to process.
await new Promise(r => setTimeout(r, process.env.CI ? 500 : 50));
}
wizardProcess.stdin.end();
}
it('should create a new project', async () => {
const wizardProcess = spawn(CLI_PATH, ['wizard']);
wizardProcess.stdoutMemory = '';
wizardProcess.stderrMemory = '';
wizardProcess.stdout.on('data', chunk => (wizardProcess.stdoutMemory += chunk.toString()));
wizardProcess.stderr.on('data', chunk => (wizardProcess.stderrMemory += chunk.toString()));
await waitForCondition(() => wizardProcess.stdoutMemory.includes('Which wizard'));
await writeAllInputs(wizardProcess, [
'', // Just ENTER key to select "new-project"
`http://localhost:${server.port}`, // The base URL to talk to
'AwesomeCIProjectName', // Project name
'https://example.com', // External build URL
]);
expect(wizardProcess.stdoutMemory).toContain('Use token');
expect(wizardProcess.stderrMemory).toEqual('');
const tokenSentence = wizardProcess.stdoutMemory
.match(/Use token [\s\S]+/im)[0]
.replace(log.bold, '')
.replace(log.reset, '');
projectToken = tokenSentence.match(/Use token ([\w-]+)/)[1];
}, 30000);
});
describe('healthcheck', () => {
it('should pass when things are good', async () => {
const LHCI_TOKEN = projectToken;
const LHCI_SERVER_BASE_URL = `http://localhost:${server.port}`;
const {stdout, stderr, status} = runCLI(['healthcheck', `--fatal`], {
env: {LHCI_TOKEN, LHCI_SERVER_BASE_URL},
});
expect(stdout).toMatchInlineSnapshot(`
"✅ .lighthouseci/ directory writable
✅ Ancestor hash determinable
⚠️ GitHub token set
✅ LHCI server reachable
✅ LHCI server token valid
✅ LHCI server unique build for this hash
Healthcheck passed!
"
`);
expect(stderr).toMatchInlineSnapshot(`""`);
expect(status).toEqual(0);
});
it('should fail when things are bad', async () => {
const LHCI_TOKEN = projectToken;
const LHCI_SERVER_BASE_URL = `http://localhost:${server.port}`;
const {stdout, stderr, status} = runCLI(
['healthcheck', `--rc-file=${rcFile}`, `--fatal`, '--checks=githubToken'],
{env: {LHCI_TOKEN, LHCI_SERVER_BASE_URL}}
);
expect(stdout).toMatchInlineSnapshot(`
"✅ .lighthouseci/ directory writable
✅ Ancestor hash determinable
❌ GitHub token set
✅ LHCI server reachable
✅ LHCI server token valid
✅ LHCI server unique build for this hash
Healthcheck failed!
"
`);
expect(stderr).toMatchInlineSnapshot(`""`);
expect(status).toEqual(1);
});
});
describe('collect', () => {
it('should collect results from staticDistDir', () => {
const {stdout, stderr, status} = runCLI([
'collect',
`--rc-file=${rcFile}`,
`--static-dist-dir=${staticDistDir}`,
]);
const stdoutClean = stdout.replace(/:\d{4,6}/g, ':XXXX').replace(/port \d{4,6}/, 'port XXXX');
expect(stdoutClean).toMatchInlineSnapshot(`
"Started a web server on port XXXX...
Running Lighthouse 2 time(s) on http://localhost:XXXX/checkout.html
Run #1...done.
Run #2...done.
Running Lighthouse 2 time(s) on http://localhost:XXXX/index.html
Run #1...done.
Run #2...done.
Done running Lighthouse!
"
`);
expect(stderr.toString()).toMatchInlineSnapshot(`""`);
expect(status).toEqual(0);
}, 90000);
it('should collect results with a server command', () => {
const startCommand = `yarn start server -p=14927 --storage.sqlDatabasePath=${tmpSqlFilePath}`;
const {stdout, stderr, status} = runCLI([
'collect',
`-n=1`,
`--rc-file=${rcFile}`,
`--start-server-command=${startCommand}`,
`--url=http://localhost:14927/app/`,
]);
const stdoutClean = stdout
.replace(/:\d{4,6}/g, ':XXXX')
.replace(/sqlDatabasePath=.*?"/, 'sqlDatabasePath=<file>"');
expect(stdoutClean).toMatchInlineSnapshot(`
"Started a web server with \\"yarn start server -p=14927 --storage.sqlDatabasePath=<file>\\"...
Running Lighthouse 1 time(s) on http://localhost:XXXX/app/
Run #1...done.
Done running Lighthouse!
"
`);
expect(stderr.toString()).toMatchInlineSnapshot(`""`);
expect(status).toEqual(0);
}, 60000);
it('should collect results from explicit urls', () => {
const {stdout, stderr, status} = runCLI([
'collect',
`--rc-file=${rcFile}`,
`--url=${urlToCollect}`,
]);
const stdoutClean = stdout.replace(/:\d{4,6}/g, ':XXXX');
expect(stdoutClean).toMatchInlineSnapshot(`
"Running Lighthouse 2 time(s) on http://localhost:XXXX/app/
Run #1...done.
Run #2...done.
Done running Lighthouse!
"
`);
expect(stderr.toString()).toMatchInlineSnapshot(`""`);
expect(status).toEqual(0);
}, 60000);
});
describe('upload', () => {
let uuids;
it('should read LHRs from folders', () => {
const {stdout, stderr, status} = runCLI(
['upload', `--serverBaseUrl=http://localhost:${server.port}`],
{env: {LHCI_TOKEN: projectToken}}
);
const UUID_REGEX = /[0-9a-f-]{36}/gi;
uuids = stdout.match(UUID_REGEX);
const cleansedStdout = stdout.replace(UUID_REGEX, '<UUID>').replace(/:\d+/g, '<PORT>');
expect(cleansedStdout).toMatchInlineSnapshot(`
"Saving CI project AwesomeCIProjectName (<UUID>)
Saving CI build (<UUID>)
Saved LHR to http://localhost<PORT> (<UUID>)
Saved LHR to http://localhost<PORT> (<UUID>)
Done saving build results to Lighthouse CI
View build diff at http://localhost<PORT>/app/projects/<UUID>/builds/<UUID>
No GitHub token set, skipping.
"
`);
expect(stderr).toMatchInlineSnapshot(`""`);
expect(status).toEqual(0);
expect(uuids).toHaveLength(6);
});
it('should have saved lhrs to the API', async () => {
const [projectId, buildId, runAId, runBId] = uuids;
const response = await fetch(
`http://localhost:${server.port}/v1/projects/${projectId}/builds/${buildId}/runs`
);
const runs = await response.json();
expect(runs.map(run => run.id)).toEqual([runBId, runAId]);
expect(runs.map(run => run.url)).toEqual([
'http://localhost:PORT/app/', // make sure we replaced the port
'http://localhost:PORT/app/',
]);
expect(runs.map(run => JSON.parse(run.lhr))).toMatchObject([
{requestedUrl: urlToCollect},
{requestedUrl: urlToCollect},
]);
});
it('should have sealed the build', async () => {
const [projectId, buildId] = uuids;
const response = await fetch(
`http://localhost:${server.port}/v1/projects/${projectId}/builds/${buildId}`
);
const build = await response.json();
expect(build).toMatchObject({lifecycle: 'sealed'});
});
it('should support target=temporary-public-storage', async () => {
const {stdout, stderr, status} = runCLI(['upload', `--target=temporary-public-storage`]);
expect(stdout).toContain('...success!');
expect(stdout).toContain('Open the report at');
expect(stderr).toEqual(``);
expect(status).toEqual(0);
});
it('should fail repeated attempts', () => {
const {stdout, stderr, status} = runCLI(
['upload', `--serverBaseUrl=http://localhost:${server.port}`],
{env: {LHCI_TOKEN: projectToken}}
);
expect(stdout).toEqual('');
expect(stderr).toContain('Unexpected status code 422');
expect(stderr).toContain('Build already exists for hash');
expect(status).toEqual(1);
});
});
describe('assert', () => {
it('should assert failures', () => {
const {stdout, stderr, status} = runCLI(['assert', `--assertions.works-offline=error`]);
const stderrClean = stderr.replace(/:\d{4,6}/g, ':XXXX');
expect(stdout).toMatchInlineSnapshot(`""`);
expect(stderrClean).toMatchInlineSnapshot(`
"Checking assertions against 1 URL(s), 2 total run(s)
1 result(s) for [1mhttp://localhost:XXXX/app/[0m
[31m✘[0m [1mworks-offline[0m failure for [1mminScore[0m assertion
Current page does not respond with a 200 when offline
Documentation: https://web.dev/works-offline
expected: >=[32m1[0m
found: [31m0[0m
[2mall values: 0, 0[0m
Assertion failed. Exiting with status code 1.
"
`);
expect(status).toEqual(1);
});
it('should assert failures from an rcfile', () => {
const {stdout, stderr, status} = runCLI([
'assert',
`--assertions.first-contentful-paint=off`,
`--assertions.speed-index=off`,
`--assertions.interactive=off`,
`--rc-file=${rcFile}`,
]);
const stderrClean = stderr.replace(/\d{4,8}(\.\d{1,8})?/g, 'XXXX');
expect(stdout).toMatchInlineSnapshot(`""`);
expect(stderrClean).toMatchInlineSnapshot(`
"Checking assertions against 1 URL(s), 2 total run(s)
1 result(s) for [1mhttp://localhost:XXXX/app/[0m
[31m✘[0m [1mperformance-budget[0m.script.size failure for [1mmaxNumericValue[0m assertion
Performance budget
Documentation: https://developers.google.com/web/tools/lighthouse/audits/budgets
expected: <=[32mXXXX[0m
found: [31mXXXX[0m
[2mall values: XXXX[0m
Assertion failed. Exiting with status code 1.
"
`);
expect(status).toEqual(1);
});
it('should assert failures from a matrix rcfile', () => {
const {stdout, stderr, status} = runCLI(['assert', `--rc-file=${rcMatrixFile}`]);
const stderrClean = stderr.replace(/:\d{4,6}/g, ':XXXX');
expect(stdout).toMatchInlineSnapshot(`""`);
expect(stderrClean).toMatchInlineSnapshot(`
"Checking assertions against 1 URL(s), 2 total run(s)
1 result(s) for [1mhttp://localhost:XXXX/app/[0m
[31m✘[0m [1mworks-offline[0m failure for [1mminScore[0m assertion
Current page does not respond with a 200 when offline
Documentation: https://web.dev/works-offline
expected: >=[32m1[0m
found: [31m0[0m
[2mall values: 0, 0[0m
Assertion failed. Exiting with status code 1.
"
`);
expect(status).toEqual(1);
});
it('should assert failures from an extended rcfile', () => {
const {stdout, stderr, status} = runCLI([
'assert',
`--assertions.speed-index=off`,
`--assertions.interactive=off`,
`--rc-file=${rcExtendedFile}`,
]);
const stderrClean = stderr.replace(/\d{4,}(\.\d{1,})?/g, 'XXXX');
expect(stdout).toMatchInlineSnapshot(`""`);
expect(stderrClean).toMatchInlineSnapshot(`
"Checking assertions against 1 URL(s), 2 total run(s)
2 result(s) for [1mhttp://localhost:XXXX/app/[0m
[31m✘[0m [1mfirst-contentful-paint[0m failure for [1mmaxNumericValue[0m assertion
First Contentful Paint
Documentation: https://web.dev/first-contentful-paint
expected: <=[32m1[0m
found: [31mXXXX[0m
[2mall values: XXXX, XXXX[0m
[31m✘[0m [1mperformance-budget[0m.script.size failure for [1mmaxNumericValue[0m assertion
Performance budget
Documentation: https://developers.google.com/web/tools/lighthouse/audits/budgets
expected: <=[32mXXXX[0m
found: [31mXXXX[0m
[2mall values: XXXX[0m
Assertion failed. Exiting with status code 1.
"
`);
expect(status).toEqual(1);
});
it('should assert failures from a budgets file', () => {
const {stdout, stderr, status} = runCLI(['assert', `--budgets-file=${budgetsFile}`]);
const stderrClean = stderr.replace(/\d{4,}(\.\d{1,})?/g, 'XXXX');
expect(stdout).toMatchInlineSnapshot(`""`);
expect(stderrClean).toMatchInlineSnapshot(`
"Checking assertions against 1 URL(s), 2 total run(s)
1 result(s) for [1mhttp://localhost:XXXX/app/[0m
[31m✘[0m [1mresource-summary[0m.script.size failure for [1mmaxNumericValue[0m assertion
Keep request counts low and transfer sizes small
Documentation: https://developers.google.com/web/tools/lighthouse/audits/budgets
expected: <=[32m1[0m
found: [31mXXXX[0m
[2mall values: XXXX, XXXX[0m
Assertion failed. Exiting with status code 1.
"
`);
expect(status).toEqual(1);
});
});
describe('ui', () => {
/** @type {import('puppeteer').Browser} */
let browser;
/** @type {import('puppeteer').Page} */
let page;
beforeAll(async () => {
browser = await puppeteer.launch();
});
afterAll(async () => {
await browser.close();
});
it('should load the page', async () => {
page = await browser.newPage();
await page.goto(`http://localhost:${server.port}/app`, {waitUntil: 'networkidle0'});
});
it('should list the projects', async () => {
const contents = await page.evaluate('document.body.innerHTML');
expect(contents).toContain('AwesomeCIProjectName');
});
});
});