-
Notifications
You must be signed in to change notification settings - Fork 0
/
testHelpers.js
687 lines (586 loc) · 19.2 KB
/
testHelpers.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
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
const os = require("os");
const fs = require("fs");
const path = require("path");
const Table = require("cli-table");
/**
*
* @param {string} string String of text to clean
* @returns {string}
* @description
* Clear the text string and return the clean string
*/
const getCleanedString = (string) => {
// Characters we don't want to support
var specialChars = "!@#$^&%*()+=-[]\/{}|:<>?,.";
// Remove characters we don't support
for (var i = 0; i < specialChars.length; i++) {
string = string.replaceAll(new RegExp("\\" + specialChars[i], 'gi'), '');
}
// Convert to lowercase
string = string.toLowerCase();
// Replace spaces with "_"
string = string.replace(/ /g, "_");
// Replace special characters
string = string.replace(/á/gi, "a");
string = string.replace(/é/gi, "e");
string = string.replace(/í/gi, "i");
string = string.replace(/ó/gi, "o");
string = string.replace(/ú/gi, "u");
string = string.replace(/ñ/gi, "n");
return string;
}
/**
*
* @param {object} vars User-defined variables
* @param {string} pre_name name placed at the beginning of a transformed variable
* @param {object} vars_to_env Object of variables changed
*
* @returns {object} Format for environment variables
*
* @description
* Converts sent variables to a specific format to store them in
* environment variables:
*
* Example:
*
* Defined Variables :
* "variables" : {
* "looneyTunes" : {
* "character": "coyote",
* "category" : "guns",
* "item": "bomb"
* },
* "cartoonNetwork" : {
* "character": "dexter",
* "category" : "laboratory",
* "item": "door"
* }
* }
*
* Transforms them for use :
* "variables" : {
* "lonneyTunes___character": "coyote",
* "lonneyTunes___category": "guns",
* "lonneyTunes___item": "bomb",
* "cartoonNetwork___character": "dexter",
* "cartoonNetwork___category": "laboratory",
* "cartoonNetwork___item": "door"
* }
*
*/
const formatVarsEnv = (vars, pre_name = "", vars_to_env = {}) => {
for (const propertyObject in vars) {
let originalPropertyObject = vars[propertyObject];
if (typeof originalPropertyObject == "object") {
let concatAntecesor = pre_name.concat(propertyObject, "___");
vars_to_env = {...formatVarsEnv(originalPropertyObject, concatAntecesor, vars_to_env )};
} else {
let new_var = `
{"${pre_name.length > 0 ? pre_name : ""}${propertyObject}":"${vars[propertyObject]}"}
`;
new_var = JSON.parse(new_var);
vars_to_env = { ...vars_to_env, ...new_var };
}
}
return vars_to_env;
}
const formatVarsEnvOriginal = (vars) => {
let vars_to_env = {};
for (const propertyObject in vars) {
//key , value
console.log(propertyObject, "-+", vars[propertyObject].length, typeof vars[propertyObject], "+-");
/**
* If the property does not have an object assigned, the property and its
* value are used for the vars_to_env
*/
if (vars[propertyObject].length > 0) {
let new_var = `
{"${propertyObject}":"${vars[propertyObject]}"}
`;
new_var = JSON.parse(new_var)
vars_to_env = { ...vars_to_env, ...new_var }
}
/**
* If the property has an object assigned, the assigned object is iterated
* and the initial property is contacted with that of the contained object
* and assigning its value to this new property to add it to vars_to_env
*/
else {
for (const propertyValue in vars[propertyObject]) {
let new_var = `
{"${propertyObject}___${propertyValue}":"${vars[propertyObject][propertyValue]}"}
`;
new_var = JSON.parse(new_var)
vars_to_env = { ...vars_to_env, ...new_var }
}
}
}
return vars_to_env;
}
/**
*
* @param {string} variable Variable to get from environment variables
* @returns {string | number} Variable obtained from environment variables
*
* @description
* Gets the transformed environment variables
*
* How to use:
* Para las propiedades definidas:
* "variables" : {
* "lonneyTunes___character": "coyote",
* "lonneyTunes___category": "guns",
* "lonneyTunes___item": "bomb",
* "cartoonNetwork___character": "dexter",
* "cartoonNetwork___category": "laboratory",
* "cartoonNetwork___item": "door"
* }
*
* In case you want to get the "lonneyTunes___character" property:
*
* Call the function with the format: object.key
*
* Example :
*
* Run function : getVariable('lonneyTunes.character')
*
* This returns : "coyote"
*
*/
const getVariable = (variable) => {
let var_search = variable.replaceAll('.', '___');
var_search = process.env[var_search];
return var_search
}
/**
*
* @param {array} results Test results array[object]
* @returns {object} Order test results
*
* @description
* Sort the testResults alphabetically at the first level
*/
const sortTestResults = (results) => {
if (!results) {
return "You must send an array with data";
};
if (results.length === 0) {
return "The array must contain data";
};
// Return result if it only has one content
if (results.length === 1)
return results;
// Get the result object
let object = results.slice(0);
// Define the type of separator according to the system
const OS_SPLIT = os.type() === "Windows_NT" ? "\\" : "/";
// Get the results in alphabetical order at the first level
object.sort((firstElement, secondElement) => {
let firstOriginalPathTestFile = firstElement.name.split(OS_SPLIT);
let secondOriginalPathTestFile = secondElement.name.split(OS_SPLIT);
let countFirstOriginalPathTestFile = firstOriginalPathTestFile.length;
let countSecondOriginalPathTestFile = secondOriginalPathTestFile.length;
const testsIndex = firstOriginalPathTestFile.indexOf('tests');
let first = firstOriginalPathTestFile.slice(testsIndex + 1);
let second = secondOriginalPathTestFile.slice(testsIndex + 1);
if(first == -1 || second == - 1) {
return 0;
}
first = first[0].toLowerCase()
second = second[0].toLowerCase()
if (first < second) {
return -1
}else if (first > second) {
return 1
}else {
// Ordered for the second level
let featureNameFirst = firstOriginalPathTestFile.slice(testsIndex + 2, countFirstOriginalPathTestFile - 1).join("/");
let featureNameSecond = secondOriginalPathTestFile.slice(testsIndex + 2, countSecondOriginalPathTestFile - 1).join("/");
if(!featureNameFirst || !featureNameSecond) {
return 0;
}
featureNameFirst = featureNameFirst.toLowerCase();
featureNameSecond = featureNameSecond.toLowerCase();
return featureNameFirst < featureNameSecond ? -1 : featureNameFirst > featureNameSecond ? 1 : 0;
}
// return first < second ? -1 : first > second ? 1 : 0
});
return object;
}
/**
*
* @param {object} driver Selenium driver
* @param {string} filePath Path where the test is executed
* @param {string} screenshotAlias
* @param {string} error_screen
*
* @description
* Take a screenshot of the window that is being navigated with the driver,
* save this capture in screenshots grouped by the first column of the test
*/
const takeScreenshot = async ({ driver, filePath, screenshotAlias, error_screen = false }) => {
const SPLIT_PATH = os.type() === 'Windows_NT' ? '\\' : '/';
const TEST_UUID = getVariable('TEST_UUID');
const EXECUTION_SUITE = getVariable('EXECUTION_SUITE');
const DEFAULT_PATH =
error_screen
? `.${SPLIT_PATH}report${SPLIT_PATH}${TEST_UUID}${SPLIT_PATH}${EXECUTION_SUITE}${SPLIT_PATH}screenshots`
: `.${SPLIT_PATH}screenshots`;
// Get the execution path of the test and add the folder for the test id
let file_path = filePath.split(SPLIT_PATH);
let tests_index = file_path.indexOf('tests');
file_path = file_path.slice(tests_index + 1);
file_path.unshift(TEST_UUID);
// Take the screenshot
const screenshot = await driver.takeScreenshot();
/**
* File name : create a sanitized file name from screenshot alias
*/
const file = `${getCleanedString(screenshotAlias)}.jpg`;
// Verify that the default folder for screenshots exists
if (!fs.existsSync(DEFAULT_PATH))
await fs.promises.mkdir(DEFAULT_PATH, { recursive: true })
// Build the screenshot path
let screenshot_test_path = '';
if (!error_screen) {
file_path.map((el) => {
screenshot_test_path += `${SPLIT_PATH}${el}`
})
} else {
file_path.map((el, index) => {
if (index > 0) {
screenshot_test_path += `${SPLIT_PATH}${el}`
}
})
}
// Create the folders to save the screenshot
await fs.promises.mkdir(path.join(DEFAULT_PATH, screenshot_test_path), { recursive: true })
// Create the file in the defined path
fs.writeFile(
`${DEFAULT_PATH}${screenshot_test_path}${SPLIT_PATH}${file}`,
await screenshot,
{ encoding: 'base64' },
(err) => {
if (err) {
console.log(err)
} else {
console.log('File written successfully\n', `${file}`)
}
}
)
}
/**
*
* @param {string | number} suiteIdentifier Test Suite Identifier
* @param {number} virtualUser Test run number
* @param {string} testUuid Running test identifier
* @param {Object} testOptions Options for the general test
* @param {string} rootPath Path of root of your project
*
*
* @description
* Adapt the test results to three columns and then call the function
* to create the web report
*/
const createReportHTML = async (suiteIdentifier, virtualUser, testOptions, testUuid, rootPath) => {
if (!suiteIdentifier) {
return 'The suiteIdentifier must be a real value { string | number | string && number }, diferent undefined, null, etc.';
}
if (virtualUser === undefined || virtualUser === null) {
return 'The virtualUser must be a real value { string | number | string && number }, diferent undefined, null, etc.';
}
if (!testOptions) {
return 'The testOptions must be a real value { Object }, diferent undefined, null, etc.';
}
if (!testUuid) {
return 'The testUuid must be a real value { string | number | string && number }, diferent undefined, null, etc.';
}
// const rootPath = path.dirname(packPath(("")));
/**
* @description
* Receive the seconds and return in hh:mm:ss format
*
* @returns {string}
*/
function __secondsToDurationStr(seconds) {
let hour = Math.floor(seconds / 3600);
hour = (hour < 10) ? '0' + hour : hour;
let minute = Math.floor((seconds / 60) % 60);
minute = (minute < 10) ? '0' + minute : minute;
let second = Math.floor(seconds % 60);
second = (second < 10) ? '0' + second : second;
return hour + ':' + minute + ':' + second;
}
const { reportWeb, columnNames } = testOptions;
const SPLIT_PATH = os.type() === "Windows_NT" ? "\\" : "/";
const report_data_json = {};
let test_exec_time = 0;
/**
* Verify that the report is generated in HTML
*/
if (!reportWeb)
return "The report web is not required here";
if (!fileExists(path.join(rootPath,`${suiteIdentifier}-jest-output.json`))){
return "There isnt jest output test";
}
const jestOutput = require( path.join(rootPath,`${suiteIdentifier}-jest-output.json`));
let testResults = sortTestResults(jestOutput.testResults);
const dataToReport = [];
/**
* Preparar los datos para el reporte web
*/
for (const testResult of testResults) {
const path = testResult.name.split(SPLIT_PATH)
const testIndex = path.indexOf("tests");
if (testIndex === -1) {
console.log(
`${path[path.length - 1]} test is not inside the correct directory.`
.yellow
);
continue;
}
/**
* Acumular la duración de ejecución de los test
*/
test_exec_time += (testResult.endTime - testResult.startTime)
let tableValues = path.slice(testIndex + 1, path.length);
/**
* Adjust the columns for the web report
*/
let fixedColumns = [];
/**
* The first is always used for column 'C1'
*/
fixedColumns.push((tableValues.length > 1 && columnNames.length > 1) ? tableValues[0] : "");
/**
* Iterate and concatenate the folder to fixed
*/
let dynamicColumn = '';
for (let index = 0; index < tableValues.length - 1; index++) {
index === 0 ? '' : dynamicColumn += '/';
dynamicColumn += `${tableValues[index]}`;
}
// deleted the first dir
let dynamicColumnArr = dynamicColumn.split('/')
// if (dynamicColumnArr.length > 1) {
dynamicColumnArr.shift();
// }
dynamicColumn = dynamicColumnArr.join('/')
/**
* Add the fixed column 'C2'
*/
fixedColumns.push(dynamicColumn);
/**
* Add the value of the last column 'C3'
*/
fixedColumns.push(tableValues[tableValues.length - 1].split('.test')[0]);
if (fixedColumns) {
/**
* Build the array for the errors
*/
let error_log = [];
for (const assertionResult of testResult.assertionResults) {
const {
ancestorTitles,
failureMessages,
title
} = assertionResult;
let error_image_name = getCleanedString(`${ancestorTitles} - ${title}`)
let error_image_path = 'screenshots';
tableValues.map(el => {
error_image_path += `/${el}`;
})
error_image_path += `/${error_image_name}.jpg`
if (failureMessages.length > 0) {
error_log.push({
error_log: `${title}\n${failureMessages[0]}`,
screenshot: error_image_path.replaceAll(' ', '%20')
})
}
}
let value = [
...fixedColumns,
...[
testResult.status === "passed"
? testResult.status
: testResult.status
],
error_log
];
dataToReport.push(value);
}
}
/**
* Create the web report
*/
report_data_json.duration = __secondsToDurationStr(test_exec_time / 1000)
report_data_json.columnsData = dataToReport;
report_data_json.report_name = testUuid;
report_data_json.passed = jestOutput.numPassedTests;
report_data_json.failed = jestOutput.numFailedTests;
report_data_json.total = jestOutput.numTotalTests;
report_data_json.date = new Date(jestOutput.startTime).toString()
try {
const index =
fs.readFileSync(
path.resolve(__dirname, "ReportTemplate/index.html"),
{ encoding: 'utf8' }
);
let result = index.replace(/#data_report/g, JSON.stringify(report_data_json));
result = result.replace(/#columns_name/g, JSON.stringify(columnNames));
result = result.replace(/#report_duration/g, report_data_json.duration);
// Verify that the default folder for report exists
if (!fs.existsSync(`.${SPLIT_PATH}report${SPLIT_PATH}${testUuid}${SPLIT_PATH}${virtualUser}${SPLIT_PATH}`)) {
await fs.promises.mkdir(
`.${SPLIT_PATH}report${SPLIT_PATH}${testUuid}${SPLIT_PATH}${virtualUser}${SPLIT_PATH}`,
{ recursive: true }
);
}
fs.writeFileSync(
`.${SPLIT_PATH}report${SPLIT_PATH}${testUuid}${SPLIT_PATH}${virtualUser}${SPLIT_PATH}index.html`,
result,
'utf-8'
);
return "Created report";
} catch (err) {
console.log(err)
return err;
}
};
function fileExists(path) {
try {
return fs.statSync(path).isFile();
} catch (e) {
return false;
}
}
/**
*
* @param {string | number} suiteIdentifier Test Suite Identifier
* @param {number} virtualUser Test run number
* @param {string} testUuid Running test identifier
* @param {string} rootPath Path of the root folder of the project from which it is called
* @param {Array} columnNames Name of table headers
* @param {string} reportMode Type of report mode ( dynamicDeep | normal )
*
* @description Print the report table
* @returns Table || string
*/
const createTable = async (suiteIdentifier, virtualUser, testUuid, rootPath, columnNames, reportMode) => {
if (!suiteIdentifier) {
return 'The suiteIdentifier must be a real value, diferent undefined, null, etc.';
}
const pathJsonFile = path.join(rootPath, `${suiteIdentifier}-jest-output.json`);
if (!fileExists(pathJsonFile)) {
return `The file that contains jest result not exist`;
}
const jestOutput = require(pathJsonFile);
let date = new Date();
console.info(
`\n# ${virtualUser} Jest report : ${suiteIdentifier}\n`
.yellow?.bold
);
console.info(
`Test uuid: ${testUuid}\n`
.yellow?.bold
);
console.info(
`Test timestamp: ${date.toString()}\n`
.yellow?.bold
);
const tableHead = [];
const colWidths = [];
tableHead.push("#".blue);
colWidths.push(5);
columnNames.forEach((column, index) => {
let columnWidth = 35;
if (reportMode === "dynamicDeep")
columnWidth = index !== 1 ? 35 : 50
tableHead.push(`${column}`.blue);
colWidths.push(columnWidth);
});
tableHead.push("Status".blue);
colWidths.push(15);
const table = new Table({
head: [...tableHead],
colWidths: [...colWidths],
colors: true,
}); //* Creates the table
let testResultIndex = 0;
let testResults = sortTestResults(jestOutput.testResults)
for (const testResult of testResults) {
const path =
os.type() === "Windows_NT"
? testResult.name.split("\\")
: testResult.name.split("/");
const testIndex = path.indexOf("tests");
if (testIndex === -1) {
console.log(
`${path[path.length - 1]} test is not inside the correct directory.`
.yellow
);
testResultIndex++;
continue;
}
let tableValues = path.slice(testIndex + 1, path.length);
if (tableValues.length !== columnNames.length && reportMode !== 'dynamicDeep') {
console.log(
`${path[path.length - 1]} does not meet your columns definition.`.yellow
);
}
/**
* If the type of report is dynamic, adjust depth of folders in columns
*/
if (reportMode === 'dynamicDeep') {
let fixedColumns = [];
/**
* The first is always used for column 'C1'
*/
fixedColumns.push((tableValues.length > 1 && columnNames.length > 1) ? tableValues.shift() : "");
/**
* Iterate and concatenate the folder to fixed
*/
let dynamicColumn = ''
for (let index = 0; index < tableValues.length - 1; index++) {
index === 0 ? '' : dynamicColumn += '/';
dynamicColumn += `${tableValues[index]}`
}
/**
* Add the fixed column 'C2'
*/
fixedColumns.push(dynamicColumn)
/**
* Add the value of the last column 'C3'
*/
fixedColumns.push(tableValues.pop().split('.test')[0])
// Replace table value
tableValues = fixedColumns
}
const contentToPush = [];
contentToPush.push((testResultIndex + 1).toString());
for (let index = 0; index < columnNames.length; index++) {
if (tableValues[index]) {
contentToPush.push(tableValues[index]);
} else {
contentToPush.push("");
}
}
contentToPush.push(
testResult.status === "passed"
? testResult.status.green
: testResult.status.red
);
table.push([...contentToPush]);
testResultIndex++;
} //* Inserts data to the table
return table;
};
module.exports = {
formatVarsEnv,
getVariable,
sortTestResults,
takeScreenshot,
createReportHTML,
createTable,
fileExists
}