forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun-example-e2e.js
443 lines (391 loc) · 15.6 KB
/
run-example-e2e.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
const path = require('canonical-path');
const fs = require('fs-extra');
const argv = require('yargs').argv;
const globby = require('globby');
const xSpawn = require('cross-spawn');
const treeKill = require('tree-kill');
const shelljs = require('shelljs');
const findFreePort = require('find-free-port');
shelljs.set('-e');
// Set `CHROME_BIN` as an environment variable for Karma to pick up in unit tests.
process.env.CHROME_BIN = require('puppeteer').executablePath();
const AIO_PATH = path.join(__dirname, '../../');
const SHARED_PATH = path.join(__dirname, '/shared');
const EXAMPLES_PATH = path.join(AIO_PATH, './content/examples/');
const PROTRACTOR_CONFIG_FILENAME = path.join(__dirname, './shared/protractor.config.js');
const SJS_SPEC_FILENAME = 'e2e-spec.ts';
const CLI_SPEC_FILENAME = 'e2e/src/app.e2e-spec.ts';
const EXAMPLE_CONFIG_FILENAME = 'example-config.json';
const DEFAULT_CLI_EXAMPLE_PORT = 4200;
const DEFAULT_CLI_SPECS_CONCURRENCY = 1;
const IGNORED_EXAMPLES = [];
const fixmeIvyExamples = [];
if (!argv.viewengine) {
IGNORED_EXAMPLES.push(...fixmeIvyExamples);
}
/**
* Run Protractor End-to-End Tests for Doc Samples
*
* Flags
* --filter to filter/select _example app subdir names
* e.g. --filter=foo // all example apps with 'foo' in their folder names.
*
* --setup to run yarn install, copy boilerplate and update webdriver
* e.g. --setup
*
* --local to use the locally built Angular packages, rather than versions from npm
* Must be used in conjunction with --setup as this is when the packages are copied.
* e.g. --setup --local
*
* --viewengine to turn on `ViewEngine` mode
*
* --shard to shard the specs into groups to allow you to run them in parallel
* e.g. --shard=0/2 // the even specs: 0, 2, 4, etc
* e.g. --shard=1/2 // the odd specs: 1, 3, 5, etc
* e.g. --shard=1/3 // the second of every three specs: 1, 4, 7, etc
*
* --cliSpecsConcurrency Amount of CLI example specs that should be executed concurrently.
* By default runs specs sequentially.
*
* --retry to retry failed tests (useful for overcoming flakes)
* e.g. --retry 3 // To try each test up to 3 times.
*/
function runE2e() {
if (argv.setup) {
// Run setup.
console.log('runE2e: setup boilerplate');
const installPackagesCommand = `example-use-${argv.local ? 'local' : 'npm'}`;
const addBoilerplateCommand = `boilerplate:add${argv.viewengine ? ':viewengine' : ''}`;
shelljs.exec(`yarn ${installPackagesCommand}`, {cwd: AIO_PATH});
shelljs.exec(`yarn ${addBoilerplateCommand}`, {cwd: AIO_PATH});
}
const outputFile = path.join(AIO_PATH, './protractor-results.txt');
return Promise.resolve()
.then(
() => findAndRunE2eTests(
argv.filter, outputFile, argv.shard,
argv.cliSpecsConcurrency || DEFAULT_CLI_SPECS_CONCURRENCY, argv.retry || 1))
.then((status) => {
reportStatus(status, outputFile);
if (status.failed.length > 0) {
return Promise.reject('Some test suites failed');
}
})
.catch(function(e) {
console.log(e);
process.exitCode = 1;
});
}
// Finds all of the *e2e-spec.tests under the examples folder along with the corresponding apps
// that they should run under. Then run each app/spec collection sequentially.
function findAndRunE2eTests(filter, outputFile, shard, cliSpecsConcurrency, maxAttempts) {
const shardParts = shard ? shard.split('/') : [0, 1];
const shardModulo = parseInt(shardParts[0], 10);
const shardDivider = parseInt(shardParts[1], 10);
// create an output file with header.
const startTime = new Date().getTime();
let header = `Doc Sample Protractor Results on ${new Date().toLocaleString()}\n`;
header += ` Filter: ${filter ? filter : 'All tests'}\n\n`;
fs.writeFileSync(outputFile, header);
const status = {passed: [], failed: []};
const updateStatus = (specDescription, passed) => {
const arr = passed ? status.passed : status.failed;
arr.push(specDescription);
};
const runTest = async (specPath, testFn) => {
let attempts = 0;
let passed = false;
while (true) {
attempts++;
passed = await testFn();
if (passed || (attempts >= maxAttempts)) break;
}
updateStatus(`${specPath} (attempts: ${attempts})`, passed);
};
return getE2eSpecs(EXAMPLES_PATH, filter)
.then(e2eSpecPaths => {
console.log('All e2e specs:');
logSpecs(e2eSpecPaths);
Object.keys(e2eSpecPaths).forEach(key => {
const value = e2eSpecPaths[key];
e2eSpecPaths[key] = value.filter((p, index) => index % shardDivider === shardModulo);
});
console.log(`E2e specs for shard ${shardParts.join('/')}:`);
logSpecs(e2eSpecPaths);
return e2eSpecPaths.systemjs
.reduce(
async (prevPromise, specPath) => {
await prevPromise;
const examplePath = path.dirname(specPath);
const testFn = () => runE2eTestsSystemJS(examplePath, outputFile);
await runTest(examplePath, testFn);
},
Promise.resolve())
.then(async () => {
const specQueue = [...e2eSpecPaths.cli];
// Determine free ports for the amount of pending CLI specs before starting
// any tests. This is necessary because ports can stuck in the "TIME_WAIT"
// state after others specs which used that port exited. This works around
// this potential race condition which surfaces on Windows.
const ports = await findFreePort(4000, 6000, '127.0.0.1', specQueue.length);
// Enable buffering of the process output in case multiple CLI specs will
// be executed concurrently. This means that we can can print out the full
// output at once without interfering with other CLI specs printing as well.
const bufferOutput = cliSpecsConcurrency > 1;
while (specQueue.length) {
const chunk = specQueue.splice(0, cliSpecsConcurrency);
await Promise.all(chunk.map(testDir => {
const port = ports.pop();
const testFn = () => runE2eTestsCLI(testDir, outputFile, bufferOutput, port);
return runTest(testDir, testFn);
}));
}
});
})
.then(() => {
const stopTime = new Date().getTime();
status.elapsedTime = (stopTime - startTime) / 1000;
return status;
});
}
// Start the example in appDir; then run protractor with the specified
// fileName; then shut down the example.
// All protractor output is appended to the outputFile.
// SystemJS version
function runE2eTestsSystemJS(appDir, outputFile) {
const config = loadExampleConfig(appDir);
const appBuildSpawnInfo = spawnExt('yarn', [config.build], {cwd: appDir});
const appRunSpawnInfo = spawnExt('yarn', [config.run, '-s'], {cwd: appDir}, true);
let run = runProtractorSystemJS(appBuildSpawnInfo.promise, appDir, appRunSpawnInfo, outputFile);
// Only run AOT tests in ViewEngine mode. The current AOT setup does not work in Ivy.
// See https://github.com/angular/angular/issues/35989.
if (argv.viewengine && fs.existsSync(appDir + '/aot/index.html')) {
run = run.then((ok) => ok && runProtractorAoT(appDir, outputFile));
}
return run;
}
function runProtractorSystemJS(prepPromise, appDir, appRunSpawnInfo, outputFile) {
const specFilename = path.resolve(`${appDir}/${SJS_SPEC_FILENAME}`);
return prepPromise
.catch(function() {
const emsg = `Application at ${appDir} failed to transpile.\n\n`;
console.log(emsg);
fs.appendFileSync(outputFile, emsg);
return Promise.reject(emsg);
})
.then(function() {
let transpileError = false;
// Start protractor.
console.log(`\n\n=========== Running aio example tests for: ${appDir}`);
const spawnInfo = spawnExt(
'yarn',
[
'protractor', PROTRACTOR_CONFIG_FILENAME, `--specs=${specFilename}`,
'--params.appDir=' + appDir, '--params.outputFile=' + outputFile
],
{cwd: SHARED_PATH});
spawnInfo.proc.stderr.on('data', function(data) {
transpileError = transpileError || /npm ERR! Exit status 100/.test(data.toString());
});
return spawnInfo.promise.catch(function() {
if (transpileError) {
const emsg = `${specFilename} failed to transpile.\n\n`;
console.log(emsg);
fs.appendFileSync(outputFile, emsg);
}
return Promise.reject();
});
})
.then(
function() {
return finish(appRunSpawnInfo.proc.pid, true);
},
function() {
return finish(appRunSpawnInfo.proc.pid, false);
});
}
function finish(spawnProcId, ok) {
// Ugh... proc.kill does not work properly on windows with child processes.
// appRun.proc.kill();
treeKill(spawnProcId);
return ok;
}
// Run e2e tests over the AOT build for projects that examples it.
function runProtractorAoT(appDir, outputFile) {
fs.appendFileSync(outputFile, '++ AoT version ++\n');
const aotBuildSpawnInfo = spawnExt('yarn', ['build:aot'], {cwd: appDir});
let promise = aotBuildSpawnInfo.promise;
const copyFileCmd = 'copy-dist-files.js';
if (fs.existsSync(appDir + '/' + copyFileCmd)) {
promise = promise.then(() => spawnExt('node', [copyFileCmd], {cwd: appDir}).promise);
}
const aotRunSpawnInfo = spawnExt('yarn', ['serve:aot'], {cwd: appDir}, true);
return runProtractorSystemJS(promise, appDir, aotRunSpawnInfo, outputFile);
}
// Start the example in appDir; then run protractor with the specified
// fileName; then shut down the example.
// All protractor output is appended to the outputFile.
// CLI version
function runE2eTestsCLI(appDir, outputFile, bufferOutput, port) {
if (!bufferOutput) {
console.log(`\n\n=========== Running aio example tests for: ${appDir}`);
}
// `--no-webdriver-update` is needed to preserve the ChromeDriver version already installed.
const config = loadExampleConfig(appDir);
const testCommands = config.tests || [{
cmd: 'yarn',
args: [
'e2e',
'--prod',
'--protractor-config=e2e/protractor-puppeteer.conf.js',
'--no-webdriver-update',
'--port={PORT}',
],
}];
let bufferedOutput = `\n\n============== AIO example output for: ${appDir}\n\n`;
const e2eSpawnPromise = testCommands.reduce((prevSpawnPromise, {cmd, args}) => {
// Replace the port placeholder with the specified port if present. Specs that
// define their e2e test commands in the example config are able to use the
// given available port. This ensures that the CLI tests can be run concurrently.
args = args.map(a => a.replace('{PORT}', port || DEFAULT_CLI_EXAMPLE_PORT));
return prevSpawnPromise.then(() => {
const currSpawn = spawnExt(
cmd, args, {cwd: appDir}, false, bufferOutput ? msg => bufferedOutput += msg : undefined);
return currSpawn.promise.then(
() => Promise.resolve(finish(currSpawn.proc.pid, true)),
() => Promise.reject(finish(currSpawn.proc.pid, false)));
});
}, Promise.resolve());
return e2eSpawnPromise
.then(
() => {
fs.appendFileSync(outputFile, `Passed: ${appDir}\n\n`);
return true;
},
() => {
fs.appendFileSync(outputFile, `Failed: ${appDir}\n\n`);
return false;
})
.then(passed => {
if (bufferOutput) {
process.stdout.write(bufferedOutput);
}
return passed;
});
}
// Report final status.
function reportStatus(status, outputFile) {
let log = [''];
log.push('Suites ignored due to legacy guides:');
IGNORED_EXAMPLES.filter(example => !fixmeIvyExamples.find(ex => ex.startsWith(example)))
.forEach(function(val) {
log.push(' ' + val);
});
if (!argv.viewengine) {
log.push('');
log.push('Suites ignored due to breakage with Ivy:');
fixmeIvyExamples.forEach(function(val) {
log.push(' ' + val);
});
}
log.push('');
log.push('Suites passed:');
status.passed.forEach(function(val) {
log.push(' ' + val);
});
if (status.failed.length == 0) {
log.push('All tests passed');
} else {
log.push('Suites failed:');
status.failed.forEach(function(val) {
log.push(' ' + val);
});
}
log.push('\nElapsed time: ' + status.elapsedTime + ' seconds');
log = log.join('\n');
console.log(log);
fs.appendFileSync(outputFile, log);
}
// Returns both a promise and the spawned process so that it can be killed if needed.
function spawnExt(
command, args, options, ignoreClose = false, printMessage = msg => process.stdout.write(msg)) {
let proc;
const promise = new Promise((resolve, reject) => {
let descr = command + ' ' + args.join(' ');
let processOutput = '';
printMessage(`running: ${descr}\n`);
try {
proc = xSpawn.spawn(command, args, options);
} catch (e) {
console.log(e);
reject(e);
return {proc: null, promise};
}
proc.stdout.on('data', printMessage);
proc.stderr.on('data', printMessage);
proc.on('close', function(returnCode) {
printMessage(`completed: ${descr}\n\n`);
// Many tasks (e.g., tsc) complete but are actually errors;
// Confirm return code is zero.
returnCode === 0 || ignoreClose ? resolve(0) : reject(returnCode);
});
proc.on('error', function(data) {
printMessage(`completed with error: ${descr}\n\n`);
printMessage(`${data.toString()}\n`);
reject(data);
});
});
return {proc, promise};
}
function getE2eSpecs(basePath, filter) {
let specs = {};
return getE2eSpecsFor(basePath, SJS_SPEC_FILENAME, filter)
.then(sjsPaths => {
specs.systemjs = sjsPaths;
})
.then(() => {
return getE2eSpecsFor(basePath, CLI_SPEC_FILENAME, filter).then(cliPaths => {
return cliPaths.map(p => {
return p.replace(`${CLI_SPEC_FILENAME}`, '');
});
});
})
.then(cliPaths => {
specs.cli = cliPaths;
})
.then(() => specs);
}
// Find all e2e specs in a given example folder.
function getE2eSpecsFor(basePath, specFile, filter) {
// Only get spec file at the example root.
// The formatter doesn't understand nested template string expressions (honestly, neither do I).
// clang-format off
const e2eSpecGlob = `${filter ? `*${filter}*` : '*'}/${specFile}`;
// clang-format on
return globby(e2eSpecGlob, {cwd: basePath, nodir: true})
.then(
paths => paths.filter(file => !IGNORED_EXAMPLES.some(ignored => file.startsWith(ignored)))
.map(file => path.join(basePath, file)));
}
// Load configuration for an example. Used for SystemJS
function loadExampleConfig(exampleFolder) {
// Default config.
let config = {build: 'build', run: 'serve:e2e'};
try {
const exampleConfig = fs.readJsonSync(`${exampleFolder}/${EXAMPLE_CONFIG_FILENAME}`);
Object.assign(config, exampleConfig);
} catch (e) {
}
return config;
}
// Log the specs (for debugging purposes).
// `e2eSpecPaths` is of type: `{[type: string]: string[]}`
// (where `type` is `systemjs`, `cli, etc.)
function logSpecs(e2eSpecPaths) {
Object.keys(e2eSpecPaths).forEach(type => {
const paths = e2eSpecPaths[type];
console.log(` ${type.toUpperCase()}:`);
console.log(paths.map(p => ` ${p}`).join('\n'));
});
}
runE2e();