Socket
Socket
Sign inDemoInstall

serverless-mocha-plugin

Package Overview
Dependencies
38
Maintainers
2
Versions
46
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.9.0 to 1.9.1

404

index.js

@@ -14,2 +14,3 @@ 'use strict';

const fse = require('fs-extra');
const fs = require('fs');
const utils = require('./utils');

@@ -60,3 +61,4 @@ const BbPromise = require('bluebird');

lifecycleEvents: [
'create',
'function',
'test',
],

@@ -90,3 +92,3 @@ options: {

lifecycleEvents: [
'test',
'invoke'
],

@@ -134,15 +136,7 @@ options: {

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);
},
'create:test:test': this.createTest.bind(this),
'invoke:test:invoke': this.runTests.bind(this),
'create:function:function': this.createFunction.bind(this),
'create:function:test': this.createTest.bind(this),
// 'create:function:create'
};

@@ -169,159 +163,161 @@ }

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,
});
return new Promise((resolve, error) => {
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;
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.`;
let funcNames = [];
if (typeof funcOption === 'string') {
funcNames = [funcOption];
} else if (funcOption.length > 0) {
funcNames = funcOption;
}
this.serverless.cli.log(errorMsg);
}
const inited = this.serverless.service;
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.`;
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');
}
this.serverless.cli.log(errorMsg);
}
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);
}
myModule.serverless.environment = inited.environment;
const vars = new myModule.serverless.classes.Variables(myModule.serverless);
const testPath = funcs[func].mochaPlugin.testPath;
myModule.runScripts('preTestCommands')
.then(() => {
const svcFuncs = myModule.getFunctions(funcNames);
const funcs = utils.getTestFiles(svcFuncs, testsPath, funcNames);
if (fse.existsSync(testPath)) {
mocha.addFile(testPath);
}
}
});
// Run the tests that were actually found
funcNames = Object.keys(funcs);
if (funcNames.length === 0) {
return myModule.serverless.cli.log('No tests to run');
}
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);
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);
}
if (myModule.options.grep) {
mocha.grep(myModule.options.grep);
const testPath = funcs[func].mochaPlugin.testPath;
if (fs.existsSync(testPath)) {
mocha.addFile(testPath);
}
}
// set the SERVERLESS_TEST_ROOT variable to define root for tests
let rootFolder = this.serverless.config.servicePath;
const reporter = myModule.options.reporter;
if (myModule.options.root) {
rootFolder = myModule.options.root;
myModule.serverless.cli.log(`Run tests against code under '${rootFolder}'`);
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);
}
// 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);
}
if (myModule.options.grep) {
mocha.grep(myModule.options.grep);
}
/* eslint-disable dot-notation */
process.env['SERVERLESS_TEST_ROOT'] = rootFolder;
// set the SERVERLESS_TEST_ROOT variable to define root for tests
let rootFolder = this.serverless.config.servicePath;
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 */
if (myModule.options.root) {
rootFolder = myModule.options.root;
myModule.serverless.cli.log(`Run tests against code under '${rootFolder}'`);
}
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];
// 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);
}
if (mod[0] === '.') {
mod = path.join(process.cwd(), mod);
}
require(mod); // eslint-disable-line global-require
extensions.push(ext);
});
}
/* eslint-disable dot-notation */
process.env['SERVERLESS_TEST_ROOT'] = rootFolder;
const mochaRunner = mocha.run((failures) => {
process.on('exit', () => {
myModule.runScripts('postTestCommands')
// exit with non-zero status if there were failures
.then(() => process.exit(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);
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);
});
}
const mochaRunner = mocha.run((failures) => {
process.on('exit', () => {
myModule.runScripts('postTestCommands')
// exit with non-zero status if there were failures
.then(() => process.exit(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);
}
}).on('end', () => {
resolve();
if (myModule.options.exit) {
mochaRunner.on('end', process.exit);
process.exit();
}
});
return null;
}, error => myModule.serverless.cli.log(error));
return null;
}, error => myModule.serverless.cli.log(error));
});
});
}

@@ -331,50 +327,43 @@

const funcName = this.options.f || this.options.function;
const testsRootFolder = this.options.p || this.options.path;
const testsRootFolder = this.options.p || this.options.path || 'test';
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];
const testsFolder = utils.createTestFolder(testsRootFolder);
fse.exists(testFilePath, (exists) => {
if (exists) {
myModule.serverless.cli.log(`Test file ${testFilePath} already exists`);
return (new Error(`File ${testFilePath} already exists`));
}
const testFilePath = utils.getTestFilePath(funcName, testsFolder);
if (fs.existsSync(testFilePath)) {
myModule.serverless.cli.log(`Test file ${testFilePath} already exists`);
return (new Error(`File ${testFilePath} already exists`));
}
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];
let templateFilenamePath = '';
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);
}
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);
}
if ((! templateFilenamePath) || (! fs.existsSync(templateFilenamePath))) {
templateFilenamePath = path.join(__dirname, testTemplateFile);
}
fse.exists(templateFilenamePath, (exists2) => {
if (!exists2) {
templateFilenamePath = path.join(__dirname, testTemplateFile);
}
const templateString = utils.getTemplateFromFile(templateFilenamePath);
const templateString = utils.getTemplateFromFile(templateFilenamePath);
const content = ejs.render(templateString, {
functionName: funcName,
functionPath: funcPath,
handlerName: handler,
});
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;
});
});
const err = fs.writeFileSync(testFilePath, content);
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}`);
}

@@ -386,24 +375,21 @@

const myModule = this;
const funcObjs = {};
const allFuncs = myModule.serverless.service.functions;
return new BbPromise((resolve) => {
const funcObjs = {};
const allFuncs = myModule.serverless.service.functions;
if (funcList.length === 0) {
return allFuncs;
}
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}'.`);
}
});
return (funcObjs);
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;
});
return null;
}

