forked from Cropster/ember-visual-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
403 lines (335 loc) · 10.4 KB
/
index.js
File metadata and controls
403 lines (335 loc) · 10.4 KB
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
'use strict';
const path = require('path');
const fs = require('fs-extra');
const pixelmatch = require('pixelmatch');
const puppeteer = require('puppeteer');
const os = require('os');
/* eslint-disable node/no-extraneous-require */
const bodyParser = require('body-parser');
const { PNG } = require('pngjs');
/* eslint-enable node/no-extraneous-require */
module.exports = {
name: require('./package').name,
visualTest: {
imageDirectory: 'visual-test-output/baseline',
imageDiffDirectory: 'visual-test-output/diff',
imageTmpDirectory: 'visual-test-output/tmp',
imageMatchAllowedFailures: 2,
imageMatchThreshold: 0.3,
imageLogging: true,
debugLogging: true,
includeAA: true,
groupByOs: true,
chromePort: 9222,
windowWidth: 1440,
windowHeight: 900,
os: 'Linux',
chromeFlags: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-gpu',
'--headless',
'--disable-dev-shm-usage',
'--disable-software-rasterizer',
'--mute-audio',
'--remote-debugging-port=0',
'--window-size=1440,900',
].filter(Boolean),
},
included(/* app */) {
this._super.included.apply(this, arguments);
this._ensureThisImport();
this._debugLog('Setting up ember-visual-test...');
let osType = os.type().toLowerCase();
switch (osType) {
case 'windows_nt':
osType = 'win';
break;
case 'darwin':
osType = 'mac';
break;
}
this.visualTest.os = osType;
this.import('vendor/visual-test.css', {
type: 'test',
});
},
async _getBrowser({ windowWidth, windowHeight }) {
if (this.browser) {
return this.browser;
}
// ensure only strings are used as flags
const flags = this.visualTest.chromeFlags.filter(flag =>
typeof flag === 'string' && flag
);
log(`Options are: ${JSON.stringify(this.visualTest, null, 2)}`)
log('Launching Chrome with the flags: ', JSON.stringify(flags, null, 2));
const width = windowWidth || this.visualTest.windowWidth;
const height = windowHeight || this.visualTest.windowHeight;
// This is started while the app is building, so we can assume this will be ready
this._debugLog(`Browser: launching, size: height - ${height}, width: ${width}`);
this.browser = await puppeteer.launch({
headless: true,
dumpio: true,
ignoreHTTPSErrors: true,
defaultViewport: {
width,
height,
},
args: flags,
userDataDir: null,
});
this._debugLog(`Chrome instance initialized`);
return this.browser;
},
async _getBrowserPage({ windowWidth, windowHeight }) {
const width = Number(windowWidth) || this.visualTest.windowWidth;
const height = Number(windowHeight) || this.visualTest.windowHeight;
const browser = await this._getBrowser({ windowWidth: width, windowHeight: height });
const page = await browser.newPage();
page.setViewport({ height, width });
page.setDefaultTimeout(60 * 1000);
page.once('load', () => {
this._debugLog('Page: loaded');
});
page.on('console', message =>
this._debugLog(`Browser log: ${message.type().substr(0, 3).toUpperCase()} ${message.text()}`)
).on('pageerror', ({ message }) =>
this._debugLog(`Browser pageerror: ${message}`)
).on('response', response =>
this._debugLog(`Browser response: ${response.status()} ${response.url()}`)
).on('requestfailed', request =>
this._debugLog(`Browser requestfailed: ${request.failure().errorText} ${request.url()}`)
);
this._debugLog('Page: returned');
return page;
},
_imageLog(str) {
if (this.visualTest.imageLogging) {
log(str);
}
},
_debugLog(str) {
if (this.visualTest.debugLogging) {
log(str);
}
},
async _makeScreenshots(
url,
fileName,
{ fullPage, delayMs, windowWidth, windowHeight }
) {
let page;
try {
page = await this._getBrowserPage({ windowWidth, windowHeight });
} catch (e) {
logError('Error: launching browser!');
logError(e);
return { newBaseline: false, chromeError: true };
}
try {
await page.goto(url);
} catch (e) {
logError('Error: opening or resizing page');
logError(e);
}
// This is inserted into the DOM by the capture helper when everything is ready
await page.waitForSelector('#visual-test-has-loaded');
this._debugLog('Page: selector exist');
const fullPath = `${path.join(this.visualTest.imageDirectory, fileName)}.png`;
const screenshotOptions = {
fullPage,
type: 'png',
};
// To avoid problems...
await page.waitFor(delayMs);
this._debugLog('Page: awaited random time');
this._debugLog(
`Screenshot: params are - ${JSON.stringify(screenshotOptions, null, 2)}`
);
// only if the file does not exist, or if we force to save, do we write the actual images themselves
const newBaseline = !fs.existsSync(fullPath);
if (newBaseline) {
this._imageLog(`Screenshot: making base screen ${fileName}`);
await page.screenshot(
Object.assign({}, screenshotOptions, {
path: fullPath,
})
);
}
// Always make the tmp screenshot
const fullTmpPath = `${path.join(this.visualTest.imageTmpDirectory, fileName)}.png`;
this._imageLog(`Screenshot: making comparison screen ${fileName}`);
await page.screenshot(
Object.assign({}, screenshotOptions, {
path: fullTmpPath,
})
);
this._debugLog('Screenshot: both generated');
try {
await page.close();
this._debugLog('Page: closing');
} catch (e) {
logError('Error: closing a tab');
logError(e);
}
return { newBaseline };
},
_compareImages(fileName) {
const _this = this;
if (!fileName.includes('.png')) {
fileName = `${fileName}.png`;
}
const baselineImgPath = path.join(this.visualTest.imageDirectory, fileName);
const imgPath = path.join(this.visualTest.imageTmpDirectory, fileName);
// eslint-disable-next-line no-async-promise-executor
return new Promise(async function (resolve) {
const baseImg = fs
.createReadStream(baselineImgPath)
.pipe(new PNG())
.on('parsed', doneReading);
const tmpImg = fs
.createReadStream(imgPath)
.pipe(new PNG())
.on('parsed', doneReading);
let filesRead = 0;
async function doneReading() {
if (++filesRead < 2) {
return;
}
try {
const diff = new PNG({ width: baseImg.width, height: baseImg.height });
const errorPixelCount = pixelmatch(
baseImg.data,
tmpImg.data,
diff.data,
baseImg.width,
baseImg.height,
{
threshold: _this.visualTest.imageMatchThreshold,
includeAA: _this.visualTest.includeAA,
}
);
if (errorPixelCount <= _this.visualTest.imageMatchAllowedFailures) {
return resolve();
}
const diffPath = path.join(_this.visualTest.imageDiffDirectory, fileName);
await fs.outputFile(diffPath, PNG.sync.write(diff));
_this._debugLog('Compare: images generated');
} catch (e) {
_this._debugLog('Compare: tried to, got error');
_this._debugLog(e);
}
}
});
},
middleware(app) {
app.use(
bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 500000,
})
);
app.use(
bodyParser.json({
limit: '50mb',
})
);
app.post('/visual-test/make-screenshot', (req, res) => {
const { url } = req.body;
const fileName = this._getFileName(req.body.name);
let { fullPage = false } = req.body;
const delayMs = req.body.delayMs ? parseInt(req.body.delayMs) : 100;
const windowHeight = req.body.windowHeight
? parseInt(req.body.windowHeight)
: null;
const windowWidth = req.body.windowWidth
? parseInt(req.body.windowWidth)
: null;
const params = {
url,
fileName,
fullPage,
delayMs,
windowWidth,
windowHeight,
};
this._debugLog(
`Screenshot: posting with the options ${JSON.stringify(params, null, 2)}`
);
const data = {};
this._makeScreenshots(url, fileName, {
fullPage,
delayMs,
windowWidth,
windowHeight,
})
.then(({ newBaseline }) => {
data.newBaseline = newBaseline;
return this._compareImages(fileName);
})
.then(() => {
data.status = 'SUCCESS';
this._debugLog('images succeeded, all good');
res.send(data);
})
.catch(reason => {
this._debugLog(`Screenshot: catched, reason: ${reason}`);
const diffPath = reason ? reason.diffPath : null;
const tmpPath = reason ? reason.tmpPath : null;
const errorPixelCount = reason ? reason.errorPixelCount : null;
this._debugLog('images failed, something went wrong');
data.status = 'ERROR';
data.diffPath = diffPath;
data.fullDiffPath = path.join(__dirname, diffPath);
data.error = `${errorPixelCount} pixels differ - diff: ${diffPath}, img: ${tmpPath}`;
res.send(data);
});
});
},
testemMiddleware(app) {
this.middleware(app);
},
serverMiddleware(options) {
this.app = options.app;
this.middleware(options.app);
},
_ensureThisImport() {
if (!this.import) {
this._findHost = function findHostShim() {
let current = this;
let app;
do {
app = current.app || app;
} while (current.parent.parent && (current = current.parent));
return app;
};
this.import = function importShim(asset, options) {
const app = this._findHost();
app.import(asset, options);
};
}
},
_getFileName(fileName) {
if (this.visualTest.groupByOs) {
const { os } = this.visualTest;
const filePath = path.parse(fileName);
filePath.name = `${os}-${filePath.name}`;
delete filePath.base;
return path.format(filePath);
}
return fileName;
},
isDevelopingAddon() {
return false;
},
};
function log() {
// eslint-disable-next-line no-console
console.log(...arguments);
}
function logError() {
// eslint-disable-next-line no-console
console.error(...arguments);
}