-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualreview-run.js
472 lines (429 loc) · 14.8 KB
/
visualreview-run.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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/*
Copyright 2019 Diogo Garrido
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.
*/
/**
* Global Options
* @typedef {Object} GlobalOptions
* @property {String} projectName The project name. Can only be defined on the VisualReview class.
* @property {String} host Host. Can only be defined on the VisualReview class.
* @property {Number} port Host port number. Can only be defined on the VisualReview class.
* @property {Boolean} strictSSL True to use strict ssl.
* @property {String} scheme Http or Https
* @property {Boolean} disabled True if we don't want to take screenshots at all.
* @property {function} propertiesFn function to use to extract properties.
* Can be overrided on the suite options.
* Can be overrided on the screenshot options.
*
* Suite Options
* @typedef {Object} SuiteOptions
* @property {String} suiteName The suite name. Can only be defined here.
* @property {Boolean} disabled True if we don't want to take screenshots on this suite.
* It will be overrided if the global options disabled is true.
* @property {function} propertiesFn function to use to extract properties.
* Can be overrided on the screenshot options.
* It will override the global options property.
*
* Screenshot Options
* @typedef {Object} ScreenshotOptions
* @property {Array<Mask,ElementFinder>} exclude Masks or ElementFinder to exclude from the screenshot
* @property {ElementFinder} include ElementFinder to reach the element that will be the screenshot target
* @property {function} propertiesFn function to use to extract properties
*
* Mask of an element
* @typedef {Object} Mask
* @property {Number} x X coordinate of the element
* @property {Number} y Y coordinate of the element
* @property {Number} width width of the element
* @property {Number} height heigh of the element
*/
var q = require("q");
var VrClient = require("./lib/vr-client.js");
var fs = require('fs')
/**
* This class contains the suite options for the Visual Review
* Its main purpose is to store the options for the suite run .
* The host, port and projectName properties should not be defined here, although they can.If
* they are defined here they will override the global options.
* Even so, they can be override by the test options when taking the screenshot.
*
* @class VisualReviewRun
*/
module.exports = class VisualReviewRun {
/**
* Contructor of the class
* @param {GlobalOptions} globalOptions
* @param {SuiteOptions} suiteOptions
* @example
* {
* globalOptions:{
* hostname: 'localhost',
* port: 7000,
* projectName: 'EXAMPLE PROJECT',
* disabled: false,
* propertiesFn: (capabilities) => {
* return {
* os: capabilities.platform,
* browser: capabilities.browserName
* };
* }
* },
* suiteOptions: {
* suiteName: 'My Suite',
* propertiesFn: (capabilities, defaultFn) => {
* var defaultCapabiolities = defaultFn;
* return def;
* }
* }
* }
*/
constructor(globalOptions, suiteOptions) {
if (!suiteOptions.suiteName) {
throw new Error("Suite Name must by defined must be defined!!");
}
// Options that are set on the global Options only
this.projectName = globalOptions.projectName;
this.hostname = globalOptions.hostname;
this.port = globalOptions.port;
this.branchName = globalOptions.branchName;
this.scheme = globalOptions.scheme;
this.strictSSL = globalOptions.strictSSL;
//Get Properties Function. If not defined uses the global
this.propertiesFn = suiteOptions.propertiesFn || globalOptions.propertiesFn;
//Run specific options
this.suiteName = suiteOptions.suiteName;
//create the VRClient
this.client = new VrClient(
this.hostname,
this.port,
this.scheme,
this.strictSSL
);
//Disabled special case
this.disabled = !!(globalOptions.disabled || suiteOptions.disabled);
// To be filled after the run starts
this.projectId;
this.suiteId;
this.runId;
//Capabilities
this.capabilities = browser.capabilities;
//Create the possibility of adding includes or excludes
this.include = suiteOptions.include || null;
this.exclude = suiteOptions.exclude || null;
}
/**
* Starts a Run on the Visual Review Server
* @returns {Promise} a promise which resolves when the run is created successfuly on the server
* If an error has occurred, the promise will reject with a string containing an error message.
*/
initRun() {
//check disabled scenario
if (this.disabled) {
return;
}
return this.client
.createRun(this.projectName, this.suiteName, this.branchName)
.then(createdRun => {
if (createdRun) {
this.projectId = createdRun.project_id;
this.suiteId = createdRun.suite_id;
this.runId = createdRun.run_id;
//Log run creation into console
this._logMessage("Created run with ID " + createdRun.run_id);
}
})
.catch(err => {
this._throwError(err);
});
}
/**
* Takes the screenshot and sends it to the VisualReview Server
* @param {String} name Name of the screenshot
* @param {ScreenshotOptions} options options of the screenshot
*/
takeScreenshot(name, options) {
var elementToTakeScreenshot =
options && options.include ? options.include : this.include;
var masksToAdd =
options && options.exclude ? options.exclude : this.exclude;
var propertiesFn =
options && options.propertiesFn
? options.propertiesFn
: this.propertiesFn;
if (this.disabled || (options && options.disabled)) {
this._logMessage(
"Test screenshot is disabled. No Screenshot will be taken!."
);
return true;
}
return this._getMasks(masksToAdd, elementToTakeScreenshot).then(masks => {
// send screenshot of an element
return this._takeScreenshotAndSendToClient(
name,
elementToTakeScreenshot,
masks,
propertiesFn
)
.then(result => {
return result;
})
.catch(err => {
this._throwError(err);
});
});
}
/**
* Returns all the masks for the screenshot in the correct format
*
* NOTES: 1 - You can pass an array with masks or ElementFinders.
* 2 - If we are taking a screenshot to an element, the masks coordinates
* will be corrected regarding the element screenshot mask.
* @param {Array<Mask,ElementFinder>} masks Masks or elements to extract masks from
* @param {ElementFinder} relatedElement element that will have masks
* @return {Promise<Array<Mask>>} All the masks that the screenshot will have
*/
_getMasks(masks, relatedElement) {
var defer = q.defer();
var testMasks = [];
var mask = {
excludeZones: []
};
//Check masks (Elements to Exclude)
if (masks && masks.length > 0) {
var promises = [];
masks.forEach(mk => {
if (mk.x && mk.y && mk.width && mk.height) {
testMasks.push(mk);
} else {
promises.push(this._getMaskForElement(mk));
}
});
q.all(promises).then(masksProcessed => {
//add the elements maks to the mask array
masksProcessed.forEach(m => testMasks.push(m));
if (relatedElement) {
// Get the element mask to fix all the others that will be defined for the viewport screenshot
this._getMaskForElement(relatedElement).then(
screenshotElementMask => {
testMasks.forEach(m => {
var correctedMask = {
height: m.height,
x: m.x - screenshotElementMask.x,
width: m.width,
y: m.y - screenshotElementMask.y
};
console.log("MASCARA Elemento PRINCIPAL", screenshotElementMask);
console.log("MASCARA Elemento A REMOVER", m);
console.log("MASCARA Corrigida", correctedMask);
mask.excludeZones.push(correctedMask);
});
defer.resolve(mask);
}
);
} else {
mask.excludeZones = testMasks;
defer.resolve(mask);
}
});
} else {
defer.resolve({});
}
return defer.promise;
}
/**
* Instructs webdriverio to take a screenshot and sends it to the VisualReview server.
* @param {String} name the screenshot's name.
* @param {ElementFinder} element ElementFinder if you don't want to take a picture of the entire screen
* @param {Array<Mask>} mask Array of masks that you want to add to the screenshot.
* @returns {Promise} Promise that will be solved when we gt the result from the screenshot sent to the server
*/
_takeScreenshotAndSendToClient(name, element, masks, propertiesFn) {
return this._getProperties(propertiesFn)
.then(properties => {
var maskToUse = masks ? Object.assign(masks) : {};
var elementToTakeScreenShot = element ? element : browser;
var fileName = `${process.cwd()}/temporary.png`;
console.log("ESTOU AQUI", browser.saveDocumentScreenshot);
return elementToTakeScreenShot.saveScreenshot(fileName).then(png => {
if (!this.runId) {
return q.reject(
"VisualReview-webdriverio: Could not send screenshot to VisualReview server, could not find any run ID. Was initRun called before starting this test? See VisualReview-webdriverio's documentation for more details on how to set this up."
);
}
console.log("PNG", png);
return this.client
.sendScreenshot(
name,
this.runId,
{},
properties,
this.compareSettings,
png,
maskToUse
)
.then(() => {
return this._getTestResult(name)
.then(result => {
return result;
})
.catch(err => {
return q.reject(
"Something went wrong while tryint to get the result for the test. " +
err
);
});
})
.catch(err => {
return q.reject(
"Something went wrong while sending a screenshot to the VisualReview server. " +
err
);
})
.finally(() => {
fs.unlinkSync(fileName);
});
});
})
.catch(err => {
return q.reject(
"Something went wrong while trying to get the capabilities for this test " +
err
);
});
}
/**
* Extracts the mask from an element
* @param {ElementFinder} elem Element that we want to extract the mask from
* @returns {Promise<Mask>} Promise that will be solkved into the mask of the element.
* If something goes wrong we throw an error.
* @example
* {
* height: 200,
* x: 0,
* width: 45,
* y: 0
* }
*/
_getMaskForElement(elem) {
var defer = q.defer();
elem
.getSize()
.then(size => {
elem
.getLocation()
.then(location => {
defer.resolve({
height: size.height,
x: location.x + 370,
width: size.width,
y: location.y + 300
});
})
.catch(err => {
defer.reject(
"Error trying to get the mask location for the element ",
err
);
});
})
.catch(err => {
defer.reject("Error trying to get the mask size for the element ", err);
});
return defer.promise;
}
/**
* Gets the test result from the analysis of the run.
* @param {String} testName
* @returns {Promise<boolean>} Promise that will be resolved into a boolean. True if the test passed.
*/
_getTestResult(testName) {
return this.client
.getRunAnalysisByRunId(this.runId)
.then(results => {
return this._extractResultsforTest(results, testName);
})
.catch(err => {
this._throwError(
"Something went wrong while getting the test results. " + err
);
});
}
/**
* Returns the test result
* Everything that is not "accepted" will be considered a failure
* @param {Object} results results of the run.
* @param {String} testName test name
* @returns {boolean} True if the screenshot was accepted.
*/
_extractResultsforTest(results, testName) {
var parsedResults = JSON.parse(results);
var tests = parsedResults.diffs.filter(test => {
return test.after.screenshotName == testName;
});
if (tests.length !== 1) {
this._logMessage(
`There are 0 or more than 1 screenshot with this name: ${testName}`
);
return false;
}
return tests[0].status === "accepted";
}
/**
* Returns the system capabilities if they are not defined
* @returns {Object} Object that represents the system properties
*/
_getProperties(propertiesFn) {
return browser.getWindowSize().then(size => {
var properties = propertiesFn(this.capabilities, this.propertiesFn);
properties.resolution = size.width + "x" + size.height;
return properties;
});
}
/**
* Logs the pretended message on the console
* @param {String} message Message to log
*/
_logMessage(message) {
console.log(
`[Visual Review][${this.projectName}][${this.suiteName}][${this.runId}] ${message}`
);
}
/**
* Throws an error with the pretended message
* @param {String} message Pretended Message
*/
_throwError(message) {
throw `[Visual Review][${this.projectName}][${this.suiteName}][${this.runId}] ${message}`;
}
/**
* Prints the location results
* NOTE: Can be used in the future to present more complete logs
* @returns {Promise}
*/
cleanup() {
if (!this.disabled) {
this._logMessage(
"Tests finished. Your results can be viewed at: " +
"http://" +
this.hostname +
":" +
this.port +
"/#/" +
this.projectId +
"/" +
this.suiteId +
"/" +
this.runId +
"/rp"
);
}
}
};