@@ -439,4 +425,6 @@

}
fse.writeFileSync(path.join(handlerDir, handlerFile), jsFile);
if(fs.writeFileSync(path.join(handlerDir, handlerFile), jsFile)) {
myModule.serverless.cli.log(`Creating file ${handlerFile} failed`);
return new Error(`Creating file ${handlerFile} failed`);
}
this.serverless.cli.log(`Created function file "${path.join(handlerDir, handlerFile)}"`);

@@ -446,2 +434,8 @@ return BbPromise.resolve();

createFunctionTest() {
const plugin=this;
return plugin.createFunction()
.then(plugin.createTest);
}
createFunction() {

@@ -448,0 +442,0 @@ this.serverless.cli.log('Generating function...');

{
"name": "serverless-mocha-plugin",
"version": "1.9.0",
"version": "1.9.1",
"engines": {

@@ -49,3 +49,3 @@ "node": ">=4.0"

"nyc": "^11.4.1",
"serverless": "latest",
"serverless": "^1.33.2",
"serverless-webpack": "^1.0.0-rc.4",

@@ -56,3 +56,3 @@ "webpack-node-externals": "^1.5.4"

"aws-sdk": "^2.6.3",
"bluebird": "3.4.6",
"bluebird": "^3.4.6",
"chai": "^3.5.0",

@@ -59,0 +59,0 @@ "delayed-stream": "^1.0.0",

@@ -185,2 +185,3 @@ # Serverless Mocha Plugin

* 2018/12/15 - v1.9.1 - fix to work with serverless 1.33 and later
* 2018/09/16 - v1.9.0 - add support for --exit option

@@ -187,0 +188,0 @@ * 2018/04/03 - v1.8.0 - add support for Node 8

@@ -26,6 +26,7 @@ 'use strict';

'create:test:test',
'invoke:test:test',
'create:function:create',
'invoke:test:invoke',
'create:function:function',
'create:function:test',
]);
});
});

@@ -45,20 +45,12 @@ 'use strict';

it('tests default createTestFolder', () =>
utils.createTestFolder().then((folder) => {
it('tests default createTestFolder', () => {
const folder = utils.createTestFolder();
expect(folder).to.be.equal('test');
})
);
});
it('tests default createTestFolder (exists)', () =>
utils.createTestFolder().then((folder) => {
expect(folder).to.be.equal('test');
})
);
it('tests custom createTestFolder', () => {
const folder = utils.createTestFolder('custom');
expect(folder).to.be.equal('custom');
});
it('tests custom createTestFolder', () =>
utils.createTestFolder('custom').then((folder) => {
expect(folder).to.be.equal('custom');
})
);
it('tests funcNameFromPath', () => {

@@ -65,0 +57,0 @@ const functionName = utils.funcNameFromPath('path/to/functionName.js');

@@ -39,23 +39,20 @@ 'use strict';

function getTestFiles(funcs, testFolder, funcList) {
return new BbPromise((resolve) => {
const funcFiles = traverseTestFolder(testFolder);
if (funcFiles.length > 0) {
const resFuncs = {};
funcFiles.forEach((val) => {
if (path.extname(val) === '.js') {
const base = path.basename(val).replace(/.js$/, '');
// Create test for non-functions only if no funcList
if (funcs[base] || funcList.length === 0) {
resFuncs[base] = funcs[base] || { };
const funcFiles = traverseTestFolder(testFolder);
let resFuncs = {};
if (funcFiles.length > 0) {
funcFiles.forEach((val) => {
if (path.extname(val) === '.js') {
const base = path.basename(val).replace(/.js$/, '');
// Create test for non-functions only if no funcList
if (funcs[base] || funcList.length === 0) {
resFuncs[base] = funcs[base] || { };
resFuncs[base].mochaPlugin = {
testPath: path.join(getTestsFolder(testFolder), val),
};
}
resFuncs[base].mochaPlugin = {
testPath: path.join(getTestsFolder(testFolder), val),
};
}
});
return resolve(resFuncs);
}
return resolve({});
});
}
});
}
return resFuncs;
}

@@ -65,17 +62,10 @@

function createTestFolder(testsRootFolder) {
return new BbPromise((resolve, reject) => {
const testsFolder = getTestsFolder(testsRootFolder);
fs.exists(testsFolder, (exists) => {
if (exists) {
return resolve(testsFolder);
}
fs.mkdir(testsFolder, (err) => {
if (err) {
return reject(err);
}
return resolve(testsFolder);
});
return null;
});
});
const testsFolder = getTestsFolder(testsRootFolder);
const exists = fs.existsSync(testsFolder);
if (exists) {
return testsFolder;
}
const create = fs.mkdirSync(testsFolder);
return testsFolder;
}

@@ -82,0 +72,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with âšĄïž by Socket Inc