diff --git a/.github/ISSUE_TEMPLATE/Pull_request.md b/.github/ISSUE_TEMPLATE/Pull_request.md new file mode 100644 index 000000000..44d73c1e6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Pull_request.md @@ -0,0 +1,18 @@ + **What this PR does** +<< Please describe briefly what this PR is trying to solve >> + +**Changes you made** +<< List all the changes you made >> + +**Screenshot/ CodeSnippet** +<< Attach relevant screenshots or code snippets related to this PR >> + +**Test Configuration**: +<< Please describe the tests that you ran to verify your changes >> + +**Follow up** +<< Anything you want to share >> + + + +*Thanks for contributing!* ❤️ \ No newline at end of file diff --git a/.gitignore b/.gitignore index 3d3f1a253..e3034d0ee 100644 --- a/.gitignore +++ b/.gitignore @@ -66,4 +66,5 @@ typings/ out/ -newmanResponses.json \ No newline at end of file +newmanResponses.json +dummyFile*.txt \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..bf30a8c78 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +v1.0.0 (May 29, 2020) +- Add axios framework support +- Add ES6 syntax support for NodeJS Request, NodeJS Native and NodeJS Unirest +- Fix snippet generation for powershell and jquery, where form data params had no type field \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b671790f6..9fdf9aefe 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,7 +10,7 @@ - [Pull request guidelines](#pull-request-guidelines) - [Tests](#tests) - [Build Failures](build-failures) - - [Security guildelines](security-guidelines) + - [Security guidelines](security-guidelines) ## Getting Started Quick @@ -33,7 +33,7 @@ Installs all `dependencies` of all the codegens. This runs the command `npm inst The script associated with `npm test` will run all tests that ensures that your commit does not break anything in the repository. Additional requirements to run these tests have been listed down in [ADDITIONAL_DEPENDENCIES](/ADDITIONAL_DEPENDENCIES.md) -* `npm test`: Runs strucutre, unit, newman and system tests for all codegens +* `npm test`: Runs structure, unit, newman and system tests for all codegens * `npm run test `: Runs tests for a particular codegen. @@ -86,7 +86,7 @@ One of the following two contributions are possible for postman-code-generators: - All pull requests should be to the develop branch. - Every pull request should have associated issue(s) on our [issue tracker](https://github.com/postmanlabs/postman-code-generators/issues). - For any non-trivial fixes, regression tests should be added as well. For a bug, we also recommend adding a request to the `testCollection.json` found inside `test/codegen/newman/fixtures` to run the request using common newman tests. - - For a new language to be added as a part of postman-code-generators, we will need some level of community support before we are able to accept the pull request. Feel free to add links to any sort of report/statistics from trusted sources that might help us understand the relavance and popularity of this language among users. + - For a new language to be added as a part of postman-code-generators, we will need some level of community support before we are able to accept the pull request. Feel free to add links to any sort of report/statistics from trusted sources that might help us understand the relevance and popularity of this language among users. ## Tests diff --git a/README.md b/README.md index 471261795..f4beebd32 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ List of supported code generators: | Language | Variant | |-----------|---------------| +| C | libcurl | | C# | RestSharp | | cURL | cURL | | Go | Native | @@ -25,7 +26,8 @@ List of supported code generators: | Java | Unirest | | JavaScript | Fetch | | JavaScript | jQuery | -| JavaScript | XHR | +| JavaScript | XHR | +| NodeJs | Axios | | NodeJs | Native | | NodeJs | Request | | NodeJs | Unirest | @@ -35,6 +37,8 @@ List of supported code generators: |PHP | pecl_http | |PHP | HTTP_Request2 | | PowerShell | RestMethod | +| Python | http.client | +| Python | Requests | | Ruby | Net:HTTP | | Shell | Httpie | | Shell | wget | @@ -104,7 +108,7 @@ var codegen = require('postman-code-generators'), // require postman-code-genera This function takes in three parameters and returns a callback with error and supported options of that code generator. -* `language` - langugage key from the language list returned from getLanguageList function +* `language` - language key from the language list returned from getLanguageList function * `variant` - variant key provided by getLanguageList function * `callback` - callback function with first parameter as error and second parameter as array of options supported by the codegen. @@ -153,15 +157,16 @@ This function takes in five parameters and returns a callback with error and gen * `language` - lang key from the language list returned from getLanguageList function * `variant` - variant key provided by getLanguageList function * `request` - [Postman-SDK](https://github.com/postmanlabs/postman-collection) Request Object -* `options` - Options that can be used to configure generated code snippet. Defaults will be used for the +* `options` - Options that can be used to configure generated code snippet. Defaults will be used for the unspecified attributes * `callback` - callback function with first parameter as error and second parameter as string for code snippet ##### Example: ```js var codegen = require('postman-code-generators'), // require postman-code-generators in your project - request = new sdk.Request('www.google.com'), //using postman sdk to create request + sdk = require('postman-collection'), // require postman-collection in your project + request = new sdk.Request('https://www.google.com'), //using postman sdk to create request language = 'nodejs', - variant = 'requests', + variant = 'request', options = { indentCount: 3, indentType: 'Space', diff --git a/codegens/csharp-restsharp/lib/parseRequest.js b/codegens/csharp-restsharp/lib/parseRequest.js index 94e320ebc..c900f42b7 100644 --- a/codegens/csharp-restsharp/lib/parseRequest.js +++ b/codegens/csharp-restsharp/lib/parseRequest.js @@ -96,7 +96,7 @@ function parseBody (request, trimFields) { /** * Parses header in Postman-SDK request and returns code snippet of csharp-restsharp for adding headers * - * @param {Object} requestJson - Postman SDK reqeust object + * @param {Object} requestJson - Postman SDK request object * @returns {String} code snippet for adding headers in csharp-restsharp */ function parseHeader (requestJson) { @@ -106,7 +106,12 @@ function parseHeader (requestJson) { return requestJson.header.reduce((headerSnippet, header) => { if (!header.disabled) { - headerSnippet += `request.AddHeader("${sanitize(header.key, true)}", "${sanitize(header.value)}");\n`; + if (sanitize(header.key, true).toLowerCase() === 'user-agent') { + headerSnippet += `client.UserAgent = "${sanitize(header.value)}";\n`; + } + else { + headerSnippet += `request.AddHeader("${sanitize(header.key, true)}", "${sanitize(header.value)}");\n`; + } } return headerSnippet; }, ''); diff --git a/codegens/csharp-restsharp/lib/restsharp.js b/codegens/csharp-restsharp/lib/restsharp.js index b1902240d..ec0b86bc8 100644 --- a/codegens/csharp-restsharp/lib/restsharp.js +++ b/codegens/csharp-restsharp/lib/restsharp.js @@ -172,7 +172,7 @@ self = module.exports = { * @param {String} options.indentType - type for indentation eg: Space, Tab (default: Space) * @param {String} options.indentCount - number of spaces or tabs for indentation. (default: 4 for indentType: Space, default: 1 for indentType: Tab) - * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class defination in C# + * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class definition in C# * @param {Boolean} options.followRedirect - whether to enable followredirect * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not (default: false) * @param {Number} options.requestTimeout - time in milli-seconds after which request will bail out diff --git a/codegens/csharp-restsharp/npm/test-lint.js b/codegens/csharp-restsharp/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/csharp-restsharp/npm/test-lint.js +++ b/codegens/csharp-restsharp/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/csharp-restsharp/npm/test-newman.js b/codegens/csharp-restsharp/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/csharp-restsharp/npm/test-newman.js +++ b/codegens/csharp-restsharp/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/csharp-restsharp/npm/test-unit.js b/codegens/csharp-restsharp/npm/test-unit.js index 1bd787adb..0de7fd529 100644 --- a/codegens/csharp-restsharp/npm/test-unit.js +++ b/codegens/csharp-restsharp/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/csharp-restsharp/test/unit/convert.test.js b/codegens/csharp-restsharp/test/unit/convert.test.js index 764147477..dafd37385 100644 --- a/codegens/csharp-restsharp/test/unit/convert.test.js +++ b/codegens/csharp-restsharp/test/unit/convert.test.js @@ -162,6 +162,36 @@ describe('csharp restsharp function', function () { expect(snippet).to.include('request.AddFile("invalid src", "/path/to/file"'); }); }); + + it('should use client.UserAgent instead of AddHeader function', function () { + const sampleUA = 'Safari/605.1.15', + expectValue = `client.UserAgent = "${sampleUA}";`; + + var request = new sdk.Request({ + 'method': 'GET', + 'header': [ + { + 'key': 'User-Agent', + 'value': sampleUA + } + ], + 'url': { + 'raw': 'https://google.com', + 'protocol': 'https', + 'host': [ + 'google', + 'com' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include(expectValue); + }); + }); }); describe('getOptions function', function () { diff --git a/codegens/curl/npm/test-lint.js b/codegens/curl/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/curl/npm/test-lint.js +++ b/codegens/curl/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/curl/npm/test-newman.js b/codegens/curl/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/curl/npm/test-newman.js +++ b/codegens/curl/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/curl/npm/test-unit.js b/codegens/curl/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/curl/npm/test-unit.js +++ b/codegens/curl/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/golang/npm/test-lint.js b/codegens/golang/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/golang/npm/test-lint.js +++ b/codegens/golang/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/golang/npm/test-newman.js b/codegens/golang/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/golang/npm/test-newman.js +++ b/codegens/golang/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/golang/npm/test-unit.js b/codegens/golang/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/golang/npm/test-unit.js +++ b/codegens/golang/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/http/README.md b/codegens/http/README.md index 0b8ec276f..16e6b4546 100644 --- a/codegens/http/README.md +++ b/codegens/http/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `trimRequestBody` - Trim request body fields * `callback` - callback function with first parameter as error and second parameter as string for code snippet diff --git a/codegens/http/lib/util.js b/codegens/http/lib/util.js index d8d951c42..ff27ec296 100644 --- a/codegens/http/lib/util.js +++ b/codegens/http/lib/util.js @@ -104,7 +104,7 @@ function getMembersOfPropertyList (propertyList, includeDisabled = false) { * @param {Object} propertyList propertyList * @param {String} joinUsing specify string that should be used to join the list of properties * @param {Boolean} includeDisabled indicated whether or not to include disabled properties - * @param {Boolean} trimRequestBody indicates whether or not to trin request body + * @param {Boolean} trimRequestBody indicates whether or not to trim request body * @returns {String} Stringified property List */ function convertPropertyListToString (propertyList, joinUsing, includeDisabled = false, trimRequestBody = false) { diff --git a/codegens/http/npm/test-lint.js b/codegens/http/npm/test-lint.js index 3e9e49302..b0642c0b3 100644 --- a/codegens/http/npm/test-lint.js +++ b/codegens/http/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -52,4 +51,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/http/npm/test-unit.js b/codegens/http/npm/test-unit.js index 007c2507c..a7f794be6 100644 --- a/codegens/http/npm/test-unit.js +++ b/codegens/http/npm/test-unit.js @@ -1,9 +1,9 @@ #!/usr/bin/env node -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -16,8 +16,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -52,4 +52,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-okhttp/README.md b/codegens/java-okhttp/README.md index 9ea23f404..c0c749a97 100644 --- a/codegens/java-okhttp/README.md +++ b/codegens/java-okhttp/README.md @@ -61,7 +61,7 @@ console.log(options); ``` ### Guideline for using generated snippet -* Generated snippet requires dependecies [okhttp3](https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/3.9.1) and [okio](https://mvnrepository.com/artifact/com.squareup.okio/okio/1.13.0) to compile and run +* Generated snippet requires dependencies [okhttp3](https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/3.9.1) and [okio](https://mvnrepository.com/artifact/com.squareup.okio/okio/1.13.0) to compile and run * Generated snippet uses `.method(nameOfMethod, body)` from `Request` class to form HTTP request. If the `method` doesn't require body then the value of `body` will be `null`. diff --git a/codegens/java-okhttp/lib/okhttp.js b/codegens/java-okhttp/lib/okhttp.js index d7e927a6c..e4d73b504 100644 --- a/codegens/java-okhttp/lib/okhttp.js +++ b/codegens/java-okhttp/lib/okhttp.js @@ -9,7 +9,7 @@ var _ = require('./lodash'), const METHODS_WITHOUT_BODY = ['GET', 'HEAD', 'COPY', 'UNLOCK', 'UNLINK', 'PURGE', 'LINK', 'VIEW']; /** - * retuns snippet of java okhttp by parsing data from Postman-SDK request object + * returns snippet of java okhttp by parsing data from Postman-SDK request object * * @param {Object} request - Postman SDK request object * @param {String} indentString - indentation required for code snippet @@ -157,7 +157,7 @@ function getOptions () { * @param {Object} options - Options to tweak code snippet generated in Java-OkHttp * @param {String} options.indentType - type for indentation eg: Space, Tab * @param {String} options.indentCount - number of spaces or tabs for indentation. - * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class defination in java + * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class definition in java * @param {Boolean} options.followRedirect - whether to enable followredirect * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out diff --git a/codegens/java-okhttp/lib/parseRequest.js b/codegens/java-okhttp/lib/parseRequest.js index b3805953d..530d8a8aa 100644 --- a/codegens/java-okhttp/lib/parseRequest.js +++ b/codegens/java-okhttp/lib/parseRequest.js @@ -107,7 +107,7 @@ function parseBody (requestBody, indentString, trimFields) { /** * Parses header in Postman-SDK request and returns code snippet of java okhttp for adding headers * - * @param {Object} request - Postman SDK reqeust object + * @param {Object} request - Postman SDK request object * @param {String} indentString - indentation for code snippet * @returns {String} - code snippet for adding headers in java-okhttp */ diff --git a/codegens/java-okhttp/npm/test-lint.js b/codegens/java-okhttp/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/java-okhttp/npm/test-lint.js +++ b/codegens/java-okhttp/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-okhttp/npm/test-newman.js b/codegens/java-okhttp/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/java-okhttp/npm/test-newman.js +++ b/codegens/java-okhttp/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-okhttp/npm/test-unit.js b/codegens/java-okhttp/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/java-okhttp/npm/test-unit.js +++ b/codegens/java-okhttp/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-okhttp/test/newman/newman.test.js b/codegens/java-okhttp/test/newman/newman.test.js index 6b6b472bd..f2dc6fb3f 100644 --- a/codegens/java-okhttp/test/newman/newman.test.js +++ b/codegens/java-okhttp/test/newman/newman.test.js @@ -1,12 +1,13 @@ var runNewmanTest = require('../../../../test/codegen/newman/newmanTestUtil').runNewmanTest, convert = require('../../lib/index').convert; -describe('convert for different request types', function () { +describe.skip('convert for different request types', function () { var options = {indentCount: 3, indentType: 'Space', includeBoilerplate: true}, testConfig = { compileScript: 'javac -cp *: main.java', runScript: 'java -cp *: main', - fileName: 'main.java' + fileName: 'main.java', + skipCollections: ['redirectCollection'] }; runNewmanTest(convert, options, testConfig); }); diff --git a/codegens/java-okhttp/test/unit/fixtures/dependencies.zip b/codegens/java-okhttp/test/unit/fixtures/dependencies.zip new file mode 100644 index 000000000..fdffe48b5 Binary files /dev/null and b/codegens/java-okhttp/test/unit/fixtures/dependencies.zip differ diff --git a/codegens/java-unirest/README.md b/codegens/java-unirest/README.md index 10fbc0208..d72945d19 100644 --- a/codegens/java-unirest/README.md +++ b/codegens/java-unirest/README.md @@ -61,7 +61,7 @@ console.log(options); ``` ### Guideline for using generated snippet -* To download dependecies to use snippet please see [unirest-doc](http://unirest.io/java.html) +* To download dependencies to use snippet please see [unirest-doc](http://unirest.io/java.html) * This module supports six HTTP request methods. **GET** **POST** **PUT** **PATCH** **DELETE** **OPTIONS** **HEAD** diff --git a/codegens/java-unirest/lib/unirest.js b/codegens/java-unirest/lib/unirest.js index 8a3b0b397..f72043563 100644 --- a/codegens/java-unirest/lib/unirest.js +++ b/codegens/java-unirest/lib/unirest.js @@ -158,7 +158,7 @@ function getOptions () { * @param {Object} options * @param {String} options.indentType - type for indentation eg: Space, Tab * @param {String} options.indentCount - number of spaces or tabs for indentation. - * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class defination in java + * @param {Boolean} [options.includeBoilerplate] - indicates whether to include class definition in java * @param {Boolean} options.followRedirect - whether to enable followredirect * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out diff --git a/codegens/java-unirest/npm/test-lint.js b/codegens/java-unirest/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/java-unirest/npm/test-lint.js +++ b/codegens/java-unirest/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-unirest/npm/test-newman.js b/codegens/java-unirest/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/java-unirest/npm/test-newman.js +++ b/codegens/java-unirest/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-unirest/npm/test-unit.js b/codegens/java-unirest/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/java-unirest/npm/test-unit.js +++ b/codegens/java-unirest/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/java-unirest/test/unit/fixtures/dependencies.zip b/codegens/java-unirest/test/unit/fixtures/dependencies.zip new file mode 100644 index 000000000..b85e54359 Binary files /dev/null and b/codegens/java-unirest/test/unit/fixtures/dependencies.zip differ diff --git a/codegens/js-fetch/README.md b/codegens/js-fetch/README.md index 00d392269..2d592ae1d 100644 --- a/codegens/js-fetch/README.md +++ b/codegens/js-fetch/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Trim request body fields diff --git a/codegens/js-fetch/npm/test-lint.js b/codegens/js-fetch/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/js-fetch/npm/test-lint.js +++ b/codegens/js-fetch/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-fetch/npm/test-newman.js b/codegens/js-fetch/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/js-fetch/npm/test-newman.js +++ b/codegens/js-fetch/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-fetch/npm/test-unit.js b/codegens/js-fetch/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/js-fetch/npm/test-unit.js +++ b/codegens/js-fetch/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-fetch/package.json b/codegens/js-fetch/package.json index f7c864b59..f68ffd0e3 100644 --- a/codegens/js-fetch/package.json +++ b/codegens/js-fetch/package.json @@ -28,7 +28,7 @@ "homepage": "https://github.com/postmanlabs/code-generators/tree/master/codegens/js-fetch", "dependencies": {}, "devDependencies": { - "form-data": "2.3.2", + "form-data": "2.5.1", "node-fetch": "2.1.1" }, "engines": { diff --git a/codegens/js-jquery/README.md b/codegens/js-jquery/README.md index 0dce1f18c..6c4c64f65 100644 --- a/codegens/js-jquery/README.md +++ b/codegens/js-jquery/README.md @@ -12,7 +12,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Trim request body fields diff --git a/codegens/js-jquery/lib/js-jquery.js b/codegens/js-jquery/lib/js-jquery.js index c03d3e99e..b2e1feae5 100644 --- a/codegens/js-jquery/lib/js-jquery.js +++ b/codegens/js-jquery/lib/js-jquery.js @@ -51,14 +51,15 @@ function createForm (request, trimRequestBody) { enabledFormList = _.reject(request.body[request.body.mode], 'disabled'); if (!_.isEmpty(enabledFormList)) { formMap = _.map(enabledFormList, function (value) { - if (value.type === 'text') { - return (`form.append("${sanitize(value.key, request.body.mode, trimRequestBody)}", "` + - `${sanitize(value.value, request.body.mode, trimRequestBody)}");`); + if (value.type === 'file') { + var pathArray = value.src.split(path.sep), + fileName = pathArray[pathArray.length - 1]; + return (`form.append("${sanitize(value.key, request.body.mode, trimRequestBody)}", fileInput.files[0], ` + + `"${sanitize(fileName, request.body.mode, trimRequestBody)}");`); } - var pathArray = value.src.split(path.sep), - fileName = pathArray[pathArray.length - 1]; - return (`form.append("${sanitize(value.key, request.body.mode, trimRequestBody)}", fileInput.files[0], ` + - `"${sanitize(fileName, request.body.mode, trimRequestBody)}");`); + return (`form.append("${sanitize(value.key, request.body.mode, trimRequestBody)}", "` + + `${sanitize(value.value, request.body.mode, trimRequestBody)}");`); + }); form += `${formMap.join('\n')}\n\n`; } diff --git a/codegens/js-jquery/npm/test-lint.js b/codegens/js-jquery/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/js-jquery/npm/test-lint.js +++ b/codegens/js-jquery/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-jquery/npm/test-unit.js b/codegens/js-jquery/npm/test-unit.js index 1bd787adb..0de7fd529 100644 --- a/codegens/js-jquery/npm/test-unit.js +++ b/codegens/js-jquery/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-jquery/test/unit/converter.test.js b/codegens/js-jquery/test/unit/converter.test.js index 0d2c3b819..08caf83a5 100644 --- a/codegens/js-jquery/test/unit/converter.test.js +++ b/codegens/js-jquery/test/unit/converter.test.js @@ -268,4 +268,36 @@ describe('jQuery converter', function () { expect(snippet).to.not.include('"sample_key": "value2"'); }); }); + + it('should generate snippet for form data params with no type key present', function () { + var request = new sdk.Request({ + method: 'POST', + header: [], + url: { + raw: 'https://postman-echo.com/post', + protocol: 'https', + host: [ + 'postman-echo', + 'com' + ], + path: [ + 'post' + ] + }, + body: { + mode: 'formdata', + formdata: [ + { + key: 'sample_key', + value: 'sample_value' + } + ] + } + }); + convert(request, {}, function (error, snippet) { + expect(error).to.be.null; + expect(snippet).to.be.a('string'); + expect(snippet).to.include('form.append("sample_key", "sample_value")'); + }); + }); }); diff --git a/codegens/js-xhr/README.md b/codegens/js-xhr/README.md index 5d7f657dc..76895ca68 100644 --- a/codegens/js-xhr/README.md +++ b/codegens/js-xhr/README.md @@ -12,7 +12,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Trim request body fields diff --git a/codegens/js-xhr/npm/test-lint.js b/codegens/js-xhr/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/js-xhr/npm/test-lint.js +++ b/codegens/js-xhr/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-xhr/npm/test-newman.js b/codegens/js-xhr/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/js-xhr/npm/test-newman.js +++ b/codegens/js-xhr/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/js-xhr/npm/test-unit.js b/codegens/js-xhr/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/js-xhr/npm/test-unit.js +++ b/codegens/js-xhr/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/libcurl/README.md b/codegens/libcurl/README.md index 679d634cc..adcc33b7b 100644 --- a/codegens/libcurl/README.md +++ b/codegens/libcurl/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - Integer denoting count of indentation required * `trimRequestBody` - Boolean denoting whether to trim request body fields diff --git a/codegens/libcurl/npm/test-lint.js b/codegens/libcurl/npm/test-lint.js index 2b644372b..6c197c5f2 100644 --- a/codegens/libcurl/npm/test-lint.js +++ b/codegens/libcurl/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -57,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/libcurl/npm/test-newman.js b/codegens/libcurl/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/libcurl/npm/test-newman.js +++ b/codegens/libcurl/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/libcurl/npm/test-unit.js b/codegens/libcurl/npm/test-unit.js index c778ceba3..846b4b374 100755 --- a/codegens/libcurl/npm/test-unit.js +++ b/codegens/libcurl/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -60,4 +60,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-axios/.gitignore b/codegens/nodejs-axios/.gitignore new file mode 100644 index 000000000..dd41cd99b --- /dev/null +++ b/codegens/nodejs-axios/.gitignore @@ -0,0 +1,69 @@ +.DS_Store +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# temporarily generated file +run.js + +# Prevent IDE stuff +.idea +.vscode +*.sublime-* + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +.coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +out/ diff --git a/codegens/nodejs-axios/README.md b/codegens/nodejs-axios/README.md new file mode 100644 index 000000000..d4e0b6f20 --- /dev/null +++ b/codegens/nodejs-axios/README.md @@ -0,0 +1,67 @@ +# codegen-nodejs-axios + +> Converts Postman-SDK Request into code snippet for NodeJS-axios. + +#### Prerequisites +To run the module, ensure that you have NodeJS >= v8. A copy of the NodeJS installable can be downloaded from https://nodejs.org/en/download/package-manager. + +## Using the Module +The module will expose an object which will have property `convert` which is the function for converting the Postman-SDK request to nodejs-axios code snippet and `getOptions` function which returns an array of supported options. + +### convert function +Convert function will take three parameters +* `request`- Postman-SDK Request object + +* `options`- options is an object which can have following properties + * `indentType`- String denoting type of indentation for code snippet. eg: 'Space', 'Tab' + * `indentCount`- positiveInteger representing count of indentation required. + * `requestTimeout` : Integer denoting time after which the request will bail out in milli-seconds + * `trimRequestBody` : Trim request body fields + * `followRedirect` : Boolean denoting whether to redirect a request + +* `callback`- callback function with first parameter as error and second parameter as string for code snippet + +##### Example: +```js +var request = new sdk.Request('www.google.com'), //using postman sdk to create request + options = { + indentType: 'Space', + indentCount: 2, + ES6_enabled: true + }; +convert(request, options, function(error, snippet) { + if (error) { + // handle error + } + // handle snippet +}); +``` + +### getOptions function + +This function returns a list of options supported by this codegen. + +#### Example +```js +var options = getOptions(); + +console.log(options); +// output +// [ +// { +// name: 'Set indentation count', +// id: 'indentCount', +// type: 'positiveInteger', +// default: 2, +// description: 'Set the number of indentation characters to add per code level' +// }, +// ... +// ] +``` + +### Guideline for using generated snippet +* Generated snippet requires `axios`, `form-data`, `qs` and `fs` modules. + +* Since Postman-SDK Request object doesn't provide complete path of the file, it needs to be manually inserted in case of uploading a file. + +* This module doesn't support cookies. diff --git a/codegens/nodejs-axios/index.js b/codegens/nodejs-axios/index.js new file mode 100644 index 000000000..bb0a047c4 --- /dev/null +++ b/codegens/nodejs-axios/index.js @@ -0,0 +1 @@ +module.exports = require('./lib'); diff --git a/codegens/nodejs-axios/lib/axios.js b/codegens/nodejs-axios/lib/axios.js new file mode 100644 index 000000000..b645fda3f --- /dev/null +++ b/codegens/nodejs-axios/lib/axios.js @@ -0,0 +1,241 @@ +const _ = require('./lodash'), + parseRequest = require('./parseRequest'), + sanitize = require('./util').sanitize, + sanitizeOptions = require('./util').sanitizeOptions, + addFormParam = require('./util').addFormParam; + +/** + * returns snippet of nodejs(axios) by parsing data from Postman-SDK request object + * + * @param {Object} request - Postman SDK request object + * @param {String} indentString - indentation required for code snippet + * @param {Object} options + * @returns {String} - nodejs(axios) code snippet for given request object + */ +function makeSnippet (request, indentString, options) { + + var snippet = options.ES6_enabled ? 'const' : 'var', + configArray = [], + dataSnippet = '', + body, + headers; + + snippet += ' axios = require(\'axios\');\n'; + if (request.body && !request.headers.has('Content-Type')) { + if (request.body.mode === 'file') { + request.addHeader({ + key: 'Content-Type', + value: 'text/plain' + }); + } + else if (request.body.mode === 'graphql') { + request.addHeader({ + key: 'Content-Type', + value: 'application/json' + }); + } + } + + // The following code handles multiple files in the same formdata param. + // It removes the form data params where the src property is an array of filepath strings + // Splits that array into different form data params with src set as a single filepath string + if (request.body && request.body.mode === 'formdata') { + let formdata = request.body.formdata, + formdataArray = []; + formdata.members.forEach((param) => { + let key = param.key, + type = param.type, + disabled = param.disabled, + contentType = param.contentType; + // check if type is file or text + if (type === 'file') { + // if src is not of type string we check for array(multiple files) + if (typeof param.src !== 'string') { + // if src is an array(not empty), iterate over it and add files as separate form fields + if (Array.isArray(param.src) && param.src.length) { + param.src.forEach((filePath) => { + addFormParam(formdataArray, key, param.type, filePath, disabled, contentType); + }); + } + // if src is not an array or string, or is an empty array, add a placeholder for file path(no files case) + else { + addFormParam(formdataArray, key, param.type, '/path/to/file', disabled, contentType); + } + } + // if src is string, directly add the param with src as filepath + else { + addFormParam(formdataArray, key, param.type, param.src, disabled, contentType); + } + } + // if type is text, directly add it to formdata array + else { + addFormParam(formdataArray, key, param.type, param.value, disabled, contentType); + } + }); + + request.body.update({ + mode: 'formdata', + formdata: formdataArray + }); + } + + body = request.body && request.body.toJSON(); + + dataSnippet = !_.isEmpty(body) ? parseRequest.parseBody(body, + options.trimRequestBody, + indentString, + request.headers.get('Content-Type'), + options.ES6_enabled) : ''; + snippet += dataSnippet + '\n'; + + configArray.push(indentString + `method: '${request.method.toLowerCase()}'`); + configArray.push(indentString + `url: '${sanitize(request.url.toString())}'`); + + headers = parseRequest.parseHeader(request, indentString); + // https://github.com/axios/axios/issues/789#issuecomment-577177492 + if (!_.isEmpty(body) && body.formdata) { + // we can assume that data object is filled up + headers.push(`${indentString.repeat(2)}...data.getHeaders()`); + } + let headerSnippet = indentString + 'headers: { '; + if (headers.length > 0) { + headerSnippet += '\n'; + headerSnippet += headers.join(', \n') + '\n'; + headerSnippet += indentString + '}'; + } + else { + headerSnippet += '}'; + } + + configArray.push(headerSnippet); + + if (options.requestTimeout) { + configArray.push(indentString + `timeout: ${options.requestTimeout}`); + } + if (options.followRedirect === false) { + // setting the maxRedirects to 0 will disable any redirects. + // by default, maxRedirects are set to 5 + configArray.push(indentString + 'maxRedirects: 0'); + } + if (dataSnippet !== '') { + // although just data is enough, whatever :shrug: + configArray.push(indentString + 'data : data'); + } + + if (options.ES6_enabled) { + snippet += 'let'; + } + else { + snippet += 'var'; + } + + snippet += ' config = {\n'; + snippet += configArray.join(',\n') + '\n'; + snippet += '};\n\n'; + snippet += 'axios(config)\n'; + if (options.ES6_enabled) { + snippet += '.then((response) => {\n'; + } + else { + snippet += '.then(function (response) {\n'; + } + snippet += indentString + 'console.log(JSON.stringify(response.data));\n'; + snippet += '})\n'; + if (options.ES6_enabled) { + snippet += '.catch((error) => {\n'; + } + else { + snippet += '.catch(function (error) {\n'; + } + snippet += indentString + 'console.log(error);\n'; + snippet += '});\n'; + + return snippet; +} + +/** + * Used to get the options specific to this codegen + * + * @returns {Array} - Returns an array of option objects + */ +function getOptions () { + return [ + { + name: 'Set indentation count', + id: 'indentCount', + type: 'positiveInteger', + default: 2, + description: 'Set the number of indentation characters to add per code level' + }, + { + name: 'Set indentation type', + id: 'indentType', + type: 'enum', + availableOptions: ['Tab', 'Space'], + default: 'Space', + description: 'Select the character used to indent lines of code' + }, + { + name: 'Set request timeout', + id: 'requestTimeout', + type: 'positiveInteger', + default: 0, + description: 'Set number of milliseconds the request should wait for a response' + + ' before timing out (use 0 for infinity)' + }, + { + name: 'Follow redirects', + id: 'followRedirect', + type: 'boolean', + default: true, + description: 'Automatically follow HTTP redirects' + }, + { + name: 'Trim request body fields', + id: 'trimRequestBody', + type: 'boolean', + default: false, + description: 'Remove white space and additional lines that may affect the server\'s response' + }, + { + name: 'Enable ES6 features', + id: 'ES6_enabled', + type: 'boolean', + default: false, + description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features' + } + ]; +} + + +/** + * Converts Postman sdk request object to nodejs axios code snippet + * + * @param {Object} request - postman-SDK request object + * @param {Object} options + * @param {String} options.indentType - type for indentation eg: Space, Tab + * @param {String} options.indentCount - number of spaces or tabs for indentation. + * @param {Boolean} options.followRedirect - whether to enable followredirect + * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not + * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out + * @param {Function} callback - callback function with parameters (error, snippet) + */ +function convert (request, options, callback) { + if (!_.isFunction(callback)) { + throw new Error('NodeJS-Axios-Converter: callback is not valid function'); + } + options = sanitizeOptions(options, getOptions()); + + // String representing value of indentation required + var indentString; + + indentString = options.indentType === 'Tab' ? '\t' : ' '; + indentString = indentString.repeat(options.indentCount); + + return callback(null, makeSnippet(request, indentString, options)); +} + +module.exports = { + convert: convert, + getOptions: getOptions +}; diff --git a/codegens/nodejs-axios/lib/index.js b/codegens/nodejs-axios/lib/index.js new file mode 100644 index 000000000..3c01771b0 --- /dev/null +++ b/codegens/nodejs-axios/lib/index.js @@ -0,0 +1,4 @@ +module.exports = { + convert: require('./axios').convert, + getOptions: require('./axios').getOptions +}; diff --git a/codegens/nodejs-axios/lib/lodash.js b/codegens/nodejs-axios/lib/lodash.js new file mode 100644 index 000000000..55ea6666d --- /dev/null +++ b/codegens/nodejs-axios/lib/lodash.js @@ -0,0 +1,456 @@ +/* istanbul ignore next */ +module.exports = { + + /** + * Checks if `value` is an empty object, array or string. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Values such as strings, arrays are considered empty if they have a `length` of `0`. + * + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * isEmpty(null) + * // => true + * + * isEmpty(true) + * // => true + * + * isEmpty(1) + * // => true + * + * isEmpty([1, 2, 3]) + * // => false + * + * isEmpty('abc') + * // => false + * + * isEmpty({ 'a': 1 }) + * // => false + */ + isEmpty: function (value) { + // eslint-disable-next-line lodash/prefer-is-nil + if (value === null || value === undefined) { + return true; + } + if (Array.isArray(value) || typeof value === 'string' || typeof value.splice === 'function') { + return !value.length; + } + + for (const key in value) { + if (Object.prototype.hasOwnProperty.call(value, key)) { + return false; + } + } + + return true; + }, + + /** + * Checks if `value` is `undefined`. + * + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * isUndefined(void 0) + * // => true + * + * isUndefined(null) + * // => false + */ + isUndefined: function (value) { + return value === undefined; + }, + + /** + * Checks if `func` is classified as a `Function` object. + * + * @param {*} func The value to check. + * @returns {boolean} Returns `true` if `func` is a function, else `false`. + * @example + * + * isFunction(self.isEmpty) + * // => true + * + * isFunction(/abc/) + * // => false + */ + isFunction: function (func) { + return typeof func === 'function'; + }, + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * capitalize('FRED') + * // => 'Fred' + * + * capitalize('john') + * // => 'John' + */ + + capitalize: function (string) { + return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + }, + + /** + * Reduces `array` to a value which is the accumulated result of running + * each element in `array` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `array` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, array). + * + * @param {Array} array The Array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @example + * + * reduce([1, 2], (sum, n) => sum + n, 0) + * // => 3 + * + */ + reduce: function (array, iteratee, accumulator) { + return array.reduce(iteratee, accumulator); + }, + + /** + * Iterates over elements of `array`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index, array). + * + * @param {Array} array The array to iterate over. + * @param {Function|object} predicate The function/object invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @example + * + * const users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ] + * + * filter(users, ({ active }) => active) + * // => object for ['barney'] + */ + filter: function (array, predicate) { + if (typeof predicate === 'function') { + return array.filter(predicate); + } + var key = Object.keys(predicate), + val = predicate[key], + res = []; + array.forEach(function (item) { + if (item[key] && item[key] === val) { + res.push(item); + } + }); + return res; + }, + + /** + * The opposite of `filter` this method returns the elements of `array` + * that `predicate` does **not** return truthy for. + * + * @param {Array} array collection to iterate over. + * @param {String} predicate The String that needs to have truthy value, invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @example + * + * const users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ] + * + * reject(users, 'active') + * // => object for ['fred'] + */ + reject: function (array, predicate) { + var res = []; + array.forEach((object) => { + if (!object[predicate]) { + res.push(object); + } + }); + return res; + }, + + /** + * Creates an array of values by running each element of `array` thru `iteratee`. + * The iteratee is invoked with three arguments: (value, index, array). + * + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n + * } + * + * map([4, 8], square) + * // => [16, 64] + */ + map: function (array, iteratee) { + return array.map(iteratee); + }, + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @example + * + * forEach([1, 2], value => console.log(value)) + * // => Logs `1` then `2`. + * + * forEach({ 'a': 1, 'b': 2 }, (value, key) => console.log(key)) + * // => Logs 'a' then 'b' + */ + + forEach: function (collection, iteratee) { + if (collection === null) { + return null; + } + + if (Array.isArray(collection)) { + return collection.forEach(iteratee); + } + const iterable = Object(collection), + props = Object.keys(collection); + var index = -1, + key, i; + + for (i = 0; i < props.length; i++) { + key = props[++index]; + iteratee(iterable[key], key, iterable); + } + return collection; + }, + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise it checks if the `value` is present + * as a key in a `collection` object. + * + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + includes: function (collection, value) { + if (Array.isArray(collection) || typeof collection === 'string') { + return collection.includes(value); + } + for (var key in collection) { + if (collection.hasOwnProperty(key)) { + if (collection[key] === value) { + return true; + } + } + } + return false; + }, + + /** + * Gets the size of `collection` by returning its length for array and strings. + * For objects it returns the number of enumerable string keyed + * properties. + * + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * size([1, 2, 3]) + * // => 3 + * + * size({ 'a': 1, 'b': 2 }) + * // => 2 + * + * size('pebbles') + * // => 7 + */ + size: function (collection) { + // eslint-disable-next-line lodash/prefer-is-nil + if (collection === null || collection === undefined) { + return 0; + } + if (Array.isArray(collection) || typeof collection === 'string') { + return collection.length; + } + + return Object.keys(collection).length; + }, + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + join: function (array, separator) { + if (array === null) { + return ''; + } + return array.join(separator); + }, + + /** + * Removes trailing whitespace or specified characters from `string`. + * + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @returns {string} Returns the trimmed string. + * @example + * + * trimEnd(' abc ') + * // => ' abc' + * + * trimEnd('-_-abc-_-', '_-') + * // => '-_-abc' + */ + trimEnd: function (string, chars) { + if (!string) { + return ''; + } + if (string && !chars) { + return string.replace(/\s*$/, ''); + } + chars += '$'; + return string.replace(new RegExp(chars, 'g'), ''); + }, + + /** + * Returns the index of the first + * element `predicate` returns truthy for. + * + * @param {Array} array The array to inspect. + * @param {Object} predicate The exact object to be searched for in the array. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * _.findIndex(users, {'active' : false}); + * // => 0 + * + */ + findIndex: function (array, predicate) { + var length = array === null ? 0 : array.length, + index = -1, + keys = Object.keys(predicate), + found, i; + if (!length) { + return -1; + } + for (i = 0; i < array.length; i++) { + found = true; + // eslint-disable-next-line no-loop-func + keys.forEach((key) => { + if (!(array[i][key] && array[i][key] === predicate[key])) { + found = false; + } + }); + if (found) { + index = i; + break; + } + } + return index; + }, + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @param {Object} object The object to query. + * @param {string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * const object = { a: {b : 'c'} } + * + * + * get(object, 'a.b.c', 'default') + * // => 'default' + * + * get(object, 'a.b', 'default') + * // => 'c' + */ + get: function (object, path, defaultValue) { + if (object === null) { + return undefined; + } + var arr = path.split('.'), + res = object, + i; + for (i = 0; i < arr.length; i++) { + res = res[arr[i]]; + if (res === undefined) { + return defaultValue; + } + } + return res; + }, + + /** + * Checks if `predicate` returns truthy for **all** elements of `array`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @param {Array} array The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * every([true, 1, null, 'yes'], Boolean) + * // => false + */ + every: function (array, predicate) { + var index = -1, + length = array === null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + +}; diff --git a/codegens/nodejs-axios/lib/parseRequest.js b/codegens/nodejs-axios/lib/parseRequest.js new file mode 100644 index 000000000..1640939ed --- /dev/null +++ b/codegens/nodejs-axios/lib/parseRequest.js @@ -0,0 +1,201 @@ +var _ = require('./lodash'), + sanitize = require('./util').sanitize; + +/** + * Parses URLEncoded body from request to axios syntax + * + * @param {Object} body URLEncoded Body + * @param {boolean} trim trim body option + * @param {boolean} ES6_enabled ES6 syntax option + */ +function parseURLEncodedBody (body, trim, ES6_enabled) { + var varDeclare = ES6_enabled ? 'const' : 'var', + bodySnippet = varDeclare + ' qs = require(\'qs\');\n', + dataArray = []; + + _.forEach(body, function (data) { + if (!data.disabled) { + dataArray.push(`'${sanitize(data.key, trim)}': '${sanitize(data.value, trim)}'`); + } + }); + if (ES6_enabled) { + bodySnippet += 'let'; + } + else { + bodySnippet += 'var'; + } + bodySnippet += ` data = qs.stringify({\n ${dataArray.join(',\n')} \n});`; + return bodySnippet; +} + +/** + * Parses Formdata from request to axios syntax + * + * @param {Object} body FormData body + * @param {boolean} trim trim body option + * @param {boolean} ES6_enabled ES6 syntax option + */ +function parseFormData (body, trim, ES6_enabled) { + var varDeclare = ES6_enabled ? 'const' : 'var', + bodySnippet = varDeclare + ' FormData = require(\'form-data\');\n'; + // check if there's file + const fileArray = body.filter(function (item) { return !item.disabled && item.type === 'file'; }); + if (fileArray.length > 0) { + bodySnippet += varDeclare + ' fs = require(\'fs\');\n'; + } + if (ES6_enabled) { + bodySnippet += 'let'; + } + else { + bodySnippet += 'var'; + } + bodySnippet += ' data = new FormData();\n'; + + _.forEach(body, function (data) { + if (!data.disabled) { + if (data.type === 'file') { + var fileContent = `fs.createReadStream('${data.src}')`; + bodySnippet += `data.append('${sanitize(data.key, trim)}', ${fileContent});\n`; + } + else { + bodySnippet += `data.append('${sanitize(data.key, trim)}', '${sanitize(data.value, trim)}');\n`; + } + } + }); + return bodySnippet; +} + +/** + * Parses Raw data to axios syntax + * + * @param {Object} body Raw body data + * @param {boolean} trim trim body option + * @param {String} contentType Content type of the body being sent + * @param {boolean} ES6_enabled ES6 syntax option + */ +function parseRawBody (body, trim, contentType, ES6_enabled) { + var varDeclare = ES6_enabled ? 'let' : 'var', + bodySnippet = varDeclare + ' data = '; + if (contentType === 'application/json') { + try { + let jsonBody = JSON.parse(body); + bodySnippet += `JSON.stringify(${JSON.stringify(jsonBody)});\n`; + } + catch (error) { + bodySnippet += `'${sanitize(body.toString(), trim)}';\n`; + } + } + else { + bodySnippet += `'${sanitize(body.toString(), trim)}';\n`; + } + return bodySnippet; +} + +/** + * Parses graphql data to axios syntax + * + * @param {Object} body graphql body data + * @param {boolean} trim trim body option + * @param {String} indentString indentation to be added to the snippet + * @param {boolean} ES6_enabled ES6 syntax option + */ +function parseGraphQL (body, trim, indentString, ES6_enabled) { + var varDeclare = ES6_enabled ? 'let' : 'var'; + let query = body.query, + graphqlVariables, + bodySnippet; + try { + graphqlVariables = JSON.parse(body.variables); + } + catch (e) { + graphqlVariables = {}; + } + bodySnippet = varDeclare + ' data = JSON.stringify({\n'; + bodySnippet += `${indentString}query: '${sanitize(query, trim)}',\n`; + bodySnippet += `${indentString}variables: ${JSON.stringify(graphqlVariables)}\n});\n`; + return bodySnippet; +} + + +/* istanbul ignore next */ +/** + * parses binamry file data + * + * @param {boolean} ES6_enabled ES6 syntax option + */ +function parseFileData (ES6_enabled) { + var varDeclare = ES6_enabled ? 'let' : 'var', + bodySnippet = varDeclare + ' data = \'\';\n'; + return bodySnippet; +} + +/** + * Parses Body from the Request + * + * @param {Object} body body object from request. + * @param {boolean} trim trim body option + * @param {String} indentString indentation to be added to the snippet + * @param {String} contentType Content type of the body being sent + * @param {boolean} ES6_enabled ES6 syntax option + */ +function parseBody (body, trim, indentString, contentType, ES6_enabled) { + if (!_.isEmpty(body)) { + switch (body.mode) { + case 'urlencoded': + return parseURLEncodedBody(body.urlencoded, trim, ES6_enabled); + case 'raw': + return parseRawBody(body.raw, trim, contentType, ES6_enabled); + case 'graphql': + return parseGraphQL(body.graphql, trim, indentString, ES6_enabled); + case 'formdata': + return parseFormData(body.formdata, trim, ES6_enabled); + /* istanbul ignore next */ + case 'file': + return parseFileData(ES6_enabled); + default: + return parseRawBody(body[body.mode], trim, contentType, ES6_enabled); + } + } + return ''; +} + + +/** + * parses header of request object and returns code snippet of nodejs axios to add headers + * + * @param {Object} request - Postman SDK request object + * @param {String} indentString - indentation required in code snippet + * @returns {String} - code snippet of nodejs request to add header + */ +function parseHeader (request, indentString) { + var headerObject = request.getHeaders({enabled: true}), + headerArray = []; + + if (!_.isEmpty(headerObject)) { + headerArray = _.reduce(Object.keys(headerObject), function (accumalator, key) { + if (Array.isArray(headerObject[key])) { + var headerValues = []; + _.forEach(headerObject[key], (value) => { + headerValues.push(`${sanitize(value)}`); + }); + accumalator.push( + indentString.repeat(2) + `'${sanitize(key, true)}': '${headerValues.join(', ')}'` + ); + } + else { + accumalator.push( + indentString.repeat(2) + `'${sanitize(key, true)}': '${sanitize(headerObject[key])}'` + ); + } + return accumalator; + }, []); + } + + return headerArray; +} + +module.exports = { + parseBody: parseBody, + parseHeader: parseHeader, + parseFormData: parseFormData +}; diff --git a/codegens/nodejs-axios/lib/util.js b/codegens/nodejs-axios/lib/util.js new file mode 100644 index 000000000..740f0c3e5 --- /dev/null +++ b/codegens/nodejs-axios/lib/util.js @@ -0,0 +1,121 @@ + +/** + * sanitizes input string by handling escape characters eg: converts '''' to '\'\'' + * and trim input if required + * + * @param {String} inputString + * @param {Boolean} [trim] - indicates whether to trim string or not + * @returns {String} + */ +function sanitize (inputString, trim) { + if (typeof inputString !== 'string') { + return ''; + } + (trim) && (inputString = inputString.trim()); + return inputString.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/\n/g, '\\n'); +} + +/** + * sanitizes input options + * + * @param {Object} options - Options provided by the user + * @param {Array} optionsArray - options array received from getOptions function + * + * @returns {Object} - Sanitized options object + */ +function sanitizeOptions (options, optionsArray) { + var result = {}, + defaultOptions = {}, + id; + optionsArray.forEach((option) => { + defaultOptions[option.id] = { + default: option.default, + type: option.type + }; + if (option.type === 'enum') { + defaultOptions[option.id].availableOptions = option.availableOptions; + } + }); + + for (id in options) { + if (options.hasOwnProperty(id)) { + if (defaultOptions[id] === undefined) { + continue; + } + switch (defaultOptions[id].type) { + case 'boolean': + if (typeof options[id] !== 'boolean') { + result[id] = defaultOptions[id].default; + } + else { + result[id] = options[id]; + } + break; + case 'positiveInteger': + if (typeof options[id] !== 'number' || options[id] < 0) { + result[id] = defaultOptions[id].default; + } + else { + result[id] = options[id]; + } + break; + case 'enum': + if (!defaultOptions[id].availableOptions.includes(options[id])) { + result[id] = defaultOptions[id].default; + } + else { + result[id] = options[id]; + } + break; + default: + result[id] = options[id]; + } + } + } + + for (id in defaultOptions) { + if (defaultOptions.hasOwnProperty(id)) { + if (result[id] === undefined) { + result[id] = defaultOptions[id].default; + } + } + } + return result; +} +/** + * + * @param {Array} array - form data array + * @param {String} key - key of form data param + * @param {String} type - type of form data param(file/text) + * @param {String} val - value/src property of form data param + * @param {String} disabled - Boolean denoting whether the param is disabled or not + * @param {String} contentType - content type header of the param + * + * Appends a single param to form data array + */ +function addFormParam (array, key, type, val, disabled, contentType) { + if (type === 'file') { + array.push({ + key: key, + type: type, + src: val, + disabled: disabled, + contentType: contentType + }); + } + else { + array.push({ + key: key, + type: type, + value: val, + disabled: disabled, + contentType: contentType + }); + } +} + +module.exports = { + sanitize: sanitize, + sanitizeOptions: sanitizeOptions, + addFormParam: addFormParam +}; diff --git a/codegens/nodejs-axios/npm/test-lint.js b/codegens/nodejs-axios/npm/test-lint.js new file mode 100644 index 000000000..9c66a5680 --- /dev/null +++ b/codegens/nodejs-axios/npm/test-lint.js @@ -0,0 +1,58 @@ +#!/usr/bin/env node +var shell = require('shelljs'), + 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', + './bin', + './test', + './examples/*.js', + './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({fix:true})).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(shell.exit); diff --git a/codegens/nodejs-axios/npm/test-newman.js b/codegens/nodejs-axios/npm/test-newman.js new file mode 100644 index 000000000..ae7d2afe1 --- /dev/null +++ b/codegens/nodejs-axios/npm/test-newman.js @@ -0,0 +1,59 @@ +#!/usr/bin/env node +/* eslint-env node, es6 */ +// --------------------------------------------------------------------------------------------------------------------- +// This script is intended to execute all newman tests. +// --------------------------------------------------------------------------------------------------------------------- + +var shell = require('shelljs'), + + // set directories and files for test and coverage report + path = require('path'), + + NYC = require('nyc'), + chalk = require('chalk'), + recursive = require('recursive-readdir'), + + COV_REPORT_PATH = '.coverage', + SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'newman'); + +module.exports = function (exit) { + // banner line + console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); + + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); + + 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(shell.exit); diff --git a/codegens/nodejs-axios/npm/test-unit.js b/codegens/nodejs-axios/npm/test-unit.js new file mode 100755 index 000000000..305e2f815 --- /dev/null +++ b/codegens/nodejs-axios/npm/test-unit.js @@ -0,0 +1,59 @@ +#!/usr/bin/env node +/* eslint-env node, es6 */ +// --------------------------------------------------------------------------------------------------------------------- +// This script is intended to execute all unit tests. +// --------------------------------------------------------------------------------------------------------------------- + +var shell = require('shelljs'), + + // set directories and files for test and coverage report + 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...')); + + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); + + 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(shell.exit); diff --git a/codegens/nodejs-axios/npm/test.js b/codegens/nodejs-axios/npm/test.js new file mode 100755 index 000000000..da2816f09 --- /dev/null +++ b/codegens/nodejs-axios/npm/test.js @@ -0,0 +1,18 @@ +#!/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-newman'), + require('./test-unit') + // require('./test-browser') + // require('./test-integration') +], 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); +}); diff --git a/codegens/nodejs-axios/package-lock.json b/codegens/nodejs-axios/package-lock.json new file mode 100644 index 000000000..1837d0bfe --- /dev/null +++ b/codegens/nodejs-axios/package-lock.json @@ -0,0 +1,94 @@ +{ + "name": "@postman/codegen-nodejs-axios", + "version": "0.0.1", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true + }, + "axios": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz", + "integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==", + "dev": true, + "requires": { + "follow-redirects": "1.5.10" + } + }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true + }, + "follow-redirects": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", + "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", + "dev": true, + "requires": { + "debug": "=3.1.0" + } + }, + "form-data": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz", + "integrity": "sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, + "mime-db": { + "version": "1.43.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.43.0.tgz", + "integrity": "sha512-+5dsGEEovYbT8UY9yD7eE4XTc4UwJ1jBYlgaQQF38ENsKR3wj/8q8RFZrF9WIZpB2V1ArTVFUva8sAul1NzRzQ==", + "dev": true + }, + "mime-types": { + "version": "2.1.26", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.26.tgz", + "integrity": "sha512-01paPWYgLrkqAyrlDorC1uDwl2p3qZT7yl806vW7DvDoxwXi46jsjFbg+WdwotBIk6/MbEhO/dh5aZ5sNj/dWQ==", + "dev": true, + "requires": { + "mime-db": "1.43.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "qs": { + "version": "6.9.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.9.2.tgz", + "integrity": "sha512-2eQ6zajpK7HwqrY1rRtGw5IZvjgtELXzJECaEDuzDFo2jjnIXpJSimzd4qflWZq6bLLi+Zgfj5eDrAzl/lptyg==", + "dev": true + } + } +} diff --git a/codegens/nodejs-axios/package.json b/codegens/nodejs-axios/package.json new file mode 100644 index 000000000..3c8d2c674 --- /dev/null +++ b/codegens/nodejs-axios/package.json @@ -0,0 +1,38 @@ +{ + "name": "@postman/codegen-nodejs-axios", + "version": "0.0.1", + "description": "Converts Postman-SDK Request into code snippet for NodeJS(Axios)", + "com_postman_plugin": { + "type": "code_generator", + "lang": "nodejs", + "variant": "Axios", + "syntax_mode": "javascript" + }, + "main": "index.js", + "directories": { + "lib": "lib", + "test": "test" + }, + "scripts": { + "test": "node npm/test.js", + "test-lint": "node npm/test-lint.js", + "test-newman": "node npm/test-newman.js", + "test-unit": "node npm/test-unit.js" + }, + "repository": { + "type": "git", + "url": "" + }, + "author": "Postman Labs ", + "license": "Apache-2.0", + "homepage": "https://github.com/postmanlabs/code-generators/tree/master/codegens/nodejs-axios", + "dependencies": {}, + "devDependencies": { + "axios": "0.19.2", + "form-data": "3.0.0", + "qs": "6.9.2" + }, + "engines": { + "node": ">=8" + } +} diff --git a/codegens/nodejs-axios/test/.eslintrc b/codegens/nodejs-axios/test/.eslintrc new file mode 100644 index 000000000..f0fefbaea --- /dev/null +++ b/codegens/nodejs-axios/test/.eslintrc @@ -0,0 +1,30 @@ +{ + "plugins": [ + "mocha" + ], + "env": { + "mocha": true, + "node": true, + "es6": true + }, + "rules": { + // Mocha + "mocha/handle-done-callback": "error", + "mocha/max-top-level-suites": "error", + // "mocha/no-exclusive-tests": "error", + "mocha/no-global-tests": "error", + "mocha/no-hooks-for-single-case": "off", + "mocha/no-hooks": "off", + "mocha/no-identical-title": "error", + "mocha/no-mocha-arrows": "error", + "mocha/no-nested-tests": "error", + "mocha/no-pending-tests": "error", + "mocha/no-return-and-callback": "error", + "mocha/no-sibling-hooks": "error", + "mocha/no-skipped-tests": "warn", + "mocha/no-synchronous-tests": "off", + "mocha/no-top-level-hooks": "warn", + "mocha/valid-test-description": "off", + "mocha/valid-suite-description": "off" + } +} diff --git a/codegens/nodejs-axios/test/newman/newman.test.js b/codegens/nodejs-axios/test/newman/newman.test.js new file mode 100644 index 000000000..faa8cac1a --- /dev/null +++ b/codegens/nodejs-axios/test/newman/newman.test.js @@ -0,0 +1,27 @@ +var runNewmanTest = require('../../../../test/codegen/newman/newmanTestUtil').runNewmanTest, + convert = require('../../lib/index').convert; + +describe('Convert for different types of request', function () { + var options = {indentCount: 2, indentType: 'Space'}, + testConfig = { + compileScript: null, + runScript: 'node run.js', + fileName: 'run.js', + headerSnippet: '/* eslint-disable */\n' + }; + + runNewmanTest(convert, options, testConfig); + + describe('Convert for request incorporating ES6 features', function () { + var options = {indentCount: 2, indentType: 'Space', ES6_enabled: true}, + testConfig = { + compileScript: null, + runScript: 'node run.js', + fileName: 'run.js', + headerSnippet: '/* eslint-disable */\n' + }; + + runNewmanTest(convert, options, testConfig); + }); + +}); diff --git a/codegens/nodejs-axios/test/unit/.gitkeep b/codegens/nodejs-axios/test/unit/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/codegens/nodejs-axios/test/unit/fixtures/testcollection/collection.json b/codegens/nodejs-axios/test/unit/fixtures/testcollection/collection.json new file mode 100644 index 000000000..186aa9ce5 --- /dev/null +++ b/codegens/nodejs-axios/test/unit/fixtures/testcollection/collection.json @@ -0,0 +1,1349 @@ +{ + "info": { + "name": "Code-Gen Test Cases", + "_postman_id": "41182fad-912e-6bc9-d6b9-dfb6f5bf5ffb", + "description": "This collection contains requests that will be used to test validity of plugin created to convert postman request into code snippet of particular language.", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "Request Headers with disabled headers", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "try {", + " tests[\"Body contains headers\"] = responseBody.has(\"headers\");", + " responseJSON = JSON.parse(responseBody);", + " tests[\"Header contains host\"] = \"host\" in responseJSON.headers;", + " tests[\"Header contains test parameter sent as part of request header\"] = \"my-sample-header\" in responseJSON.headers;", + "}", + "catch (e) { }", + "", + "", + "", + "" + ] + } + } + ], + "request": { + "method": "GET", + "header": [ + { + "key": "my-sample-header", + "value": "Lorem ipsum dolor sit amet" + }, + { + "key": "not-disabled-header", + "value": "ENABLED" + }, + { + "key": "disabled header", + "value": "DISABLED", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "https://postman-echo.com/headers", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "headers" + ] + }, + "description": "A `GET` request to this endpoint returns the list of all request headers as part of the response JSON.\nIn Postman, sending your own set of headers through the [Headers tab](https://www.getpostman.com/docs/requests#headers?source=echo-collection-app-onboarding) will reveal the headers as part of the response." + }, + "response": [] + }, + { + "name": "GET Request with disabled query", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "tests['response json contains headers'] = _.has(responseJSON, 'headers');", + "tests['response json contains args'] = _.has(responseJSON, 'args');", + "tests['response json contains url'] = _.has(responseJSON, 'url');", + "", + "tests['args key contains argument passed as url parameter'] = ('test' in responseJSON.args);", + "tests['args passed via request url params has value \"123\"'] = (_.get(responseJSON, 'args.test') === \"123\");" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "body": {}, + "url": { + "raw": "https://postman-echo.com/get?test=123&anotherone=232", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "get" + ], + "query": [ + { + "key": "test", + "value": "123", + "equals": true + }, + { + "key": "anotherone", + "value": "232", + "equals": true + }, + { + "key": "anotheroneone", + "value": "sdfsdf", + "equals": true, + "disabled": true + } + ] + }, + "description": "The 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." + }, + "response": [] + }, + { + "name": "POST Raw Text", + "event": [ + { + "listen": "test", + "script": { + "id": "753f8a33-adb6-402f-8d19-386c1981ecb6", + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "\"'Duis posuere augue vel cursus pharetra. In luctus a ex nec pretium. Praesent neque quam, tincidunt nec leo eget, rutrum vehicula magna.\nMaecenas consequat elementum elit, \"id\" \"se\\\"mper\" sem tristique et. Integer pulvinar enim quis consectetur interdum volutpat.'\"" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "POST form data with file", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded", + "disabled": true + }, + { + "key": "content-type", + "value": "application/json", + "disabled": true + } + ], + "body": { + "mode": "formdata", + "formdata": [ + { + "key": "fdjks", + "value": "dsf", + "type": "text" + }, + { + "key": "sdf", + "value": "helo", + "type": "text" + }, + { + "key": "12", + "value": "\"23\"", + "description": "", + "type": "text" + }, + { + "key": "'123'", + "value": "'\"23\\\"4\\\"\"'", + "description": "", + "type": "text" + }, + { + "key": "", + "value": "", + "description": "", + "type": "text", + "disabled": true + } + ] + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "POST urlencoded data with disabled entries", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "1", + "value": "a", + "description": "", + "type": "text" + }, + { + "key": "2", + "value": "b", + "description": "", + "type": "text" + }, + { + "key": "\"\"12\"\"", + "value": "\"23\"", + "description": "", + "type": "text" + }, + { + "key": "'1\"2\\\"\"3'", + "value": "'1\"23\"4'", + "description": "", + "type": "text" + } + ] + }, + "url": { + "raw": "https://postman-echo.com/post/?hardik=\"me\"", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post", + "" + ], + "query": [ + { + "key": "hardik", + "value": "\"me\"", + "equals": true + } + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "POST json with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"json\": \"Test-Test\"\n}" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [ + { + "id": "a331f873-b13f-459f-82f4-506d65e41bef", + "name": "POST json with raw", + "originalRequest": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"json\": \"Test-Test\"\n}" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [ + { + "key": "Access-Control-Allow-Credentials", + "value": "", + "name": "Access-Control-Allow-Credentials", + "description": "Indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials." + }, + { + "key": "Access-Control-Allow-Headers", + "value": "", + "name": "Access-Control-Allow-Headers", + "description": "Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request." + }, + { + "key": "Access-Control-Allow-Methods", + "value": "", + "name": "Access-Control-Allow-Methods", + "description": "Specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request." + }, + { + "key": "Access-Control-Allow-Origin", + "value": "", + "name": "Access-Control-Allow-Origin", + "description": "Specifies a URI that may access the resource. For requests without credentials, the server may specify '*' as a wildcard, thereby allowing any origin to access the resource." + }, + { + "key": "Access-Control-Expose-Headers", + "value": "", + "name": "Access-Control-Expose-Headers", + "description": "Lets a server whitelist headers that browsers are allowed to access." + }, + { + "key": "Connection", + "value": "keep-alive", + "name": "Connection", + "description": "Options that are desired for the connection" + }, + { + "key": "Content-Encoding", + "value": "gzip", + "name": "Content-Encoding", + "description": "The type of encoding used on the data." + }, + { + "key": "Content-Length", + "value": "385", + "name": "Content-Length", + "description": "The length of the response body in octets (8-bit bytes)" + }, + { + "key": "Content-Type", + "value": "application/json; charset=utf-8", + "name": "Content-Type", + "description": "The mime type of this content" + }, + { + "key": "Date", + "value": "Wed, 07 Feb 2018 10:06:15 GMT", + "name": "Date", + "description": "The date and time that the message was sent" + }, + { + "key": "ETag", + "value": "W/\"215-u7EU1nFtauIn0/aVifjuXA\"", + "name": "ETag", + "description": "An identifier for a specific version of a resource, often a message digest" + }, + { + "key": "Server", + "value": "nginx", + "name": "Server", + "description": "A name for the server" + }, + { + "key": "Vary", + "value": "X-HTTP-Method-Override, Accept-Encoding", + "name": "Vary", + "description": "Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server." + }, + { + "key": "set-cookie", + "value": "sails.sid=s%3AxRBxgrc9M-jKK_l1mX3y3rM_ry8wYLz4.Of4qpOzd9hi6uO0sAQIj%2Bxs2VeppWxYjJa4OpIW3PKg; Path=/; HttpOnly", + "name": "set-cookie", + "description": "an HTTP cookie" + } + ], + "cookie": [ + { + "expires": "Tue Jan 19 2038 08:44:07 GMT+0530 (IST)", + "httpOnly": true, + "domain": "postman-echo.com", + "path": "/", + "secure": false, + "value": "s%3AxRBxgrc9M-jKK_l1mX3y3rM_ry8wYLz4.Of4qpOzd9hi6uO0sAQIj%2Bxs2VeppWxYjJa4OpIW3PKg", + "key": "sails.sid" + } + ], + "body": "{\"args\":{},\"data\":\"{\\n \\\"json\\\": \\\"Test-Test\\\"\\n}\",\"files\":{},\"form\":{},\"headers\":{\"host\":\"postman-echo.com\",\"content-length\":\"25\",\"accept\":\"*/*\",\"accept-encoding\":\"gzip, deflate\",\"cache-control\":\"no-cache\",\"content-type\":\"text/plain\",\"cookie\":\"sails.sid=s%3AkOgtF1XmXtVFx-Eg3S7-37BKKaMqMDPe.hnwldNwyvsaASUiRR0Y0vcowadkMXO4HMegTeVIPgqo\",\"postman-token\":\"2ced782f-a141-428e-8af6-04ce954a77d5\",\"user-agent\":\"PostmanRuntime/7.1.1\",\"x-forwarded-port\":\"443\",\"x-forwarded-proto\":\"https\"},\"json\":null,\"url\":\"https://postman-echo.com/post\"}" + } + ] + }, + { + "name": "POST javascript with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/javascript" + } + ], + "body": { + "mode": "raw", + "raw": "var val = 6;\nconsole.log(val);" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "POST text/xml with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "text/xml" + } + ], + "body": { + "mode": "raw", + "raw": "\n Test Test\n" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "POST text/html with raw", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "text/html" + } + ], + "body": { + "mode": "raw", + "raw": "\n Test Test\n" + }, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "Resolve URL", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": { + "mode": "raw", + "raw": "Duis posuere augue vel cursus pharetra. In luctus a ex nec pretium. Praesent neque quam, tincidunt nec leo eget, rutrum vehicula magna.\nMaecenas consequat elementum elit, id semper sem tristique et. Integer pulvinar enim quis consectetur interdum volutpat." + }, + "url": { + "raw": "https://postman-echo.com/:action", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + ":action" + ], + "variable": [ + { + "key": "action", + "value": "post" + } + ] + }, + "description": null + }, + "response": [] + }, + { + "name": "PUT Request", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has PUT data'] = _.has(responseJSON, 'data');", + "tests['response matches the data sent in request'] = (responseJSON.data && responseJSON.data.length === 256);" + ] + } + } + ], + "request": { + "method": "PUT", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "Etiam mi lacus, cursus vitae felis et, blandit pellentesque neque. Vestibulum eget nisi a tortor commodo dignissim.\nQuisque ipsum ligula, faucibus a felis a, commodo elementum nisl. Mauris vulputate sapien et tincidunt viverra. Donec vitae velit nec metus." + }, + "url": { + "raw": "https://postman-echo.com/put", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "put" + ] + }, + "description": "The HTTP `PUT` request method is similar to HTTP `POST`. It too is meant to \ntransfer data to a server (and elicit a response). What data is returned depends on the implementation\nof the server.\n\nA `PUT` request can pass parameters to the server using \"Query String \nParameters\", as well as the Request Body. For example, in the following \nraw HTTP request,\n\n> PUT /hi/there?hand=wave\n>\n> \n\n\n" + }, + "response": [] + }, + { + "name": "PATCH Request", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has PUT data'] = _.has(responseJSON, 'data');", + "tests['response matches the data sent in request'] = (responseJSON.data && responseJSON.data.length === 256);" + ] + } + } + ], + "request": { + "method": "PATCH", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "Curabitur auctor, elit nec pulvinar porttitor, ex augue condimentum enim, eget suscipit urna felis quis neque.\nSuspendisse sit amet luctus massa, nec venenatis mi. Suspendisse tincidunt massa at nibh efficitur fringilla. Nam quis congue mi. Etiam volutpat." + }, + "url": { + "raw": "https://postman-echo.com/patch", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "patch" + ] + }, + "description": "The HTTP `PATCH` method is used to update resources on a server. The exact\nuse of `PATCH` requests depends on the server in question. There are a number\nof server implementations which handle `PATCH` differently. Technically, \n`PATCH` supports both Query String parameters and a Request Body.\n\nThis endpoint accepts an HTTP `PATCH` request and provides debug information\nsuch as the HTTP headers, Query String arguments, and the Request Body." + }, + "response": [] + }, + { + "name": "DELETE Request", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has PUT data'] = _.has(responseJSON, 'data');", + "tests['response matches the data sent in request'] = (responseJSON.data && responseJSON.data.length === 256);" + ] + } + } + ], + "request": { + "method": "DELETE", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + }, + { + "key": "Content-Length", + "value": "1000", + "disabled": true + } + ], + "body": { + "mode": "urlencoded", + "urlencoded": [ + { + "key": "dsfs", + "value": "sfdds", + "description": "", + "type": "text" + }, + { + "key": "sfdsdf", + "value": "sdf", + "description": "", + "type": "text" + } + ] + }, + "url": { + "raw": "https://postman-echo.com/delete", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "delete" + ] + }, + "description": "The HTTP `DELETE` method is used to delete resources on a server. The exact\nuse of `DELETE` requests depends on the server implementation. In general, \n`DELETE` requests support both, Query String parameters as well as a Request \nBody.\n\nThis endpoint accepts an HTTP `DELETE` request and provides debug information\nsuch as the HTTP headers, Query String arguments, and the Request Body." + }, + "response": [] + }, + { + "name": "OPTIONS to postman echo", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "var responseJSON;", + "", + "try { ", + " responseJSON = JSON.parse(responseBody); ", + " tests['response is valid JSON'] = true;", + "}", + "catch (e) { ", + " responseJSON = {}; ", + " tests['response is valid JSON'] = false;", + "}", + "", + "", + "tests['response has post data'] = _.has(responseJSON, 'data');", + "tests['response matches the data posted'] = (responseJSON.data && responseJSON.data.length === 256);", + "", + "tests[\"content-type equals text/plain\"] = responseJSON && responseJSON.headers && (responseJSON.headers[\"content-type\"] === 'text/plain');" + ] + } + } + ], + "request": { + "method": "OPTIONS", + "header": [ + { + "key": "Content-Type", + "value": "application/x-www-form-urlencoded" + } + ], + "body": {}, + "url": { + "raw": "https://postman-echo.com/post", + "protocol": "https", + "host": [ + "postman-echo", + "com" + ], + "path": [ + "post" + ] + }, + "description": "The 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> \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." + }, + "response": [] + }, + { + "name": "HEAD request", + "request": { + "method": "HEAD", + "header": [ + { + "key": "hello", + "value": "helloagain", + "disabled": true + } + ], + "body": {}, + "url": { + "raw": "https://bf1621bb-f962-46b8-bf28-459e03b513ff.mock.pstmn.io/head", + "protocol": "https", + "host": [ + "bf1621bb-f962-46b8-bf28-459e03b513ff", + "mock", + "pstmn", + "io" + ], + "path": [ + "head" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "LINK request", + "request": { + "method": "LINK", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "https://mockbin.org/request", + "protocol": "https", + "host": [ + "mockbin", + "org" + ], + "path": [ + "request" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "UNLINK request", + "request": { + "method": "UNLINK", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "https://mockbin.org/request", + "protocol": "https", + "host": [ + "mockbin", + "org" + ], + "path": [ + "request" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "LOCK request", + "request": { + "method": "LOCK", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "https://mockbin.org/request", + "protocol": "https", + "host": [ + "mockbin", + "org" + ], + "path": [ + "request" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "UNLOCK request", + "request": { + "method": "UNLOCK", + "header": [], + "body": {}, + "url": { + "raw": "https://mockbin.org/request", + "protocol": "https", + "host": [ + "mockbin", + "org" + ], + "path": [ + "request" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "PROPFIND request", + "request": { + "method": "PROPFIND", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "https://mockbin.org/request", + "protocol": "https", + "host": [ + "mockbin", + "org" + ], + "path": [ + "request" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "VIEW request", + "request": { + "method": "VIEW", + "header": [ + { + "key": "Content-Type", + "value": "text/plain" + } + ], + "body": { + "mode": "raw", + "raw": "" + }, + "url": { + "raw": "https://mockbin.org/request", + "protocol": "https", + "host": [ + "mockbin", + "org" + ], + "path": [ + "request" + ] + }, + "description": "" + }, + "response": [] + }, + { + "name": "PURGE Request", + "request": { + "method": "PURGE", + "header": [], + "body": {}, + "url": { + "raw": "https://9c76407d-5b8d-4b22-99fb-8c47a85d9848.mock.pstmn.io", + "protocol": "https", + "host": [ + "9c76407d-5b8d-4b22-99fb-8c47a85d9848", + "mock", + "pstmn", + "io" + ] + }, + "description": null + }, + "response": [ + { + "id": "95c11e09-9abe-4b26-a6b0-bc7f40dded08", + "name": "PURGE Request", + "originalRequest": { + "method": "PURGE", + "header": [], + "body": {}, + "url": { + "raw": "https://9c76407d-5b8d-4b22-99fb-8c47a85d9848.mock.pstmn.io", + "protocol": "https", + "host": [ + "9c76407d-5b8d-4b22-99fb-8c47a85d9848", + "mock", + "pstmn", + "io" + ] + } + }, + "status": "Not Found", + "code": 404, + "_postman_previewlanguage": "text", + "header": [ + { + "key": "Access-Control-Allow-Credentials", + "value": "", + "name": "Access-Control-Allow-Credentials", + "description": "" + }, + { + "key": "Access-Control-Allow-Headers", + "value": "", + "name": "Access-Control-Allow-Headers", + "description": "" + }, + { + "key": "Access-Control-Allow-Methods", + "value": "", + "name": "Access-Control-Allow-Methods", + "description": "" + }, + { + "key": "Access-Control-Allow-Origin", + "value": "*", + "name": "Access-Control-Allow-Origin", + "description": "" + }, + { + "key": "Access-Control-Expose-Headers", + "value": "", + "name": "Access-Control-Expose-Headers", + "description": "" + }, + { + "key": "Connection", + "value": "keep-alive", + "name": "Connection", + "description": "" + }, + { + "key": "Content-Encoding", + "value": "gzip", + "name": "Content-Encoding", + "description": "" + }, + { + "key": "Content-Length", + "value": "152", + "name": "Content-Length", + "description": "" + }, + { + "key": "Content-Type", + "value": "application/json; charset=utf-8", + "name": "Content-Type", + "description": "" + }, + { + "key": "Date", + "value": "Tue, 13 Feb 2018 13:58:56 GMT", + "name": "Date", + "description": "" + }, + { + "key": "ETag", + "value": "W/\"a7-kIxN5L9H0YwilUQPUUio9A\"", + "name": "ETag", + "description": "" + }, + { + "key": "Server", + "value": "nginx", + "name": "Server", + "description": "" + }, + { + "key": "Vary", + "value": "Accept-Encoding", + "name": "Vary", + "description": "" + } + ], + "cookie": [], + "responseTime": "375", + "body": "{\n \"args\": {},\n \"data\": \"Curabitur auctor, elit nec pulvinar porttitor, ex augue condimentum enim, eget suscipit urna felis quis neque.\\nSuspendisse sit amet luctus massa, nec venenatis mi. Suspendisse tincidunt massa at nibh efficitur fringilla. Nam quis congue mi. Etiam volutpat.\",\n \"files\": {},\n \"form\": {},\n \"headers\": {\n \"host\": \"postman-echo.com\",\n \"content-length\": \"256\",\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate\",\n \"content-type\": \"text/plain\",\n \"cookie\": \"sails.sid=s%3A1wOi4AdoZEbqBjGi6oSUC5Vlfje8wJvs.DHQfRLXfIBvZ%2Bv0KhLAThMDz%2FXvxh9gyxWYa0u1EZOU\",\n \"user-agent\": \"PostmanRuntime/7.1.1\",\n \"x-forwarded-port\": \"443\",\n \"x-forwarded-proto\": \"https\"\n },\n \"json\": null,\n \"url\": \"https://9c76407d-5b8d-4b22-99fb-8c47a85d9848.mock.pstmn.io\"\n}" + } + ] + }, + { + "name": "COPY Request", + "request": { + "method": "COPY", + "header": [], + "body": {}, + "url": { + "raw": "https://9c76407d-5b8d-4b22-99fb-8c47a85d9848.mock.pstmn.io", + "protocol": "https", + "host": [ + "9c76407d-5b8d-4b22-99fb-8c47a85d9848", + "mock", + "pstmn", + "io" + ] + } + }, + "response": [ + { + "id": "b8517e1f-3aad-4c0e-bc2d-fb8d834adba7", + "name": "COPY Request", + "originalRequest": { + "method": "COPY", + "header": [], + "body": {}, + "url": { + "raw": "https://9c76407d-5b8d-4b22-99fb-8c47a85d9848.mock.pstmn.io", + "protocol": "https", + "host": [ + "9c76407d-5b8d-4b22-99fb-8c47a85d9848", + "mock", + "pstmn", + "io" + ] + } + }, + "status": "OK", + "code": 200, + "_postman_previewlanguage": "json", + "header": [], + "cookie": [], + "responseTime": "0", + "body": "{\n \"args\": {},\n \"data\": \"Curabitur auctor, elit nec pulvinar porttitor, ex augue condimentum enim, eget suscipit urna felis quis neque.\\nSuspendisse sit amet luctus massa, nec venenatis mi. Suspendisse tincidunt massa at nibh efficitur fringilla. Nam quis congue mi. Etiam volutpat.\",\n \"files\": {},\n \"form\": {},\n \"headers\": {\n \"host\": \"postman-echo.com\",\n \"content-length\": \"256\",\n \"accept\": \"*/*\",\n \"accept-encoding\": \"gzip, deflate\",\n \"content-type\": \"text/plain\",\n \"cookie\": \"sails.sid=s%3A1wOi4AdoZEbqBjGi6oSUC5Vlfje8wJvs.DHQfRLXfIBvZ%2Bv0KhLAThMDz%2FXvxh9gyxWYa0u1EZOU\",\n \"user-agent\": \"PostmanRuntime/7.1.1\",\n \"x-forwarded-port\": \"443\",\n \"x-forwarded-proto\": \"https\"\n },\n \"json\": null,\n \"url\": \"https://9c76407d-5b8d-4b22-99fb-8c47a85d9848.mock.pstmn.io\"\n}" + } + ] + } + ] +} \ No newline at end of file diff --git a/codegens/nodejs-axios/test/unit/snippet.test.js b/codegens/nodejs-axios/test/unit/snippet.test.js new file mode 100644 index 000000000..bc8b1c87f --- /dev/null +++ b/codegens/nodejs-axios/test/unit/snippet.test.js @@ -0,0 +1,395 @@ +var expect = require('chai').expect, + sdk = require('postman-collection'), + sanitize = require('../../lib/util').sanitize, + parseBody = require('../../lib/parseRequest').parseBody, + getOptions = require('../../lib/index').getOptions, + convert = require('../../lib/index').convert, + mainCollection = require('./fixtures/testcollection/collection.json'); + +describe('nodejs-axios convert function', function () { + describe('Convert function', function () { + var request, + reqObject, + options = {}, + snippetArray, + line_no; + + it('should return a Tab indented snippet ', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + indentType: 'Tab', + indentCount: 1 + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + + expect(snippet).to.be.a('string'); + snippetArray = snippet.split('\n'); + for (var i = 0; i < snippetArray.length; i++) { + if (snippetArray[i] === 'var config = {') { line_no = i + 1; } + } + expect(snippetArray[line_no].charAt(0)).to.equal('\t'); + }); + }); + + it('should return snippet with timeout property when timeout is set to non zero', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + requestTimeout: 1000 + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('timeout: 1000'); + }); + }); + + it('should return snippet with maxRedirects property set to ' + + '0 for no follow redirect', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + followRedirect: false + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + + expect(snippet).to.be.a('string'); + expect(snippet).to.include('maxRedirects: 0'); + }); + }); + + it('should return valid code snippet for no headers and no body', function () { + reqObject = { + 'description': 'This is a sample POST request without headers and body', + 'url': 'https://echo.getpostman.com/post', + 'method': 'POST' + }; + request = new sdk.Request(reqObject); + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('headers: { }'); + }); + }); + + it('should not fail for a random body mode', function () { + request = new sdk.Request(mainCollection.item[2].request); + request.body.mode = 'random'; + request.body[request.body.mode] = {}; + + convert(request, options, function (error, snippet) { + + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.be.a('string'); + expect(snippet).to.not.include('body:'); + }); + }); + + it('should generate snippet for file body mode', function () { + request = new sdk.Request({ + 'url': 'https://echo.getpostman.com/post', + 'method': 'POST', + 'body': { + 'mode': 'file', + 'file': [ + { + 'key': 'fileName', + 'src': 'file', + 'type': 'file' + } + ] + } + }); + options = { indentType: 'Space', indentCount: 2 }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.not.equal(''); + }); + }); + + it('should return snippet with proper semicolon placed where required', function () { + // testing for the below snippet + /* + const axios = require('axios'); + const config = { + 'method': 'get', + 'url': 'https://postman-echo.com/headers', + 'headers': { + 'my-sample-header': 'Lorem ipsum dolor sit amet', + 'not-disabled-header': 'ENABLED' + } + } + axios(config) + .then(function (response) { + console.log(JSON.stringify(response.data)); + }) + .catch(function (error) { + console.log(error); + }); + */ + request = new sdk.Request(mainCollection.item[0].request); + options = {}; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + var snippetArray = snippet.split('\n'); + snippetArray.forEach(function (line) { + if (line.charAt(line.length - 2) === ')') { + expect(line.charAt(line.length - 1)).to.equal(';'); + } + }); + // -2 because last one is a newline + const lastLine = snippetArray[snippetArray.length - 2] + expect(lastLine.charAt(lastLine.length - 1)).to.equal(';'); + }); + }); + + it('should return snippet with no trailing comma when requestTimeout ' + + 'is set to non zero', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + requestTimeout: 1000 + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + + expect(snippet).to.be.a('string'); + expect(snippet).to.not.include('timeout: 1000,'); + expect(snippet).to.include('timeout: 1000'); + }); + }); + + it('should return snippet with just a single comma when requestTimeout ' + + 'is set to non zero and followRedirect as false', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + requestTimeout: 1000, + followRedirect: false, + indentCount: 1, + indentType: 'space' + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + + expect(snippet).to.be.a('string'); + expect(snippet).to.not.include('timeout: 1000,,'); + expect(snippet).to.include('timeout: 1000,\n maxRedirects: 0'); + }); + }); + + it('should not require unused fs', function () { + request = new sdk.Request({ + 'url': 'https://postman-echo.com/get', + 'method': 'GET', + 'body': { + 'mode': 'raw', + 'raw': '' + } + }); + convert(request, {}, (error, snippet) => { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.not.include('const fs = require(\'fs\')'); + }); + }); + + it('should add fs for form-data file upload', function () { + request = new sdk.Request({ + 'url': 'https://postman-echo.com/post', + 'method': 'POST', + 'body': { + 'mode': 'formdata', + 'formdata': [ + { + 'key': 'fileName', + 'src': '/some/path/file.txt', + 'type': 'file' + } + ] + } + }); + convert(request, {}, (error, snippet) => { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('var data = new FormData()'); + }); + }); + + it('should trim header keys and not trim header values', function () { + var request = new sdk.Request({ + 'method': 'GET', + 'header': [ + { + 'key': ' key_containing_whitespaces ', + 'value': ' value_containing_whitespaces ' + } + ], + 'url': { + 'raw': 'https://google.com', + 'protocol': 'https', + 'host': [ + 'google', + 'com' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('\'key_containing_whitespaces\': \' value_containing_whitespaces \''); + }); + }); + + it('should include JSON.stringify in the snippet for raw json bodies', function () { + var request = new sdk.Request({ + 'method': 'POST', + 'header': [ + { + 'key': 'Content-Type', + 'value': 'application/json' + } + ], + 'body': { + 'mode': 'raw', + 'raw': '{\n "json": "Test-Test"\n}' + }, + 'url': { + 'raw': 'https://postman-echo.com/post', + 'protocol': 'https', + 'host': [ + 'postman-echo', + 'com' + ], + 'path': [ + 'post' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('var data = JSON.stringify({"json":"Test-Test"});'); + }); + }); + + it('should generate snippets for no files in form data', function () { + var request = new sdk.Request({ + 'method': 'POST', + 'header': [], + 'body': { + 'mode': 'formdata', + 'formdata': [ + { + 'key': 'no file', + 'value': '', + 'type': 'file', + 'src': [] + }, + { + 'key': 'no src', + 'value': '', + 'type': 'file' + }, + { + 'key': 'invalid src', + 'value': '', + 'type': 'file', + 'src': {} + } + ] + }, + 'url': { + 'raw': 'https://postman-echo.com/post', + 'protocol': 'https', + 'host': [ + 'postman-echo', + 'com' + ], + 'path': [ + 'post' + ] + } + }); + convert(request, {}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + expect(snippet).to.include('data.append(\'no file\', fs.createReadStream(\'/path/to/file\'));'); + expect(snippet).to.include('data.append(\'no src\', fs.createReadStream(\'/path/to/file\'));'); + expect(snippet).to.include('data.append(\'invalid src\', fs.createReadStream(\'/path/to/file\'));'); + }); + }); + + describe('getOptions function', function () { + + it('should return an array of specific options', function () { + expect(getOptions()).to.be.an('array'); + }); + + it('should return all the valid options', function () { + expect(getOptions()[0]).to.have.property('id', 'indentCount'); + expect(getOptions()[1]).to.have.property('id', 'indentType'); + expect(getOptions()[2]).to.have.property('id', 'requestTimeout'); + expect(getOptions()[3]).to.have.property('id', 'followRedirect'); + expect(getOptions()[4]).to.have.property('id', 'trimRequestBody'); + // expect(getOptions()[5]).to.have.property('id', 'AsyncAwait_enabled'); + }); + }); + + describe('Sanitize function', function () { + + it('should return empty string when input is not a string type', function () { + expect(sanitize(123, false)).to.equal(''); + expect(sanitize(null, false)).to.equal(''); + expect(sanitize({}, false)).to.equal(''); + expect(sanitize([], false)).to.equal(''); + }); + + it('should trim input string when needed', function () { + expect(sanitize('inputString ', true)).to.equal('inputString'); + }); + }); + + describe('parseRequest function', function () { + + it('should return empty string for empty body', function () { + expect(parseBody(null, ' ', false)).to.equal(''); + }); + }); + }); +}); diff --git a/codegens/nodejs-axios/test/unit/validation.test.js b/codegens/nodejs-axios/test/unit/validation.test.js new file mode 100644 index 000000000..f1083b153 --- /dev/null +++ b/codegens/nodejs-axios/test/unit/validation.test.js @@ -0,0 +1,30 @@ +var expect = require('chai').expect, + path = require('path'), + + package = require(path.resolve('.', 'package.json')); + + +describe('package.json', function () { + it('should have com_postman_plugin object with valid properties', function () { + expect(package).to.have.property('com_postman_plugin'); + + expect(package.com_postman_plugin.type).to.equal('code_generator'); + expect(package.com_postman_plugin.lang).to.be.a('string'); + expect(package.com_postman_plugin.variant).to.be.a('string'); + expect(package.com_postman_plugin.syntax_mode).to.be.equal('javascript'); + }); + it('should have main property with relative path to object with convert property', function () { + var languageModule; + + expect(package.main).to.be.a('string'); + + try { + languageModule = require(path.resolve('.', package.main)); + } + catch (error) { + console.error(error); + } + expect(languageModule).to.be.a('object'); + expect(languageModule.convert).to.be.a('function'); + }); +}); diff --git a/codegens/nodejs-native/README.md b/codegens/nodejs-native/README.md index c8dabc223..3a77b77ca 100644 --- a/codegens/nodejs-native/README.md +++ b/codegens/nodejs-native/README.md @@ -20,6 +20,7 @@ Convert function will take three parameters * `requestTimeout` : Integer denoting time after which the request will bail out in milli-seconds * `trimRequestBody` : Trim request body fields * `followRedirect` : Boolean denoting whether to redirect a request + * `ES6_enabled` : Boolean denoting whether to generate snippet with ES6 features * `callback`- callback function with first parameter as error and second parameter as string for code snippet diff --git a/codegens/nodejs-native/lib/request.js b/codegens/nodejs-native/lib/request.js index e7a2bed89..523af521f 100644 --- a/codegens/nodejs-native/lib/request.js +++ b/codegens/nodejs-native/lib/request.js @@ -6,7 +6,7 @@ const _ = require('./lodash'), var self; /** - * retuns snippet of nodejs(native) by parsing data from Postman-SDK request object + * returns snippet of nodejs(native) by parsing data from Postman-SDK request object * * @param {Object} request - Postman SDK request object * @param {String} indentString - indentation required for code snippet @@ -15,19 +15,44 @@ var self; */ function makeSnippet (request, indentString, options) { var nativeModule = (request.url.protocol === 'http' ? 'http' : 'https'), - snippet = `var ${nativeModule} = require('${nativeModule}');\n`, + snippet, optionsArray = [], postData = ''; - + if (options.ES6_enabled) { + snippet = 'const '; + } + else { + snippet = 'var '; + } if (options.followRedirect) { - snippet = `var ${nativeModule} = require('follow-redirects').${nativeModule};\n`; + snippet += `${nativeModule} = require('follow-redirects').${nativeModule};\n`; + } + else { + snippet += `${nativeModule} = require('${nativeModule}');\n`; } - snippet += 'var fs = require(\'fs\');\n\n'; + if (options.ES6_enabled) { + snippet += 'const '; + } + else { + snippet += 'var '; + } + snippet += 'fs = require(\'fs\');\n\n'; if (_.get(request, 'body.mode') && request.body.mode === 'urlencoded') { - snippet += 'var qs = require(\'querystring\');\n\n'; + if (options.ES6_enabled) { + snippet += 'const '; + } + else { + snippet += 'var '; + } + snippet += 'qs = require(\'querystring\');\n\n'; } - - snippet += 'var options = {\n'; + if (options.ES6_enabled) { + snippet += 'let '; + } + else { + snippet += 'var '; + } + snippet += 'options = {\n'; /** * creating string to represent options object using optionArray.join() @@ -117,27 +142,55 @@ function makeSnippet (request, indentString, options) { snippet += optionsArray.join(',\n') + '\n'; snippet += '};\n\n'; - - snippet += `var req = ${nativeModule}.request(options, function (res) {\n`; - - snippet += indentString + 'var chunks = [];\n\n'; - snippet += indentString + 'res.on("data", function (chunk) {\n'; + if (options.ES6_enabled) { + snippet += 'const '; + } + else { + snippet += 'var '; + } + snippet += `req = ${nativeModule}.request(options, `; + if (options.ES6_enabled) { + snippet += '(res) => {\n'; + snippet += indentString + 'let chunks = [];\n\n'; + snippet += indentString + 'res.on("data", (chunk) => {\n'; + } + else { + snippet += 'function (res) {\n'; + snippet += indentString + 'var chunks = [];\n\n'; + snippet += indentString + 'res.on("data", function (chunk) {\n'; + } snippet += indentString.repeat(2) + 'chunks.push(chunk);\n'; snippet += indentString + '});\n\n'; - snippet += indentString + 'res.on("end", function (chunk) {\n'; - snippet += indentString.repeat(2) + 'var body = Buffer.concat(chunks);\n'; + if (options.ES6_enabled) { + snippet += indentString + 'res.on("end", (chunk) => {\n'; + snippet += indentString.repeat(2) + 'let body = Buffer.concat(chunks);\n'; + } + else { + snippet += indentString + 'res.on("end", function (chunk) {\n'; + snippet += indentString.repeat(2) + 'var body = Buffer.concat(chunks);\n'; + } snippet += indentString.repeat(2) + 'console.log(body.toString());\n'; snippet += indentString + '});\n\n'; + if (options.ES6_enabled) { + snippet += indentString + 'res.on("error", (error) => {\n'; + } + else { + snippet += indentString + 'res.on("error", function (error) {\n'; + } - snippet += indentString + 'res.on("error", function (error) {\n'; snippet += indentString.repeat(2) + 'console.error(error);\n'; snippet += indentString + '});\n'; - snippet += '});\n\n'; if (request.body && !(_.isEmpty(request.body)) && postData.length) { - snippet += `var postData = ${postData};\n\n`; + if (options.ES6_enabled) { + snippet += 'let '; + } + else { + snippet += 'var '; + } + snippet += `postData = ${postData};\n\n`; if (request.method === 'DELETE') { snippet += 'req.setHeader(\'Content-Length\', postData.length);\n\n'; @@ -170,6 +223,7 @@ function makeSnippet (request, indentString, options) { * @param {String} options.indentCount - number of spaces or tabs for indentation. * @param {Boolean} options.followRedirect - whether to enable followredirect * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not + * @param {Boolean} options.ES6_enabled - whether to generate snippet with ES6 features * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out * @param {Function} callback - callback function with parameters (error, snippet) */ @@ -216,6 +270,13 @@ self = module.exports = { type: 'boolean', default: false, description: 'Remove white space and additional lines that may affect the server\'s response' + }, + { + name: 'Enable ES6 features', + id: 'ES6_enabled', + type: 'boolean', + default: false, + description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features' }]; }, diff --git a/codegens/nodejs-native/npm/test-lint.js b/codegens/nodejs-native/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/nodejs-native/npm/test-lint.js +++ b/codegens/nodejs-native/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-native/npm/test-newman.js b/codegens/nodejs-native/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/nodejs-native/npm/test-newman.js +++ b/codegens/nodejs-native/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-native/npm/test-unit.js b/codegens/nodejs-native/npm/test-unit.js index 1bd787adb..b6eada01b 100644 --- a/codegens/nodejs-native/npm/test-unit.js +++ b/codegens/nodejs-native/npm/test-unit.js @@ -4,10 +4,8 @@ // 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'), +var shell = require('shelljs'), + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +18,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +54,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-native/test/newman/newman.test.js b/codegens/nodejs-native/test/newman/newman.test.js index 409685f51..77fa0174e 100644 --- a/codegens/nodejs-native/test/newman/newman.test.js +++ b/codegens/nodejs-native/test/newman/newman.test.js @@ -11,4 +11,16 @@ describe('Convert for different types of request', function () { }; runNewmanTest(convert, options, testConfig); + + describe('Convert for request incorporating ES6 features', function () { + var options = {indentCount: 2, indentType: 'Space', ES6_enabled: true}, + testConfig = { + compileScript: null, + runScript: 'node run.js', + fileName: 'run.js', + headerSnippet: '/* eslint-disable */\n' + }; + + runNewmanTest(convert, options, testConfig); + }); }); diff --git a/codegens/nodejs-native/test/unit/snippet.test.js b/codegens/nodejs-native/test/unit/snippet.test.js index 3c24788ca..db4212a11 100644 --- a/codegens/nodejs-native/test/unit/snippet.test.js +++ b/codegens/nodejs-native/test/unit/snippet.test.js @@ -94,6 +94,51 @@ describe('nodejs-native convert function', function () { expect(snippet).to.include('\'key_containing_whitespaces\': \' value_containing_whitespaces \''); }); }); + + it('should return snippet with ES6 features when ES6_enabled is set to true', function () { + var request = new sdk.Request({ + 'method': 'POST', + 'header': [ + { + 'key': 'lorem', + 'value': 'lorem_ipsum' + } + ], + 'url': { + 'raw': 'http://httpbin.org/post', + 'protocol': 'http', + 'host': [ + 'httpbin', + 'org' + ] + }, + 'body': { + 'mode': 'urlencoded', + 'urlencoded': { + 'title': 'foo-bar' + } + } + }), + snippetArray; + convert(request, {'followRedirect': true, 'ES6_enabled': true}, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + } + expect(snippet).to.be.a('string'); + snippetArray = snippet.split('\n'); + expect(snippetArray[0]).to.equal('const http = require(\'follow-redirects\').http;'); + expect(snippetArray).to.include('const fs = require(\'fs\');'); + expect(snippetArray).to.include('const qs = require(\'querystring\');'); + expect(snippetArray).to.include('let options = {'); + expect(snippetArray).to.include('const req = http.request(options, (res) => {'); + expect(snippetArray).to.include(' let chunks = [];'); + expect(snippetArray).to.include(' res.on("data", (chunk) => {'); + expect(snippetArray).to.include(' res.on("end", (chunk) => {'); + expect(snippetArray).to.include(' let body = Buffer.concat(chunks);'); + expect(snippetArray).to.include(' res.on("error", (error) => {'); + }); + }); + it('should include JSON.stringify in the snippet for raw json bodies', function () { var request = new sdk.Request({ 'method': 'POST', diff --git a/codegens/nodejs-request/README.md b/codegens/nodejs-request/README.md index e0d7f5287..ec86322bf 100644 --- a/codegens/nodejs-request/README.md +++ b/codegens/nodejs-request/README.md @@ -18,6 +18,7 @@ Convert function will take three parameters * `requestTimeout` : Integer denoting time after which the request will bail out in milli-seconds * `trimRequestBody` : Trim request body fields * `followRedirect` : Boolean denoting whether to redirect a request + * `ES6_enabled` : Boolean denoting whether to generate snippet with ES6 features * `callback`- callback function with first parameter as error and second parameter as string for code snippet @@ -26,7 +27,8 @@ Convert function will take three parameters var request = new sdk.Request('www.google.com'), //using postman sdk to create request options = { indentType: 'Space', - indentCount: 2 + indentCount: 2, + ES6_enabled: true }; convert(request, options, function(error, snippet) { if (error) { diff --git a/codegens/nodejs-request/lib/request.js b/codegens/nodejs-request/lib/request.js index 205060722..73d2e5d29 100644 --- a/codegens/nodejs-request/lib/request.js +++ b/codegens/nodejs-request/lib/request.js @@ -5,7 +5,7 @@ var _ = require('./lodash'), sanitizeOptions = require('./util').sanitizeOptions; /** - * retuns snippet of nodejs(request) by parsing data from Postman-SDK request object + * returns snippet of nodejs(request) by parsing data from Postman-SDK request object * * @param {Object} request - Postman SDK request object * @param {String} indentString - indentation required for code snippet @@ -13,9 +13,16 @@ var _ = require('./lodash'), * @returns {String} - nodejs(request) code snippet for given request object */ function makeSnippet (request, indentString, options) { - var snippet = 'var request = require(\'request\');\n', + var snippet, optionsArray = [], isFormDataFile = false; + if (options.ES6_enabled) { + snippet = 'const '; + } + else { + snippet = 'var '; + } + snippet += 'request = require(\'request\');\n'; if (request.body && request.body.mode === 'formdata') { _.forEach(request.body.toJSON().formdata, function (data) { if (!data.disabled && data.type === 'file') { @@ -24,9 +31,21 @@ function makeSnippet (request, indentString, options) { }); } if (isFormDataFile) { - snippet += 'var fs = require(\'fs\');\n'; + if (options.ES6_enabled) { + snippet += 'const '; + } + else { + snippet += 'var '; + } + snippet += 'fs = require(\'fs\');\n'; + } + if (options.ES6_enabled) { + snippet += 'let '; + } + else { + snippet += 'var '; } - snippet += 'var options = {\n'; + snippet += 'options = {\n'; /** * creating string to represent options object using optionArray.join() @@ -70,7 +89,13 @@ function makeSnippet (request, indentString, options) { snippet += optionsArray.join(',\n') + '\n'; snippet += '};\n'; - snippet += 'request(options, function (error, response) { \n'; + snippet += 'request(options, '; + if (options.ES6_enabled) { + snippet += '(error, response) => {\n'; + } + else { + snippet += 'function (error, response) {\n'; + } snippet += indentString + 'if (error) throw new Error(error);\n'; snippet += indentString + 'console.log(response.body);\n'; snippet += '});\n'; @@ -120,6 +145,13 @@ function getOptions () { type: 'boolean', default: false, description: 'Remove white space and additional lines that may affect the server\'s response' + }, + { + name: 'Enable ES6 features', + id: 'ES6_enabled', + type: 'boolean', + default: false, + description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features' } ]; } @@ -133,6 +165,7 @@ function getOptions () { * @param {String} options.indentCount - number of spaces or tabs for indentation. * @param {Boolean} options.followRedirect - whether to enable followredirect * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not + * @param {Boolean} options.ES6_enabled - whether to generate snippet with ES6 features * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out * @param {Function} callback - callback function with parameters (error, snippet) */ diff --git a/codegens/nodejs-request/npm/test-lint.js b/codegens/nodejs-request/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/nodejs-request/npm/test-lint.js +++ b/codegens/nodejs-request/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-request/npm/test-newman.js b/codegens/nodejs-request/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/nodejs-request/npm/test-newman.js +++ b/codegens/nodejs-request/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-request/npm/test-unit.js b/codegens/nodejs-request/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/nodejs-request/npm/test-unit.js +++ b/codegens/nodejs-request/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-request/test/newman/newman.test.js b/codegens/nodejs-request/test/newman/newman.test.js index eab899b32..faa8cac1a 100644 --- a/codegens/nodejs-request/test/newman/newman.test.js +++ b/codegens/nodejs-request/test/newman/newman.test.js @@ -11,4 +11,17 @@ describe('Convert for different types of request', function () { }; runNewmanTest(convert, options, testConfig); + + describe('Convert for request incorporating ES6 features', function () { + var options = {indentCount: 2, indentType: 'Space', ES6_enabled: true}, + testConfig = { + compileScript: null, + runScript: 'node run.js', + fileName: 'run.js', + headerSnippet: '/* eslint-disable */\n' + }; + + runNewmanTest(convert, options, testConfig); + }); + }); diff --git a/codegens/nodejs-request/test/unit/snippet.test.js b/codegens/nodejs-request/test/unit/snippet.test.js index f4a8b54a9..1d4102e34 100644 --- a/codegens/nodejs-request/test/unit/snippet.test.js +++ b/codegens/nodejs-request/test/unit/snippet.test.js @@ -51,6 +51,25 @@ describe('nodejs-request convert function', function () { }); }); + it('should return snippet with ES6 features when ES6_enabled is set to true', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + ES6_enabled: true + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + + expect(snippet).to.be.a('string'); + snippetArray = snippet.split('\n'); + expect(snippetArray[0]).to.equal('const request = require(\'request\');'); + expect(snippetArray).to.include('let options = {'); + expect(snippetArray).to.include('request(options, (error, response) => {'); + }); + }); + it('should return snippet with followRedirect property set to ' + 'false for no follow redirect', function () { request = new sdk.Request(mainCollection.item[0].request); diff --git a/codegens/nodejs-unirest/README.md b/codegens/nodejs-unirest/README.md index 9ec888e57..889e88429 100644 --- a/codegens/nodejs-unirest/README.md +++ b/codegens/nodejs-unirest/README.md @@ -18,6 +18,7 @@ Convert function will take three parameters * `requestTimeout` : Integer denoting time after which the request will bail out in milli-seconds * `trimRequestBody` : Trim request body fields * `followRedirect` : Boolean denoting whether to redirect a request + * `ES6_enabled` : Boolean denoting whether to generate snippet with ES6 features * `callback`- callback function with first parameter as error and second parameter as string for code snippet @@ -26,7 +27,8 @@ Convert function will take three parameters var request = new sdk.Request('www.google.com'), //using postman sdk to create request options = { indentType: 'Space', - indentCount: 2 + indentCount: 2, + ES6_enabled: true }; convert(request, options, function(error, snippet) { if (error) { diff --git a/codegens/nodejs-unirest/lib/unirest.js b/codegens/nodejs-unirest/lib/unirest.js index f60be5fd6..30bafd7ca 100644 --- a/codegens/nodejs-unirest/lib/unirest.js +++ b/codegens/nodejs-unirest/lib/unirest.js @@ -6,7 +6,7 @@ var _ = require('./lodash'), parseRequest = require('./parseRequest'); /** - * retuns snippet of nodejs(unirest) by parsing data from Postman-SDK request object + * returns snippet of nodejs(unirest) by parsing data from Postman-SDK request object * * @param {Object} request - Postman SDK request object * @param {String} indentString - indentation required for code snippet @@ -14,9 +14,21 @@ var _ = require('./lodash'), * @returns {String} - nodejs(unirest) code snippet for given request object */ function makeSnippet (request, indentString, options) { - var snippet = 'var unirest = require(\'unirest\');\n'; - - snippet += `var req = unirest('${request.method}', '${sanitize(request.url.toString())}')\n`; + var snippet; + if (options.ES6_enabled) { + snippet = 'const '; + } + else { + snippet = 'var '; + } + snippet += 'unirest = require(\'unirest\');\n'; + if (options.ES6_enabled) { + snippet += 'const '; + } + else { + snippet += 'var '; + } + snippet += `req = unirest('${request.method}', '${sanitize(request.url.toString())}')\n`; if (request.body && !request.headers.has('Content-Type')) { if (request.body.mode === 'file') { request.addHeader({ @@ -80,13 +92,17 @@ function makeSnippet (request, indentString, options) { request.headers.get('Content-Type')); } if (options.requestTimeout) { - snippet += indentString + `.timeout(${options.requestTimeout})`; + snippet += indentString + `.timeout(${options.requestTimeout})\n`; } if (options.followRedirect === false) { snippet += indentString + '.followRedirect(false)\n'; } - - snippet += indentString + '.end(function (res) { \n'; + if (options.ES6_enabled) { + snippet += indentString + '.end((res) => { \n'; + } + else { + snippet += indentString + '.end(function (res) { \n'; + } snippet += indentString.repeat(2) + 'if (res.error) throw new Error(res.error); \n'; snippet += indentString.repeat(2) + 'console.log(res.raw_body);\n'; snippet += indentString + '});\n'; @@ -137,6 +153,13 @@ function getOptions () { type: 'boolean', default: false, description: 'Remove white space and additional lines that may affect the server\'s response' + }, + { + name: 'Enable ES6 features', + id: 'ES6_enabled', + type: 'boolean', + default: false, + description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features' } ]; } @@ -150,6 +173,7 @@ function getOptions () { * @param {String} options.indentCount - number of spaces or tabs for indentation. * @param {Boolean} options.followRedirect - whether to enable followredirect * @param {Boolean} options.trimRequestBody - whether to trim fields in request body or not + * @param {Boolean} options.ES6_enabled - whether to generate snippet with ES6 features * @param {Number} options.requestTimeout : time in milli-seconds after which request will bail out * @param {Function} callback - callback function with parameters (error, snippet) */ diff --git a/codegens/nodejs-unirest/npm/test-lint.js b/codegens/nodejs-unirest/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/nodejs-unirest/npm/test-lint.js +++ b/codegens/nodejs-unirest/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-unirest/npm/test-newman.js b/codegens/nodejs-unirest/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/nodejs-unirest/npm/test-newman.js +++ b/codegens/nodejs-unirest/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-unirest/npm/test-unit.js b/codegens/nodejs-unirest/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/nodejs-unirest/npm/test-unit.js +++ b/codegens/nodejs-unirest/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/nodejs-unirest/test/newman/newman.test.js b/codegens/nodejs-unirest/test/newman/newman.test.js index eab899b32..2e10a6591 100644 --- a/codegens/nodejs-unirest/test/newman/newman.test.js +++ b/codegens/nodejs-unirest/test/newman/newman.test.js @@ -11,4 +11,16 @@ describe('Convert for different types of request', function () { }; runNewmanTest(convert, options, testConfig); + + describe('Convert for request incorporating ES6 features', function () { + var options = {indentCount: 2, indentType: 'Space', ES6_enabled: true}, + testConfig = { + compileScript: null, + runScript: 'node run.js', + fileName: 'run.js', + headerSnippet: '/* eslint-disable */\n' + }; + + runNewmanTest(convert, options, testConfig); + }); }); diff --git a/codegens/nodejs-unirest/test/unit/snippet.test.js b/codegens/nodejs-unirest/test/unit/snippet.test.js index c025a42c0..070afe161 100644 --- a/codegens/nodejs-unirest/test/unit/snippet.test.js +++ b/codegens/nodejs-unirest/test/unit/snippet.test.js @@ -48,6 +48,25 @@ describe('nodejs unirest convert function', function () { }); }); + it('should return snippet with ES6 features', function () { + request = new sdk.Request(mainCollection.item[0].request); + options = { + ES6_enabled: true + }; + convert(request, options, function (error, snippet) { + if (error) { + expect.fail(null, null, error); + return; + } + expect(snippet).to.be.a('string'); + snippetArray = snippet.split('\n'); + expect(snippetArray[0]).to.equal('const unirest = require(\'unirest\');'); + expect(snippetArray).to.include(`const req = unirest('${mainCollection.item[0].request.method}', ` + + `'${mainCollection.item[0].request.url.raw}')`); + expect(snippetArray).to.include(' .end((res) => { '); + }); + }); + it('should return snippet with followRedirect function having ' + 'parameter false for no follow redirect', function () { request = new sdk.Request(mainCollection.item[0].request); diff --git a/codegens/objective-c/README.md b/codegens/objective-c/README.md index 9226872cb..4a719e4ca 100644 --- a/codegens/objective-c/README.md +++ b/codegens/objective-c/README.md @@ -12,7 +12,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Whether or not request body fields should be trimmed diff --git a/codegens/objective-c/npm/test-lint.js b/codegens/objective-c/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/objective-c/npm/test-lint.js +++ b/codegens/objective-c/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/objective-c/npm/test-newman.js b/codegens/objective-c/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/objective-c/npm/test-newman.js +++ b/codegens/objective-c/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/objective-c/npm/test-unit.js b/codegens/objective-c/npm/test-unit.js index 1bd787adb..0de7fd529 100644 --- a/codegens/objective-c/npm/test-unit.js +++ b/codegens/objective-c/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/ocaml-cohttp/README.md b/codegens/ocaml-cohttp/README.md index 3aafd938c..ebc7cb072 100644 --- a/codegens/ocaml-cohttp/README.md +++ b/codegens/ocaml-cohttp/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Trim request body fields diff --git a/codegens/ocaml-cohttp/lib/ocaml.js b/codegens/ocaml-cohttp/lib/ocaml.js index 01c1bce49..b9d29d8df 100644 --- a/codegens/ocaml-cohttp/lib/ocaml.js +++ b/codegens/ocaml-cohttp/lib/ocaml.js @@ -389,7 +389,7 @@ self = module.exports = { if (bodySnippet !== '') { codeSnippet += '~body '; } - codeSnippet += `${methodArg} uri >>= fun (resp, body) ->\n`; + codeSnippet += `${methodArg} uri >>= fun (_resp, body) ->\n`; codeSnippet += `${indent}body |> Cohttp_lwt.Body.to_string >|= fun body -> body\n\n`; codeSnippet += 'let () =\n'; codeSnippet += `${indent}let respBody = Lwt_main.run reqBody in\n`; diff --git a/codegens/ocaml-cohttp/npm/test-lint.js b/codegens/ocaml-cohttp/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/ocaml-cohttp/npm/test-lint.js +++ b/codegens/ocaml-cohttp/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/ocaml-cohttp/npm/test-unit.js b/codegens/ocaml-cohttp/npm/test-unit.js index 1bd787adb..0de7fd529 100644 --- a/codegens/ocaml-cohttp/npm/test-unit.js +++ b/codegens/ocaml-cohttp/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-curl/npm/test-lint.js b/codegens/php-curl/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/php-curl/npm/test-lint.js +++ b/codegens/php-curl/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-curl/npm/test-newman.js b/codegens/php-curl/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/php-curl/npm/test-newman.js +++ b/codegens/php-curl/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-curl/npm/test-unit.js b/codegens/php-curl/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/php-curl/npm/test-unit.js +++ b/codegens/php-curl/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-httprequest2/README.md b/codegens/php-httprequest2/README.md index a6b89e9ff..f92e15d41 100644 --- a/codegens/php-httprequest2/README.md +++ b/codegens/php-httprequest2/README.md @@ -12,7 +12,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Whether or not request body fields should be trimmed diff --git a/codegens/php-httprequest2/npm/test-lint.js b/codegens/php-httprequest2/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/php-httprequest2/npm/test-lint.js +++ b/codegens/php-httprequest2/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-httprequest2/npm/test-newman.js b/codegens/php-httprequest2/npm/test-newman.js index b24727822..0c8559a8e 100644 --- a/codegens/php-httprequest2/npm/test-newman.js +++ b/codegens/php-httprequest2/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-httprequest2/npm/test-unit.js b/codegens/php-httprequest2/npm/test-unit.js index 1bd787adb..0de7fd529 100644 --- a/codegens/php-httprequest2/npm/test-unit.js +++ b/codegens/php-httprequest2/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-pecl-http/README.md b/codegens/php-pecl-http/README.md index c59d808ab..3c11ae580 100644 --- a/codegens/php-pecl-http/README.md +++ b/codegens/php-pecl-http/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Trim request body fields diff --git a/codegens/php-pecl-http/npm/test-lint.js b/codegens/php-pecl-http/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/php-pecl-http/npm/test-lint.js +++ b/codegens/php-pecl-http/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/php-pecl-http/npm/test-unit.js b/codegens/php-pecl-http/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/php-pecl-http/npm/test-unit.js +++ b/codegens/php-pecl-http/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/powershell-restmethod/README.md b/codegens/powershell-restmethod/README.md index f4cd3430f..2ebe860dc 100644 --- a/codegens/powershell-restmethod/README.md +++ b/codegens/powershell-restmethod/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `trimRequestBody` - Trim request body fields * `followRedirect` - Boolean denoting whether to redirect a request * `requestTimeout` - Integer denoting time after which the request will bail out in milli-seconds diff --git a/codegens/powershell-restmethod/lib/index.js b/codegens/powershell-restmethod/lib/index.js index 579db4ac2..e9966409a 100644 --- a/codegens/powershell-restmethod/lib/index.js +++ b/codegens/powershell-restmethod/lib/index.js @@ -45,7 +45,19 @@ function parseFormData (body, trim) { var bodySnippet = '$multipartContent = [System.Net.Http.MultipartFormDataContent]::new()\n'; _.forEach(body, function (data) { if (!data.disabled) { - if (data.type === 'text') { + if (data.type === 'file') { + var pathArray = data.src.split(path.sep), + fileName = pathArray[pathArray.length - 1]; + bodySnippet += `$multipartFile = '${data.src}'\n` + + '$FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open)\n' + + '$fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")\n' + + `$fileHeader.Name = "${sanitize(data.key)}"\n` + + `$fileHeader.FileName = "${sanitize(fileName, trim)}"\n` + + '$fileContent = [System.Net.Http.StreamContent]::new($FileStream)\n' + + '$fileContent.Headers.ContentDisposition = $fileHeader\n' + + '$multipartContent.Add($fileContent)\n\n'; + } + else { bodySnippet += '$stringHeader = ' + '[System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")\n' + `$stringHeader.Name = "${sanitize(data.key, trim)}"\n` + @@ -53,18 +65,6 @@ function parseFormData (body, trim) { '$StringContent.Headers.ContentDisposition = $stringHeader\n' + '$multipartContent.Add($stringContent)\n\n'; } - else { - var pathArray = data.src.split(path.sep), - fileName = pathArray[pathArray.length - 1]; - bodySnippet += `$multipartFile = '${data.src}'\n` + - '$FileStream = [System.IO.FileStream]::new($multipartFile, [System.IO.FileMode]::Open)\n' + - '$fileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new("form-data")\n' + - `$fileHeader.Name = "${sanitize(data.key)}"\n` + - `$fileHeader.FileName = "${sanitize(fileName, trim)}"\n` + - '$fileContent = [System.Net.Http.StreamContent]::new($FileStream)\n' + - '$fileContent.Headers.ContentDisposition = $fileHeader\n' + - '$multipartContent.Add($fileContent)\n\n'; - } } }); bodySnippet += '$body = $multipartContent\n'; diff --git a/codegens/powershell-restmethod/npm/test-lint.js b/codegens/powershell-restmethod/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/powershell-restmethod/npm/test-lint.js +++ b/codegens/powershell-restmethod/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/powershell-restmethod/npm/test-unit.js b/codegens/powershell-restmethod/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/powershell-restmethod/npm/test-unit.js +++ b/codegens/powershell-restmethod/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/powershell-restmethod/test/unit/convert.test.js b/codegens/powershell-restmethod/test/unit/convert.test.js index 430fa7824..35b471679 100644 --- a/codegens/powershell-restmethod/test/unit/convert.test.js +++ b/codegens/powershell-restmethod/test/unit/convert.test.js @@ -458,6 +458,41 @@ describe('Powershell-restmethod converter', function () { expect(snippet).to.include("'https://postman-echo.com/get?query1=b''b&query2=c\"c'"); }); }); + + it('should generate snippet for form data params with no type key present', function () { + var request = new sdk.Request({ + method: 'POST', + header: [], + url: { + raw: 'https://postman-echo.com/post', + protocol: 'https', + host: [ + 'postman-echo', + 'com' + ], + path: [ + 'post' + ] + }, + body: { + mode: 'formdata', + formdata: [ + { + key: 'sample_key', + value: 'sample_value' + } + ] + } + }); + convert(request, {}, function (error, snippet) { + expect(error).to.be.null; + expect(snippet).to.be.a('string'); + expect(snippet).to.include('$stringHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]' + + '::new("form-data")'); + expect(snippet).to.include('$stringHeader.Name = "sample_key"'); + expect(snippet).to.include('$StringContent = [System.Net.Http.StringContent]::new("sample_value")'); + }); + }); }); describe('getOptions function', function () { diff --git a/codegens/python-http.client/README.md b/codegens/python-http.client/README.md index 34d4601e3..3932e1386 100644 --- a/codegens/python-http.client/README.md +++ b/codegens/python-http.client/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - Set the number of indentation characters to add per code level * `trimRequestBody` - Trim request body fields diff --git a/codegens/python-http.client/npm/test-lint.js b/codegens/python-http.client/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/python-http.client/npm/test-lint.js +++ b/codegens/python-http.client/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/python-http.client/npm/test-newman.js b/codegens/python-http.client/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/python-http.client/npm/test-newman.js +++ b/codegens/python-http.client/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/python-http.client/npm/test-unit.js b/codegens/python-http.client/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/python-http.client/npm/test-unit.js +++ b/codegens/python-http.client/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/python-requests/npm/test-lint.js b/codegens/python-requests/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/python-requests/npm/test-lint.js +++ b/codegens/python-requests/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/python-requests/npm/test-newman.js b/codegens/python-requests/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/python-requests/npm/test-newman.js +++ b/codegens/python-requests/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/python-requests/npm/test-unit.js b/codegens/python-requests/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/python-requests/npm/test-unit.js +++ b/codegens/python-requests/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/ruby/lib/ruby.js b/codegens/ruby/lib/ruby.js index e68a09626..280c6b6b0 100644 --- a/codegens/ruby/lib/ruby.js +++ b/codegens/ruby/lib/ruby.js @@ -127,6 +127,20 @@ self = module.exports = { snippet += `https.read_timeout = ${Math.ceil(options.requestTimeout / 1000)}\n`; } snippet += `request = Net::HTTP::${_.capitalize(request.method)}.new(url)\n`; + if (request.body && !request.headers.has('Content-Type')) { + if (request.body.mode === 'file') { + request.addHeader({ + key: 'Content-Type', + value: 'text/plain' + }); + } + else if (request.body.mode === 'graphql') { + request.addHeader({ + key: 'Content-Type', + value: 'application/json' + }); + } + } headerSnippet = parseHeaders(request.getHeaders({enabled: true})); if (headerSnippet !== '') { snippet += headerSnippet; diff --git a/codegens/ruby/npm/test-lint.js b/codegens/ruby/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/ruby/npm/test-lint.js +++ b/codegens/ruby/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/ruby/npm/test-newman.js b/codegens/ruby/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/ruby/npm/test-newman.js +++ b/codegens/ruby/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/ruby/npm/test-unit.js b/codegens/ruby/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/ruby/npm/test-unit.js +++ b/codegens/ruby/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/shell-httpie/README.md b/codegens/shell-httpie/README.md index 0489248aa..e952c79e4 100644 --- a/codegens/shell-httpie/README.md +++ b/codegens/shell-httpie/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `followRedirect` - Boolean denoting whether to redirect a request * `requestTimeout` - Integer denoting time after which the request will bail out in milli-seconds diff --git a/codegens/shell-httpie/lib/shell-httpie.js b/codegens/shell-httpie/lib/shell-httpie.js index d4bf6159a..c94550cdf 100644 --- a/codegens/shell-httpie/lib/shell-httpie.js +++ b/codegens/shell-httpie/lib/shell-httpie.js @@ -53,7 +53,10 @@ self = module.exports = { parsedHeaders, bodyMode, timeout, - url = '', + // https://httpie.org/docs#request-url + // default scheme is `http://` for httpie + // thus, for url starting with `http://`, no need to add protocol + url = request.url.toString().startsWith('https') ? 'https://' : '', handleRedirect = (enableRedirect) => { if (enableRedirect) { return GAP + '--follow' + GAP; } return GAP; }, handleRequestTimeout = (time) => { if (time) { @@ -74,7 +77,7 @@ self = module.exports = { options = sanitizeOptions(options, self.getOptions()); Helpers.parseURLVariable(request); - url = Helpers.addHost(request) + Helpers.addPort(request) + Helpers.addPathandQuery(request); + url += Helpers.addHost(request) + Helpers.addPort(request) + Helpers.addPathandQuery(request); timeout = options.requestTimeout; if (request.body && request.body.mode === 'graphql' && !request.headers.has('Content-Type')) { request.addHeader({ diff --git a/codegens/shell-httpie/test/unit/converter.test.js b/codegens/shell-httpie/test/unit/converter.test.js index ecbe70aec..82680becb 100644 --- a/codegens/shell-httpie/test/unit/converter.test.js +++ b/codegens/shell-httpie/test/unit/converter.test.js @@ -64,7 +64,7 @@ describe('Shell-Httpie convert function', function () { expect.fail(null, null, error); } expect(snippet).to.be.a('string'); - expect(snippet).to.include('GET localhost:3000/getSelfBody'); + expect(snippet).to.include('GET https://localhost:3000/getSelfBody'); }); }); diff --git a/codegens/shell-wget/npm/test-lint.js b/codegens/shell-wget/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/shell-wget/npm/test-lint.js +++ b/codegens/shell-wget/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/shell-wget/npm/test-newman.js b/codegens/shell-wget/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/shell-wget/npm/test-newman.js +++ b/codegens/shell-wget/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/shell-wget/npm/test-unit.js b/codegens/shell-wget/npm/test-unit.js index 1bd787adb..0de7fd529 100755 --- a/codegens/shell-wget/npm/test-unit.js +++ b/codegens/shell-wget/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/swift/README.md b/codegens/swift/README.md index 0d8f90027..7f581c368 100644 --- a/codegens/swift/README.md +++ b/codegens/swift/README.md @@ -13,7 +13,7 @@ Convert function takes three parameters * `request` - Postman-SDK Request Object -* `options` - options is an object which hsa following properties +* `options` - options is an object which has following properties * `indentType` - String denoting type of indentation for code snippet. eg: 'Space', 'Tab' * `indentCount` - The number of indentation characters to add per code level * `trimRequestBody` - Whether or not request body fields should be trimmed diff --git a/codegens/swift/npm/test-lint.js b/codegens/swift/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/codegens/swift/npm/test-lint.js +++ b/codegens/swift/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/swift/npm/test-newman.js b/codegens/swift/npm/test-newman.js index e8f970755..ae7d2afe1 100644 --- a/codegens/swift/npm/test-newman.js +++ b/codegens/swift/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all newman tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/codegens/swift/npm/test-unit.js b/codegens/swift/npm/test-unit.js index 1bd787adb..0de7fd529 100644 --- a/codegens/swift/npm/test-unit.js +++ b/codegens/swift/npm/test-unit.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ 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); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/lib/index.js b/lib/index.js index 77f5dd8a6..4c075a099 100644 --- a/lib/index.js +++ b/lib/index.js @@ -23,7 +23,7 @@ module.exports = { return callback('Codegen~getOptions: getOptions is not a function'); } if (!main.getOptions) { - return callback('Codegen~convert: Could not find condegen corresponding to provided language, variant pair'); + return callback('Codegen~convert: Could not find codegen corresponding to provided language, variant pair'); } return callback(null, main.getOptions()); @@ -103,7 +103,7 @@ module.exports = { } }); if (!convert) { - return callback('Codegen~convert: Could not find condegen corresponding to provided language, variant pair'); + return callback('Codegen~convert: Could not find codegen corresponding to provided language, variant pair'); } diff --git a/npm/addPathToFormdataFile.js b/npm/addPathToFormdataFile.js index 609465766..18ea536fd 100644 --- a/npm/addPathToFormdataFile.js +++ b/npm/addPathToFormdataFile.js @@ -3,9 +3,9 @@ var path = require('path'), let collectionPath = path.resolve(__dirname, '../test/codegen/newman/fixtures/formdataFileCollection.json'), collection = require(collectionPath), formdata = collection.item[0].request.body.formdata; -formdata[0].src = path.resolve(__dirname, '../test1.txt'); -formdata[1].src[0] = path.resolve(__dirname, '../test2.txt'); -formdata[1].src[1] = path.resolve(__dirname, '../test3.txt'); +formdata[0].src = path.resolve(__dirname, '../dummyFile1.txt'); +formdata[1].src[0] = path.resolve(__dirname, '../dummyFile2.txt'); +formdata[1].src[1] = path.resolve(__dirname, '../dummyFile3.txt'); fs.writeFileSync(collectionPath, JSON.stringify(collection, null, 2), function (error) { if (error) { diff --git a/npm/boilerplate/npm/test-lint.js b/npm/boilerplate/npm/test-lint.js index 59ae3a010..b113b8bfd 100644 --- a/npm/boilerplate/npm/test-lint.js +++ b/npm/boilerplate/npm/test-lint.js @@ -1,7 +1,6 @@ #!/usr/bin/env node -require('shelljs/global'); - -var chalk = require('chalk'), +var shell = require('shelljs'), + chalk = require('chalk'), async = require('async'), ESLintCLIEngine = require('eslint').CLIEngine, @@ -56,4 +55,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/npm/boilerplate/npm/test-newman.js b/npm/boilerplate/npm/test-newman.js index b24727822..0c8559a8e 100644 --- a/npm/boilerplate/npm/test-newman.js +++ b/npm/boilerplate/npm/test-newman.js @@ -4,10 +4,10 @@ // This script is intended to execute all unit tests. // --------------------------------------------------------------------------------------------------------------------- -require('shelljs/global'); +var shell = require('shelljs'), -// set directories and files for test and coverage report -var path = require('path'), + // set directories and files for test and coverage report + path = require('path'), NYC = require('nyc'), chalk = require('chalk'), @@ -20,8 +20,8 @@ module.exports = function (exit) { // banner line console.info(chalk.yellow.bold('Running newman tests using mocha on node...')); - test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH); - mkdir('-p', COV_REPORT_PATH); + shell.test('-d', COV_REPORT_PATH) && shell.rm('-rf', COV_REPORT_PATH); + shell.mkdir('-p', COV_REPORT_PATH); var Mocha = require('mocha'), nyc = new NYC({ @@ -56,4 +56,4 @@ module.exports = function (exit) { }; // ensure we run this script exports if this is a direct stdin.tty run -!module.parent && module.exports(exit); +!module.parent && module.exports(shell.exit); diff --git a/npm/ci-requirements.sh b/npm/ci-requirements.sh index 62a914cb2..c62e395b0 100755 --- a/npm/ci-requirements.sh +++ b/npm/ci-requirements.sh @@ -1,12 +1,5 @@ #!/bin/bash set -ev; # stop on error -echo "Creating test files and adding paths to collection for testing form data file uploads" -pushd /home/travis/build/postmanlabs/postman-code-generators/ &>/dev/null; - echo "Sample file 1" >> test1.txt; - echo "Sample file 2" >> test2.txt; - echo "Sample file 3" >> test3.txt; - node ./npm/addPathToFormdataFile.js -popd &>/dev/null; echo "Installing dependencies required for tests in codegens/java-okhttp" pushd ./codegens/java-okhttp &>/dev/null; @@ -14,21 +7,12 @@ pushd ./codegens/java-okhttp &>/dev/null; sudo rm -rf /var/lib/apt/lists/* sudo apt-get update sudo apt-get install -y openjdk-8-jdk - sudo wget http://central.maven.org/maven2/com/squareup/okhttp3/okhttp/3.9.1/okhttp-3.9.1.jar - sudo wget http://central.maven.org/maven2/com/squareup/okio/okio/1.14.0/okio-1.14.0.jar + unzip test/unit/fixtures/dependencies.zip popd &>/dev/null; echo "Installing dependencies required for tests in codegens/java-unirest" pushd ./codegens/java-unirest &>/dev/null; - sudo wget http://central.maven.org/maven2/com/mashape/unirest/unirest-java/1.4.9/unirest-java-1.4.9.jar - sudo wget http://central.maven.org/maven2/org/apache/httpcomponents/httpclient/4.5.2/httpclient-4.5.2.jar - sudo wget http://central.maven.org/maven2/commons-codec/commons-codec/1.9/commons-codec-1.9.jar - sudo wget http://central.maven.org/maven2/commons-logging/commons-logging/1.2/commons-logging-1.2.jar - sudo wget http://central.maven.org/maven2/org/apache/httpcomponents/httpcore/4.4.4/httpcore-4.4.4.jar - sudo wget http://central.maven.org/maven2/org/apache/httpcomponents/httpasyncclient/4.1.1/httpasyncclient-4.1.1.jar - sudo wget http://central.maven.org/maven2/org/apache/httpcomponents/httpcore-nio/4.4.4/httpcore-nio-4.4.4.jar - sudo wget http://central.maven.org/maven2/org/json/json/20160212/json-20160212.jar - sudo wget http://central.maven.org/maven2/org/apache/httpcomponents/httpmime/4.3.6/httpmime-4.3.6.jar + unzip test/unit/fixtures/dependencies.zip popd &>/dev/null; echo "Installing dependencies required for tests in codegens/csharp-restsharp" diff --git a/npm/package.js b/npm/package.js new file mode 100644 index 000000000..445e33196 --- /dev/null +++ b/npm/package.js @@ -0,0 +1,81 @@ +var shell = require('shelljs'), + path = require('path'), + async = require('async'), + fs = require('fs'), + exists, + codegen, + codegens, + codegen_path, + getSubfolders, + individual_test, + commandOut; + +const args = process.argv[2], + PATH_TO_CODEGENS_FOLDER = path.resolve(__dirname, '../codegens'); + +// throw JS error when any shell.js command encounters an error +shell.config.fatal = true; + +// ensure that the working tree is clean before packaging +commandOut = shell.exec('source ./npm/package/require_clean_work_tree.sh'); +if (commandOut.code !== 0) { + shell.exit(1); +} + +getSubfolders = (folder) => { + return fs.readdirSync(folder) + .map((subfolder) => { return { path: path.join(folder, subfolder), name: subfolder}; }) + .filter((obj) => { return fs.statSync(obj.path).isDirectory(); }); +}; + +individual_test = (codegen) => { + + console.log(`Creating package for ${codegen}`); + async.series([ + function (next) { + console.log(`Running codegen test for codegen ${codegen}`); + commandOut = shell.exec(`npm run test ${codegen} --color always`); + if (commandOut.code !== 0) { + console.error(`Failed to run codegen test on codegen ${codegen}, here's the error:`); + return next(commandOut.stderr); + } + console.log(commandOut.stdout); + return next(); + }, + function (next) { + console.log(`Generating zip for codegen ${codegen}`); + commandOut = shell.exec(`npm run zip ${codegen} --color always`); + if (commandOut.code !== 0) { + console.error(`Failed to zip codegen ${codegen}, here's the error:`); + return next(commandOut.stderr); + } + console.log(commandOut.stdout); + } + ], (err) => { + console.error(err); + shell.exit(1); + }); +}; + +if (args) { + codegen = args; + codegen_path = path.join(PATH_TO_CODEGENS_FOLDER, codegen); + try { + exists = fs.statSync(codegen_path).isDirectory(); + } + catch (err) { + console.log(`Codegen ${codegen} doesn't exist, please enter a valid name`); + console.log(err); + shell.exit(1); + } + if (exists) { + individual_test(codegen); + } +} +else { + console.log('Packaging all the codegens'); + codegens = getSubfolders(PATH_TO_CODEGENS_FOLDER); + codegens.forEach((codegen) => { + individual_test(codegen.name); + }); +} diff --git a/npm/package.sh b/npm/package.sh deleted file mode 100755 index 47930450c..000000000 --- a/npm/package.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -set -e; # stop on error - -# ensure that the working tree is clean before packaging -source ./npm/package/require_clean_work_tree.sh; -require_clean_work_tree "create package"; - -if [ -n "$1" ]; -then - CODEGEN=$1 # Code gen where npm install is desired to run , first input argument - if [ ! -d "./codegens/$CODEGEN" ]; - then - echo "Codegen $CODEGEN doesn't exist, please enter valid name"; - exit 1; - fi - echo "Creating package for $1"; - npm run deepinstall $1; - npm run test $1; - npm run zip $1; - exit 0; -else - echo "Packaging all the codegens" - for directory in codegens/*; do - if [ -d ${directory} ]; - then - codegen_name=${directory:9} # directory contains codegens/js-jquery, we need to pass js-jquery - echo "Creating package for $codegen_name"; - npm run deepinstall $codegen_name; - npm run test $codegen_name; - npm run zip $codegen_name; - else - echo "No Code gen folders present"; - exit 0; - fi - done -fi diff --git a/npm/test-lint.js b/npm/test-lint.js new file mode 100644 index 000000000..91bdef168 --- /dev/null +++ b/npm/test-lint.js @@ -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); diff --git a/npm/test.sh b/npm/test.sh index 4848f131d..43b9bff13 100755 --- a/npm/test.sh +++ b/npm/test.sh @@ -12,6 +12,22 @@ else exit 1; fi popd &>/dev/null + +echo "Creating test files and adding paths to collection for testing form data file uploads" +if [ ! -e dummyFile1.txt ]; +then + echo "Sample file 1" >> dummyFile1.txt; +fi +if [ ! -e dummyFile2.txt ]; +then + echo "Sample file 2" >> dummyFile2.txt; +fi +if [ ! -e dummyFile3.txt ]; +then + echo "Sample file 3" >> dummyFile3.txt; +fi +node ./npm/addPathToFormdataFile.js + echo "Running newman for common collection and storing results in newmanResponses.json" node ./test/codegen/newman/runNewman.js @@ -83,3 +99,7 @@ else done fi + +echo "Deleting test files used for testing form data file uploads" +# Also handles the case when files does not exist +rm -f -- dummyFile1.txt dummyFile2.txt dummyFile3.txt; \ No newline at end of file diff --git a/npm/zip.js b/npm/zip.js new file mode 100644 index 000000000..b33ff6115 --- /dev/null +++ b/npm/zip.js @@ -0,0 +1,33 @@ +var shell = require('shelljs'), + path = require('path'), + fs = require('fs'), + codegen_path, + commandOut, + exists; + +const codegen = process.argv[2], + PATH_TO_CODEGENS_FOLDER = path.resolve(__dirname, '../codegens'); + +// throw JS error when any shell.js command encounters an error +shell.config.fatal = true; + +codegen_path = path.join(PATH_TO_CODEGENS_FOLDER, codegen); + +try { + exists = fs.statSync(codegen_path).isDirectory(); +} +catch (err) { + console.log(`Codegen ${codegen} doesn't exist, please enter a valid name`); + shell.exit(1); +} +if (exists) { + console.log(`${codegen} : zip`); + shell.pushd(codegen_path, 'q'); + commandOut = shell.exec('npm pack --color always'); + if (commandOut.code !== 0) { + console.error(`Failed to run pre-package.js for codegen ${codegen}, here's the error:`); + console.log(commandOut.stderr); + shell.exit(1); + } + shell.popd(null, 'q'); +} diff --git a/npm/zip.sh b/npm/zip.sh deleted file mode 100755 index fc3999031..000000000 --- a/npm/zip.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -set -e; -CODEGEN=$1; -if [ ! -d "./codegens/$CODEGEN" ]; -then - echo "Codegen $CODEGEN doesn't exist, please enter valid name"; - exit 1; -fi -echo "$1 : zip"; -pushd ./codegens/$CODEGEN &>/dev/null; -npm pack; -popd &>/dev/null; diff --git a/package-lock.json b/package-lock.json index 27f3094b3..1b3889196 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "postman-code-generators", - "version": "0.2.4", + "version": "1.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { @@ -2303,7 +2303,8 @@ "ansi-regex": { "version": "2.1.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -2324,12 +2325,14 @@ "balanced-match": { "version": "1.0.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, "dev": true, + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -2344,17 +2347,20 @@ "code-point-at": { "version": "1.1.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "concat-map": { "version": "0.0.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "console-control-strings": { "version": "1.1.0", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -2471,7 +2477,8 @@ "inherits": { "version": "2.0.3", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "ini": { "version": "1.3.5", @@ -2483,6 +2490,7 @@ "version": "1.0.0", "bundled": true, "dev": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -2497,6 +2505,7 @@ "version": "3.0.4", "bundled": true, "dev": true, + "optional": true, "requires": { "brace-expansion": "^1.1.7" } @@ -2504,12 +2513,14 @@ "minimist": { "version": "0.0.8", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "minipass": { "version": "2.3.5", "bundled": true, "dev": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -2528,6 +2539,7 @@ "version": "0.5.1", "bundled": true, "dev": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -2608,7 +2620,8 @@ "number-is-nan": { "version": "1.0.1", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "object-assign": { "version": "4.1.1", @@ -2620,6 +2633,7 @@ "version": "1.4.0", "bundled": true, "dev": true, + "optional": true, "requires": { "wrappy": "1" } @@ -2705,7 +2719,8 @@ "safe-buffer": { "version": "5.1.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -2741,6 +2756,7 @@ "version": "1.0.2", "bundled": true, "dev": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -2760,6 +2776,7 @@ "version": "3.0.1", "bundled": true, "dev": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -2803,12 +2820,14 @@ "wrappy": { "version": "1.0.2", "bundled": true, - "dev": true + "dev": true, + "optional": true }, "yallist": { "version": "3.0.3", "bundled": true, - "dev": true + "dev": true, + "optional": true } } }, diff --git a/package.json b/package.json index edd4c2ce0..358011ec3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "postman-code-generators", - "version": "0.2.4", + "version": "1.0.0", "description": "Generates code snippets for a postman collection", "main": "index.js", "directories": { @@ -8,13 +8,14 @@ }, "scripts": { "test": "npm/test.sh", - "package": "npm/package.sh", - "zip": "npm/zip.sh", + "package": "node npm/package.js", + "zip": "node npm/zip.js", "prepack": "node npm/pre-package.js", "postinstall": "node npm/deepinstall.js", "deepinstall": "node npm/deepinstall.js", "boilerplate": "node npm/boilerplate.js", - "cirequirements": "npm/ci-requirements.sh" + "cirequirements": "npm/ci-requirements.sh", + "test-lint": "node npm/test-lint.js" }, "repository": { "type": "git", @@ -48,7 +49,6 @@ "newman": "4.5.7", "nyc": "14.1.1", "parse-gitignore": "1.0.1", - "postman-collection": "3.5.1", "pretty-ms": "3.0.1", "recursive-readdir": "2.1.0", "watchify": "3.11.1" diff --git a/test/codegen/newman/fixtures/basicCollection.json b/test/codegen/newman/fixtures/basicCollection.json index 4c66de56c..eaf29c7e1 100644 --- a/test/codegen/newman/fixtures/basicCollection.json +++ b/test/codegen/newman/fixtures/basicCollection.json @@ -293,8 +293,8 @@ } }, "url": { - "raw": "http://postman-echo.com/post", - "protocol": "http", + "raw": "https://postman-echo.com/post", + "protocol": "https", "host": [ "postman-echo", "com" @@ -643,14 +643,14 @@ ], "body": {}, "url": { - "raw": "https://postman-echo.com/delete", + "raw": "https://mockbin.org/request", "protocol": "https", "host": [ - "postman-echo", - "com" + "mockbin", + "org" ], "path": [ - "delete" + "request" ] }, "description": "The HTTP `DELETE` method is used to delete resources on a server. The exact\nuse of `DELETE` requests depends on the server implementation. In general, \n`DELETE` requests support both, Query String parameters as well as a Request \nBody.\n\nThis endpoint accepts an HTTP `DELETE` request and provides debug information\nsuch as the HTTP headers, Query String arguments, and the Request Body." diff --git a/test/codegen/newman/fixtures/redirectCollection.json b/test/codegen/newman/fixtures/redirectCollection.json index 50ab950f2..5fb851c47 100644 --- a/test/codegen/newman/fixtures/redirectCollection.json +++ b/test/codegen/newman/fixtures/redirectCollection.json @@ -1,6 +1,6 @@ { "info": { - "_postman_id": "d5d65b0c-0f10-4455-8ba2-d887c4180a08", + "_postman_id": "3ef1c00f-c58f-4604-8419-7a4931958235", "name": "Redirect test", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, @@ -11,18 +11,21 @@ "method": "GET", "header": [], "url": { - "raw": "https://httpbin.org/redirect-to?url=https://postman-echo.com/get", + "raw": "https://mockbin.org/redirect/302/1/?to=https://postman-echo.com/get", "protocol": "https", "host": [ - "httpbin", + "mockbin", "org" ], "path": [ - "redirect-to" + "redirect", + "302", + "1", + "" ], "query": [ { - "key": "url", + "key": "to", "value": "https://postman-echo.com/get" } ] diff --git a/test/codegen/newman/newmanTestUtil.js b/test/codegen/newman/newmanTestUtil.js index 4cea0a588..a51102647 100644 --- a/test/codegen/newman/newmanTestUtil.js +++ b/test/codegen/newman/newmanTestUtil.js @@ -124,7 +124,9 @@ function runSnippet (testConfig, snippets, collectionName) { 'accept-language', 'x-forwarded-port', 'if-none-match', - 'referer' + 'referer', + 'x-amzn-trace-id', + 'transfer-encoding' ]; if (result[0]) { propertiesTodelete.forEach(function (property) { diff --git a/test/codegen/structure.test.js b/test/codegen/structure.test.js index 91bd1ae38..aaaa3e1ae 100644 --- a/test/codegen/structure.test.js +++ b/test/codegen/structure.test.js @@ -41,7 +41,8 @@ const expectedOptions = { name: 'Set request timeout', type: 'positiveInteger', default: 0, - description: 'Set number of milliseconds the request should wait for a response before timing out (use 0 for infinity)' + description: 'Set number of milliseconds the request should wait' + + ' for a response before timing out (use 0 for infinity)' }, followRedirect: { name: 'Follow redirects', @@ -60,6 +61,12 @@ const expectedOptions = { type: 'boolean', default: false, description: 'Display the requested data without showing the cURL progress meter or error messages' + }, + ES6_enabled: { + name: 'Enable ES6 features', + type: 'boolean', + default: false, + description: 'Modifies code snippet to incorporate ES6 (EcmaScript) features' } }, // Standard array of ids that should be used for options ids. Any new option should be updated here. @@ -75,7 +82,8 @@ const expectedOptions = { 'followRedirect', 'lineContinuationCharacter', 'protocol', - 'useMimeType' + 'useMimeType', + 'ES6_enabled' ], CODEGEN_ABS_PATH = `./codegens/${codegen}`; describe('Code-gen repository ' + codegen, function () { diff --git a/test/system/repository.test.js b/test/system/repository.test.js index 33e3d9c16..c243a570e 100644 --- a/test/system/repository.test.js +++ b/test/system/repository.test.js @@ -3,138 +3,138 @@ * content of the file as well. Any change to package.json must be accompanied by valid test case in this spec-sheet. */ var _ = require('lodash'), - expect = require('chai').expect, - parseIgnore = require('parse-gitignore'); + expect = require('chai').expect, + parseIgnore = require('parse-gitignore'); /* global describe, it */ describe('project repository', function () { - var fs = require('fs'); - - describe('package.json', function () { - var content, - json; - - try { - content = fs.readFileSync('./package.json').toString(); - json = JSON.parse(content); - } - catch (e) { - console.error(e); - content = ''; - json = {}; - } - - it('must have readable JSON content', function () { - expect(content).to.be.ok; - expect(json).to.not.eql({}); - }); + var fs = require('fs'); + + describe('package.json', function () { + var content, + json; + + try { + content = fs.readFileSync('./package.json').toString(); + json = JSON.parse(content); + } + catch (e) { + console.error(e); + content = ''; + json = {}; + } + + it('must have readable JSON content', function () { + expect(content).to.be.ok; + expect(json).to.not.eql({}); + }); - describe('package.json JSON data', function () { - it('must have valid name, description and author', function () { - expect(json).to.have.property('name', 'postman-code-generators'); - expect(json).to.have.property('author', 'Postman Labs '); - expect(json).to.have.property('license', 'Apache-2.0'); + describe('package.json JSON data', function () { + it('must have valid name, description and author', function () { + expect(json).to.have.property('name', 'postman-code-generators'); + expect(json).to.have.property('author', 'Postman Labs '); + expect(json).to.have.property('license', 'Apache-2.0'); - expect(json).to.have.property('repository'); + expect(json).to.have.property('repository'); - expect(json).to.have.property('engines'); - expect(json.engines).to.eql({ node: '>=6' }); - }); + expect(json).to.have.property('engines'); + expect(json.engines).to.eql({ node: '>=6' }); + }); - it('must have a valid version string in form of ..', function () { - // eslint-disable-next-line max-len - expect(json.version).to.match(/^((\d+)\.(\d+)\.(\d+))(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/); - }); - }); + it('must have a valid version string in form of ..', function () { + // eslint-disable-next-line max-len + expect(json.version).to.match(/^((\d+)\.(\d+)\.(\d+))(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/); + }); + }); - describe.skip('dependencies', function () { - it('must exist', function () { - expect(json.dependencies).to.be.a('object'); - }); + describe('dependencies', function () { + it('must exist', function () { + expect(json.dependencies).to.be.a('object'); + }); - it('must point to a valid and precise (no * or ^) semver', function () { - json.dependencies && Object.keys(json.dependencies).forEach(function (item) { - expect(json.dependencies[item]).to.match(new RegExp('^((\\d+)\\.(\\d+)\\.(\\d+))(?:-' + + it('must point to a valid and precise (no * or ^) semver', function () { + json.dependencies && Object.keys(json.dependencies).forEach(function (item) { + expect(json.dependencies[item]).to.match(new RegExp('^((\\d+)\\.(\\d+)\\.(\\d+))(?:-' + '([\\dA-Za-z\\-]+(?:\\.[\\dA-Za-z\\-]+)*))?(?:\\+([\\dA-Za-z\\-]+(?:\\.[\\dA-Za-z\\-]+)*))?$')); - }); - }); }); + }); + }); - describe('devDependencies', function () { - it('must exist', function () { - expect(json.devDependencies).to.be.a('object'); - }); + describe('devDependencies', function () { + it('must exist', function () { + expect(json.devDependencies).to.be.a('object'); + }); - it('must point to a valid and precise (no * or ^) semver', function () { - json.devDependencies && Object.keys(json.devDependencies).forEach(function (item) { - expect(json.devDependencies[item]).to.match(new RegExp('^((\\d+)\\.(\\d+)\\.(\\d+))(?:-' + + it('must point to a valid and precise (no * or ^) semver', function () { + json.devDependencies && Object.keys(json.devDependencies).forEach(function (item) { + expect(json.devDependencies[item]).to.match(new RegExp('^((\\d+)\\.(\\d+)\\.(\\d+))(?:-' + '([\\dA-Za-z\\-]+(?:\\.[\\dA-Za-z\\-]+)*))?(?:\\+([\\dA-Za-z\\-]+(?:\\.[\\dA-Za-z\\-]+)*))?$')); - }); - }); - - it.skip('should not overlap dependencies', function () { - var clean = []; + }); + }); - json.devDependencies && Object.keys(json.devDependencies).forEach(function (item) { - !json.dependencies[item] && clean.push(item); - }); + it('should not overlap dependencies', function () { + var clean = []; - expect(Object.keys(json.devDependencies)).to.eql(clean); - }); + json.devDependencies && Object.keys(json.devDependencies).forEach(function (item) { + !json.dependencies[item] && clean.push(item); }); - describe('main entry script', function () { - it('must point to a valid file', function (done) { - expect(json.main).to.equal('index.js'); - fs.stat(json.main, done); - }); - }); + expect(Object.keys(json.devDependencies)).to.eql(clean); + }); }); - describe('README.md', function () { - it('must exist', function (done) { - fs.stat('./README.md', done); - }); + describe('main entry script', function () { + it('must point to a valid file', function (done) { + expect(json.main).to.equal('index.js'); + fs.stat(json.main, done); + }); + }); + }); - it('must have readable content', function () { - expect(fs.readFileSync('./README.md').toString()).to.be.ok; - }); + describe('README.md', function () { + it('must exist', function (done) { + fs.stat('./README.md', done); }); - describe('LICENSE.md', function () { - it('must exist', function (done) { - fs.stat('./LICENSE.md', done); - }); + it('must have readable content', function () { + expect(fs.readFileSync('./README.md').toString()).to.be.ok; + }); + }); - it('must have readable content', function () { - expect(fs.readFileSync('./LICENSE.md').toString()).to.be.ok; - }); + describe('LICENSE.md', function () { + it('must exist', function (done) { + fs.stat('./LICENSE.md', done); }); - describe('.ignore files', function () { - var gitignorePath = '.gitignore', - gitignore = parseIgnore(gitignorePath); + it('must have readable content', function () { + expect(fs.readFileSync('./LICENSE.md').toString()).to.be.ok; + }); + }); - describe(gitignorePath, function () { - it('must exist', function (done) { - fs.stat(gitignorePath, done); - }); + describe('.ignore files', function () { + var gitignorePath = '.gitignore', + gitignore = parseIgnore(gitignorePath); - it('must have valid content', function () { - expect(_.isEmpty(gitignore)).to.not.be.ok; - }); - }); + describe(gitignorePath, function () { + it('must exist', function (done) { + fs.stat(gitignorePath, done); + }); + it('must have valid content', function () { + expect(_.isEmpty(gitignore)).to.not.be.ok; + }); }); - describe('.eslintrc', function () { - it('must exist', function (done) { - fs.stat('./.eslintrc', done); - }); + }); - it('must have readable content', function () { - expect(fs.readFileSync('./.eslintrc').toString()).to.be.ok; - }); + describe('.eslintrc', function () { + it('must exist', function (done) { + fs.stat('./.eslintrc', done); + }); + + it('must have readable content', function () { + expect(fs.readFileSync('./.eslintrc').toString()).to.be.ok; }); + }); });