forked from Enase/serverless-mocha-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
538 lines (470 loc) · 17.5 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
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
'use strict';
/**
* serverless-mocha-plugin
* - a plugin for TDD with Serverless Framework
*/
const path = require('path');
const lambdaWrapper = require('lambda-wrapper');
const Mocha = require('mocha');
const chai = require('chai');
const ejs = require('ejs');
const fse = require('fs-extra');
const utils = require('./utils');
const BbPromise = require('bluebird');
const yamlEdit = require('yaml-edit');
const execSync = require('child_process').execSync;
const testTemplateFile = path.join('templates', 'test-template.ejs');
const functionTemplateFile = path.join('templates', 'function-template.ejs');
const validFunctionRuntimes = [
'aws-nodejs4.3',
'aws-nodejs6.10',
];
const humanReadableFunctionRuntimes = `${validFunctionRuntimes
.map(template => `"${template}"`).join(', ')}`;
class mochaPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
create: {
commands: {
test: {
usage: 'Create mocha tests for service / function',
lifecycleEvents: [
'test',
],
options: {
function: {
usage: 'Name of the function',
shortcut: 'f',
required: true,
},
path: {
usage: 'Path for the tests',
shortcut: 'p',
},
},
},
function: {
usage: 'Create a function into the service',
lifecycleEvents: [
'create',
],
options: {
function: {
usage: 'Name of the function',
shortcut: 'f',
required: true,
},
handler: {
usage: 'Handler for the function (e.g. --handler my-function/index.handler)',
required: true,
},
path: {
usage: 'Path for the tests (e.g. --path tests)',
shortcut: 'p',
},
httpEvent: {
usage: 'Add an http endpoint (e.g. --httpEvent "verb relative-path")',
},
},
},
},
},
invoke: {
usage: 'Invoke mocha tests for service / function',
commands: {
test: {
usage: 'Invoke test(s)',
lifecycleEvents: [
'test',
],
options: {
function: {
usage: 'Name of the function',
shortcut: 'f',
},
reporter: {
usage: 'Mocha reporter to use',
shortcut: 'R',
},
'reporter-options': {
usage: 'Options for mocha reporter',
shortcut: 'O',
},
grep: {
usage: 'Run only matching tests',
shortcut: 'G',
},
live: {
usage: 'Run the Lambda function in AWS',
shortcut: 'l',
},
root: {
usage: 'Service root for running tests',
shortcut: 'r',
},
path: {
usage: 'Path for the tests for running tests in other than default "test" folder',
},
compilers: {
usage: 'Compiler to use on Mocha',
},
},
},
},
},
};
this.hooks = {
'create:test:test': () => {
BbPromise.bind(this)
.then(this.createTest);
},
'invoke:test:test': () => {
BbPromise.bind(this)
.then(this.runTests);
},
'create:function:create': () => {
BbPromise.bind(this)
.then(this.createFunction)
.then(this.createTest);
},
};
}
// Run pre/postTest scriprs
runScripts(testStage) {
const myModule = this;
return new Promise((succeed) => {
const cmds = myModule.config[testStage] || [];
cmds.forEach((cmd) => {
this.serverless.cli.log(`Run command: ${cmd}`);
const cmdOut = execSync(cmd);
if (process.env.SLS_DEBUG) {
const output = new Buffer(cmdOut, 'base64').toString();
this.serverless.cli.log(output);
}
});
succeed();
});
}
runTests() {
const myModule = this;
const funcOption = this.options.f || this.options.function || [];
const testsPath = this.options.p || this.options.path || utils.getTestsFolder();
const testFileMap = {};
const mocha = new Mocha({
timeout: 6000,
});
const stage = this.options.stage;
const region = this.options.region;
let funcNames = [];
if (typeof funcOption === 'string') {
funcNames = [funcOption];
} else if (funcOption.length > 0) {
funcNames = funcOption;
}
this.serverless.service.load({
stage,
region,
})
.then((inited) => {
myModule.config = (inited.custom || {})['serverless-mocha-plugin'] || {};
// Verify that the service runtime matches with the current runtime
let nodeVersion;
if (typeof process.versions === 'object') {
nodeVersion = process.versions.node;
} else {
nodeVersion = process.versions;
}
nodeVersion = nodeVersion.replace(/\.[^.]*$/, '');
if (`nodejs${nodeVersion}` !== inited.provider.runtime) {
let errorMsg = `Tests being run with nodejs${nodeVersion}, `;
errorMsg = `${errorMsg} service is using ${inited.provider.runtime}.`;
errorMsg = `${errorMsg} Tests may not be reliable.`;
this.serverless.cli.log(errorMsg);
}
myModule.serverless.environment = inited.environment;
const vars = new myModule.serverless.classes.Variables(myModule.serverless);
vars.populateService(this.options)
.then(() => myModule.runScripts('preTestCommands'))
.then(() => myModule.getFunctions(funcNames))
.then((funcs) => utils.getTestFiles(funcs, testsPath, funcNames))
.then((funcs) => {
// Run the tests that were actually found
funcNames = Object.keys(funcs);
if (funcNames.length === 0) {
return myModule.serverless.cli.log('No tests to run');
}
funcNames.forEach((func) => {
if (funcs[func].mochaPlugin) {
if (funcs[func].handler) {
// Map only functions
testFileMap[func] = funcs[func];
utils.setEnv(this.serverless, func);
} else {
utils.setEnv(this.serverless);
}
const testPath = funcs[func].mochaPlugin.testPath;
if (fse.existsSync(testPath)) {
mocha.addFile(testPath);
}
}
});
const reporter = myModule.options.reporter;
if (reporter !== undefined) {
const reporterOptions = {};
if (myModule.options['reporter-options'] !== undefined) {
myModule.options['reporter-options'].split(',').forEach((opt) => {
const L = opt.split('=');
if (L.length > 2 || L.length === 0) {
throw new Error(`invalid reporter option "${opt}"`);
} else if (L.length === 2) {
reporterOptions[L[0]] = L[1];
} else {
reporterOptions[L[0]] = true;
}
});
}
mocha.reporter(reporter, reporterOptions);
}
if (myModule.options.grep) {
mocha.grep(myModule.options.grep);
}
// set the SERVERLESS_TEST_ROOT variable to define root for tests
let rootFolder = this.serverless.config.servicePath;
if (myModule.options.root) {
rootFolder = myModule.options.root;
myModule.serverless.cli.log(`Run tests against code under '${rootFolder}'`);
}
// Use full paths to ensure that the code is correctly required in tests
if (!path.isAbsolute(rootFolder)) {
const currDir = process.cwd();
rootFolder = path.join(currDir, rootFolder);
}
/* eslint-disable dot-notation */
process.env['SERVERLESS_TEST_ROOT'] = rootFolder;
if (myModule.options.live) {
process.env['SERVERLESS_MOCHA_PLUGIN_LIVE'] = true;
process.env['SERVERLESS_MOCHA_PLUGIN_REGION'] = region || inited.provider.region;
process.env['SERVERLESS_MOCHA_PLUGIN_SERVICE'] = inited.service;
process.env['SERVERLESS_MOCHA_PLUGIN_STAGE'] = stage || inited.provider.stage;
}
/* eslint-enable dot-notation */
const compilers = myModule.options.compilers;
if (typeof compilers !== 'undefined') {
const extensions = ['js'];
myModule.options.compilers.split(',').filter(e => e !== '').forEach(c => {
const split = c.split(/:(.+)/);
const ext = split[0];
let mod = split[1];
if (mod[0] === '.') {
mod = path.join(process.cwd(), mod);
}
require(mod); // eslint-disable-line global-require
extensions.push(ext);
});
}
mocha.run((failures) => {
process
.on('exit', () => {
myModule.runScripts('postTestCommands').then(() => {
process.exit(failures); // exit with non-zero status if there were failures
});
})
.on('test', (suite) => {
const testFuncName = utils.funcNameFromPath(suite.file);
// set env only for functions
if (testFileMap[testFuncName]) {
utils.setEnv(myModule.serverless, testFuncName);
} else {
utils.setEnv(myModule.serverless);
}
});
});
return null;
}, error => myModule.serverless.cli.log(error));
});
}
createTest() {
const funcName = this.options.f || this.options.function;
const testsRootFolder = this.options.p || this.options.path;
const myModule = this;
utils.createTestFolder(testsRootFolder).then(() => {
const testFilePath = utils.getTestFilePath(funcName, testsRootFolder);
const func = myModule.serverless.service.functions[funcName];
const handlerParts = func.handler.split('.');
const funcPath = (`${handlerParts[0]}.js`).replace(/\\/g, '/');
const handler = handlerParts[handlerParts.length - 1];
fse.exists(testFilePath, (exists) => {
if (exists) {
myModule.serverless.cli.log(`Test file ${testFilePath} already exists`);
return (new Error(`File ${testFilePath} already exists`));
}
let templateFilenamePath = '';
if (this.serverless.service.custom &&
this.serverless.service.custom['serverless-mocha-plugin'] &&
this.serverless.service.custom['serverless-mocha-plugin'].testTemplate) {
templateFilenamePath = path.join(this.serverless.config.servicePath,
this.serverless.service.custom['serverless-mocha-plugin'].testTemplate);
}
fse.exists(templateFilenamePath, (exists2) => {
if (!exists2) {
templateFilenamePath = path.join(__dirname, testTemplateFile);
}
const templateString = utils.getTemplateFromFile(templateFilenamePath);
const content = ejs.render(templateString, {
functionName: funcName,
functionPath: funcPath,
handlerName: handler,
});
fse.writeFile(testFilePath, content, (err) => {
if (err) {
myModule.serverless.cli.log(`Creating file ${testFilePath} failed: ${err}`);
return new Error(`Creating file ${testFilePath} failed: ${err}`);
}
return myModule.serverless.cli.log(`serverless-mocha-plugin: created ${testFilePath}`);
});
});
return null;
});
});
}
// Helper functions
getFunctions(funcList) {
const myModule = this;
return new BbPromise((resolve) => {
const funcObjs = {};
const allFuncs = myModule.serverless.service.functions;
if (funcList.length === 0) {
return resolve(allFuncs);
}
let func;
funcList.forEach((funcName) => {
func = allFuncs[funcName];
if (func) {
funcObjs[funcName] = func;
} else {
myModule.serverless.cli.log(`Warning: Could not find function '${funcName}'.`);
}
});
resolve(funcObjs);
return null;
});
}
createAWSNodeJSFuncFile(handlerPath) {
const handlerInfo = path.parse(handlerPath);
const handlerDir = path.join(this.serverless.config.servicePath, handlerInfo.dir);
const handlerFile = `${handlerInfo.name}.js`;
const handlerFunction = handlerInfo.ext.replace(/^\./, '');
let templateFile = path.join(__dirname, functionTemplateFile);
if (this.serverless.service.custom &&
this.serverless.service.custom['serverless-mocha-plugin'] &&
this.serverless.service.custom['serverless-mocha-plugin'].functionTemplate) {
templateFile = path.join(this.serverless.config.servicePath,
this.serverless.service.custom['serverless-mocha-plugin'].functionTemplate);
}
const templateText = fse.readFileSync(templateFile).toString();
const jsFile = ejs.render(templateText, {
handlerFunction,
});
const filePath = path.join(handlerDir, handlerFile);
this.serverless.utils.writeFileDir(filePath);
if (this.serverless.utils.fileExistsSync(filePath)) {
const errorMessage = [
`File "${filePath}" already exists. Cannot create function.`,
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
fse.writeFileSync(path.join(handlerDir, handlerFile), jsFile);
this.serverless.cli.log(`Created function file "${path.join(handlerDir, handlerFile)}"`);
return BbPromise.resolve();
}
createFunction() {
this.serverless.cli.log('Generating function...');
const functionName = this.options.function;
const handler = this.options.handler;
const serverlessYmlFilePath = path
.join(this.serverless.config.servicePath, 'serverless.yml');
const serverlessYmlFileContent = fse
.readFileSync(serverlessYmlFilePath).toString();
return this.serverless.yamlParser.parse(serverlessYmlFilePath)
.then((config) => {
const runtime = [config.provider.name, config.provider.runtime].join('-');
if (validFunctionRuntimes.indexOf(runtime) < 0) {
const errorMessage = [
`Provider / Runtime "${runtime}" is not supported.`,
` Supported runtimes are: ${humanReadableFunctionRuntimes}.`,
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
const ymlEditor = yamlEdit(serverlessYmlFileContent);
if (ymlEditor.hasKey(`functions.${functionName}`)) {
const errorMessage = [
`Function "${functionName}" already exists. Cannot create function.`,
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
const funcDoc = {};
const funcData = { handler };
if (this.options.httpEvent) {
let events = [];
if (typeof this.options.httpEvent === 'string') {
events = [
this.options.httpEvent,
];
} else {
events = this.options.httpEvent;
}
funcData.events = [];
events.forEach((val) => {
this.serverless.cli.log(`Add http event '${val}'`);
funcData.events.push({
http: val,
});
});
}
funcDoc[functionName] = this.serverless.service.functions[functionName] = funcData;
if (ymlEditor.insertChild('functions', funcDoc)) {
const errorMessage = [
`Could not find functions in ${serverlessYmlFilePath}`,
].join('');
throw new this.serverless.classes.Error(errorMessage);
}
fse.writeFileSync(serverlessYmlFilePath, ymlEditor.dump());
if (runtime === 'aws-nodejs4.3' || runtime === 'aws-nodejs6.10') {
return this.createAWSNodeJSFuncFile(handler);
}
return BbPromise.resolve();
});
}
}
module.exports = mochaPlugin;
module.exports.lambdaWrapper = lambdaWrapper;
module.exports.chai = chai;
const initLiveModule = module.exports.initLiveModule = (modName) => {
const functionName = [
process.env.SERVERLESS_MOCHA_PLUGIN_SERVICE,
process.env.SERVERLESS_MOCHA_PLUGIN_STAGE,
modName,
].join('-');
return {
region: process.env.SERVERLESS_MOCHA_PLUGIN_REGION,
lambdaFunction: functionName,
};
};
module.exports.getWrapper = (modName, modPath, handler) => {
let wrapped;
// TODO: make this fetch the data from serverless.yml
if (process.env.SERVERLESS_MOCHA_PLUGIN_LIVE) {
const mod = initLiveModule(modName);
wrapped = lambdaWrapper.wrap(mod);
} else {
/* eslint-disable global-require */
const mod = require(process.env.SERVERLESS_TEST_ROOT + modPath);
/* eslint-enable global-require */
wrapped = lambdaWrapper.wrap(mod, {
handler,
});
}
return wrapped;
};