Tests: remove FunctionInvoke test

This commit is contained in:
Austen Collins 2016-02-07 17:36:17 -08:00
parent 422cb94e4e
commit 98e7cab81f
9 changed files with 43 additions and 331 deletions

View File

@ -28,7 +28,6 @@
"./actions/RegionRemove.js",
"./actions/StageRemove.js",
"./actions/ProjectRemove.js",
"./actions/FunctionLogs.js",
"./actions/FunctionInvoke.js"
"./actions/FunctionLogs.js"
]
}

View File

@ -120,24 +120,10 @@ module.exports = function(SPlugin, serverlessPath) {
_this.function = _this.S.state.getFunctions({ paths: [_this.evt.options.path] })[0];
// Set default function name
_this.functionName = _this.Lambda.sGetLambdaName(_this.project.name, _this.function.getComponent().name, null, _this.function.name);
// Backwards Compatibility Support TODO: Remove in the future but will result in breaking change.
if (_this.function._config.sPath.split('/').length == 3) {
// Check if s-module.json exists in subfolder
if (SUtils.fileExistsSync(path.join(
_this.S.config.projectPath,
_this.function._config.sPath.split('/').splice(0, 2).join(path.sep),
's-module.json'))) {
_this.functionName = _this.Lambda.sGetLambdaName(_this.project.name, _this.function.getComponent().name, _this.function._config.sPath.split('/')[1], _this.function.name);
}
}
// If nameTemplate, use that
if (_this.function.nameTemplate) {
_this.functionName = _this.function.getPopulated({
stage: _this.evt.options.stage,
region: _this.evt.options.region }).nameTemplate;
}
_this.functionName = _this.function.getDeployedName({
stage: _this.evt.options.stage,
region: _this.evt.options.region
});
return BbPromise.resolve();
}

View File

