This repository has been archived by the owner on Oct 29, 2024. It is now read-only.
forked from canvaspixels/courgette
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·254 lines (214 loc) · 7.92 KB
/
index.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
#! /usr/bin/env node
const fs = require('fs');
const path = require('path');
const { argv } = require('yargs');
const Table = require('cli-table');
require('colors');
const os = require('os');
const imagemin = require('imagemin');
const imageminPngquant = require('imagemin-pngquant');
const generateScreenshotViewer = require('./uiTestHelpers/generateScreenshotViewer');
// eslint-disable-next-line
const confFile = argv.confFile || process.env.confFile || 'courgette-conf.js';
console.log('Loading confFile: ', confFile);
const { pomConfig } = require(path.resolve(confFile));
const { spawn } = require('child_process');
const cucumberHtmlReporter = require('cucumber-html-reporter');
const log = (...args) => {
console.log(...args);
};
log('Nom nom... off we go!');
const rmDir = function rmDir(dir, rmSelf) {
let files;
const isSelf = (rmSelf === undefined) ? true : rmSelf;
const directory = dir;
try {
files = fs.readdirSync(directory);
} catch (e) {
log('Directory not exist.');
return;
}
if (files.length > 0) {
files.forEach((x) => {
const newPath = path.join(directory, x);
if (fs.statSync(newPath).isDirectory()) {
rmDir(newPath);
} else {
fs.unlinkSync(newPath);
}
});
}
if (isSelf) {
// check if user want to delete the directory ir just the files in this directory
fs.rmdirSync(directory);
}
};
const outputPath = pomConfig.outputPath.startsWith('/') ? pomConfig.outputPath : path.join(process.cwd(), pomConfig.outputPath);
if (fs.existsSync(outputPath)) {
rmDir(outputPath);
}
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath);
}
const screenshotStepPath = (pomConfig.screenshotStepPath || 'stepDefinitionScreenshots');
const screenshotsDir = path.join(pomConfig.screenshotPath || pomConfig.outputPath, screenshotStepPath);
if (!fs.existsSync(screenshotsDir)) {
fs.mkdirSync(screenshotsDir);
}
const logPath = path.join(outputPath, 'test-result.log');
const logStream = fs.createWriteStream(logPath);
const cmd = path.join('node_modules', '.bin', `protractor${os.type().toLowerCase().includes('windows') ? '.cmd' : ''}`);
const args = [confFile];
const firstArg = process.argv && process.argv[2];
const tags = firstArg && firstArg.indexOf('--') !== 0 ? firstArg : null;
const spawnedProcess = spawn(cmd, args, {
env: Object.assign({}, process.env, {
tags: (tags || argv.tags || '').replace(',', ' or '),
confFile,
showStepDefinitionUsage: process.env.showStepDefinitionUsage || argv.showStepDefinitionUsage || '',
}),
});
const cucumberHtmlReporterConfig = Object.assign({
theme: 'bootstrap',
jsonDir: outputPath,
output: path.join(outputPath, 'cucumberReport.html'),
reportSuiteAsScenarios: true,
launchReport: false,
}, pomConfig.cucumberHtmlReporterConfig);
const printCukeErrors = (el, step, feature) => {
const red = '\x1b[31m%s\x1b[0m';
const yellow = '\x1b[33m%s\x1b[0m';
if (step.result.error_message) {
log(red, `\n------------------ Scenario Error --------------- ${el.name}`);
log(yellow, `Tags: ${el.tags.map((tag) => tag.name).join(', ')}`);
log(yellow, `Step: ${step.keyword}${step.name}`);
log(yellow, `Location: ${step.match.location}`);
log(yellow, `Feature: ${feature.uri}${el.tags && el.tags.length ? `:${el.tags[el.tags.length - 1].line}` : ''}`);
log(yellow, `Error message: ${step.result.error_message}`);
} else if (step.result.status === 'undefined') {
log(red, `\n------------------ Scenario Undefined Step Definition --------------- ${el.name}`);
log(yellow, `Tags: ${el.tags.map((tag) => tag.name).join(', ')}`);
log(yellow, `Step: ${step.keyword}${step.name}`);
}
if (step.result.error_message || step.result.status === 'undefined') {
const screenshotStep = el.steps.find((stp) =>
stp.keyword === 'After' &&
stp.match &&
stp.match.location &&
stp.match.location.includes('attachScreenshotAfter'));
const screenshotFilePath = screenshotStep &&
screenshotStep.embeddings &&
screenshotStep.embeddings
.find((embed) =>
embed.data && embed.data.includes('ScreenshotFilePath'));
log('-----SCREENSHOT - hold cmd (on mac) and click .png below if using iterm ----');
log(screenshotFilePath ? screenshotFilePath.data : '');
log('---------');
}
};
const loopThroughReport = () => new Promise((resolve, reject) => {
try {
// eslint-disable-next-line
const features = JSON.parse(fs.readFileSync(`${cucumberHtmlReporterConfig.output}.json`, 'utf8'));
// const elements = features.reduce((arr, scenario) => arr.concat(scenario.elements), []);
let successCount = 0;
let failureCount = 0;
let totalCount = 0;
features.forEach((feature) => {
feature.elements.forEach((el) => {
let scenarioStatus = 'passed';
el.steps.forEach((step) => {
const { status } = step.result;
const { keyword } = step;
if (!keyword.includes('After') && !keyword.includes('Before')) {
if (status === 'failed' || scenarioStatus !== 'failed') {
scenarioStatus = status;
}
}
printCukeErrors(el, step, feature);
return step.result.status;
});
if (scenarioStatus === 'passed') {
successCount += 1;
} else {
failureCount += 1;
}
totalCount += 1;
});
});
resolve({ successCount, failureCount, totalCount });
} catch (e) {
reject(e);
}
});
const output = (data) => {
log(data.toString());
// eslint-disable-next-line
logStream.write(data.toString().replace(/\x1b\[\d\dm/g, ''));
};
const deleteEmptyJSONS = (jsonOutputPath) => {
fs.readdirSync(jsonOutputPath).forEach((file) => {
if (file.includes('.json')) {
const filePath = path.join(jsonOutputPath, file);
const fileContents = fs.readFileSync(filePath, 'utf8');
if (fileContents === '[]') {
console.log('deleting empty file: ', file);
fs.unlinkSync(filePath);
}
}
});
};
const outputDirContainsJsons = (jsonOutputPath) => {
let containsJsons = false;
fs.readdirSync(jsonOutputPath).forEach((file) => {
if (file.includes('.json')) {
containsJsons = true;
}
});
return containsJsons;
};
spawnedProcess.stdout.on('data', output);
spawnedProcess.stderr.on('data', output);
spawnedProcess.on('exit', async () => {
logStream.end();
deleteEmptyJSONS(pomConfig.outputPath);
if (!outputDirContainsJsons(pomConfig.outputPath)) {
console.log('-----------------------------------');
console.error('NO COURGETTE SCENARIOS HAVE BEEN RUN, MAYBE YOU HAVE AN @ignore TAG ON THE ONE YOU’RE TRYING TO RUN?');
console.log('-----------------------------------');
process.exitCode = 1;
return;
}
cucumberHtmlReporter.generate(cucumberHtmlReporterConfig);
generateScreenshotViewer();
const { successCount, failureCount, totalCount } = await loopThroughReport();
const table = new Table({
head: [
'Total Scenarios'.white,
'Successful'.green,
'Failures'.red,
],
});
table.push([totalCount, `${successCount}`.green, `${failureCount}`.red]);
log('');
log(table.toString());
if (pomConfig.minifyPng !== false) {
const minifyQuality = typeof pomConfig.minifyPng === 'string' ? pomConfig.minifyPng : '0.6-0.8';
const quality = minifyQuality.split('-').map((num) => parseFloat(num));
const imageminConf = {
plugins: [imageminPngquant({ quality })],
};
const minifyOutputPath = pomConfig.screenshotPath || pomConfig.outputPath;
await imagemin(
[pomConfig.minifyPathGlob || `${minifyOutputPath}/*.png`],
pomConfig.minifyPathOutput || 'uiTestResult',
imageminConf,
);
await imagemin(
[pomConfig.minifyStepPathGlob || `${minifyOutputPath}/${screenshotStepPath}/*.png`],
pomConfig.minifyStepPathOutput || 'uiTestResult/stepDefinitionScreenshots',
imageminConf,
);
}
process.exitCode = totalCount === successCount ? 0 : 1;
});