Skip to content
This repository was archived by the owner on May 11, 2023. It is now read-only.
Open
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
57 changes: 57 additions & 0 deletions sdkgen/nodejs-request/npm/test-lint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env node
require('shelljs/global');

var chalk = require('chalk'),
async = require('async'),
ESLintCLIEngine = require('eslint').CLIEngine,

/**
* The list of source code files / directories to be linted.
*
* @type {Array}
*/
LINT_SOURCE_DIRS = [
'./lib',
// './test',
'./npm/*.js',
'./index.js'
];

module.exports = function (exit) {
// banner line
console.info(chalk.yellow.bold('\nLinting files using eslint...'));

async.waterfall([

/**
* Instantiates an ESLint CLI engine and runs it in the scope defined within LINT_SOURCE_DIRS.
*
* @param {Function} next - The callback function whose invocation marks the end of the lint test run.
* @returns {*}
*/
function (next) {
next(null, (new ESLintCLIEngine()).executeOnFiles(LINT_SOURCE_DIRS));
},

/**
* Processes a test report from the Lint test runner, and displays meaningful results.
*
* @param {Object} report - The overall test report for the current lint test.
* @param {Object} report.results - The set of test results for the current lint run.
* @param {Function} next - The callback whose invocation marks the completion of the post run tasks.
* @returns {*}
*/
function (report, next) {
var errorReport = ESLintCLIEngine.getErrorResults(report.results);
// log the result to CLI
console.info(ESLintCLIEngine.getFormatter()(report.results));
// log the success of the parser if it has no errors
(errorReport && !errorReport.length) && console.info(chalk.green('eslint ok!'));
// ensure that the exit code is non zero in case there was an error
next(Number(errorReport && errorReport.length) || 0);
}
], exit);
};

// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
60 changes: 60 additions & 0 deletions sdkgen/nodejs-request/npm/test-unit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/usr/bin/env node
/* eslint-env node, es6 */
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to execute all unit tests.
// ---------------------------------------------------------------------------------------------------------------------

require('shelljs/global');

// set directories and files for test and coverage report
var path = require('path'),

NYC = require('nyc'),
chalk = require('chalk'),
recursive = require('recursive-readdir'),

COV_REPORT_PATH = '.coverage',
SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'unit');

module.exports = function (exit) {
// banner line
console.info(chalk.yellow.bold('Running unit tests using mocha on node...'));

test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH);
mkdir('-p', COV_REPORT_PATH);
mkdir('-p', COV_REPORT_PATH + '/processinfo');

var Mocha = require('mocha'),
nyc = new NYC({
reportDir: COV_REPORT_PATH,
tempDirectory: COV_REPORT_PATH,
reporter: ['text', 'lcov', 'text-summary'],
exclude: ['config', 'test'],
hookRunInContext: true,
hookRunInThisContext: true
});

nyc.wrap();
// add all spec files to mocha
recursive(SPEC_SOURCE_DIR, function (err, files) {
if (err) { console.error(err); return exit(1); }

var mocha = new Mocha({ timeout: 1000 * 60 });

files.filter(function (file) { // extract all test files
return (file.substr(-8) === '.test.js');
}).forEach(mocha.addFile.bind(mocha));

mocha.run(function (runError) {
runError && console.error(runError.stack || runError);

nyc.reset();
nyc.writeCoverageFile();
nyc.report();
exit(runError ? 1 : 0);
});
});
};

// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
15 changes: 15 additions & 0 deletions sdkgen/nodejs-request/npm/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node
var chalk = require('chalk'),
exit = require('shelljs').exit,
prettyms = require('pretty-ms'),
startedAt = Date.now(),
name = require('../package.json').name;