@ -160,24 +160,11 @@ module.exports = function(SPlugin, serverlessPath) {
if (!_this.endpoint) BbPromise.reject(new SError(`Endpoint could not be found: ${_this.evt.options.path}`));
// Set default function name
_this.functionName = _this.Lambda.sGetLambdaName(_this.project.name, _this.endpoint.getComponent().name, null, _this.endpoint.getFunction().name);
// Backwards Compatibility Support TODO: Remove in the future but will result in breaking change.
if (_this.endpoint.getFunction()._config.sPath.split('/').length == 3) {
// Check if s-module.json exists in subfolder
if (SUtils.fileExistsSync(path.join(
_this.S.config.projectPath,
_this.endpoint._config.sPath.split('/').splice(0, 2).join(path.sep),
's-module.json'))) {
_this.functionName = _this.Lambda.sGetLambdaName(_this.project.name, _this.endpoint.getComponent().name, _this.endpoint._config.sPath.split('/')[1], _this.endpoint.getFunction().name);
}
}
// If nameTemplate, use that
if (_this.endpoint.getFunction().nameTemplate) {
_this.functionName = _this.endpoint.getFunction().getPopulated({
stage: _this.evt.options.stage,
region: _this.evt.options.region }).nameTemplate;
}
// Set function name
_this.functionName = _this.function.getDeployedName({
stage: _this.evt.options.stage,
region: _this.evt.options.region
});
// Populate endpoint
_this.endpoint = _this.endpoint.getPopulated({ stage: _this.evt.options.stage, region: _this.evt.options.region });

View File

@ -1,185 +0,0 @@
'use strict';
/**
* Action: FunctionInvoke
* - Invokes the function in the CWD
*
* Event Properties:
* - stage: (String) The function stage
* - region: (String) The function region
* - log: (Boolean) Show the log output
* - invocationType: (String) Invocation Type
*/
module.exports = function(SPlugin, serverlessPath) {
const path = require('path'),
SUtils = require( path.join( serverlessPath, 'utils' ) ),
SError = require(path.join(serverlessPath, 'ServerlessError')),
BbPromise = require('bluebird'),
SCli = require( path.join( serverlessPath, 'utils', 'cli')),
_ = require('lodash'),
chalk = require('chalk');
/**
* FunctionInvoke Class
*/
return class FunctionInvoke extends SPlugin {
constructor(S, config) {
super(S, config);
}
static getName() {
return 'serverless.core.' + FunctionInvoke.name;
}
registerActions() {
this.S.addAction(this.functionInvoke.bind(this), {
handler: 'functionInvoke',
description: 'Invokes the function',
context: 'function',
contextAction: 'invoke',
options: [
{
option: 'stage',
shortcut: 's',
description: 'The function stage'
}
, {
option: 'region',
shortcut: 'r',
description: 'The function region'
}
, {
option: 'invocationType',
shortcut: 'i',
description: 'Valid Values: Event | RequestResponse | DryRun . Default is RequestResponse'
}
, {
option: 'log',
shortcut: 'l',
description: 'Show the log output'
}
],
parameters: [
{
parameter: 'path',
description: 'Path of the function you want to run (componentName/moduleName/functionName)',
position: '0'
}
]
});
return BbPromise.resolve();
}
checkPath() {
// If a function path was not specified.
if(!this.evt.options.path) {
// If s-function.json exists in the current path, then use the current function path.
if(SUtils.fileExistsSync(path.join(process.cwd(), 's-function.json'))) {
let componentName = path.basename(path.join(process.cwd(), '..', '..'));
let moduleName = path.basename(path.join(process.cwd(), '..'));
let functionName = path.basename(process.cwd());
this.evt.options.path = componentName + "/" + moduleName + "/" + functionName;
}
else {
return BbPromise.reject(new SError('Missing required function path param. Run from within a function directory, or add a function path in this format: componentName/moduleName/functionName'));
}
}
return BbPromise.resolve()
}
/**
* Action
*/
functionInvoke(evt) {
this.evt = evt;
if (!this.S.state.meta.getStages().length) return BbPromise.reject(new SError('No existing stages in the project'));
return this.cliPromptSelectStage('Function Invoke - Choose a stage: ', evt.options.stage, false)
.then(stage => evt.options.stage = stage)
.bind(this)
.then(()=> this.cliPromptSelectRegion('Choose a Region in this Stage: ', false, true, evt.options.region, evt.options.stage))
.then(region => evt.options.region = region)
.then(this._validateAndPrepare)
.then(this._invoke)
.then(() => this.evt);
}
_validateAndPrepare() {
if (!this.evt.options.stage) return BbPromise.reject(new SError(`Stage is required`));
if (!this.evt.options.region) return BbPromise.reject(new SError(`Region is required`));
this.evt.options.invocationType = this.evt.options.invocationType || 'RequestResponse'
if (this.evt.options.invocationType !== 'RequestResponse') {
this.evt.options.logType = 'None';
} else {
this.evt.options.logType = this.evt.options.log ? 'Tail' : 'None'
}
// validate stage: make sure stage exists
if (!this.S.state.meta.get().stages[this.evt.options.stage]) {
return BbPromise.reject(new SError('Stage ' + this.evt.options.stage + ' does not exist in your project', SError.errorCodes.UNKNOWN));
}
// validate region: make sure region exists in stage
if (!this.S.state.meta.get().stages[this.evt.options.stage].regions[this.evt.options.region]) {
return BbPromise.reject(new SError('Region "' + this.evt.options.region + '" does not exist in stage "' + this.evt.options.stage + '"'));
}
this.Lambda = require('../utils/aws/Lambda')({
region: this.evt.options.region,
accessKeyId: this.S.config.awsAdminKeyId,
secretAccessKey: this.S.config.awsAdminSecretKey
});
return this.checkPath()
.then( () => {
const func = this.S.state.getFunctions({paths: [this.evt.options.path]})[0];
this.evt.data.lambdaName = this.Lambda.sGetLambdaName(func.getProject().name, func.getComponent().name, func.getModule().name, func.name);
let functionPath = path.join(this.S.config.projectPath, this.evt.options.path);
this.evt.data.event = require(path.join(functionPath, 'event'));
})
.then(() => {
this.function = this.S.state.getFunctions({ paths: [this.evt.options.path] })[0];
// Missing function
if (!this.function) return BbPromise.reject(new SError('Function could not be found at the path specified.'));
});
}
_invoke() {
let params = {
FunctionName: this.evt.data.lambdaName,
// ClientContext: new Buffer(JSON.stringify({x: 1, y: [3,4]})).toString('base64'),
InvocationType: this.evt.options.invocationType,
LogType: this.evt.options.logType,
Payload: new Buffer(JSON.stringify(this.evt.data.event)),
Qualifier: this.evt.options.stage
};
return this.Lambda.invokePromised(params)
.then( reply => {
let color = !reply.FunctionError ? 'white' : 'red';
if (reply.Payload) {
this.S.config.interactive && console.log(chalk[color](JSON.stringify(JSON.parse(reply.Payload), null, ' ')));
this.evt.data.payload = reply.Payload
}
if (reply.LogResult) {
console.log(chalk.gray('--------------------------------------------------------------------'))
let logResult = new Buffer(reply.LogResult, 'base64').toString()
_.each(logResult.split('\n'), (line) => {
console.log(SCli.formatLambdaLogEvent(line));
});
}
});
}
}
};

View File

@ -75,7 +75,7 @@ module.exports = function(SPlugin, serverlessPath) {
parameters: [
{
parameter: 'path',
description: 'Path of the function you want get logs from (componentName/moduleName/functionName)',
description: 'Path of the function you want get logs from (componentName/functionName)',
position: '0'
}
]
@ -86,7 +86,7 @@ module.exports = function(SPlugin, serverlessPath) {
functionLogs(evt) {
// Prompt: Stage
this.evt = evt
this.evt = evt;
// if (!this.S.config.interactive) return BbPromise.resolve();
if (!this.S.state.getStages().length) return BbPromise.reject(new SError('No existing stages in the project'));
@ -108,18 +108,14 @@ module.exports = function(SPlugin, serverlessPath) {
if (!this.evt.options.pollInterval) this.evt.options.pollInterval = 1000;
if (!this.evt.options.duration) this.evt.options.duration = '5m';
// If a function path was not specified.
if(!this.evt.options.path) {
// If s-function.json exists in the current path, then use the current function path.
if(SUtils.fileExistsSync(path.join(process.cwd(), 's-function.json'))) {
const componentName = path.basename(path.join(process.cwd(), '..', '..'));
const moduleName = path.basename(path.join(process.cwd(), '..'));
const functionName = path.basename(process.cwd());
this.evt.options.path = componentName + "/" + moduleName + "/" + functionName;
}
else {
return BbPromise.reject(new SError('Missing required function path param. Run from within a function directory, or add a function path in this format: componentName/moduleName/functionName'));
// If CLI and path is not specified, deploy from CWD if Function
if (this.S.cli && !this.evt.options.path) {
// Get all functions in CWD
let sPath = this.getSPathFromCwd(this.S.config.projectPath);
if (!sPath) {
throw new SError(`You must be in a function folder to run it`);
}
this.evt.options.path = [sPath];
}
this.spinner = SCli.spinner();
@ -141,7 +137,7 @@ module.exports = function(SPlugin, serverlessPath) {
this.evt.data.startTime = moment().subtract(duration.replace(/\D/g,''), duration.replace(/\d/g,'')).valueOf();
const lambdaName = this.Lambda.sGetLambdaName(func.getProject().name, func.getComponent().name, func.getModule().name, func.name);
const lambdaName = func.getDeployedName({ options: this.evt.options.stage, region: this.evt.options.region });
this.evt.data.logGroupName = '/aws/lambda/' + lambdaName;
this.evt.data.lambdaName = lambdaName;
@ -215,7 +211,5 @@ module.exports = function(SPlugin, serverlessPath) {
});
});
}
}
}
};

View File

@ -108,7 +108,7 @@ module.exports = function(SPlugin, serverlessPath) {
// Instantiate Classes
_this.project = _this.S.state.project.get();
// If CLI and no paths targeted, deploy from CWD if Function
// If CLI and path is not specified, deploy from CWD if Function
if (_this.S.cli && !_this.evt.options.path) {
// Get all functions in CWD
let sPath = _this.getSPathFromCwd(_this.S.config.projectPath);

View File

@ -10,26 +10,26 @@ describe('All Tests', function() {
});
after(function() {});
//require('./tests/classes/ServerlessStateTest');
//require('./tests/classes/ServerlessProjectTest');
//require('./tests/classes/ServerlessComponentTest');
//require('./tests/classes/ServerlessFunctionTest');
//require('./tests/classes/ServerlessEndpointTest');
//require('./tests/actions/TestPluginCustom');
//require('./tests/actions/TestDefaultActionHook');
//require('./tests/actions/StageCreate');
//require('./tests/actions/RegionCreate');
//require('./tests/actions/ComponentCreate');
//require('./tests/actions/FunctionCreate');
//require('./tests/actions/EnvList');
//require('./tests/actions/EnvGet');
//require('./tests/actions/EnvSetUnset');
//require('./tests/actions/ResourcesDeploy');
require('./tests/classes/ServerlessStateTest');
require('./tests/classes/ServerlessProjectTest');
require('./tests/classes/ServerlessComponentTest');
require('./tests/classes/ServerlessFunctionTest');
require('./tests/classes/ServerlessEndpointTest');
require('./tests/actions/TestPluginCustom');
require('./tests/actions/TestDefaultActionHook');
require('./tests/actions/StageCreate');
require('./tests/actions/RegionCreate');
require('./tests/actions/ComponentCreate');
require('./tests/actions/FunctionCreate');
require('./tests/actions/EnvList');
require('./tests/actions/EnvGet');
require('./tests/actions/EnvSetUnset');
require('./tests/actions/ResourcesDeploy');
require('./tests/actions/FunctionRun');
//require('./tests/actions/FunctionLogs');
//require('./tests/actions/FunctionDeploy');
//require('./tests/actions/EndpointDeploy');
//require('./tests/actions/ProjectInit');
//require('./tests/actions/ProjectInstall');
//require('./tests/actions/ProjectLifeCycle.js');
require('./tests/actions/FunctionLogs');
require('./tests/actions/FunctionDeploy');
require('./tests/actions/EndpointDeploy');
require('./tests/actions/ProjectInit');
require('./tests/actions/ProjectInstall');
require('./tests/actions/ProjectLifeCycle.js');
});

View File

@ -25,14 +25,12 @@ let validateEvent = function(evt) {
assert.equal(true, typeof evt.options.aliasFunction != 'undefined');
assert.equal(true, typeof evt.options.paths != 'undefined');
if (evt.data.failed) {
for (let i = 0; i < Object.keys(evt.data.failed).length; i++) {
console.log(Object.keys(evt.data.failed)[i]);
console.log(evt.data.failed[Object.keys(evt.data.failed)[i]]);
}
}
console.log(evt);
assert.equal(true, typeof evt.data.failed === 'undefined');
assert.equal(true, typeof evt.data.deployed != 'undefined');
};

View File

@ -1,67 +0,0 @@
'use strict';
/**
* Test: Function Invoke Action
* - Invokes a function
*/
let Serverless = require('../../../lib/Serverless.js'),
assert = require('chai').assert,
testUtils = require('../../test_utils'),
config = require('../../config');
let Lambda = require('../../../lib/utils/aws/Lambda')({
region: config.region,
accessKeyId: config.awsAdminKeyId,
secretAccessKey: config.awsAdminSecretKey
});
let serverless;
/**
* Validate Event
* - Validate an event object's properties
*/
let validateEvent = function(evt) {
assert.equal(true, typeof evt.options.stage != 'undefined');
assert.equal(true, typeof evt.options.region != 'undefined');
assert.equal(true, typeof evt.data.lambdaName != 'undefined');
assert.equal(true, typeof evt.data.payload != 'undefined');
};
describe('Test action: Function invoke', function() {
this.timeout(0);
before(function() {
return testUtils.createTestProject(config)
.then(projPath => {
process.chdir(projPath);
serverless = new Serverless({
awsAdminKeyId: config.awsAdminKeyId,
awsAdminSecretKey: config.awsAdminSecretKey,
interactive: false,
projectPath: projPath
});
return serverless.state.load();
});
});
describe('Function Invoke positive tests', function() {
it('should invoke the function', function() {
let evt = {
options: {
stage: config.stage,
region: config.region,
path: 'nodejscomponent/module1/function1'
}
};
return serverless.actions.functionInvoke(evt)
.then(validateEvent);
});
});
});