/
test-adapter.js
448 lines (348 loc) · 13.5 KB
/
test-adapter.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
'use strict';
const _ = require('lodash');
const fs = require('fs-extra');
const path = require('path');
const tmp = require('tmp');
const crypto = require('crypto');
const SuiteAdapter = require('./suite-adapter');
const {DB_COLUMNS} = require('./constants/database');
const {getSuitePath} = require('./plugin-utils').getHermioneUtils();
const {getCommandsHistory} = require('./history-utils');
const {SUCCESS, FAIL, ERROR, UPDATED} = require('./constants/test-statuses');
const {ERROR_DETAILS_PATH} = require('./constants/paths');
const utils = require('./server-utils');
const {logger} = require('./common-utils');
const globalCacheAllImages = new Map();
const globalCacheExpectedPaths = new Map();
const globalCacheDiffImages = new Map();
const testsAttempts = new Map();
function createHash(buffer) {
return crypto
.createHash('sha1')
.update(buffer)
.digest('base64');
}
module.exports = class TestAdapter {
static create(testResult = {}, {hermione, sqliteAdapter, status}) {
return new this(testResult, {hermione, sqliteAdapter, status});
}
constructor(testResult, {hermione, sqliteAdapter, status}) {
this._testResult = testResult;
this._hermione = hermione;
this._sqliteAdapter = sqliteAdapter;
this._errors = this._hermione.errors;
this._suite = SuiteAdapter.create(this._testResult);
this._imagesSaver = this._hermione.htmlReporter.imagesSaver;
this._testId = `${this._testResult.fullTitle()}.${this._testResult.browserId}`;
this._errorDetails = undefined;
this._timestamp = this._testResult.timestamp;
const browserVersion = _.get(this._testResult, 'meta.browserVersion', this._testResult.browserVersion);
_.set(this._testResult, 'meta.browserVersion', browserVersion);
if (utils.shouldUpdateAttempt(status)) {
testsAttempts.set(this._testId, _.isUndefined(testsAttempts.get(this._testId)) ? 0 : testsAttempts.get(this._testId) + 1);
}
this._attempt = testsAttempts.get(this._testId) || 0;
}
get suite() {
return this._suite;
}
get sessionId() {
return this._testResult.sessionId || 'unknown session id';
}
get browserId() {
return this._testResult.browserId;
}
get imagesInfo() {
return this._testResult.imagesInfo;
}
set imagesInfo(imagesInfo) {
this._testResult.imagesInfo = imagesInfo;
}
_getImgFromStorage(imgPath) {
// fallback for updating image in gui mode
return globalCacheAllImages.get(imgPath) || imgPath;
}
_getLastImageInfoFromDB(stateName) {
const browserName = this._testResult.browserId;
const suitePath = getSuitePath(this._testResult);
const suitePathString = JSON.stringify(suitePath);
const imagesInfoResult = this._sqliteAdapter.query({
select: DB_COLUMNS.IMAGES_INFO,
where: `${DB_COLUMNS.SUITE_PATH} = ? AND ${DB_COLUMNS.NAME} = ?`,
orderBy: DB_COLUMNS.TIMESTAMP,
orderDescending: true
}, suitePathString, browserName);
const imagesInfo = imagesInfoResult && JSON.parse(imagesInfoResult[DB_COLUMNS.IMAGES_INFO]) || [];
return imagesInfo.find(info => info.stateName === stateName);
}
_getExpectedKey(stateName) {
// TODO: remove toString after publish major version
return this._testResult.id.toString() + '#' + stateName;
}
_getExpectedPath(stateName, status) {
const key = this._getExpectedKey(stateName);
if (status === UPDATED) {
const expectedPath = utils.getReferencePath(this, stateName);
globalCacheExpectedPaths.set(key, expectedPath);
return expectedPath;
}
if (globalCacheExpectedPaths.has(key)) {
return globalCacheExpectedPaths.get(key);
}
const imageInfo = this._getLastImageInfoFromDB(stateName);
const expectedPath = imageInfo && imageInfo.expectedImg
? imageInfo.expectedImg.path
: utils.getReferencePath(this, stateName);
globalCacheExpectedPaths.set(key, expectedPath);
return expectedPath;
}
getImagesFor(status, stateName) {
const refImg = this.getRefImg(stateName);
const currImg = this.getCurrImg(stateName);
const errImg = this.getErrImg();
const refPath = this._getExpectedPath(stateName, status);
const currPath = utils.getCurrentPath(this, stateName);
const diffPath = utils.getDiffPath(this, stateName);
if (status === SUCCESS || status === UPDATED) {
return {expectedImg: {path: this._getImgFromStorage(refPath), size: refImg.size}};
}
if (status === FAIL) {
return {
expectedImg: {
path: this._getImgFromStorage(refPath),
size: refImg.size
},
actualImg: {
path: this._getImgFromStorage(currPath),
size: currImg.size
},
diffImg: {
path: this._getImgFromStorage(diffPath),
size: {
width: _.max([_.get(refImg, 'size.width'), _.get(currImg, 'size.width')]),
height: _.max([_.get(refImg, 'size.height'), _.get(currImg, 'size.height')])
}
}
};
}
if (status === ERROR) {
return {
actualImg: {
path: this.state ? this._getImgFromStorage(currPath) : '',
size: currImg.size || errImg.size
}
};
}
return {};
}
async _saveErrorScreenshot(reportPath) {
if (!this.screenshot.base64) {
logger.warn('Cannot save screenshot on reject');
return Promise.resolve();
}
const currPath = utils.getCurrentPath(this);
const localPath = path.resolve(tmp.tmpdir, currPath);
await utils.makeDirFor(localPath);
await fs.writeFile(localPath, new Buffer(this.screenshot.base64, 'base64'), 'base64');
return this._saveImg(localPath, currPath, reportPath);
}
async _saveImg(localPath, destPath, reportDir) {
if (!localPath) {
return Promise.resolve();
}
const res = await this._imagesSaver.saveImg(localPath, {destPath, reportDir});
globalCacheAllImages.set(destPath, res || destPath);
return res;
}
get attempt() {
return this._attempt;
}
get origAttempt() {
return this._testResult.origAttempt;
}
set attempt(attemptNum) {
testsAttempts.set(this._testId, attemptNum);
this._attempt = attemptNum;
}
hasDiff() {
return this.assertViewResults.some((result) => this.isImageDiffError(result));
}
get assertViewResults() {
return this._testResult.assertViewResults || [];
}
isImageDiffError(assertResult) {
return assertResult instanceof this._errors.ImageDiffError;
}
isNoRefImageError(assertResult) {
return assertResult instanceof this._errors.NoRefImageError;
}
getImagesInfo() {
if (!_.isEmpty(this.imagesInfo)) {
return this.imagesInfo;
}
this.imagesInfo = this.assertViewResults.map((assertResult) => {
let status, error;
if (!(assertResult instanceof Error)) {
status = SUCCESS;
}
if (this.isImageDiffError(assertResult)) {
status = FAIL;
}
if (this.isNoRefImageError(assertResult)) {
status = ERROR;
error = _.pick(assertResult, ['message', 'stack']);
}
const {stateName, refImg, diffClusters} = assertResult;
return _.extend(
{stateName, refImg, status, error, diffClusters},
this.getImagesFor(status, stateName)
);
});
// common screenshot on test fail
if (this.screenshot) {
const errorImage = _.extend(
{status: ERROR, error: this.error},
this.getImagesFor(ERROR)
);
this.imagesInfo.push(errorImage);
}
return this.imagesInfo;
}
get history() {
return getCommandsHistory(this._testResult.history);
}
get error() {
return _.pick(this._testResult.err, ['message', 'stack', 'stateName']);
}
get imageDir() {
// TODO: remove toString after publish major version
return this._testResult.id.toString();
}
get state() {
return {name: this._testResult.title};
}
get testPath() {
return this._suite.path.concat(this._testResult.title);
}
get id() {
return this.testPath.concat(this.browserId, this.attempt).join(' ');
}
get screenshot() {
return _.get(this._testResult, 'err.screenshot');
}
get description() {
return this._testResult.description;
}
get meta() {
return this._testResult.meta;
}
get errorDetails() {
if (!_.isUndefined(this._errorDetails)) {
return this._errorDetails;
}
const details = _.get(this._testResult, 'err.details', null);
if (details) {
this._errorDetails = {
title: details.title || 'error details',
data: details.data,
filePath: `${ERROR_DETAILS_PATH}/${utils.getDetailsFileName(
this._testResult.id, this._testResult.browserId, this.attempt
)}`
};
} else {
this._errorDetails = null;
}
return this._errorDetails;
}
getRefImg(stateName) {
return _.get(_.find(this.assertViewResults, {stateName}), 'refImg', {});
}
getCurrImg(stateName) {
return _.get(_.find(this.assertViewResults, {stateName}), 'currImg', {});
}
getErrImg() {
return this.screenshot || {};
}
prepareTestResult() {
const {title: name, browserId} = this._testResult;
const suitePath = getSuitePath(this._testResult);
return {name, suitePath, browserId};
}
get multipleTabs() {
return true;
}
get timestamp() {
return this._timestamp;
}
set timestamp(timestamp) {
if (!_.isNumber(this._timestamp)) {
this._timestamp = timestamp;
}
}
async saveErrorDetails(reportPath) {
if (!this.errorDetails) {
return;
}
const detailsFilePath = path.resolve(reportPath, this.errorDetails.filePath);
const detailsData = _.isObject(this.errorDetails.data)
? JSON.stringify(this.errorDetails.data, null, 2)
: this.errorDetails.data;
await utils.makeDirFor(detailsFilePath);
await fs.writeFile(detailsFilePath, detailsData);
}
async saveTestImages(reportPath, workers) {
const result = await Promise.all(this.assertViewResults.map(async (assertResult) => {
const {stateName} = assertResult;
const destRefPath = this._getExpectedPath(stateName);
const srcRefPath = this.getRefImg(stateName).path;
const destCurrPath = utils.getCurrentPath(this, stateName);
const srcCurrPath = this.getCurrImg(stateName).path || this.getErrImg().path;
const dstCurrPath = utils.getDiffPath(this, stateName);
const srcDiffPath = path.resolve(tmp.tmpdir, dstCurrPath);
const actions = [];
if (!(assertResult instanceof Error)) {
actions.push(this._saveImg(srcRefPath, destRefPath, reportPath));
}
if (this.isImageDiffError(assertResult)) {
await this._saveDiffInWorker(assertResult, srcDiffPath, workers);
actions.push(
this._saveImg(srcCurrPath, destCurrPath, reportPath),
this._saveImg(srcDiffPath, dstCurrPath, reportPath),
this._saveImg(srcRefPath, destRefPath, reportPath)
);
}
if (this.isNoRefImageError(assertResult)) {
actions.push(this._saveImg(srcCurrPath, destCurrPath, reportPath));
}
return Promise.all(actions);
}));
if (this.screenshot) {
await this._saveErrorScreenshot(reportPath);
}
const htmlReporter = this._hermione.htmlReporter;
await htmlReporter.emitAsync(htmlReporter.events.TEST_SCREENSHOTS_SAVED, {
testId: this._testId,
attempt: this.attempt,
imagesInfo: this.getImagesInfo()
});
return result;
}
//parallelize and cache of 'looks-same.createDiff' (because it is very slow)
async _saveDiffInWorker(imageDiffError, destPath, workers, cacheDiffImages = globalCacheDiffImages) {
await utils.makeDirFor(destPath);
const currPath = imageDiffError.currImg.path;
const refPath = imageDiffError.refImg.path;
const [currBuffer, refBuffer] = await Promise.all([
fs.readFile(currPath),
fs.readFile(refPath)
]);
const hash = createHash(currBuffer) + createHash(refBuffer);
if (cacheDiffImages.has(hash)) {
const cachedDiffPath = cacheDiffImages.get(hash);
await fs.copy(cachedDiffPath, destPath);
return;
}
await workers.saveDiffTo(imageDiffError, destPath);
cacheDiffImages.set(hash, destPath);
}
};