require('async').series([
require('./test-lint'),
require('./test-unit')
], function (code) {
// eslint-disable-next-line max-len
console.info(chalk[code ? 'red' : 'green'](`\n${name}: duration ${prettyms(Date.now() - startedAt)}\n${name}: ${code ? 'not ok' : 'ok'}!`));
exit(code && (typeof code === 'number' ? code : 1) || 0);
});
3 changes: 3 additions & 0 deletions sdkgen/nodejs-request/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
"description": "Converts Postman Collection to nodejs-request client SDK",
"main": "index.js",
"license": "Apache-2.0",
"scripts": {
"test": "node npm/test.js"
},
"dependencies": {
"request": "^2.88.2"
}
Expand Down
9 changes: 9 additions & 0 deletions sdkgen/nodejs-request/test/fixtures/utilMethodOutputs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"SANITIZE" : "test\\'string\\\\n\\\\",
"GENERATE_FUNCTION_SNIPPEPT": "/**\nThe HTTP `GET` request method is meant to retrieve data from a server. The data\nis identified by a unique URI (Uniform Resource Identifier). \n\nA `GET` request can pass parameters to the server using "Query String \nParameters". For example, in the following request,\n\n> http://example.com/hi/there?hand=wave\n\nThe parameter "hand" has the value "wave".\n\nThis endpoint echoes the HTTP headers, request parameters and the complete\nURI requested.\n@param {String} variables.url\n@param {String} variables.var1\n@param {String} variables.var4\n@param {String} variables.var2\n@param {String} variables.var5\n@param {Function} callback - Callback function to return response (err, res)\n*/\nthis.GET_REQUEST = function(variables, callback){\nif (typeof variables === 'function') {\ncallback = variables;\nvariables = {};\n}\nvar url = variables.url ? variables.url : self.variables.url;\nvar var1 = variables.var1 ? variables.var1 : self.variables.var1;\nvar var4 = variables.var4 ? variables.var4 : self.variables.var4;\nvar var2 = variables.var2 ? variables.var2 : self.variables.var2;\nvar var5 = variables.var5 ? variables.var5 : self.variables.var5;\nvar options = {\n 'method': 'GET',\n 'url': '' + url + '/get?foo1=' + var1 + '' + var4 + '&foo2=' + var2 + '' + var5 + '',\n 'headers': {\n }\n};\nrequest(options, function (error, response) {\n callback(error, response);\n});\n}",
"ITEM_HANDLER": {
"COLLECTION_AS_PARENT": "/**\nThe HTTP `GET` request method is meant to retrieve data from a server. The data\nis identified by a unique URI (Uniform Resource Identifier). \n\nA `GET` request can pass parameters to the server using "Query String \nParameters". For example, in the following request,\n\n> http://example.com/hi/there?hand=wave\n\nThe parameter "hand" has the value "wave".\n\nThis endpoint echoes the HTTP headers, request parameters and the complete\nURI requested.\n@param {String} variables.url\n@param {String} variables.var1\n@param {String} variables.var4\n@param {String} variables.var2\n@param {String} variables.var5\n@param {Function} callback - Callback function to return response (err, res)\n*/\nthis.GET_REQUEST = function(variables, callback){\nif (typeof variables === 'function') {\ncallback = variables;\nvariables = {};\n}\nvar url = variables.url ? variables.url : self.variables.url;\nvar var1 = variables.var1 ? variables.var1 : self.variables.var1;\nvar var4 = variables.var4 ? variables.var4 : self.variables.var4;\nvar var2 = variables.var2 ? variables.var2 : self.variables.var2;\nvar var5 = variables.var5 ? variables.var5 : self.variables.var5;\nvar options = {\n 'method': 'GET',\n 'url': '' + url + '/get?foo1=' + var1 + '' + var4 + '&foo2=' + var2 + '' + var5 + '',\n 'headers': {\n }\n};\nrequest(options, function (error, response) {\n callback(error, response);\n});\n};\n\n",
"ITEMGROUP_AS_PARENT": "/**\nThe HTTP `POST` request method is meant to transfer data to a server \n(and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `POST` request can pass parameters to the server using "Query String \nParameters", as well as the Request Body. For example, in the following request,\n\n> POST /hi/there?hand=wave\n>\n> <request-body>\n\nThe parameter "hand" has the value "wave". The request body can be in multiple\nformats. These formats are defined by the MIME type of the request. The MIME \nType can be set using the ``Content-Type`` HTTP header. The most commonly used \nMIME types are:\n\n* `multipart/form-data`\n* `application/x-www-form-urlencoded`\n* `application/json`\n\nThis endpoint echoes the HTTP headers, request parameters, the contents of\nthe request body and the complete URI requested when data is sent as a form parameter.\n@param {String} variables.url\n@param {String} variables.var4\n@param {String} variables.var5\n@param {Function} callback - Callback function to return response (err, res)\n*/\n\"POST_FORM_DATA\": function(variables, callback){\nif (typeof variables === 'function') {\ncallback = variables;\nvariables = {};\n}\nvar url = variables.url ? variables.url : self.variables.url;\nvar var4 = variables.var4 ? variables.var4 : self.variables.var4;\nvar var5 = variables.var5 ? variables.var5 : self.variables.var5;\nvar options = {\n 'method': 'POST',\n 'url': '' + url + '/post',\n 'headers': {\n },\n form: {\n 'foo1': '' + var4 + '',\n 'foo2': '' + var5 + ''\n }\n};\nrequest(options, function (error, response) {\n callback(error, response);\n});\n}\n"
},
"GET_VARIABLE_FUNCTIONS": "/**\nFunction to set variables for entire SDK. These variables will override existing/default values.\n\n@param {Object} Object containing env variables\n*/\nSDK.prototype.setVariables = function (vars) {\nlet variables = JSON.parse(JSON.stringify(this.variables || configVariables));\nObject.keys(vars).forEach(function (key) {\nvariables[key] = vars[key];\n});\nthis.variables = variables;\nreturn this.variables;\n};\n\n/**\nMethod to retrieve current variable.\n\n@param {string} [var] - Variable name\n@returns {Object} object containing variables\n*/\nSDK.prototype.getVariables = function (variable) {\nreturn variable ? this.variables[variable] : this.variables;\n};\n\nmodule.exports = SDK;\n"
}
96 changes: 96 additions & 0 deletions sdkgen/nodejs-request/test/unit/snippet.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const expect = require('chai').expect,
sdk = require('postman-collection'),
collection = {
SDKGEN: require('../../../../test/fixtures/SDKGEN.postman_collection.json')
},
variables = {
SDKGEN: require('../../../../test/fixtures/SDKGEN_ENVIRONMENT.json')
},
generate = require('../../index').generate,
COLLECTION_INSTANCE = new sdk.Collection(collection.SDKGEN);

