Merge pull request #3 from amarzavery/sway2

Sway2
This commit is contained in:
Amar Zavery 2017-01-24 13:40:40 -08:00 коммит произвёл GitHub
Родитель 9c59fd3073 2a95d0225d
Коммит 127930a667
8 изменённых файлов: 93 добавлений и 47 удалений

Просмотреть файл

@ -55,9 +55,12 @@ Commands:
validate-spec <spec-path> Performs semantic validation of the spec.
Options:
--version Show version number [boolean]
-j, --json Show json output [boolean]
-h, --help Show help [boolean]
--version Show version number [boolean]
-j, --json Show json output [boolean]
-l, --logLevel Set the logging level for console.
[choices: "error", "warn", "info", "verbose", "debug", "silly"] [default:
"warn"]
-h, --help Show help [boolean]
```
---

12
cli.js
Просмотреть файл

@ -11,10 +11,14 @@ yargs
.commandDir('lib/commands')
.option('h', {alias: 'help'})
.option('j', {alias: 'json', describe: 'Show json output', boolean: true})
.global(['h', 'j'])
.option('l', {alias: 'logLevel', describe: 'Set the logging level for console.', choices: ['error', 'warn', 'info' , 'verbose', 'debug', 'silly'], default: 'warn'})
.global(['h', 'j', 'l'])
.help()
.argv;
if (yargs.argv._.length === 0 && yargs.argv.h === false && yargs.argv.j === false) {
yargs.coerce('help', function(arg) {return true;}).argv;
}
//setting console logging level to the value provided by the user.
log.consoleLogLevel = yargs.argv.l;
if (yargs.argv._.length === 0 && yargs.argv.h === false && yargs.argv.j === false) {
yargs.coerce('help', function(arg) {return true;}).argv;
}

Просмотреть файл

@ -500,16 +500,24 @@ class SpecValidator {
if (exampleParameterValues === null || exampleParameterValues === undefined || typeof exampleParameterValues !== 'object') {
throw new Error(`In operation "${operation.operationId}", exampleParameterValues cannot be null or undefined and must be of type "object" (A dictionary of key-value pairs of parameter-names and their values).`);
}
let parameters = operation.getParameters();
let result = {request: null, validationResult: [] }, foundIssues = false;
let options = {};
options.method = operation.method;
options.pathTemplate = operation.pathObject.path;
parameters.forEach(function(parameter) {
for (let i=0; i<parameters.length; i++) {
let parameter = parameters[i];
if (!exampleParameterValues[parameter.name]) {
if (parameter.required) {
throw new Error(`In operation "${operation.operationId}", parameter ${parameter.name} is required in the swagger spec but is not present in the provided example parameter values.`);
let msg = `In operation "${operation.operationId}", parameter ${parameter.name} is required in the swagger spec but is not present in the provided example parameter values.`;
let e = self.constructErrorObject(ErrorCodes.RequiredParameterExampleNotFound, msg);
result.validationResult.push(e);
foundIssues = true;
break;
}
return;
continue;
}
let location = parameter.in;
if (location === 'path' || location === 'query') {
@ -530,11 +538,24 @@ class SpecValidator {
if (!options.headers) options.headers = {};
options.headers[parameter.name] = exampleParameterValues[parameter.name];
}
});
let request = new HttpRequest();
request = request.prepare(options);
let validationResult = operation.validateRequest(request);
let result = { request: request, validationResult: validationResult };
}
let request = null;
let validationResult = [];
if (!foundIssues) {
try {
request = new HttpRequest()
request = request.prepare(options);
validationResult = operation.validateRequest(request);
} catch (err) {
request = null;
let e = self.constructErrorObject(ErrorCodes.ErrorInPreparingRequest, error.message, [err]);
validationResult.push(e);
}
}
result.request = request;
result.validationResult = result.validationResult.concat(validationResult);
return result;
}

Просмотреть файл

@ -17,6 +17,8 @@ var Constants = {
ResolveSpecError: 'RESOLVE_SPEC_ERROR',
RefNotFoundError: 'REF_NOTFOUND_ERROR',
JsonParsingError: 'JSON_PARSING_ERROR',
RequiredParameterExampleNotFound: 'REQUIRED_PARAMETER_EXAMPLE_NOT_FOUND',
ErrorInPreparingRequest: 'ERROR_IN_PREPARING_REQUEST',
XmsExampleNotFoundError: 'X-MS-EXAMPLE_NOTFOUND_ERROR',
ResponseValidationError: 'RESPONSE_VALIDATION_ERROR',
RequestValidationError: 'REQUEST_VALIDATION_ERROR',

Просмотреть файл

@ -6,7 +6,6 @@
var winston = require('winston'),
path = require('path'),
fs = require('fs'),
utils = require('./utils'),
logDir = path.resolve(__dirname, '../..', 'output');
var currentLogFile;
@ -30,6 +29,31 @@ var logger = new (winston.Logger)({
]
});
/*
* Provides current time in custom format that will be used in naming log files. Example:'20140820_151113'
* @return {string} Current time in a custom string format
*/
function getTimeStamp() {
// We pad each value so that sorted directory listings show the files in chronological order
function pad(number){
if (number < 10)
{
return '0' + number;
}
return number;
}
var now = new Date();
return pad(now.getFullYear())
+ pad(now.getMonth() + 1)
+ pad(now.getDate())
+ "_"
+ pad(now.getHours())
+ pad(now.getMinutes())
+ pad(now.getSeconds());
}
//provides the log directory where the logs would reside
function getLogDir() {
if(!fs.existsSync(logDir)) {
@ -41,11 +65,26 @@ function getLogDir() {
//provides the log file path where logs would be stored
function getLogFilePath() {
if (!currentLogFile) {
let filename = `validate_log_${utils.getTimeStamp()}.log`;
let filename = `validate_log_${getTimeStamp()}.log`;
currentLogFile = path.join(getLogDir(), filename);
}
return currentLogFile;
}
Object.defineProperty(logger, 'consoleLogLevel', {
get: function() { return this.transports.console.level; },
set: function(level) {
if (!level) {
level = 'warn';
}
let validLevels = ['error', 'warn', 'info' , 'verbose', 'debug', 'silly'];
if (!validLevels.some(function(item) { return item === level; })) {
throw new Error(`The logging level provided is "${level}". Valid values are: "${validLevels}".`);
}
this.transports.console.level = level;
return;
}
});
module.exports = logger;

Просмотреть файл

@ -5,6 +5,7 @@
var fs = require('fs'),
util = require('util'),
path = require('path'),
log = require('./logging'),
request = require('request');
/*
@ -136,31 +137,6 @@ exports.makeRequest = function makeRequest(options) {
return promise;
};
/*
* Provides current time in custom format that will be used in naming log files. Example:'20140820_151113'
* @return {string} Current time in a custom string format
*/
exports.getTimeStamp = function getTimeStamp() {
// We pad each value so that sorted directory listings show the files in chronological order
function pad(number){
if (number < 10)
{
return '0' + number;
}
return number;
}
var now = new Date();
return pad(now.getFullYear())
+ pad(now.getMonth() + 1)
+ pad(now.getDate())
+ "_"
+ pad(now.getHours())
+ pad(now.getMinutes())
+ pad(now.getSeconds());
};
/*
* Executes an array of promises sequentially. Inspiration of this method is here:
* https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!

Просмотреть файл

@ -15,7 +15,6 @@
"ms-rest": "^1.15.2",
"ms-rest-azure": "^1.15.2",
"request": "^2.79.0",
"swagger-tools": "^0.10.1",
"sway": "^1.0.0",
"winston": "^2.3.0",
"yargs": "^6.6.0"

Просмотреть файл

@ -96,9 +96,10 @@ exports.validateExamplesInCompositeSpec = function validateExamplesInCompositeSp
exports.updateEndResultOfSingleValidation = function updateEndResultOfSingleValidation(validator) {
if (validator.specValidationResult.validityStatus) {
log.transports.console.level = 'info';
let consoleLevel = log.consoleLogLevel;
log.consoleLogLevel = 'info';
log.info('No Errors were found.');
log.transports.console.level = 'warn';
log.consoleLogLevel = consoleLevel;
}
if (!validator.specValidationResult.validityStatus) {
exports.finalValidationResult.validityStatus = validator.specValidationResult.validityStatus;
@ -108,11 +109,12 @@ exports.updateEndResultOfSingleValidation = function updateEndResultOfSingleVali
exports.logDetailedInfo = function logDetailedInfo(validator, json) {
if (json) {
log.transports.console.level = 'info';
let consoleLevel = log.consoleLogLevel;
log.consoleLogLevel = 'info';
log.info('############################');
log.info(validator.specValidationResult);
log.info('----------------------------');
log.transports.console.level = 'warn';
log.consoleLogLevel = consoleLevel;
} else {
log.silly('############################');
log.silly(validator.specValidationResult);