Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored and add test #294

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions lib/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ var fs = require('fs-extra');
var packageJson = require(path.join(__dirname, '..', 'package.json'));
var minimatch = require('minimatch');
var async = require('async');
var zip = new require('node-zip')();
var zip = new (require('node-zip'))();
var dotenv = require('dotenv');
var ScheduleEvents = require(path.join(__dirname, 'schedule_events'));

Expand Down Expand Up @@ -162,7 +162,7 @@ Lambda.prototype._eventSourceList = function (program) {
const list = (function () {
try {
return fs.readJsonSync(program.eventSourceFile);
} catch(err) {
} catch (err) {
throw err;
}
})();
Expand Down Expand Up @@ -247,7 +247,7 @@ Lambda.prototype._fileCopy = function (program, src, dest, excludeNodeModules, c
// `_rsync` will be replaced by` _fileCopy`.
Lambda.prototype._rsync = function (program, src, dest, excludeNodeModules, callback) {
var excludes = ['.git*', '*.swp', '.editorconfig', '.lambda', 'deploy.env', '*.log', '/build/'],
excludeGlobs = [];
excludeGlobs = [];
if (program.excludeGlobs) {
excludeGlobs = program.excludeGlobs.split(' ');
}
Expand Down Expand Up @@ -284,7 +284,7 @@ Lambda.prototype._rsync = function (program, src, dest, excludeNodeModules, call
Lambda.prototype._npmInstall = function (program, codeDirectory, callback) {
const installOptions = [
`--prefix ${codeDirectory}`,
process.platform === 'win32' ? `--cwd ${codeDirectory}` : null,
process.platform === 'win32' ? `--cwd ${codeDirectory}` : null
].join(' ');
var command = program.dockerImage ?
'docker run --rm -v ' + codeDirectory + ':/var/task ' + program.dockerImage + ' npm -s install --production' :
Expand Down Expand Up @@ -384,7 +384,7 @@ Lambda.prototype._uploadExisting = function (lambda, params, cb) {
'ZipFile': params.Code.ZipFile,
'Publish': params.Publish
}, function (err, data) {
if(err) {
if (err) {
return cb(err, data);
}

Expand All @@ -399,7 +399,7 @@ Lambda.prototype._uploadExisting = function (lambda, params, cb) {
'VpcConfig': params.VpcConfig,
'Environment': params.Environment,
'DeadLetterConfig': params.DeadLetterConfig,
'TracingConfig': params.TracingConfig,
'TracingConfig': params.TracingConfig
}, function (err, data) {
return cb(err, data);
});
Expand Down Expand Up @@ -561,7 +561,7 @@ Lambda.prototype._updateEventSources = function (lambda, functionName, existingE
'EventSourceArn': eventSourceList[i]['EventSourceArn'],
'Enabled': eventSourceList[i]['Enabled'] ? eventSourceList[i]['Enabled'] : false,
'BatchSize': eventSourceList[i]['BatchSize'] ? eventSourceList[i]['BatchSize'] : 100,
'StartingPosition': eventSourceList[i]['StartingPosition'] ? eventSourceList[i]['StartingPosition'] : 'LATEST',
'StartingPosition': eventSourceList[i]['StartingPosition'] ? eventSourceList[i]['StartingPosition'] : 'LATEST'
});
}
}
Expand All @@ -586,7 +586,7 @@ Lambda.prototype._updateEventSources = function (lambda, functionName, existingE
}

return async.map(updateEventSourceList, function (updateEventSource, _cb) {
switch(updateEventSource['type']) {
switch (updateEventSource['type']) {
case 'create':
delete updateEventSource['type'];
lambda.createEventSourceMapping(updateEventSource, function (err, data) {
Expand Down Expand Up @@ -640,7 +640,7 @@ Lambda.prototype.package = function (program) {
if (!isDir) {
throw program.packageDirectory + ' is not a directory!';
}
} catch(err) {
} catch (err) {
if (err.code === 'ENOENT') {
console.log('=> Creating package directory');
fs.mkdirsSync(program.packageDirectory);
Expand Down Expand Up @@ -790,5 +790,4 @@ Lambda.prototype.deploy = function (program) {
});
};


module.exports = new Lambda();
4 changes: 2 additions & 2 deletions lib/schedule_events.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ ScheduleEvents.prototype = {
const _params = _this._putTargetsParams(params);
_this.cloudwatchevents.putTargets(_params, (err, data) => {
// even if it is already registered, it will not be an error.
if (err) throw(err);
if (err) throw (err);
resolve(data);
});
});
Expand All @@ -100,7 +100,7 @@ ScheduleEvents.prototype = {
}).then((data) => {
return _this._putTargets(params);
});
},
}
};

module.exports = ScheduleEvents;
39 changes: 25 additions & 14 deletions test/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ var program = require('commander');
var fs = require('fs-extra');
var Hoek = require('hoek');
var lambda = require(path.join(__dirname, '..', 'lib', 'main'));
var zip = require('node-zip');
var Zip = require('node-zip');

var assert = chai.assert;

Expand All @@ -30,7 +30,7 @@ var originalProgram = {
eventSourceFile: '',
contextFile: 'context.json',
deployTimeout: 120000,
prebuiltDirectory: '',
prebuiltDirectory: ''
};

var codeDirectory = lambda._codeDirectory();
Expand All @@ -44,6 +44,7 @@ function _timeout (params) {
}
}

/* global before, after, beforeEach, afterEach, describe, it */
describe('lib/main', function () {
if (process.platform === 'win32') {
// It seems that it takes time for file operation in Windows.
Expand Down Expand Up @@ -184,6 +185,7 @@ describe('lib/main', function () {

it('`codeDirectory` is empty. (For `codeDirectory` where the file was present)', function (done) {
lambda._fileCopy(program, '.', codeDirectory, true, function (err, result) {
assert.isNull(err);
const contents = fs.readdirSync(codeDirectory);
assert.isTrue(contents.length > 0);
lambda._cleanDirectory(codeDirectory, function () {
Expand Down Expand Up @@ -217,6 +219,7 @@ describe('lib/main', function () {

it(funcName + ' an index.js as well as other files', function (done) {
lambda[funcName](program, '.', codeDirectory, true, function (err, result) {
assert.isNull(err);
var contents = fs.readdirSync(codeDirectory);
['index.js', 'package.json'].forEach(function (needle) {
assert.include(contents, needle, `Target: "${needle}"`);
Expand Down Expand Up @@ -244,6 +247,7 @@ describe('lib/main', function () {

it(funcName + ' an index.js as well as other files', function (done) {
lambda[funcName](program, '.', codeDirectory, true, function (err, result) {
assert.isNull(err);
var contents = fs.readdirSync(codeDirectory);
['index.js', 'package.json'].forEach(function (needle) {
assert.include(contents, needle, `Target: "${needle}"`);
Expand All @@ -254,6 +258,7 @@ describe('lib/main', function () {

it(funcName + ' excludes files matching excludeGlobs', function (done) {
lambda[funcName](program, '.', codeDirectory, true, function (err, result) {
assert.isNull(err);
var contents = fs.readdirSync(codeDirectory);
['__unittest', 'fuga'].forEach(function (needle) {
assert.include(contents, needle, `Target: "${needle}"`);
Expand All @@ -279,6 +284,7 @@ describe('lib/main', function () {
it(funcName + ' should not exclude package.json, even when excluded by excludeGlobs', function (done) {
program.excludeGlobs = '*.json';
lambda[funcName](program, '.', codeDirectory, true, function (err, result) {
assert.isNull(err);
var contents = fs.readdirSync(codeDirectory);
assert.include(contents, 'package.json');
done();
Expand All @@ -298,6 +304,7 @@ describe('lib/main', function () {
program.excludeGlobs = '*.json';
program.prebuiltDirectory = buildDir;
lambda[funcName](program, buildDir, codeDirectory, true, function (err, result) {
assert.isNull(err);
var contents = fs.readdirSync(codeDirectory);
assert.notInclude(contents, 'package.json', 'Target: "packages.json"');
assert.include(contents, 'testa', 'Target: "testa"');
Expand Down Expand Up @@ -334,6 +341,7 @@ describe('lib/main', function () {
_timeout({ this: this, sec: 30 }); // give it time to build the node modules

lambda._npmInstall(program, codeDirectory, function (err, result) {
assert.isNull(err);
var contents = fs.readdirSync(codeDirectory);
assert.include(contents, 'node_modules');
done();
Expand Down Expand Up @@ -361,7 +369,7 @@ describe('lib/main', function () {

return {
unhook: function unhook () {
stream.write = oldWrite;
stream.write = oldWrite;
},
captured: function () {
return buf;
Expand Down Expand Up @@ -432,7 +440,8 @@ describe('lib/main', function () {
_timeout({ this: this, sec: 30 }); // give it time to zip

lambda._zip(program, codeDirectory, function (err, data) {
var archive = new zip(data);
assert.isNull(err);
var archive = new Zip(data);
var contents = Object.keys(archive.files).map(function (k) {
return archive.files[k].name.toString();
});
Expand All @@ -447,7 +456,8 @@ describe('lib/main', function () {
_timeout({ this: this, sec: 30 }); // give it time to zip

lambda._archive(program, function (err, data) {
var archive = new zip(data);
assert.isNull(err);
var archive = new Zip(data);
var contents = Object.keys(archive.files).map(function (k) {
return archive.files[k].name.toString();
});
Expand All @@ -473,7 +483,8 @@ describe('lib/main', function () {

program.prebuiltDirectory = buildDir;
lambda._archive(program, function (err, data) {
var archive = new zip(data);
assert.isNull(err);
var archive = new Zip(data);
var contents = Object.keys(archive.files).map(function (k) {
return archive.files[k].name.toString();
});
Expand All @@ -496,6 +507,7 @@ describe('lib/main', function () {
_timeout({ this: this, sec: 30 }); // give it time to zip

lambda._zip(program, codeDirectory, function (err, data) {
assert.isNull(err);
bufferExpected = data;
fs.writeFileSync(testZipFile, data);
done();
Expand Down Expand Up @@ -541,8 +553,9 @@ describe('lib/main', function () {
const _program = Object.assign({ deployZipfile: filePath }, program);
_timeout({ this: this, sec: 30 }); // give it time to zip
lambda._archive(_program, function (err, data) {
assert.isNull(err);
// same test as "installs and zips with an index.js file and node_modules/async"
var archive = new zip(data);
var archive = new Zip(data);
var contents = Object.keys(archive.files).map(function (k) {
return archive.files[k].name.toString();
});
Expand Down Expand Up @@ -574,7 +587,6 @@ describe('lib/main', function () {
});

it('should inject environment variables at runtime', function () {

// Run it...
lambda._setRunTimeEnvironmentVars({
configFile: 'tmp.env'
Expand All @@ -583,7 +595,6 @@ describe('lib/main', function () {
assert.equal(process.env.FOO, 'bar');
assert.equal(process.env.BAZ, 'bing');
});

});

describe('create sample files', function () {
Expand Down Expand Up @@ -655,7 +666,7 @@ describe('lib/main', function () {
program.eventSourceFile = 'only_EventSourceMappings.json';
const expected = {
EventSourceMappings: [{ test: 1 }],
ScheduleEvents: [],
ScheduleEvents: []
};
assert.deepEqual(lambda._eventSourceList(program), expected);
});
Expand All @@ -664,7 +675,7 @@ describe('lib/main', function () {
program.eventSourceFile = 'only_ScheduleEvents.json';
const expected = {
EventSourceMappings: [],
ScheduleEvents: [{ test: 2 }],
ScheduleEvents: [{ test: 2 }]
};
assert.deepEqual(lambda._eventSourceList(program), expected);
});
Expand All @@ -676,13 +687,13 @@ describe('lib/main', function () {
BatchSize: 100,
Enabled: true,
EventSourceArn: 'your event source arn',
StartingPosition: 'LATEST',
StartingPosition: 'LATEST'
}],
ScheduleEvents: [{
ScheduleName: 'node-lambda-test-schedule',
ScheduleState: 'ENABLED',
ScheduleExpression: 'rate(1 hour)'
}],
}]
};
assert.deepEqual(lambda._eventSourceList(program), expected);
});
Expand All @@ -693,7 +704,7 @@ describe('lib/main', function () {
BatchSize: 100,
Enabled: true,
EventSourceArn: 'your event source arn',
StartingPosition: 'LATEST',
StartingPosition: 'LATEST'
}];
const fileName = 'event_sources_old_style.json';

Expand Down
15 changes: 8 additions & 7 deletions test/node-lambda.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ const spawn = require('child_process').spawn;
const execSync = require('child_process').execSync;
const nodeLambdaPath = path.join(__dirname, '..', 'bin', 'node-lambda');

/* global before, after, describe, it */
// The reason for specifying the node command in this test is to support Windows.
describe('bin/node-lambda', () => {
describe('node-lambda run', () => {
const _testMain = (expectedValues, done) => {
const run = spawn('node', [
nodeLambdaPath, 'run',
'--handler', '__test.handler',
'--eventFile', 'event.json',
'--eventFile', 'event.json'
]);
var stdoutString = '';
run.stdout.on('data', (data) => {
Expand Down Expand Up @@ -87,21 +88,21 @@ describe('bin/node-lambda', () => {

it('`node-lambda run` exitCode is `0` (callback(null))', (done) => {
_generateEventFile(Object.assign(eventObj, {
callbackCode: 'callback(null);',
callbackCode: 'callback(null);'
}));
_testMain({ stdoutRegExp: /Success:sleep 3500 msec$/, exitCode: 0 }, done);
});

it('`node-lambda run` exitCode is `0` (callback(null, "text"))', (done) => {
_generateEventFile(Object.assign(eventObj, {
callbackCode: 'callback(null, "text");',
callbackCode: 'callback(null, "text");'
}));
_testMain({ stdoutRegExp: /Success:"text"sleep 3500 msec$/, exitCode: 0 }, done);
});

it('`node-lambda run` exitCode is `255` (callback(new Error("e")))', (done) => {
_generateEventFile(Object.assign(eventObj, {
callbackCode: 'callback(new Error("e"));',
callbackCode: 'callback(new Error("e"));'
}));
_testMain({ stdoutRegExp: /Error: Error: esleep 3500 msec$/, exitCode: 255 }, done);
});
Expand All @@ -115,21 +116,21 @@ describe('bin/node-lambda', () => {

it('`node-lambda run` exitCode is `0` (callback(null))', (done) => {
_generateEventFile(Object.assign(eventObj, {
callbackCode: 'callback(null);',
callbackCode: 'callback(null);'
}));
_testMain({ stdoutRegExp: /Success:$/, exitCode: 0 }, done);
});

it('`node-lambda run` exitCode is `0` (callback(null, "text"))', (done) => {
_generateEventFile(Object.assign(eventObj, {
callbackCode: 'callback(null, "text");',
callbackCode: 'callback(null, "text");'
}));
_testMain({ stdoutRegExp: /Success:"text"$/, exitCode: 0 }, done);
});

it('`node-lambda run` exitCode is `255` (callback(new Error("e")))', (done) => {
_generateEventFile(Object.assign(eventObj, {
callbackCode: 'callback(new Error("e"));',
callbackCode: 'callback(new Error("e"));'
}));
_testMain({ stdoutRegExp: /Error: Error: e$/, exitCode: 255 }, done);
});
Expand Down
Loading