From bc9be4a899e16309d975011a93d1e7c5a3d07615 Mon Sep 17 00:00:00 2001 From: Tomoaki Abe Date: Wed, 24 May 2017 16:11:37 +0900 Subject: [PATCH] Refactored and add test (#294) * Fix to use '===' instead of '==' (Including similar modifications) * Fix using strings for single quotes * Fix using let Fix for not being careful with `VARIABLE is already defined` in JavaScript Standard Style * Add space and format the code Fix to prevent the message like the following from being displayed - Missing space before function parentheses. - Missing space before opening brace. * Add comment about global function * Remove unused function names * Add test of variable `err` * Remove unnecessary end of line commas * Remove unnecessary line feeds * Fix to adjust the space * Remove unnecessary line feed * Fix to start variable name with uppper case For variables like class * Fix to enclose it in parentheses to make it easier to understand --- lib/main.js | 19 +++++++++---------- lib/schedule_events.js | 4 ++-- test/main.js | 39 +++++++++++++++++++++++++-------------- test/node-lambda.js | 15 ++++++++------- test/schedule_events.js | 7 ++++--- 5 files changed, 48 insertions(+), 36 deletions(-) diff --git a/lib/main.js b/lib/main.js index 5c4d32ce..c7de33cb 100644 --- a/lib/main.js +++ b/lib/main.js @@ -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')); @@ -162,7 +162,7 @@ Lambda.prototype._eventSourceList = function (program) { const list = (function () { try { return fs.readJsonSync(program.eventSourceFile); - } catch(err) { + } catch (err) { throw err; } })(); @@ -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(' '); } @@ -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' : @@ -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); } @@ -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); }); @@ -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' }); } } @@ -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) { @@ -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); @@ -790,5 +790,4 @@ Lambda.prototype.deploy = function (program) { }); }; - module.exports = new Lambda(); diff --git a/lib/schedule_events.js b/lib/schedule_events.js index 835f3c9b..d4646745 100644 --- a/lib/schedule_events.js +++ b/lib/schedule_events.js @@ -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); }); }); @@ -100,7 +100,7 @@ ScheduleEvents.prototype = { }).then((data) => { return _this._putTargets(params); }); - }, + } }; module.exports = ScheduleEvents; diff --git a/test/main.js b/test/main.js index 48be948f..7a5a7ade 100644 --- a/test/main.js +++ b/test/main.js @@ -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; @@ -30,7 +30,7 @@ var originalProgram = { eventSourceFile: '', contextFile: 'context.json', deployTimeout: 120000, - prebuiltDirectory: '', + prebuiltDirectory: '' }; var codeDirectory = lambda._codeDirectory(); @@ -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. @@ -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 () { @@ -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}"`); @@ -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}"`); @@ -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}"`); @@ -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(); @@ -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"'); @@ -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(); @@ -361,7 +369,7 @@ describe('lib/main', function () { return { unhook: function unhook () { - stream.write = oldWrite; + stream.write = oldWrite; }, captured: function () { return buf; @@ -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(); }); @@ -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(); }); @@ -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(); }); @@ -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(); @@ -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(); }); @@ -574,7 +587,6 @@ describe('lib/main', function () { }); it('should inject environment variables at runtime', function () { - // Run it... lambda._setRunTimeEnvironmentVars({ configFile: 'tmp.env' @@ -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 () { @@ -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); }); @@ -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); }); @@ -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); }); @@ -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'; diff --git a/test/node-lambda.js b/test/node-lambda.js index 0bef84ee..9c194847 100644 --- a/test/node-lambda.js +++ b/test/node-lambda.js @@ -7,6 +7,7 @@ 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', () => { @@ -14,7 +15,7 @@ describe('bin/node-lambda', () => { const run = spawn('node', [ nodeLambdaPath, 'run', '--handler', '__test.handler', - '--eventFile', 'event.json', + '--eventFile', 'event.json' ]); var stdoutString = ''; run.stdout.on('data', (data) => { @@ -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); }); @@ -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); }); diff --git a/test/schedule_events.js b/test/schedule_events.js index 7e3f3985..1058dbf7 100644 --- a/test/schedule_events.js +++ b/test/schedule_events.js @@ -33,11 +33,12 @@ const mockResponse = { putTargets: { FailedEntries: [], FailedEntryCount: 0 - }, + } }; var schedule = null; +/* global before, after, describe, it */ describe('lib/schedule_events', () => { before(() => { aws.mock('CloudWatchEvents', 'putRule', (params, callback) => { @@ -107,7 +108,7 @@ describe('lib/schedule_events', () => { FunctionName: 'node-lambda-test-function', Principal: 'events.amazonaws.com', SourceArn: 'arn:aws:events:hoge:fuga', - StatementId: 'node-lambda-test-schedule', + StatementId: 'node-lambda-test-schedule' }; const _params = Object.assign(params, mockResponse.putRule); assert.deepEqual(schedule._addPermissionParams(_params), expected); @@ -120,7 +121,7 @@ describe('lib/schedule_events', () => { Rule: 'node-lambda-test-schedule', Targets: [{ Arn: 'arn:aws:lambda:us-west-2:XXX:function:node-lambda-test-function', - Id: 'node-lambda-test-function', + Id: 'node-lambda-test-function' }] }; assert.deepEqual(schedule._putTargetsParams(params), expected);