-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathindex.ts
651 lines (579 loc) · 18.9 KB
/
index.ts
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
const { Helper } = require("codeceptjs");
const resemble = require("resemblejs");
const fs = require("fs");
const assert = require("assert");
const mkdirp = require("mkdirp");
const getDirName = require("path").dirname;
const AWS = require("aws-sdk");
const path = require("path");
const sizeOf = require("image-size");
const Container = require("codeceptjs/lib/container");
const supportedHelper = ["Playwright", "Puppeteer", "WebDriver", "TestCafe", "Appium"];
let outputDir: string;
/**
* Resemble.js helper class for CodeceptJS, this allows screen comparison
* @author Puneet Kala
*/
interface Config {
baseFolder: string;
diffFolder: string;
screenshotFolder: string;
prepareBaseImage: string;
}
interface Options {
tolerance?: any;
ignoredBox?: any;
boundingBox?: any;
needsSameDimension?: boolean;
outputSettings?: any;
prepareBaseImage?: boolean;
compareWithImage?: any;
}
interface Endpoint {
/**
* The host portion of the endpoint including the port, e.g., example.com:80.
*/
host: string;
/**
* The host portion of the endpoint, e.g., example.com.
*/
hostname: string;
/**
* The full URL of the endpoint.
*/
href: string;
/**
* The port of the endpoint.
*/
port: number;
/**
* The protocol (http or https) of the endpoint URL.
*/
protocol: string;
}
class ResembleHelper extends Helper {
baseFolder: string;
diffFolder: string;
screenshotFolder?: string;
prepareBaseImage?: boolean;
config?: any;
constructor(config: any) {
// @ts-ignore
super(config);
outputDir = require("codeceptjs").config.get().output || "output";
this.baseFolder = this.resolvePath(config.baseFolder);
this.diffFolder = this.resolvePath(config.diffFolder);
this.screenshotFolder = this.resolvePath(config.screenshotFolder || "output");
this.prepareBaseImage = config.prepareBaseImage;
}
resolvePath(folderPath: string) {
if (!path.isAbsolute(folderPath)) {
return `${path.resolve(folderPath)}/`;
}
return folderPath;
}
_resolveRelativePath(folderPath: string) {
let absolutePathOfImage = folderPath;
if (!path.isAbsolute(absolutePathOfImage)) {
absolutePathOfImage = `${path.resolve(outputDir, absolutePathOfImage)}/`;
}
let absolutePathOfReportFolder = outputDir;
// support mocha
if (Container.mocha() && typeof Container.mocha().options.reporterOptions.reportDir !== "undefined") {
absolutePathOfReportFolder = Container.mocha().options.reporterOptions.reportDir;
}
// support mocha-multi-reporters
if (
Container.mocha() &&
typeof Container.mocha().options.reporterOptions.mochawesomeReporterOptions?.reportDir !== "undefined"
) {
absolutePathOfReportFolder = Container.mocha().options.reporterOptions.mochawesomeReporterOptions.reportDir;
}
return path.relative(absolutePathOfReportFolder, absolutePathOfImage);
}
/**
* Compare Images
*
* @param image
* @param options
* @returns {Promise<resolve | reject>}
*/
async _compareImages(image: any, options: Options) {
const baseImage = this._getBaseImagePath(image, options);
const actualImage = this._getActualImagePath(image);
const diffImage = this._getDiffImagePath(image);
// check whether the base and the screenshot images are present.
fs.access(baseImage, fs.constants.F_OK | fs.constants.R_OK, (err: any) => {
if (err) {
throw new Error(
`${baseImage} ${err.code === "ENOENT" ? "base image does not exist" : "base image has an access error"}`,
);
}
});
fs.access(actualImage, fs.constants.F_OK | fs.constants.R_OK, (err: any) => {
if (err) {
throw new Error(
`${actualImage} ${
err.code === "ENOENT" ? "screenshot image does not exist" : "screenshot image has an access error"
}`,
);
}
});
return new Promise((resolve, reject) => {
if (!options.outputSettings) {
options.outputSettings = {};
}
if (typeof options.needsSameDimension === "undefined") {
options.needsSameDimension = true;
}
resemble.outputSettings({
boundingBox: options.boundingBox,
ignoredBox: options.ignoredBox,
...options.outputSettings,
});
this.debug(`Tolerance Level Provided ${options.tolerance}`);
const tolerance = options.tolerance;
resemble.compare(actualImage, baseImage, options, (err: any, data: any) => {
if (err) {
reject(err);
} else {
if (options.needsSameDimension && !data.isSameDimensions) {
const dimensions1 = sizeOf(baseImage);
const dimensions2 = sizeOf(actualImage);
reject(
new Error(
`The base image is of ${dimensions1.height} X ${dimensions1.width} and actual image is of ${dimensions2.height} X ${dimensions2.width}. Please use images of same dimensions so as to avoid any unexpected results.`,
),
);
}
resolve(data);
if (data.misMatchPercentage >= tolerance) {
if (!fs.existsSync(getDirName(diffImage))) {
fs.mkdirSync(getDirName(diffImage));
}
fs.writeFileSync(diffImage, data.getBuffer());
const diffImagePath = path.join(process.cwd(), diffImage);
this.debug(`Diff Image File Saved to: ${diffImagePath}`);
}
}
});
});
}
/**
*
* @param image
* @param options
* @returns {Promise<*>}
*/
async _fetchMisMatchPercentage(image: any, options: Options) {
const result = this._compareImages(image, options);
const data: any = await Promise.resolve(result);
return data.misMatchPercentage;
}
/**
* Take screenshot of individual element.
* @param selector selector of the element to be screenshotted
* @param name name of the image
* @returns {Promise<void>}
*/
async screenshotElement(selector: any, name: string) {
const helper = this._getHelper();
if (!helper) throw new Error("Method only works with Playwright, Puppeteer, WebDriver or TestCafe helpers.");
await helper.waitForVisible(selector);
const els = await helper._locate(selector);
if (this.helpers["Puppeteer"] || this.helpers["Playwright"] || this.helpers["WebDriver"]) {
if (!els.length) throw new Error(`Element ${selector} couldn't be located`);
const el = els[0];
if (this.helpers["Puppeteer"] || this.helpers["Playwright"]) {
await el.screenshot({ path: `${outputDir}/${name}.png` });
}
if (this.helpers["WebDriver"]) {
await el.saveScreenshot(`${this.screenshotFolder}${name}.png`);
}
}
if (this.helpers["TestCafe"]) {
if (!(await els.count)) throw new Error(`Element ${selector} couldn't be located`);
const { t } = this.helpers["TestCafe"];
await t.takeElementScreenshot(els, name);
}
}
/**
* This method attaches image attachments of the base, screenshot and diff to the allure reporter when the mismatch exceeds tolerance.
* @param baseImage
* @param misMatch
* @param options
* @returns {Promise<void>}
*/
async _addAttachment(baseImage: any, misMatch: any, options: Options) {
const allure: any = require("codeceptjs").container.plugins("allure");
if (allure !== undefined && misMatch >= options.tolerance) {
allure.addAttachment("Base Image", fs.readFileSync(this._getBaseImagePath(baseImage, options)), "image/png");
allure.addAttachment("Screenshot Image", fs.readFileSync(this._getActualImagePath(baseImage)), "image/png");
allure.addAttachment("Diff Image", fs.readFileSync(this._getDiffImagePath(baseImage)), "image/png");
}
}
/**
* This method attaches context, and images to Mochawesome reporter when the mismatch exceeds tolerance.
* @param baseImage
* @param misMatch
* @param options
* @returns {Promise<void>}
*/
async _addMochaContext(baseImage: any, misMatch: any, options: any) {
const mocha = this.helpers["Mochawesome"];
if (mocha !== undefined && misMatch >= options.tolerance) {
await mocha.addMochawesomeContext("Base Image");
await mocha.addMochawesomeContext(this._resolveRelativePath(this._getBaseImagePath(baseImage, options)));
await mocha.addMochawesomeContext("ScreenShot Image");
await mocha.addMochawesomeContext(this._resolveRelativePath(this._getActualImagePath(baseImage)));
await mocha.addMochawesomeContext("Diff Image");
await mocha.addMochawesomeContext(this._resolveRelativePath(this._getDiffImagePath(baseImage)));
}
}
/**
* This method uploads the diff and screenshot images into the bucket with diff image under bucketName/diff/diffImage and the screenshot image as
* bucketName/output/ssImage
* @param accessKeyId
* @param secretAccessKey
* @param region
* @param bucketName
* @param baseImage
* @param options
* @param {string | Endpoint } [endpoint]
* @returns {Promise<void>}
*/
async _upload(
accessKeyId: any,
secretAccessKey: any,
region: any,
bucketName: any,
baseImage: any,
options: any,
endpoint: Endpoint,
uploadOnlyBaseImage: boolean,
) {
console.log("Starting Upload... ");
const s3 = new AWS.S3({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
endpoint,
});
// If prepareBaseImage is false, then it won't upload the baseImage. However, this parameter is not considered if the config file has a prepareBaseImage set to true.
if (this._getPrepareBaseImage(options)) {
const baseImageName = this._getBaseImageName(baseImage, options);
fs.readFile(this._getBaseImagePath(baseImage, options), (err: any, data: any) => {
if (err) throw err;
else {
const base64data = new Buffer(data, "binary");
const params = {
Bucket: bucketName,
Key: `base/${baseImageName}`,
Body: base64data,
};
s3.upload(params, (uErr: any, uData: { Location: any }) => {
if (uErr) throw uErr;
console.log(`Base Image uploaded at ${uData.Location}`);
});
}
});
} else {
console.log("Not Uploading base Image");
}
if (uploadOnlyBaseImage) {
this.debug("Only the Base Image is uploaded to S3. Skipping upload of diff and output folders!");
return;
}
fs.readFile(this._getActualImagePath(baseImage), (err: any, data: any) => {
if (err) throw err;
const base64data = new Buffer(data, "binary");
const params = {
Bucket: bucketName,
Key: `output/${baseImage}`,
Body: base64data,
};
s3.upload(params, (uErr: any, uData: { Location: any }) => {
if (uErr) throw uErr;
console.log(`Screenshot Image uploaded successfully at ${uData.Location}`);
});
});
fs.readFile(this._getDiffImagePath(baseImage), (err: any, data: any) => {
if (err) console.log("Diff image not generated");
else {
const base64data = new Buffer(data, "binary");
const params = {
Bucket: bucketName,
Key: `diff/Diff_${baseImage}`,
Body: base64data,
};
s3.upload(params, (uErr: any, uData: { Location: any }) => {
if (uErr) throw uErr;
console.log(`Diff Image uploaded successfully at ${uData.Location}`);
});
}
});
}
/**
* This method downloads base images from specified bucket into the base folder as mentioned in config file.
* @param accessKeyId
* @param secretAccessKey
* @param region
* @param bucketName
* @param baseImage
* @param options
* @param {string | Endpoint } [endpoint]
* @returns {Promise<void>}
*/
_download(
accessKeyId: any,
secretAccessKey: any,
region: any,
bucketName: any,
baseImage: any,
options: any,
endpoint: Endpoint,
) {
console.log("Starting Download...");
const baseImageName = this._getBaseImageName(baseImage, options);
const s3 = new AWS.S3({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey,
region: region,
endpoint,
});
const params = {
Bucket: bucketName,
Key: `base/${baseImageName}`,
};
return new Promise((resolve) => {
s3.getObject(params, (err: any, data: { Body: any }) => {
if (err) console.error(err);
console.log(this._getBaseImagePath(baseImage, options));
fs.writeFileSync(this._getBaseImagePath(baseImage, options), data.Body);
resolve("File Downloaded Successfully");
});
});
}
/**
* Check Visual Difference for Base and Screenshot Image
* @param baseImage Name of the Base Image (Base Image path is taken from Configuration)
* @param {any} [options] Options ex {prepareBaseImage: true, tolerance: 5} along with Resemble JS Options, read more here: https://github.com/rsmbl/Resemble.js
* @returns {Promise<void>}
*/
async seeVisualDiff(baseImage: any, options?: Options) {
await this._assertVisualDiff(undefined, baseImage, options);
}
/**
* See Visual Diff for an Element on a Page
*
* @param selector Selector which has to be compared expects these -> CSS|XPath|ID
* @param baseImage Base Image for comparison
* @param {any} [options] Options ex {prepareBaseImage: true, tolerance: 5} along with Resemble JS Options, read more here: https://github.com/rsmbl/Resemble.js
* @returns {Promise<void>}
*/
async seeVisualDiffForElement(selector: any, baseImage: any, options: Options) {
await this._assertVisualDiff(selector, baseImage, options);
}
async _assertVisualDiff(
selector: undefined,
baseImage: string,
options?: { tolerance?: any; boundingBox?: any; skipFailure?: any },
) {
let newOptions = options;
if (!newOptions) {
newOptions = {};
newOptions.tolerance = 0;
}
const awsC = this.config.aws;
if (this._getPrepareBaseImage(newOptions)) {
await this._prepareBaseImage(baseImage, newOptions);
} else if (awsC !== undefined) {
await this._download(
awsC.accessKeyId,
awsC.secretAccessKey,
awsC.region,
awsC.bucketName,
baseImage,
options,
awsC.endpoint,
);
}
// BoundingBox for Playwright not necessary
if (selector && !this.helpers["Playwright"]) {
newOptions.boundingBox = await this._getBoundingBox(selector);
}
const misMatch = await this._fetchMisMatchPercentage(baseImage, newOptions);
await this._addAttachment(baseImage, misMatch, newOptions);
await this._addMochaContext(baseImage, misMatch, newOptions);
if (awsC !== undefined) {
await this._upload(
awsC.accessKeyId,
awsC.secretAccessKey,
awsC.region,
awsC.bucketName,
baseImage,
options,
awsC.endpoint,
awsC.uploadOnlyBaseImage,
);
}
this.debug(`MisMatch Percentage Calculated is ${misMatch} for baseline ${baseImage}`);
if (!newOptions.skipFailure) {
assert(
misMatch <= newOptions.tolerance,
`Screenshot does not match with the baseline ${baseImage} when MissMatch Percentage is ${misMatch}`,
);
}
}
/**
* Function to prepare Base Images from Screenshots
*
* @param screenShotImage Name of the screenshot Image (Screenshot Image Path is taken from Configuration)
* @param options
*/
async _prepareBaseImage(screenShotImage: string, options: { tolerance?: any; boundingBox?: any; skipFailure?: any }) {
const baseImage = this._getBaseImagePath(screenShotImage, options);
const actualImage = this._getActualImagePath(screenShotImage);
await this._createDir(baseImage);
fs.access(actualImage, fs.constants.F_OK | fs.constants.W_OK, (err: any) => {
if (err) {
throw new Error(`${actualImage} ${err.code === "ENOENT" ? "does not exist" : "is read-only"}`);
}
});
fs.access(this.baseFolder, fs.constants.F_OK | fs.constants.W_OK, (err: any) => {
if (err) {
throw new Error(`${this.baseFolder} ${err.code === "ENOENT" ? "does not exist" : "is read-only"}`);
}
});
fs.copyFileSync(actualImage, baseImage);
}
/**
* Function to create Directory
* @param directory
* @returns {Promise<void>}
* @private
*/
_createDir(directory: any) {
mkdirp.sync(getDirName(directory));
}
/**
* Function to fetch Bounding box for an element, fetched using selector
*
* @param selector CSS|XPath|ID selector
* @returns {Promise<{boundingBox: {left: *, top: *, right: *, bottom: *}}>}
*/
async _getBoundingBox(selector: any) {
const helper = this._getHelper();
await helper.waitForVisible(selector);
const els = await helper._locate(selector);
if (this.helpers["TestCafe"]) {
if ((await els.count) !== 1)
throw new Error(`Element ${selector} couldn't be located or isn't unique on the page`);
} else {
if (!els.length) throw new Error(`Element ${selector} couldn't be located`);
}
let location;
let size;
if (this.helpers["Puppeteer"] || this.helpers["Playwright"]) {
const el = els[0];
const box = await el.boundingBox();
size = location = box;
}
if (this.helpers["WebDriver"] || this.helpers["Appium"]) {
const el = els[0];
location = await el.getLocation();
size = await el.getSize();
}
if (this.helpers["WebDriverIO"]) {
location = await helper.browser.getLocation(selector);
size = await helper.browser.getElementSize(selector);
}
if (this.helpers["TestCafe"]) {
return await els.boundingClientRect;
}
if (!size) {
throw new Error("Cannot get element size!");
}
const bottom = size.height + location.y;
const right = size.width + location.x;
const boundingBox = {
left: location.x,
top: location.y,
right: right,
bottom: bottom,
};
this.debugSection("Area", JSON.stringify(boundingBox));
return boundingBox;
}
_getHelper() {
if (this.helpers["Puppeteer"]) {
return this.helpers["Puppeteer"];
}
if (this.helpers["WebDriver"]) {
return this.helpers["WebDriver"];
}
if (this.helpers["Appium"]) {
return this.helpers["Appium"];
}
if (this.helpers["WebDriverIO"]) {
return this.helpers["WebDriverIO"];
}
if (this.helpers["TestCafe"]) {
return this.helpers["TestCafe"];
}
if (this.helpers["Playwright"]) {
return this.helpers["Playwright"];
}
throw Error(`No matching helper found. Supported helpers: ${supportedHelper.join("/")}`);
}
/**
* Returns the final name of the expected base image, without a path
* @param image Name of the base-image, without path
* @param options Helper options
* @returns {string}
*/
_getBaseImageName(image: any, options: { compareWithImage?: any }) {
return options.compareWithImage ? options.compareWithImage : image;
}
/**
* Returns the path to the expected base image
* @param image Name of the base-image, without path
* @param options Helper options
* @returns {string}
*/
_getBaseImagePath(image: string, options: Options) {
return this.baseFolder + this._getBaseImageName(image, options);
}
/**
* Returns the path to the actual screenshot image
* @param image Name of the image, without path
* @returns {string}
*/
_getActualImagePath(image: string) {
return this.screenshotFolder + image;
}
/**
* Returns the path to the image that displays differences between base and actual image.
* @param image Name of the image, without path
* @returns {string}
*/
_getDiffImagePath(image: string) {
const diffImage = `Diff_${image.split(".")[0]}.png`;
return this.diffFolder + diffImage;
}
/**
* Returns the final `prepareBaseImage` flag after evaluating options and config values
* @param options Helper options
* @returns {boolean}
*/
_getPrepareBaseImage(options: Options) {
if ("undefined" !== typeof options.prepareBaseImage) {
// Cast to bool with `!!` for backwards compatibility
return !!options.prepareBaseImage;
} else {
// Compare with `true` for backwards compatibility
return true === this.prepareBaseImage;
}
}
}
export = ResembleHelper;