forked from apache/echarts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
309 lines (269 loc) · 9.98 KB
/
cli.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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
const puppeteer = require('puppeteer');
const slugify = require('slugify');
const fse = require('fs-extra');
const fs = require('fs');
const path = require('path');
const program = require('commander');
const compareScreenshot = require('./compareScreenshot');
const {testNameFromFile, fileNameFromTest, getVersionDir, buildRuntimeCode, waitTime, getEChartsTestFileName} = require('./util');
const {origin} = require('./config');
const Timeline = require('./Timeline');
// Handling input arguments.
program
.option('-t, --tests <tests>', 'Tests names list')
.option('--no-headless', 'Not headless')
.option('-s, --speed <speed>', 'Playback speed')
.option('--expected <expected>', 'Expected version')
.option('--actual <actual>', 'Actual version')
.option('--renderer <renderer>', 'svg/canvas renderer')
.option('--no-save', 'Don\'t save result');
program.parse(process.argv);
program.speed = +program.speed || 1;
program.actual = program.actual || 'local';
program.expected = program.expected || '4.2.1';
program.renderer = (program.renderer || 'canvas').toLowerCase();
if (!program.tests) {
throw new Error('Tests are required');
}
function getScreenshotDir() {
return 'tmp/__screenshot__';
}
function sortScreenshots(list) {
return list.sort((a, b) => {
return a.screenshotName.localeCompare(b.screenshotName);
});
}
function getClientRelativePath(absPath) {
return path.join('../', path.relative(__dirname, absPath));
}
function replaceEChartsVersion(interceptedRequest, version) {
// TODO Extensions and maps
if (interceptedRequest.url().endsWith('dist/echarts.js')) {
console.log('Use echarts version: ' + version);
interceptedRequest.continue({
url: `${origin}/test/runTest/${getVersionDir(version)}/${getEChartsTestFileName()}`
});
}
else {
interceptedRequest.continue();
}
}
async function takeScreenshot(page, fullPage, fileUrl, desc, isExpected, minor) {
let screenshotName = testNameFromFile(fileUrl);
if (desc) {
screenshotName += '-' + slugify(desc, { replacement: '-', lower: true });
}
if (minor) {
screenshotName += '-' + minor;
}
let screenshotPrefix = isExpected ? 'expected' : 'actual';
fse.ensureDirSync(path.join(__dirname, getScreenshotDir()));
let screenshotPath = path.join(__dirname, `${getScreenshotDir()}/${screenshotName}-${screenshotPrefix}.png`);
await page.screenshot({
path: screenshotPath,
fullPage
});
return {screenshotName, screenshotPath};
}
async function runActions(page, testOpt, isExpected, screenshots) {
let timeline = new Timeline(page);
let actions;
try {
let actContent = fs.readFileSync(path.join(__dirname, 'actions', testOpt.name + '.json'));
actions = JSON.parse(actContent);
}
catch (e) {
// Can't find actions
return;
}
let playbackSpeed = +program.speed;
for (let action of actions) {
await page.evaluate((x, y) => {
window.scrollTo(x, y);
}, action.scrollX, action.scrollY);
let count = 0;
async function _innerTakeScreenshot() {
if (!program.save) {
return;
}
const desc = action.desc || action.name;
const {screenshotName, screenshotPath} = await takeScreenshot(page, false, testOpt.fileUrl, desc, isExpected, count++);
screenshots.push({screenshotName, desc, screenshotPath});
}
await timeline.runAction(action, _innerTakeScreenshot, playbackSpeed);
if (count === 0) {
await waitTime(200);
await _innerTakeScreenshot();
}
// const desc = action.desc || action.name;
// const {screenshotName, screenshotPath} = await takeScreenshot(page, false, testOpt.fileUrl, desc, version);
// screenshots.push({screenshotName, desc, screenshotPath});
}
timeline.stop();
}
async function runTestPage(browser, testOpt, version, runtimeCode, isExpected) {
const fileUrl = testOpt.fileUrl;
const screenshots = [];
const logs = [];
const errors = [];
const page = await browser.newPage();
page.setRequestInterception(true);
page.on('request', request => replaceEChartsVersion(request, version));
await page.evaluateOnNewDocument(runtimeCode);
page.on('console', msg => {
logs.push(msg.text());
});
page.on('pageerror', error => {
errors.push(error.toString());
});
page.on('dialog', async dialog => {
await dialog.dismiss();
});
try {
await page.setViewport({width: 800, height: 600});
await page.goto(`${origin}/test/${fileUrl}?__RENDERER__=${program.renderer}`, {
waitUntil: 'networkidle2',
timeout: 10000
});
await waitTime(500); // Wait for animation or something else. Pending
// Final shot.
await page.mouse.move(0, 0);
if (program.save) {
let desc = 'Full Shot';
const {screenshotName, screenshotPath} = await takeScreenshot(page, true, fileUrl, desc, isExpected);
screenshots.push({screenshotName, desc, screenshotPath});
}
await runActions(page, testOpt, isExpected, screenshots);
}
catch(e) {
console.error(e);
}
await page.close();
return {
logs,
errors,
screenshots: screenshots
};
}
async function writePNG(diffPNG, diffPath) {
return new Promise(resolve => {
let writer = fs.createWriteStream(diffPath);
diffPNG.pack().pipe(writer);
writer.on('finish', () => {resolve();});
});
};
async function runTest(browser, testOpt, runtimeCode, expectedVersion, actualVersion) {
if (program.renderer === 'svg' && testOpt.ignoreSVG) {
console.log(testOpt.name + ' don\'t support svg testing.');
return;
}
if (program.save) {
testOpt.status === 'running';
const expectedResult = await runTestPage(browser, testOpt, expectedVersion, runtimeCode, true);
const actualResult = await runTestPage(browser, testOpt, actualVersion, runtimeCode, false);
// sortScreenshots(expectedResult.screenshots);
// sortScreenshots(actualResult.screenshots);
const screenshots = [];
let idx = 0;
for (let shot of expectedResult.screenshots) {
let expected = shot;
let actual = actualResult.screenshots[idx++];
let result = {
actual: getClientRelativePath(actual.screenshotPath),
expected: getClientRelativePath(expected.screenshotPath),
name: actual.screenshotName,
desc: actual.desc
};
try {
let {diffRatio, diffPNG} = await compareScreenshot(
expected.screenshotPath,
actual.screenshotPath
);
let diffPath = `${path.resolve(__dirname, getScreenshotDir())}/${shot.screenshotName}-diff.png`;
await writePNG(diffPNG, diffPath);
result.diff = getClientRelativePath(diffPath);
result.diffRatio = diffRatio;
}
catch(e) {
result.diff = '';
result.diffRatio = 1;
console.log(e);
}
screenshots.push(result);
}
testOpt.results = screenshots;
testOpt.status = 'finished';
testOpt.actualLogs = actualResult.logs;
testOpt.expectedLogs = expectedResult.logs;
testOpt.actualErrors = actualResult.errors;
testOpt.expectedErrors = expectedResult.errors;
testOpt.actualVersion = actualVersion;
testOpt.expectedVersion = expectedVersion;
testOpt.useSVG = program.renderer === 'svg';
testOpt.lastRun = Date.now();
}
else {
// Only run once
await runTestPage(browser, testOpt, 'local', runtimeCode, true);
}
}
async function runTests(pendingTests) {
const browser = await puppeteer.launch({
headless: program.headless,
args: [`--window-size=830,750`] // new option
});
// TODO Not hardcoded.
// let runtimeCode = fs.readFileSync(path.join(__dirname, 'tmp/testRuntime.js'), 'utf-8');
let runtimeCode = await buildRuntimeCode();
runtimeCode = `window.__TEST_PLAYBACK_SPEED__ = ${program.speed || 1};\n${runtimeCode}`;
try {
for (let testOpt of pendingTests) {
console.log(`Running test: ${testOpt.name}, renderer: ${program.renderer}`);
try {
await runTest(browser, testOpt, runtimeCode, program.expected, program.actual);
}
catch (e) {
// Restore status
testOpt.status = 'unsettled';
console.log(e);
}
if (program.save) {
process.send(testOpt);
}
}
}
catch(e) {
console.log(e);
}
await browser.close();
}
runTests(program.tests.split(',').map(testName => {
return {
fileUrl: fileNameFromTest(testName),
name: testName,
results: [],
actualLogs: [],
expectedLogs: [],
actualErrors: [],
expectedErrors: [],
status: 'pending'
};
}));