forked from nordcloud/serverless-mocha-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
407 lines (349 loc) · 12.8 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
'use strict';
/**
* serverless-mocha-plugin
* - a plugin for TDD with serverless
*/
const path = require('path'),
fs = require('fs'),
lambdaWrapper = require('lambda-wrapper'),
Mocha = require('mocha'),
chai = require('chai'),
Path = require('path'),
ejs = require('ejs'),
BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)
const testFolder = 'test'; // Folder used my mocha for tests
const templateFilename = 'sls-mocha-plugin-template.ejs';
module.exports = function(S) { // Always pass in the ServerlessPlugin Class
/**
* Adding/Manipulating Serverless classes
* - You can add or manipulate Serverless classes like this
*/
S.classes.Project.newStaticMethod = function() { console.log("A new method!"); };
S.classes.Project.prototype.newMethod = function() { S.classes.Project.newStaticMethod(); };
/**
* Extending the Plugin Class
* - Here is how you can add custom Actions and Hooks to Serverless.
* - This class is only required if you want to add Actions and Hooks.
*/
class PluginBoilerplate extends S.classes.Plugin {
/**
* Constructor
* - Keep this and don't touch it unless you know what you're doing.
*/
constructor() {
super();
this.name = 'io.sc5.mocha';
this.testFileMap = {};
}
/**
* Register Actions
* - function mocha-create
*/
registerActions() {
S.addAction(this._createAction.bind(this), {
handler: '_createAction',
description: 'Create mocha test for function',
context: 'function',
contextAction: 'mocha-create',
options: [{
option: 'template',
shortcut: 'T',
description: 'name of a template file used when creating test'
}],
parameters: [ // Use paths when you multiple values need to be input (like an array). Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3. Serverless will automatically turn this into an array and attach it to evt.options within your plugin
{
parameter: 'paths',
description: 'Path to function to test. If not defined, test all functions.',
position: '0->' // Can be: 0, 0-2, 0-> This tells Serverless which params are which. 3-> Means that number and infinite values after it.
}
]
});
S.addAction(this._runAction.bind(this), {
handler: '_runAction',
description: 'Runs mocha test for function',
context: 'function',
contextAction: 'mocha-run',
options: [ {
option: 'region',
shortcut: 'r',
description: 'region you want to run your function in'
},
{
option: 'stage',
shortcut: 's',
description: 'stage you want to run your function in'
},
{
option: 'reporter',
shortcut: 'R',
description: 'specify the reporter to use'
},
{
option: 'reporter-options',
shortcut: 'O',
description: 'reporter-specific options'
}],
parameters: [ // Use paths when you multiple values need to be input (like an array). Input looks like this: "serverless custom run module1/function1 module1/function2 module1/function3. Serverless will automatically turn this into an array and attach it to evt.options within your plugin
{
parameter: 'paths',
description: 'Path to function to test. If not defined, test all functions.',
position: '0->' // Can be: 0, 0-2, 0-> This tells Serverless which params are which. 3-> Means that number and infinite values after it.
}
]
});
return BbPromise.resolve();
}
/**
* Register Hooks
* - function create (post) creates mocha test file
*/
registerHooks() {
S.addHook(this._hookPostFuncCreate.bind(this), {
action: 'functionCreate',
event: 'post'
});
return BbPromise.resolve();
}
/**
* Custom action serverless function mocha-create functioName
*/
_createAction(evt) {
if (S.getProject().getFunction(evt.options.paths[0]) === undefined) {
return new BbPromise(function(resolve, reject) {
reject(`MochaPluginError: Function ${evt.options.paths[0]} does not exist in your project`);
});
}
return createTest(evt.options.paths[0], evt.options.template || templateFilename);
}
_runAction(evt) {
let _this = this;
_this.evt = evt;
_this.evt.options.stage = _this.evt.options.stage ? _this.evt.options.stage : null;
return BbPromise.try(function() {
})
.bind(_this)
.then(function() {
return _this.cliPromptSelectStage('Choose a Stage: ', _this.evt.options.stage, false)
.then(stage => {
_this.evt.options.stage = stage;
})
})
.then(function() {
return _this.cliPromptSelectRegion('Choose a Region in this Stage: ', false, true, _this.evt.options.region, _this.evt.options.stage)
.then(region => {
_this.evt.options.region = region;
})
})
.then(_this._runTests)
.then(function() {
return _this.evt;
});
}
_runTests() {
let _this = this;
return new BbPromise(function(resolve, reject) {
let functions = _this.evt.options.paths;
let mocha = new Mocha({timeout: process.env.SLS_MOCHA_TIMEOUT || 6000});
//This could pose as an issue if several functions share a common ENV name but different values.
let stage = _this.evt.options.stage;
let region = _this.evt.options.region;
getFunctions(functions)
.then(getFilePaths)
.then(function(paths) {
if (paths.length === 0) {
return reject('No tests to run.');
}
paths.forEach(function(func) {
SetEnvVars(func, {
stage: stage,
region: region
});
_this.testFileMap[funcNameFromPath(func.mochaPlugin.testPath)] = func;
mocha.addFile(func.mochaPlugin.testPath);
})
var reporter = _this.evt.options.reporter;
if ( reporter !== null) {
var reporterOptions = {};
if (_this.evt.options["reporter-options"] !== null) {
_this.evt.options["reporter-options"].split(",").forEach(function(opt) {
var 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)
}
mocha.run(function(failures){
process.on('exit', function () {
process.exit(failures); // exit with non-zero status if there were failures
});
})
.on('suite', function(suite) {
let funcName = funcNameFromPath(suite.file);
let func = _this.testFileMap[funcName];
if (func) {
SetEnvVars(func, {
stage: stage,
region: region
});
}
});
}, function(error) {
return reject(error);
});
});
}
/**
* Hook for creating the mocha test placeholder after function creation
*/
_hookPostFuncCreate(evt) {
// TODO: only run with runtime node4.3
if (evt.options.runtime != 'nodejs4.3') {
return;
}
let parsedPath = path.parse(evt.options.path);
let funcName = parsedPath.base;
return createTest(funcName, templateFilename);
}
}
//Set environment variables
function SetEnvVars(func, config) {
var envVars = func.toObjectPopulated(config).environment;
var fields = Object.keys(envVars);
for (var key in fields) {
process.env[fields[key]] = envVars[fields[key]];
}
return process.env;
}
// Create the test folder
function createTestFolder() {
return new BbPromise(function(resolve, reject) {
fs.exists(testFolder, function(exists) {
if (exists) {
return resolve(testFolder);
}
fs.mkdir(testFolder, function(err) {
if (err) {
return reject(err);
}
return resolve(testFolder);
})
})
});
}
// Create the test file (and test folder)
function createTest(funcName, templateFilename) {
return createTestFolder().then(function(testFolder) {
return new BbPromise(function(resolve, reject) {
let funcFilePath = testFilePath(funcName);
let projectPath = S.getProject().getRootPath();
let funcFullPath = S.getProject().getFunction(funcName).getRootPath();
let funcPath = path.relative(projectPath, funcFullPath).replace(/\\/g, "/");
fs.exists(funcFilePath, function (exists) {
if (exists) {
return reject(new Error(`File ${funcFilePath} already exists`));
}
let templateFilenamePath = path.join(testFolder, templateFilename);
fs.exists(templateFilenamePath, function (exists) {
let templateString = exists ? getTemplateFromFile(templateFilenamePath) : getTemplateFromString();
let content = ejs.render(templateString, {
'functionName': funcName,
'functionPath': funcPath
});
fs.writeFile(funcFilePath, content, function(err) {
if (err) {
return reject(new Error(`Creating file ${funcFilePath} failed: ${err}`));
}
console.log(`serverless-mocha-plugin: created ${funcFilePath}`);
return resolve(funcFilePath);
})
});
});
});
});
}
// getFunctions. If no functions provided, returns all files
function getFunctions(funcNames) {
return new BbPromise(function(resolve, reject) {
let funcObjs = [];
if (funcNames.length === 0) {
let sFuncs = S.getProject().getAllFunctions();
return resolve(sFuncs);
}
let func;
funcNames.forEach(function(funcName, idx) {
func = S.getProject().getFunction(funcName);
if (func) {
funcObjs.push(func);
} else {
console.log(`Warning: Could not find function '${funcName}'.`);
}
});
resolve(funcObjs);
});
}
// getTestFiles. If no functions provided, returns all files
function getFilePaths(funcs) {
return new BbPromise(function(resolve, reject) {
var paths = [];
if (funcs && (funcs.length > 0)) {
funcs.forEach(function(val, idx) {
val.mochaPlugin = {
testPath: testFilePath(val.name)
};
paths.push(val);
});
return resolve(paths);
}
return resolve([]);
});
}
// Returns the path to a function's test file
function testFilePath(funcName) {
return path.join(testFolder, `${funcName.replace(/.*\//g, '')}.js`);
}
function funcNameFromPath(filePath) {
let data = path.parse(filePath);
return data.name
}
function getTemplateFromFile(templateFilenamePath) {
return fs.readFileSync(templateFilenamePath, 'utf-8');
}
function getTemplateFromString() {
return `'use strict';
// tests for <%= functionName %>
// Generated by serverless-mocha-plugin
const mod = require('../<%= functionPath %>/handler.js');
const mochaPlugin = require('serverless-mocha-plugin');
const lambdaWrapper = mochaPlugin.lambdaWrapper;
const expect = mochaPlugin.chai.expect;
const liveFunction = {
region: process.env.SERVERLESS_REGION,
lambdaFunction: process.env.SERVERLESS_PROJECT + '-<%= functionName %>'
}
var wrapped;
describe('<%= functionName %>', () => {
before(function (done) {
// wrapped = lambdaWrapper.wrap(liveFunction); // Run the deployed lambda
wrapped = lambdaWrapper.wrap(mod);
done()
});
it('implement tests here', (done) => {
//runHandler(event, customContext, callback)
wrapped.runHandler({}, {}, (err, response) => {
done('no tests implemented');
});
});
});
`;
}
// Export Plugin Class
return PluginBoilerplate;
};
module.exports.lambdaWrapper = lambdaWrapper;
module.exports.chai = chai;