describe('Tests for generated sdk', () => {

it('should generate sdk snippet', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
});
});

it('should include nodejs-request library import', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('var request = require(\'request\')');
});
});


it('should add variable if provided', async () => {
await generate(COLLECTION_INSTANCE, {
variableList: new sdk.VariableList(null, variables.SDKGEN.values)
}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('\'url\': \'www.google.com\'');
expect(snippet).to.include('\'var1\': \'valenv1\'');
expect(snippet).to.include('\'var2\': \'valenv2\'');
});
});

it('should have default constructor for generated module', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('function SDK(config = {})');
});
});

it('should have get/set Variable methods', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('SDK.prototype.setVariables = function (vars) {');
expect(snippet).to.include('SDK.prototype.getVariables = function (variable) {');
});
});

it('should set initial variables values', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include('this.variables = this.setVariables(config)')
});
});

it('should have self variable declaration', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.include('self = this');
});
});

it('should have export module snipept', async () => {
await generate(COLLECTION_INSTANCE, {}, (err, snippet) => {
if (err) {
expect(err).to.be.null;
}
expect(snippet).to.include('module.exports = SDK');
});
});
});
60 changes: 60 additions & 0 deletions sdkgen/nodejs-request/test/unit/util.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const expect = require('chai').expect,
sdk = require('postman-collection'),
utils = require('../../lib/util'),
outputs = require('../fixtures/utilMethodOutputs.json'),
collection = {
SDKGEN: require('../../../../test/fixtures/SDKGEN.postman_collection.json')
},
COLLECTION_INSTANCE = new sdk.Collection(collection.SDKGEN);

describe('Util methods tests:', () => {
it('should sanitize strings properly', () => {
// eslint-disable-next-line quotes
let s = "test'string\\n\\";
s = utils.sanitize(s);
expect(s).to.be.a('string');
expect(s).to.equals(outputs.SANITIZE);
});

it('should generate function snippet for a request', async () => {
let snippet;
try {
snippet = await utils.generateFunctionSnippet(COLLECTION_INSTANCE.items.members[2], {});
}
catch (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.be.equals(outputs.GENERATE_FUNCTION_SNIPPEPT);
});

it('should generate item snippet for input item (parent --> collection instance)', async () => {
let snippet;
try {
snippet = await utils.itemHandler(COLLECTION_INSTANCE.items.members[2], {});
}
catch (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.be.equals(outputs.ITEM_HANDLER.COLLECTION_AS_PARENT);
});

it('should generate item snippet for input item (parent --> itemgroup instance)', async () => {
let snippet;
try {
snippet = await utils.itemHandler(COLLECTION_INSTANCE.items.members[0].items.members[0], {});
}
catch (err) {
expect(err).to.be.null;
}
expect(snippet).to.be.a('string');
expect(snippet).to.include(outputs.ITEM_HANDLER.ITEMGROUP_AS_PARENT);
});

it('should generate snippet for get/set methods', () => {
let snippet = utils.getVariableFunctions();
expect(snippet).to.be.a('string');
expect(snippet).to.include(outputs.GET_VARIABLE_FUNCTIONS);
});
});
Loading