diff --git a/.gitignore b/.gitignore index fc176c6..a56a7ef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,2 @@ node_modules -package-lock.json -__test__/collection/output -__test__/collection/new_collection.json -__test__/*copy* -coverage -new_collection.json -*.tgz \ No newline at end of file + diff --git a/CHANGELOG.md b/CHANGELOG.md index 6dbed2d..282b829 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -134,3 +134,11 @@ Added main entry point to the package to allow to be used as a dependency Added error handling for invalid source collection ### Fixed + +## [3.0.0] - 2022-02-03 + +### Added + +Added ability to move multiple collection into single collection + +### Fixed diff --git a/README.md b/README.md index 9e7d60c..2a375a8 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,80 @@ - ![logo](https://github.com/praveendvd/postman_collection_url_updater/raw/master/logo/logo.png) Github page: https://praveendvd.github.io/postman_collection_url_updater/ -# postman-collection-url-updater +- [Introduction](#introduction) +- [Getting started](#getting-started) +- [Executing the utilities](#executing-the-utilities) + + [postman-collection-url-updater:](#postman-collection-url-updater-) + + [postman-collection-aggregator:](#postman-collection-aggregator-) +- [Utitlity Specific Documentation](#utitlity-specific-documentation) + * [postman-collection-url-updater](#postman-collection-url-updater) + + [in case of PATH and Query variables:](#in-case-of-path-and-query-variables-) + + [in case of REGEx match:](#in-case-of-regex-match-) + + [Interactive Option](#interactive-option) + + [CLI Options](#cli-options) + * [postman-collection-aggregator](#postman-collection-aggregator) + + [Interactive Option](#interactive-option-1) + + [CLI Options](#cli-options-1) + + +# Introduction + +Postman collection url updater is a command line utility project that can update urls across multiple postman requests in your postman collection and, move multiple collections into single collection. It allows to **update postman request urls in bulk inside the postman collection**, and also support **migrating multiple collection into single collection**",❤️ + +To use the project , just install the package and then run any of the below commandline utilities as per your need 🎉🎉 + +1. **postman-collection-url-updater :** A commandline utilty that allows to update urls in bulk inside your collection +2. **postman-collection-aggregator :** A commandline utilty that allows to move all collections into a single collection + +# Getting started + +First install the package locally or globally + +`npm i postman-collection-url-updater` + +or + +`npm i -g postman-collection-url-updater` + + +# Executing the utilities + +Now the utility can be executed as directly or using npx, depending whether the package was installed globally or +locally + +### postman-collection-url-updater: + +**if installed locally:** + +`npx postman-collection-url-updater -c collection.json -r www.test.com -w {{Baseurl}}` + +**if installed globally:** + +`postman-collection-url-updater -c collection.json -r www.test.com -w {{Baseurl}}` + +### postman-collection-aggregator: + +**if installed locally:** + +`npx postman-collection-aggregator -d collectiondirectory -n Aggregated_collection` -Postman collection url updater (postman-collection-url-updater) is a command line utility project that can update urls across multiple postman requests in your postman collection. It allows to update postman request urls in bulk inside the postman collection +**if installed globally:** + +`postman-collection-aggregator -d collectiondirectory -n Aggregated_collection` + +# Utitlity Specific Documentation + +## postman-collection-url-updater + +postman-collection-url-updater is a command line utility project that can update urls across multiple postman requests in your postman collection. It allows to update postman request urls in bulk inside the postman collection for instance, let say your Postman request URLs where in the form https://localhost:23456/api/v1/{{path}} and you wanted modify all the requests inside your postman collection as {{baseURL}}/{{path}} you can do it as: npx postman-collection-url-updater -c "collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "new_collection.json" -## in case of PATH and Query variables: +### in case of PATH and Query variables: npx postman-collection-url-updater -c "collection.json" -r "https://{{test}}/:test/test" -w "https://localhost/newpath/:test/:test2"" @@ -28,7 +90,7 @@ makes the changes and removes :test if it doesn't exists in remaining part and r eg , output would be https://localhost/newpath/:test/new , if path variable exists else https://localhost/newpath/new -## in case of REGEx match: +### in case of REGEx match: Pass the regex as -r parameter and replace it with -w parameter. -w parameter will have the capture group available: @@ -45,14 +107,15 @@ This will replace all urls having query parameter to the form \?newquery If you want to add query parameter to all URLs irrespective of whether the query parameter exists or not, then use : npx postman-collection-url-updater -c "collection.json" -r "^(.*?)(?:\?(.*))?$" -w "$1?newquery=newvalue&$2" -p true -## Interactive Option + +### Interactive Option You can also pass arguments interactively by passing i flag `npx postman-collection-url-updater -i` -## CLI Options +### CLI Options | options | alias | description | Example | @@ -64,3 +127,39 @@ You can also pass arguments interactively by passing i flag | --with_url_part| -w| The value to replace the matching URL part with| v2 or {{baseURL}}/{{path}} or localhost:8888/| | | --save_as| -s | (Optional) Path to output collection file, DEFAULT: new_collection.json. If no value provided then the file will be saved by prefixing new to current collection name | modifiedCollection.json or project/modifiedCollection.json| +## postman-collection-aggregator + +postman-collection-aggregator is a command line utility project that can move multiple collections into a new single collection. For instance , lets say you have two collections A and B , **then a new collection C will be created with A and B as folders in C**. As folders doesn't support variables , **collection variable will be added to the parent collections variables section and duplicate variables might be merged** all other properties remains intact + +You can either pass in the directory containing all the collection.json files that you want to aggregate using -d argument or pass path to each individual target collections using -l argument + +`postman-collection-aggregator -d ./collectionFolder` or + + postman-collection-aggregator -l "./collectionFolder/collection1.json" "./collectionFolder/collection2.json" + +you can pass name of your new collection using -n + +`postman-collection-aggregator -d ./collectionFolder -n "new_collection"` + +**see more arguments in the below sections** + +### Interactive Option + +You can also pass arguments interactively by passing i flag + +`postman-collection-aggregator -i` + + +### CLI Options + + +| options | alias | description | Example | +|--|--|-- |--| +| --interactive| -i | (Optional) Allows to pass arguments interactively, DEFAULT: false.| `npx postman-collection-aggregator -i` | +| --new_collection_name| -n | (Optional) Pass name for your new collection, DEFAULT: Aggregated_collection| +| --collection_list | -l | Path to the each individual target Collection.json file separated by space|`npx postman-collection-aggregator -l "./collection1.json" "./collection2.json" -n "new_collection"` +| --collection_directory| -d | Path to the directory containing all the collection.json files. [**NOTE**: only direct childs will be considered , subdirectories are ignored]|`npx postman-collection-aggregator -d "./collectionDirectory" -n "new_collection"` +| --save_as| -s | (Optional) Path to output collection file, DEFAULT: .collection.json.|`npx postman-collection-aggregator -d "./collectionDirectory" -n "new_collection" -s "output/new.json"` + +**Note:** Either -d or -l is required . If both are given only -d will be considered + diff --git a/__test__/__snapshots__/test-cli-unit.test.js.snap b/__test__/__snapshots__/test-cli-unit.test.js.snap deleted file mode 100644 index b07aeab..0000000 --- a/__test__/__snapshots__/test-cli-unit.test.js.snap +++ /dev/null @@ -1,365 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 4`] = `"exit"`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 5`] = ` -[MockFunction] { - "calls": Array [ - Array [], - ], - "results": Array [ - Object { - "type": "throw", - "value": [Error: exit], - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 6`] = ` -[MockFunction] { - "calls": Array [ - Array [ - "ENOENT: no such file or directory, open 'test/collection/collection.json'", - ], - ], - "results": Array [ - Object { - "type": "return", - "value": undefined, - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 7`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 4`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 5`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 4`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 5`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 4`] = `"exit"`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 5`] = ` -[MockFunction] { - "calls": Array [ - Array [ - 1, - ], - ], - "results": Array [ - Object { - "type": "throw", - "value": [Error: exit], - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 6`] = ` -[MockFunction] { - "calls": Array [ - Array [ - " -Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w -\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" - -or - -Usage: -i - -Options: - --help Show help [boolean] - --version Show version number [boolean] - -i, --interactive Pass -i to enter Interactive mode - [boolean] [default: false] - -c, --collection_path Path to Collection file [string] [required] - -r, --replace_url_part Replaces only the matching part of the URL - [string] [required] - -w, --with_url_part Replaces the matching part of the URL with provided - value [string] [required] - -s, --save_as path to save new collection - [string] [default: \\"/new_.json\\"] - -p, --use_regex_pattern Flag to enable matching url using regex - [boolean] [default: false]", - ], - Array [], - Array [ - "Missing required argument: c", - ], - ], - "results": Array [ - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 7`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 4`] = `"exit"`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 5`] = ` -[MockFunction] { - "calls": Array [ - Array [ - 1, - ], - ], - "results": Array [ - Object { - "type": "throw", - "value": [Error: exit], - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 6`] = ` -[MockFunction] { - "calls": Array [ - Array [ - " -Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w -\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" - -or - -Usage: -i - -Options: - --help Show help [boolean] - --version Show version number [boolean] - -i, --interactive Pass -i to enter Interactive mode - [boolean] [default: false] - -c, --collection_path Path to Collection file [string] [required] - -r, --replace_url_part Replaces only the matching part of the URL - [string] [required] - -w, --with_url_part Replaces the matching part of the URL with provided - value [string] [required] - -s, --save_as path to save new collection - [string] [default: \\"/new_.json\\"] - -p, --use_regex_pattern Flag to enable matching url using regex - [boolean] [default: false]", - ], - Array [], - Array [ - "Missing required argument: r", - ], - ], - "results": Array [ - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 7`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 4`] = `"exit"`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 5`] = ` -[MockFunction] { - "calls": Array [ - Array [ - 1, - ], - ], - "results": Array [ - Object { - "type": "throw", - "value": [Error: exit], - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 6`] = ` -[MockFunction] { - "calls": Array [ - Array [ - " -Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w -\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" - -or - -Usage: -i - -Options: - --help Show help [boolean] - --version Show version number [boolean] - -i, --interactive Pass -i to enter Interactive mode - [boolean] [default: false] - -c, --collection_path Path to Collection file [string] [required] - -r, --replace_url_part Replaces only the matching part of the URL - [string] [required] - -w, --with_url_part Replaces the matching part of the URL with provided - value [string] [required] - -s, --save_as path to save new collection - [string] [default: \\"/new_.json\\"] - -p, --use_regex_pattern Flag to enable matching url using regex - [boolean] [default: false]", - ], - Array [], - Array [ - "Missing required argument: w", - ], - ], - "results": Array [ - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 7`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 1`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 2`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 3`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 4`] = `"exit"`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 5`] = ` -[MockFunction] { - "calls": Array [ - Array [ - 1, - ], - ], - "results": Array [ - Object { - "type": "throw", - "value": [Error: exit], - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 6`] = ` -[MockFunction] { - "calls": Array [ - Array [ - " -Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w -\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" - -or - -Usage: -i - -Options: - --help Show help [boolean] - --version Show version number [boolean] - -i, --interactive Pass -i to enter Interactive mode - [boolean] [default: false] - -c, --collection_path Path to Collection file [string] [required] - -r, --replace_url_part Replaces only the matching part of the URL - [string] [required] - -w, --with_url_part Replaces the matching part of the URL with provided - value [string] [required] - -s, --save_as path to save new collection - [string] [default: \\"/new_.json\\"] - -p, --use_regex_pattern Flag to enable matching url using regex - [boolean] [default: false]", - ], - Array [], - Array [ - "Missing required arguments: c, r, w", - ], - ], - "results": Array [ - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - Object { - "type": "return", - "value": undefined, - }, - ], -} -`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 7`] = `[MockFunction]`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should throw error if exception thrown doesnt contain error code ENOENT 1`] = `"Error: Custom error"`; - -exports[`Validate index.js unit tests Validate cli output messages for non interactive Should throw invalid collection if a valid collection is not provided 1`] = `"exit"`; diff --git a/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap b/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap new file mode 100644 index 0000000..0663f7b --- /dev/null +++ b/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap @@ -0,0 +1,408 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -1 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -1 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -1 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -1 4`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -1 5`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -d 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -d 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -d 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -d 4`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path -d 5`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default name and path if n not provided 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default name and path if n not provided 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default name and path if n not provided 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default name and path if n not provided 4`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default name and path if n not provided 5`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 4`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 5`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 6`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 7`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 8`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 9`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -d 10`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -l 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -l 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -l 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -l 4`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path for -l 5`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 4`] = `"exit"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 5`] = ` +[MockFunction] { + "calls": Array [ + Array [], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + "ENOENT: no such file or directory, scandir '__test__/collection_aggregator_test/collections'", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection directory doesnt exists 7`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 4`] = `"exit"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -n \\"new_collection\\" -l \\"path/collection1.json\\" \\"path/collection1.json\\" +\\"path/collection1.json\\" + +or + +Usage: -i + +or + +Usage: -d \\"./collection_directory\\" -n \\"new_collection\\" + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -n, --new_collection_name Name of the new collection + [string] [default: \\"Aggregated_collection\\"] + -l, --collection_list Pass relative or absolute collection file paths + [array] + -d, --collection_directory Directory containing all collection files [string] + -s, --save_as path to save new collection + [string] [default: \\"currentDirectory/.collection.json\\"] + +Examples: + postman-collection-aggregator -n - Using collection list + \\"new_collection\\" -l + \\"path/collection1.json\\" + \\"path/collection1.json\\" + \\"path/collection1.json\\" + postman-collection-aggregator -d - Using collection directory + \\"./collection_directory\\"", + ], + Array [], + Array [ + "Please provide either collection_directory or collection_list +[Missing required property -l or -d]", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show file/folder not found error if collection list file doesnt exists 7`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 4`] = `"exit"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -n \\"new_collection\\" -l \\"path/collection1.json\\" \\"path/collection1.json\\" +\\"path/collection1.json\\" + +or + +Usage: -i + +or + +Usage: -d \\"./collection_directory\\" -n \\"new_collection\\" + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -n, --new_collection_name Name of the new collection + [string] [default: \\"Aggregated_collection\\"] + -l, --collection_list Pass relative or absolute collection file paths + [array] + -d, --collection_directory Directory containing all collection files [string] + -s, --save_as path to save new collection + [string] [default: \\"currentDirectory/.collection.json\\"] + +Examples: + postman-collection-aggregator -n - Using collection list + \\"new_collection\\" -l + \\"path/collection1.json\\" + \\"path/collection1.json\\" + \\"path/collection1.json\\" + postman-collection-aggregator -d - Using collection directory + \\"./collection_directory\\"", + ], + Array [], + Array [ + "Please provide either collection_directory or collection_list +[Missing required property -l or -d]", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -l and -d argument is missing 7`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 4`] = `"exit"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + "ENOENT: no such file or directory, scandir 'undefined'", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if -n argument is missing 7`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 1`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 2`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 3`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 4`] = `"exit"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -n \\"new_collection\\" -l \\"path/collection1.json\\" \\"path/collection1.json\\" +\\"path/collection1.json\\" + +or + +Usage: -i + +or + +Usage: -d \\"./collection_directory\\" -n \\"new_collection\\" + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -n, --new_collection_name Name of the new collection + [string] [default: \\"Aggregated_collection\\"] + -l, --collection_list Pass relative or absolute collection file paths + [array] + -d, --collection_directory Directory containing all collection files [string] + -s, --save_as path to save new collection + [string] [default: \\"currentDirectory/.collection.json\\"] + +Examples: + postman-collection-aggregator -n - Using collection list + \\"new_collection\\" -l + \\"path/collection1.json\\" + \\"path/collection1.json\\" + \\"path/collection1.json\\" + postman-collection-aggregator -d - Using collection directory + \\"./collection_directory\\"", + ], + Array [], + Array [ + "Please provide either collection_directory or collection_list +[Missing required property -l or -d]", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 7`] = `[MockFunction]`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should throw error if exception thrown doesnt contain error code ENOENT 1`] = `"Custom error"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should throw invalid collection if a valid collection directory is not provided 1`] = `"exit"`; + +exports[`Validate collection_aggregator index.js unit tests Validate cli output messages for non interactive Should throw invalid collection if a valid collection is not provided in -l 1`] = `"exit"`; diff --git a/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli.system.test.js.snap b/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli.system.test.js.snap new file mode 100644 index 0000000..ae6f741 --- /dev/null +++ b/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli.system.test.js.snap @@ -0,0 +1,71 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection file is non existing 1`] = ` +"ENOENT: no such file or directory, open '__test__/collection_aggregator_test/collection/collection5.json' +" +`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection file is non existing 2`] = `""`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection file is not valid 1`] = ` +"Invalid/corrupted collection provided. Please provide path to valid source collection +" +`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection file is not valid 2`] = `""`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection folder is not folder 1`] = ` +"ENOTDIR: not a directory, scandir '__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap' +" +`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection folder is not folder 2`] = `""`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection folder is not found 1`] = ` +"ENOENT: no such file or directory, scandir '__test__/collection_aggregator_test/nonexisting' +" +`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show error if collection folder is not found 2`] = `""`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show help if arguments are missing 1`] = ` +" +Usage: -n \\"new_collection\\" -l \\"path/collection1.json\\" \\"path/collection1.json\\" +\\"path/collection1.json\\" + +or + +Usage: -i + +or + +Usage: -d \\"./collection_directory\\" -n \\"new_collection\\" + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -n, --new_collection_name Name of the new collection + [string] [default: \\"Aggregated_collection\\"] + -l, --collection_list Pass relative or absolute collection file paths + [array] + -d, --collection_directory Directory containing all collection files [string] + -s, --save_as path to save new collection + [string] [default: \\"currentDirectory/.collection.json\\"] + +Examples: + postman-collection-aggregator -n - Using collection list + \\"new_collection\\" -l + \\"path/collection1.json\\" + \\"path/collection1.json\\" + \\"path/collection1.json\\" + postman-collection-aggregator -d - Using collection directory + \\"./collection_directory\\" + +Please provide either collection_directory or collection_list +[Missing required property -l or -d] +" +`; + +exports[`Validate collection_aggregator system test Validate cli output messages Should show help if arguments are missing 2`] = `""`; diff --git a/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli.test.js.snap b/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli.test.js.snap new file mode 100644 index 0000000..9fbb192 --- /dev/null +++ b/__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli.test.js.snap @@ -0,0 +1,71 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection file is non existing 1`] = ` +"ENOENT: no such file or directory, open '__test__/collection_aggregator_test/collection/collection5.json' +" +`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection file is non existing 2`] = `""`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection file is not valid 1`] = ` +"Invalid/corrupted collection provided. Please provide path to valid source collection +" +`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection file is not valid 2`] = `""`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection folder is not folder 1`] = ` +"ENOTDIR: not a directory, scandir '__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap' +" +`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection folder is not folder 2`] = `""`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection folder is not found 1`] = ` +"ENOENT: no such file or directory, scandir '__test__/collection_aggregator_test/nonexisting' +" +`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show error if collection folder is not found 2`] = `""`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show help if arguments are missing 1`] = ` +" +Usage: -n \\"new_collection\\" -l \\"path/collection1.json\\" \\"path/collection1.json\\" +\\"path/collection1.json\\" + +or + +Usage: -i + +or + +Usage: -d \\"./collection_directory\\" -n \\"new_collection\\" + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -n, --new_collection_name Name of the new collection + [string] [default: \\"Aggregated_collection\\"] + -l, --collection_list Pass relative or absolute collection file paths + [array] + -d, --collection_directory Directory containing all collection files [string] + -s, --save_as path to save new collection + [string] [default: \\"currentDirectory/.collection.json\\"] + +Examples: + postman-collection-aggregator -n - Using collection list + \\"new_collection\\" -l + \\"path/collection1.json\\" + \\"path/collection1.json\\" + \\"path/collection1.json\\" + postman-collection-aggregator -d - Using collection directory + \\"./collection_directory\\" + +Please provide either collection_directory or collection_list +[Missing required property -l or -d] +" +`; + +exports[`Validate collection_aggregator main.js test Validate cli output messages Should show help if arguments are missing 2`] = `""`; diff --git a/__test__/collection/collection.json b/__test__/collection_aggregator_test/collection/collection.json similarity index 96% rename from __test__/collection/collection.json rename to __test__/collection_aggregator_test/collection/collection.json index 51703d3..9f4bb1d 100644 --- a/__test__/collection/collection.json +++ b/__test__/collection_aggregator_test/collection/collection.json @@ -489,13 +489,28 @@ "response": [] } ], + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "collectionvalue", + "type": "string" + }, + { + "key": "key", + "value": "collectionkey", + "type": "string" + } + ] + }, "event": [ { "listen": "prerequest", "script": { "type": "text/javascript", "exec": [ - "" + "collection level pre-request - collection named \"collection\"" ] } }, @@ -504,7 +519,7 @@ "script": { "type": "text/javascript", "exec": [ - "" + "collection level test script - collection named \"collection\"" ] } } diff --git a/__test__/collection_aggregator_test/collection/collection_2.json b/__test__/collection_aggregator_test/collection/collection_2.json new file mode 100644 index 0000000..44baf1a --- /dev/null +++ b/__test__/collection_aggregator_test/collection/collection_2.json @@ -0,0 +1,136 @@ +{ + "info": { + "_postman_id": "a9d0be8e-da2a-41ba-83b5-5694fc207086", + "name": "zebra_collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "zebra_folder1", + "item": [ + { + "name": "zebra_request", + "event": [ + { + "listen": "test", + "script": { + "exec": [ + "pm.test('Some test name zebra', function () {", + "\tpm.response.to.have.status(200);", + "\tpm.expect(pm.response.responseTime).to.be.below(400);", + "})" + ], + "type": "text/javascript" + } + } + ], + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "zebra1", + "type": "string" + }, + { + "key": "key", + "value": "zebra", + "type": "string" + } + ] + }, + "method": "GET", + "header": [], + "url": { + "raw": "https://www.testdomainzebra.ie/testpath/:pathvariablezebra-1/path/requestzebra?queryzebra=queryvaluezebra", + "protocol": "https", + "host": [ + "www", + "testdomainzebra", + "ie" + ], + "path": [ + "testpath", + ":pathvariablezebra-1", + "path", + "requestzebra" + ], + "query": [ + { + "key": "queryzebra", + "value": "queryvaluezebra" + } + ], + "variable": [ + { + "key": "pathvariablezebra-1", + "value": "zebra", + "description": "zebra" + } + ] + } + }, + "response": [] + } + ] + } + ], + "auth": { + "type": "ntlm", + "ntlm": [ + { + "key": "workstation", + "value": "testworkstation", + "type": "string" + }, + { + "key": "domain", + "value": "testdomain", + "type": "string" + }, + { + "key": "password", + "value": "testpassword", + "type": "string" + }, + { + "key": "username", + "value": "testuser", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "pre-request script collection level" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "test script collection level" + ] + } + } + ], + "variable": [ + { + "key": "collectionvariable1", + "value": "1", + "type": "string" + }, + { + "key": "collectionvariable2", + "value": "2", + "type": "string" + } + ] +} \ No newline at end of file diff --git a/__test__/collection_aggregator_test/collection_aggregator_test-cli-unit.test.js b/__test__/collection_aggregator_test/collection_aggregator_test-cli-unit.test.js new file mode 100644 index 0000000..860e515 --- /dev/null +++ b/__test__/collection_aggregator_test/collection_aggregator_test-cli-unit.test.js @@ -0,0 +1,395 @@ +const path = require('path'), + sdk = require('postman-collection'), + fs = require('fs-extra'), + { resetAndReimportUrlUpdator, CustomError, removeID } = require('./utils/helperMethods.js'); + + +let postman_url_updater, mockProcessExit, mockConsoleLog, mockConsoleError; + +describe('Validate collection_aggregator index.js unit tests', () => { + describe('Validate cli output messages for non interactive', () => { + beforeAll(() => { + mockProcessExit = jest.spyOn(process, 'exit').mockImplementation((error) => { + console.info('process.exit called with error:', error); + throw new Error("exit"); + }), + mockConsoleLog = jest.spyOn(console, 'log').mockImplementation((log) => { console.info('console.log called with:', log); }), + mockConsoleError = jest.spyOn(console, 'error').mockImplementation((error) => { console.info('console.error called with:', error); }); + }) + afterEach(() => { + jest.clearAllMocks(); + }); + + afterAll(() => { + jest.restoreAllMocks(); + }) + + it('Should show help if arguments are missing', async () => { + resetAndReimportUrlUpdator({ n: undefined, l: undefined, d: undefined, s: undefined, i: undefined }); + + expect(() => { require('../../src/indexAggregator.js') }).not.toThrowError() + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + + await expect(async () => { await require('../../src/indexAggregator.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + expect(mockProcessExit).toBeCalled(); + expect(mockConsoleError).toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + }); + + it('Should show help if -n argument is missing', async () => { + resetAndReimportUrlUpdator({ n: undefined, l: "undefined", d: "undefined", s: undefined, i: undefined }); + + expect(() => { require('../../src/indexAggregator.js') }).not.toThrowError() + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + + await expect(async () => { await require('../../src/indexAggregator.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + + expect(mockProcessExit).toBeCalled(); + expect(mockConsoleError).toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + }); + + it('Should show help if -l and -d argument is missing', async () => { + resetAndReimportUrlUpdator({ n: "new", l: undefined, d: undefined, s: undefined, i: undefined }); + + expect(() => { require('../../src/indexAggregator.js') }).not.toThrowError() + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + + await expect(async () => { await require('../../src/indexAggregator.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + + expect(mockProcessExit).toBeCalled(); + expect(mockConsoleError).toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + }); + + it('Should show file/folder not found error if collection directory doesnt exists', async () => { + resetAndReimportUrlUpdator({ n: "new", l: undefined, d: '__test__/collection_aggregator_test/collections', s: undefined, i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot(); + expect(mockProcessExit).toBeCalled(); + expect(mockConsoleError).toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + }); + + it('Should show file/folder not found error if collection list file doesnt exists', async () => { + resetAndReimportUrlUpdator({ n: "new", l: '__test__/collection_aggregator_test/collection/collection.json __test__/collection_aggregator_test/collection/collections.json', d: undefined, s: undefined, i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot(); + expect(mockProcessExit).toBeCalled(); + expect(mockConsoleError).toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + }); + + it('Should show file saved message correctly with default path for -l', async () => { + resetAndReimportUrlUpdator({ n: "new", l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection.json"', d: undefined, s: undefined, i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await postman_url_updater.createNewCollection(); + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./new.collection.json')}`); + }); + + it('Should show file saved message correctly with default path for -d', async () => { + resetAndReimportUrlUpdator({ n: "new", l: undefined, d: "__test__/collection_aggregator_test/collection", s: undefined, i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await postman_url_updater.createNewCollection(); + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./new.collection.json')}`); + }); + + it('Should show file saved message correctly with default name and path if n not provided', async () => { + resetAndReimportUrlUpdator({ n: undefined, l: undefined, d: "__test__/collection_aggregator_test/collection", s: undefined, i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await postman_url_updater.createNewCollection(); + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./Aggregated_collection.collection.json')}`); + }); + + it('Should show file saved message correctly with default path for -d', async () => { + resetAndReimportUrlUpdator({ n: "new", l: undefined, d: "__test__/collection_aggregator_test/collection", s: undefined, i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await postman_url_updater.createNewCollection(); + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./new.collection.json')}`); + }); + + it('Should show file saved message correctly with custom path -1', async () => { + resetAndReimportUrlUpdator({ + n: "new", + l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection.json"', + d: undefined, + s: '__test__/collection_aggregator_test/collection/output/test_collection.json', + i: undefined + }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await postman_url_updater.createNewCollection() + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./__test__/collection_aggregator_test/collection/output/test_collection.json')}`); + }); + + it('Should show file saved message correctly with custom path -d', async () => { + resetAndReimportUrlUpdator({ + n: "new", + l: undefined, d: "__test__/collection_aggregator_test/collection", + s: "__test__/collection_aggregator_test/collection/output/new_collection.json", + i: undefined + }); + postman_url_updater = require('../../src/indexAggregator.js') + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).not.toBeCalled(); + expect(mockConsoleLog).toMatchSnapshot(); + jest.clearAllMocks() + await postman_url_updater.createNewCollection() + expect(mockProcessExit).not.toBeCalled(); + expect(mockConsoleError).not.toBeCalled(); + expect(mockProcessExit).toMatchSnapshot(); + expect(mockConsoleError).toMatchSnapshot(); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./__test__/collection_aggregator_test/collection/output/new_collection.json')}`); + }); + + it('Should throw error if exception thrown doesnt contain error code ENOENT', async () => { + resetAndReimportUrlUpdator({ + n: "new", + l: undefined, d: "__test__/collection_aggregator_test/collection", + s: "__test__/collection_aggregator_test/collection/output/new_collection.json", + i: undefined + }); + postman_url_updater = require('../../src/indexAggregator.js') + jest.clearAllMocks() + mockConsoleLog.mockImplementationOnce(() => { throw new CustomError(256) }); + await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot() + expect(process.exit).not.toBeCalled() + }); + + it('Should throw invalid collection if a valid collection is not provided in -l', async () => { + resetAndReimportUrlUpdator({ n: "new", l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap"', d: undefined, s: 'output/new_collection.json', i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + jest.clearAllMocks() + await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot() + expect(console.error).toBeCalledWith(`Invalid/corrupted collection provided. Please provide path to valid source collection`); + }); + + + it('Should throw invalid collection if a valid collection directory is not provided', async () => { + resetAndReimportUrlUpdator({ n: "new", l: undefined, d: "__test__/collection_aggregator_test/collection/collection.json", s: 'output/new_collection.json', i: undefined }); + postman_url_updater = require('../../src/indexAggregator.js') + jest.clearAllMocks() + await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot() + expect(console.error).toBeCalledWith(`ENOTDIR: not a directory, scandir '__test__/collection_aggregator_test/collection/collection.json'`); + }); + + it('Should show -d will be used if both -d and -l provided', async () => { + resetAndReimportUrlUpdator({ + n: "new", + l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection.json"', + d: "__test__/collection_aggregator_test/collection", + s: undefined, + i: undefined + }); + + let fsDirReaderMock = jest.mock('fs-extra', () => ({ + ...jest.requireActual('fs-extra'), + readdirSync: jest.fn(function () { return ['collection.json'] }) + })).requireMock('fs-extra').readdirSync; + + postman_url_updater = require('../../src/indexAggregator.js') + jest.clearAllMocks() + await postman_url_updater.createNewCollection() + //await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot() + expect(fsDirReaderMock).toBeCalledWith('__test__/collection_aggregator_test/collection'); + expect(mockConsoleLog).toHaveBeenNthCalledWith(1, `[Warning] Both -d and -l was provided. Will be using Using -d`); + expect(mockConsoleLog).toHaveBeenNthCalledWith(2, `File saved to: ${path.resolve('./new.collection.json')}`); + + fsDirReaderMock.mockRestore(); + }); + }) + + describe('Validate cli output messages for interactive', () => { + + afterEach(() => { + jest.clearAllMocks(); + }); + + afterAll(() => { + jest.restoreAllMocks(); + }) + + it('Should call inquirer if i provided', async () => { + let inquirerSpy = resetAndReimportUrlUpdator({ n: "new", l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection.json', d: undefined, s: 'output/new_collection.json', i: true }); + await require('../../src/indexAggregator.js').createNewCollection(); + expect(inquirerSpy).toHaveBeenCalled() + }); + + it('Should not call inquirer if i not provided', async () => { + let inquirerSpy = resetAndReimportUrlUpdator({ n: "new", l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection.json"', d: undefined, s: 'output/new_collection.json', i: undefined }); + await require('../../src/indexAggregator.js').createNewCollection(); + expect(inquirerSpy).not.toHaveBeenCalled() + }); + + it('Should not show -d will be used message if -i is used with -d and -l', async () => { + resetAndReimportUrlUpdator({ + n: "new", + l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection.json"', + d: "__test__/collection_aggregator_test/collection", + s: 'output/new_collection.json', + i: true + }); + + let fsDirReaderMock = jest.mock('fs-extra', () => ({ + ...jest.requireActual('fs-extra'), + readdirSync: jest.fn(function () { return ['collection.json'] }) + })).requireMock('fs-extra').readdirSync; + + mockConsoleLog = jest.spyOn(console, 'log').mockImplementationOnce((log) => { console.info('console.log called with:', log); }), + + postman_url_updater = require('../../src/indexAggregator.js') + + jest.clearAllMocks() + await postman_url_updater.createNewCollection() + + expect(fsDirReaderMock).toBeCalledWith('__test__/collection_aggregator_test/collection'); + expect(mockConsoleLog).toHaveBeenCalledTimes(1) + expect(mockConsoleLog).toHaveBeenNthCalledWith(1, `File saved to: ${path.resolve('output/new_collection.json')}`); + + fsDirReaderMock.mockRestore(); + }); + }) + + describe('Validate collection creation', () => { + + it('validate collection aggregated without modifiying source content ', async () => { + + let inquirerSpy = resetAndReimportUrlUpdator({ + n: "new", + l: '"__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json"', + d: undefined, + s: 'output/new_collection.json', + i: undefined + }); + + await require('../../src/indexAggregator.js').createNewCollection(); + + const aggregatedCollection = new sdk.Collection(JSON.parse(fs.readFileSync('output/new_collection.json').toString())).toJSON(); + const sourceCollection1 = new sdk.Collection(JSON.parse(fs.readFileSync('__test__/collection_aggregator_test/collection/collection.json').toString())).toJSON(); + const sourceCollection2 = new sdk.Collection(JSON.parse(fs.readFileSync('__test__/collection_aggregator_test/collection/collection_2.json').toString())).toJSON(); + + removeID(sourceCollection1); + removeID(sourceCollection2); + removeID(aggregatedCollection); + + //expect source and output have same collection level settings + expect(aggregatedCollection.item[0].item).toStrictEqual(sourceCollection1.item); + expect(aggregatedCollection.item[1].item).toStrictEqual(sourceCollection2.item); + expect(aggregatedCollection.item[0].event).toStrictEqual(sourceCollection1.event); + expect(aggregatedCollection.item[1].event).toStrictEqual(sourceCollection2.event); + expect(aggregatedCollection.item[0].name).toStrictEqual(sourceCollection1.info.name); + expect(aggregatedCollection.item[1].name).toStrictEqual(sourceCollection2.info.name); + expect(aggregatedCollection.item[0].auth).toStrictEqual(sourceCollection1.auth); + expect(aggregatedCollection.item[1].auth).toStrictEqual(sourceCollection2.auth); + expect(aggregatedCollection.item[0].varible).toBeUndefined(); + expect(aggregatedCollection.item[1].variable).toBeUndefined(); + + expect(aggregatedCollection.variable.slice(0, sourceCollection1.variable.length)).toStrictEqual(sourceCollection1.variable); + expect(aggregatedCollection.variable.slice(sourceCollection1.variable.length, sourceCollection1.variable.length + sourceCollection2.variable.length)).toStrictEqual(sourceCollection2.variable); + + }); + + }) +}) + diff --git a/__test__/collection_aggregator_test/collection_aggregator_test-cli.system.test.js b/__test__/collection_aggregator_test/collection_aggregator_test-cli.system.test.js new file mode 100644 index 0000000..94d4a81 --- /dev/null +++ b/__test__/collection_aggregator_test/collection_aggregator_test-cli.system.test.js @@ -0,0 +1,107 @@ +const exec = require('shelljs').exec, + sdk = require('postman-collection'), + fs = require('fs-extra'), + { removeID } = require('./utils/helperMethods.js'); + +describe('Validate collection_aggregator system test', () => { + + describe('Validate cli output messages', () => { + + it('Should show help if arguments are missing', async () => { + const commandResponse = exec('npx postman-collection-aggregator', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection folder is not folder', async () => { + const commandResponse = exec('npx postman-collection-aggregator -d "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection file is not valid', async () => { + const commandResponse = exec('npx postman-collection-aggregator -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection folder is not found', async () => { + const commandResponse = exec('npx postman-collection-aggregator -d "__test__/collection_aggregator_test/nonexisting" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection file is non existing', async () => { + const commandResponse = exec('npx postman-collection-aggregator -l "__test__/collection_aggregator_test/collection/collection5.json" "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should not show help if -d argument is provided', async () => { + const commandResponse = exec('npx postman-collection-aggregator -d "__test__/collection_aggregator_test/collection"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*Aggregated_collection.collection.json/g); + }); + + it('Should not show help if -l argument is provided', async () => { + const commandResponse = exec('npx postman-collection-aggregator -n "test" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*test.collection.json/g); + }); + + it('Should save to custom path if -s argument is provided', async () => { + const commandResponse = exec('npx postman-collection-aggregator -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]output[\\|\/]new.json/g); + }); + + it('Should save to custom path if -s argument is provided', async () => { + const commandResponse = exec('npx postman-collection-aggregator -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]output[\\|\/]new.json/g); + }); + + it('Should show -d will be accepted if both -l and -d given', async () => { + const commandResponse = exec('npx postman-collection-aggregator -d "__test__/collection_aggregator_test/collection" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/\[Warning\] Both -d and -l was provided. Will be using Using -d/g); + + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]output[\\|\/]new.json/g); + }); + }) + + describe('Validate collection creation', () => { + + it('validate collection aggregated without modifiying source content ', async () => { + + const commandResponse = exec('npx postman-collection-aggregator -n "new" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new_collection.json"', { silent: true }); + + const aggregatedCollection = new sdk.Collection(JSON.parse(fs.readFileSync('output/new_collection.json').toString())).toJSON(); + const sourceCollection1 = new sdk.Collection(JSON.parse(fs.readFileSync('__test__/collection_aggregator_test/collection/collection.json').toString())).toJSON(); + const sourceCollection2 = new sdk.Collection(JSON.parse(fs.readFileSync('__test__/collection_aggregator_test/collection/collection_2.json').toString())).toJSON(); + + removeID(sourceCollection1); + removeID(sourceCollection2); + removeID(aggregatedCollection); + + //expect source and output have same collection level settings + expect(aggregatedCollection.item[0].item).toStrictEqual(sourceCollection1.item); + expect(aggregatedCollection.item[1].item).toStrictEqual(sourceCollection2.item); + expect(aggregatedCollection.item[0].event).toStrictEqual(sourceCollection1.event); + expect(aggregatedCollection.item[1].event).toStrictEqual(sourceCollection2.event); + expect(aggregatedCollection.item[0].name).toStrictEqual(sourceCollection1.info.name); + expect(aggregatedCollection.item[1].name).toStrictEqual(sourceCollection2.info.name); + expect(aggregatedCollection.item[0].auth).toStrictEqual(sourceCollection1.auth); + expect(aggregatedCollection.item[1].auth).toStrictEqual(sourceCollection2.auth); + expect(aggregatedCollection.item[0].varible).toBeUndefined(); + expect(aggregatedCollection.item[1].variable).toBeUndefined(); + + expect(aggregatedCollection.variable.slice(0, sourceCollection1.variable.length)).toStrictEqual(sourceCollection1.variable); + expect(aggregatedCollection.variable.slice(sourceCollection1.variable.length, sourceCollection1.variable.length + sourceCollection2.variable.length)).toStrictEqual(sourceCollection2.variable); + + }); + + }) +}) + + diff --git a/__test__/collection_aggregator_test/collection_aggregator_test-cli.test.js b/__test__/collection_aggregator_test/collection_aggregator_test-cli.test.js new file mode 100644 index 0000000..89d73f8 --- /dev/null +++ b/__test__/collection_aggregator_test/collection_aggregator_test-cli.test.js @@ -0,0 +1,106 @@ +const exec = require('shelljs').exec, + sdk = require('postman-collection'), + fs = require('fs-extra'), + { removeID } = require('./utils/helperMethods.js'); + +describe('Validate collection_aggregator main.js test', () => { + + describe('Validate cli output messages', () => { + + it('Should show help if arguments are missing', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js"', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection folder is not folder', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -d "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection file is not valid', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection folder is not found', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -d "__test__/collection_aggregator_test/nonexisting" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should show error if collection file is non existing', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -l "__test__/collection_aggregator_test/collection/collection5.json" "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap" ', { silent: true }); + expect(commandResponse.stderr).toMatchSnapshot(); + expect(commandResponse.stdout).toMatchSnapshot(); + }); + + it('Should not show help if -d argument is provided', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -d "__test__/collection_aggregator_test/collection"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*Aggregated_collection.collection.json/g); + }); + + it('Should not show help if -l argument is provided', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -n "test" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*test.collection.json/g); + }); + + it('Should show -d will be accepted if both -l and -d given', async () => { + const commandResponse = exec('npx postman-collection-aggregator -d "__test__/collection_aggregator_test/collection" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/\[Warning\] Both -d and -l was provided. Will be using Using -d/g); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]output[\\|\/]new.json/g); + }); + + it('Should save to custom path if -s argument is provided', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]output[\\|\/]new.json/g); + }); + + it('Should save to custom path if -s argument is provided', async () => { + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new.json"', { silent: true }); + expect(commandResponse.stderr).toMatch(''); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]output[\\|\/]new.json/g); + }); + }) + + describe('Validate collection creation', () => { + + it('validate collection aggregated without modifiying source content ', async () => { + + const commandResponse = exec('node "./bin/mainCollectionAggregator.js" -n "new" -l "__test__/collection_aggregator_test/collection/collection.json" "__test__/collection_aggregator_test/collection/collection_2.json" -s "output/new_collection.json"', { silent: true }); + + const aggregatedCollection = new sdk.Collection(JSON.parse(fs.readFileSync('output/new_collection.json').toString())).toJSON(); + const sourceCollection1 = new sdk.Collection(JSON.parse(fs.readFileSync('__test__/collection_aggregator_test/collection/collection.json').toString())).toJSON(); + const sourceCollection2 = new sdk.Collection(JSON.parse(fs.readFileSync('__test__/collection_aggregator_test/collection/collection_2.json').toString())).toJSON(); + + removeID(sourceCollection1); + removeID(sourceCollection2); + removeID(aggregatedCollection); + + //expect source and output have same collection level settings + expect(aggregatedCollection.item[0].item).toStrictEqual(sourceCollection1.item); + expect(aggregatedCollection.item[1].item).toStrictEqual(sourceCollection2.item); + expect(aggregatedCollection.item[0].event).toStrictEqual(sourceCollection1.event); + expect(aggregatedCollection.item[1].event).toStrictEqual(sourceCollection2.event); + expect(aggregatedCollection.item[0].name).toStrictEqual(sourceCollection1.info.name); + expect(aggregatedCollection.item[1].name).toStrictEqual(sourceCollection2.info.name); + expect(aggregatedCollection.item[0].auth).toStrictEqual(sourceCollection1.auth); + expect(aggregatedCollection.item[1].auth).toStrictEqual(sourceCollection2.auth); + expect(aggregatedCollection.item[0].varible).toBeUndefined(); + expect(aggregatedCollection.item[1].variable).toBeUndefined(); + + expect(aggregatedCollection.variable.slice(0, sourceCollection1.variable.length)).toStrictEqual(sourceCollection1.variable); + expect(aggregatedCollection.variable.slice(sourceCollection1.variable.length, sourceCollection1.variable.length + sourceCollection2.variable.length)).toStrictEqual(sourceCollection2.variable); + + }); + + }) +}) + + diff --git a/__test__/collection_aggregator_test/utils/helperMethods.js b/__test__/collection_aggregator_test/utils/helperMethods.js new file mode 100644 index 0000000..82acdb2 --- /dev/null +++ b/__test__/collection_aggregator_test/utils/helperMethods.js @@ -0,0 +1,50 @@ +function resetAndReimportUrlUpdator({ n, l, d, s, i }) { + jest.resetModules() + + let { n: mockn, l: mockl, d: mockd, s: mocks, i: mocki } = { n, l, d, s, i }, + mocklArr = []; + + while (process.argv.length > 2) { + process.argv.pop(); + } + + if (n) process.argv.push('-n', n); + if (l) { + let regEx = /"(?.*?)"/g, + matches; + do { + matches = regEx.exec(l) + matches && matches.groups + && matches.groups.path + && process.argv.push('-l', matches.groups.path) + && mocklArr.push(matches.groups.path) + } while (matches) + } + + if (d) process.argv.push('-d', d); + if (s) process.argv.push('-s', s); + if (i) process.argv.push('-i', i); + + return jest.mock('inquirer').requireMock('inquirer').prompt = jest.fn(async function () { return { new_collection_name: mockn, collection_list: mocklArr, collection_directory: mockd, save_as: mocks, interactive: mocki } }); +} + + +class CustomError extends Error { + constructor(errno) { + super(); + this.errno = errno; + this.message = 'Custom error'; + } +}; + + +function removeID(obj) { + for (prop in obj) { + if (prop === 'id' || prop === '_id') + delete obj[prop]; + else if (typeof obj[prop] === 'object') + removeID(obj[prop]); + } +} + +module.exports = { resetAndReimportUrlUpdator, CustomError, removeID }; \ No newline at end of file diff --git a/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli-unit.test.js.snap b/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli-unit.test.js.snap new file mode 100644 index 0000000..1f1c547 --- /dev/null +++ b/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli-unit.test.js.snap @@ -0,0 +1,365 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 4`] = `"exit"`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 5`] = ` +[MockFunction] { + "calls": Array [ + Array [], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + "ENOENT: no such file or directory, open 'test/collection/collection.json'", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file not found error if collection doesnt exists 7`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 4`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with custom path 5`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 4`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show file saved message correctly with default path 5`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 4`] = `"exit"`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w +\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" + +or + +Usage: -i + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -c, --collection_path Path to Collection file [string] [required] + -r, --replace_url_part Replaces only the matching part of the URL + [string] [required] + -w, --with_url_part Replaces the matching part of the URL with provided + value [string] [required] + -s, --save_as path to save new collection + [string] [default: \\"/new_.json\\"] + -p, --use_regex_pattern Flag to enable matching url using regex + [boolean] [default: false]", + ], + Array [], + Array [ + "Missing required argument: c", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -c argument is missing 7`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 4`] = `"exit"`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w +\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" + +or + +Usage: -i + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -c, --collection_path Path to Collection file [string] [required] + -r, --replace_url_part Replaces only the matching part of the URL + [string] [required] + -w, --with_url_part Replaces the matching part of the URL with provided + value [string] [required] + -s, --save_as path to save new collection + [string] [default: \\"/new_.json\\"] + -p, --use_regex_pattern Flag to enable matching url using regex + [boolean] [default: false]", + ], + Array [], + Array [ + "Missing required argument: r", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -r argument is missing 7`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 4`] = `"exit"`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w +\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" + +or + +Usage: -i + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -c, --collection_path Path to Collection file [string] [required] + -r, --replace_url_part Replaces only the matching part of the URL + [string] [required] + -w, --with_url_part Replaces the matching part of the URL with provided + value [string] [required] + -s, --save_as path to save new collection + [string] [default: \\"/new_.json\\"] + -p, --use_regex_pattern Flag to enable matching url using regex + [boolean] [default: false]", + ], + Array [], + Array [ + "Missing required argument: w", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if -w argument is missing 7`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 1`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 2`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 3`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 4`] = `"exit"`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 5`] = ` +[MockFunction] { + "calls": Array [ + Array [ + 1, + ], + ], + "results": Array [ + Object { + "type": "throw", + "value": [Error: exit], + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 6`] = ` +[MockFunction] { + "calls": Array [ + Array [ + " +Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w +\\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" + +or + +Usage: -i + +Options: + --help Show help [boolean] + --version Show version number [boolean] + -i, --interactive Pass -i to enter Interactive mode + [boolean] [default: false] + -c, --collection_path Path to Collection file [string] [required] + -r, --replace_url_part Replaces only the matching part of the URL + [string] [required] + -w, --with_url_part Replaces the matching part of the URL with provided + value [string] [required] + -s, --save_as path to save new collection + [string] [default: \\"/new_.json\\"] + -p, --use_regex_pattern Flag to enable matching url using regex + [boolean] [default: false]", + ], + Array [], + Array [ + "Missing required arguments: c, r, w", + ], + ], + "results": Array [ + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + Object { + "type": "return", + "value": undefined, + }, + ], +} +`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should show help if arguments are missing 7`] = `[MockFunction]`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should throw error if exception thrown doesnt contain error code ENOENT 1`] = `"Error: Custom error"`; + +exports[`Validate url_updator index.js unit tests Validate cli output messages for non interactive Should throw invalid collection if a valid collection is not provided 1`] = `"exit"`; diff --git a/__test__/__snapshots__/test-cli.system.test.js.snap b/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli.system.test.js.snap similarity index 81% rename from __test__/__snapshots__/test-cli.system.test.js.snap rename to __test__/url_replacer_test/__snapshots__/url_replacer_test-cli.system.test.js.snap index 3cd392a..b35bad7 100644 --- a/__test__/__snapshots__/test-cli.system.test.js.snap +++ b/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli.system.test.js.snap @@ -1,13 +1,13 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`Validate index.js system test Validate cli output messages Should show file not found error if collection doesnt exists 1`] = ` +exports[`Validate url_updator system test Validate cli output messages Should show file not found error if collection doesnt exists 1`] = ` "ENOENT: no such file or directory, open 'test/collection/collection.json' " `; -exports[`Validate index.js system test Validate cli output messages Should show file not found error if collection doesnt exists 2`] = `""`; +exports[`Validate url_updator system test Validate cli output messages Should show file not found error if collection doesnt exists 2`] = `""`; -exports[`Validate index.js system test Validate cli output messages Should show help if -c argument is missing 1`] = ` +exports[`Validate url_updator system test Validate cli output messages Should show help if -c argument is missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" @@ -35,9 +35,9 @@ Missing required argument: c " `; -exports[`Validate index.js system test Validate cli output messages Should show help if -c argument is missing 2`] = `""`; +exports[`Validate url_updator system test Validate cli output messages Should show help if -c argument is missing 2`] = `""`; -exports[`Validate index.js system test Validate cli output messages Should show help if -r argument is missing 1`] = ` +exports[`Validate url_updator system test Validate cli output messages Should show help if -r argument is missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" @@ -65,9 +65,9 @@ Missing required argument: r " `; -exports[`Validate index.js system test Validate cli output messages Should show help if -r argument is missing 2`] = `""`; +exports[`Validate url_updator system test Validate cli output messages Should show help if -r argument is missing 2`] = `""`; -exports[`Validate index.js system test Validate cli output messages Should show help if -w argument is missing 1`] = ` +exports[`Validate url_updator system test Validate cli output messages Should show help if -w argument is missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" @@ -95,9 +95,9 @@ Missing required argument: w " `; -exports[`Validate index.js system test Validate cli output messages Should show help if -w argument is missing 2`] = `""`; +exports[`Validate url_updator system test Validate cli output messages Should show help if -w argument is missing 2`] = `""`; -exports[`Validate index.js system test Validate cli output messages Should show help if arguments are missing 1`] = ` +exports[`Validate url_updator system test Validate cli output messages Should show help if arguments are missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" diff --git a/__test__/__snapshots__/test-cli.test.js.snap b/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli.test.js.snap similarity index 80% rename from __test__/__snapshots__/test-cli.test.js.snap rename to __test__/url_replacer_test/__snapshots__/url_replacer_test-cli.test.js.snap index ed8eec7..6264271 100644 --- a/__test__/__snapshots__/test-cli.test.js.snap +++ b/__test__/url_replacer_test/__snapshots__/url_replacer_test-cli.test.js.snap @@ -1,13 +1,13 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`Validate main.js test Validate cli output messages Should show file not found error if collection doesnt exists 1`] = ` +exports[`Validate url_updator main.js test Validate cli output messages Should show file not found error if collection doesnt exists 1`] = ` "ENOENT: no such file or directory, open 'test/collection/collection.json' " `; -exports[`Validate main.js test Validate cli output messages Should show file not found error if collection doesnt exists 2`] = `""`; +exports[`Validate url_updator main.js test Validate cli output messages Should show file not found error if collection doesnt exists 2`] = `""`; -exports[`Validate main.js test Validate cli output messages Should show help if -c argument is missing 1`] = ` +exports[`Validate url_updator main.js test Validate cli output messages Should show help if -c argument is missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" @@ -35,9 +35,9 @@ Missing required argument: c " `; -exports[`Validate main.js test Validate cli output messages Should show help if -c argument is missing 2`] = `""`; +exports[`Validate url_updator main.js test Validate cli output messages Should show help if -c argument is missing 2`] = `""`; -exports[`Validate main.js test Validate cli output messages Should show help if -r argument is missing 1`] = ` +exports[`Validate url_updator main.js test Validate cli output messages Should show help if -r argument is missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" @@ -65,9 +65,9 @@ Missing required argument: r " `; -exports[`Validate main.js test Validate cli output messages Should show help if -r argument is missing 2`] = `""`; +exports[`Validate url_updator main.js test Validate cli output messages Should show help if -r argument is missing 2`] = `""`; -exports[`Validate main.js test Validate cli output messages Should show help if -w argument is missing 1`] = ` +exports[`Validate url_updator main.js test Validate cli output messages Should show help if -w argument is missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" @@ -95,9 +95,9 @@ Missing required argument: w " `; -exports[`Validate main.js test Validate cli output messages Should show help if -w argument is missing 2`] = `""`; +exports[`Validate url_updator main.js test Validate cli output messages Should show help if -w argument is missing 2`] = `""`; -exports[`Validate main.js test Validate cli output messages Should show help if arguments are missing 1`] = ` +exports[`Validate url_updator main.js test Validate cli output messages Should show help if arguments are missing 1`] = ` " Usage: -c \\"root/collection_name.json\\" -r \\"{{Baseurl}}/path1/path2\\" -w \\"{{Baseurl}}/{{path}}\\" -s \\"root/new_collection_name.json\\" diff --git a/__test__/url_replacer_test/collection/collection.json b/__test__/url_replacer_test/collection/collection.json new file mode 100644 index 0000000..9f4bb1d --- /dev/null +++ b/__test__/url_replacer_test/collection/collection.json @@ -0,0 +1,539 @@ +{ + "info": { + "_postman_id": "71900852-b0b1-4329-9120-bb0a2a4340b5", + "name": "collection", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "folder1", + "item": [ + { + "name": "request1-1", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pre-request script content 1-1" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "test script content 1-1" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "in", + "value": "query", + "type": "string" + }, + { + "key": "value", + "value": "123451-1", + "type": "string" + }, + { + "key": "key", + "value": "X-API-Key-1-1", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "header", + "value": "headervalue1", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"key1-1\": \"value1-1\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "https://www.testdomain0.ie/testpath/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0&query1-1-1=queryvalue1-1-1", + "protocol": "https", + "host": [ + "www", + "testdomain0", + "ie" + ], + "path": [ + "testpath", + ":pathvariable1-1", + "path", + "request1-1" + ], + "query": [ + { + "key": "query1-1-0", + "value": "queryvalue1-1-0" + }, + { + "key": "query1-1-1", + "value": "queryvalue1-1-1" + } + ], + "variable": [ + { + "key": "pathvariable1-1", + "value": "{{testpathvalue}}" + } + ] + } + }, + "response": [] + } + ] + }, + { + "name": "folder2", + "item": [ + { + "name": "New Folder", + "item": [ + { + "name": "New Folder", + "item": [ + { + "name": "New Folder", + "item": [ + { + "name": "New Folder", + "item": [ + { + "name": "New Folder", + "item": [ + { + "name": "final", + "item": [ + { + "name": "requestn-1", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pre-request script content n-1" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "test script content n-1" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "12345n-1", + "type": "string" + }, + { + "key": "key", + "value": "X-API-Key-n-1", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "header", + "value": "headervalue1", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"keyn-1\": \"valuen-1\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "https://www.testdomain0.ie/testpath/:pathvariablen-1/path/requestn-1?queryn-1=queryvaluen-1", + "protocol": "https", + "host": [ + "www", + "testdomain0", + "ie" + ], + "path": [ + "testpath", + ":pathvariablen-1", + "path", + "requestn-1" + ], + "query": [ + { + "key": "queryn-1", + "value": "queryvaluen-1" + } + ], + "variable": [ + { + "key": "pathvariablen-1", + "value": "{{testpathvalue}}" + } + ] + } + }, + "response": [] + } + ] + } + ] + } + ] + } + ] + } + ] + } + ] + } + ] + }, + { + "name": "request0-1", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pre-request script content 0-1" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "test script content 0-1" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "key", + "value": "X-API-Key-0-1", + "type": "string" + }, + { + "key": "value", + "value": "123450-1", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "header0-1", + "value": "headervalue0-1", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"key0-1\": \"value0-1\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "https://www.testdomain0.ie/testpath/:pathvariable0-1/path/request0-1?query0-1=queryvalue0-1", + "protocol": "https", + "host": [ + "www", + "testdomain0", + "ie" + ], + "path": [ + "testpath", + ":pathvariable0-1", + "path", + "request0-1" + ], + "query": [ + { + "key": "query0-1", + "value": "queryvalue0-1" + } + ], + "variable": [ + { + "key": "pathvariable0-1", + "value": "{{testpathvalue}}" + } + ] + } + }, + "response": [] + }, + { + "name": "request0-2", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pre-request script content 0-2" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "test script content 0-2" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "key", + "value": "X-API-Key-0-2", + "type": "string" + }, + { + "key": "value", + "value": "123450-2", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "header0-2", + "value": "headervalue0-2", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"key0-2\": \"value0-2\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "https://www.testdomain0-.ie/testpath/:pathvariable0-2/path/request0-2?query0-2=queryvalue0-2", + "protocol": "https", + "host": [ + "www", + "testdomain0-", + "ie" + ], + "path": [ + "testpath", + ":pathvariable0-2", + "path", + "request0-2" + ], + "query": [ + { + "key": "query0-2", + "value": "queryvalue0-2" + } + ], + "variable": [ + { + "key": "pathvariable0-2", + "value": "pathvalue0-2" + } + ] + } + }, + "response": [] + }, + { + "name": "request0-3", + "event": [ + { + "listen": "prerequest", + "script": { + "exec": [ + "pre-request script content 0-2" + ], + "type": "text/javascript" + } + }, + { + "listen": "test", + "script": { + "exec": [ + "test script content 0-2" + ], + "type": "text/javascript" + } + } + ], + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "key", + "value": "X-API-Key-0-2", + "type": "string" + }, + { + "key": "value", + "value": "123450-2", + "type": "string" + } + ] + }, + "method": "GET", + "header": [ + { + "key": "header0-2", + "value": "headervalue0-2", + "type": "text" + } + ], + "body": { + "mode": "raw", + "raw": "{\r\n \"key0-2\": \"value0-2\"\r\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "https://www.testdomain0-.ie/testpath/:pathvariable0-2/path/request0-2", + "protocol": "https", + "host": [ + "www", + "testdomain0-", + "ie" + ], + "path": [ + "testpath", + ":pathvariable0-2", + "path", + "request0-2" + ], + "variable": [ + { + "key": "pathvariable0-2", + "value": "pathvalue0-2" + } + ] + } + }, + "response": [] + } + ], + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "value", + "value": "collectionvalue", + "type": "string" + }, + { + "key": "key", + "value": "collectionkey", + "type": "string" + } + ] + }, + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "collection level pre-request - collection named \"collection\"" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "collection level test script - collection named \"collection\"" + ] + } + } + ], + "variable": [ + { + "key": "testpathvalue", + "value": "resolvedvalue", + "type": "string" + }, + { + "key": "collectionvar", + "value": "collectionvarvalue", + "type": "string" + } + ] +} \ No newline at end of file diff --git a/__test__/test-cli-unit.test.js b/__test__/url_replacer_test/url_replacer_test-cli-unit.test.js similarity index 66% rename from __test__/test-cli-unit.test.js rename to __test__/url_replacer_test/url_replacer_test-cli-unit.test.js index d2da424..c81fa43 100644 --- a/__test__/test-cli-unit.test.js +++ b/__test__/url_replacer_test/url_replacer_test-cli-unit.test.js @@ -1,14 +1,14 @@ const path = require('path'), sdk = require('postman-collection'), fs = require('fs'), - { resetAndReimportUrlUpdator, CustomError } = require('./utils/helperMethods.js') + { resetAndReimportUrlUpdator, CustomError, removeID } = require('./utils/helperMethods.js') let postman_url_updater, mockProcessExit = jest.spyOn(process, 'exit').mockImplementation(() => { throw new Error("exit"); }), mockConsoleError = jest.spyOn(console, 'error').mockImplementation(() => { }), mockConsoleLog = jest.spyOn(console, 'log').mockImplementation(() => { }); -describe('Validate index.js unit tests', () => { +describe('Validate url_updator index.js unit tests', () => { describe('Validate cli output messages for non interactive', () => { afterEach(() => { @@ -22,7 +22,7 @@ describe('Validate index.js unit tests', () => { it('Should show help if arguments are missing', async () => { resetAndReimportUrlUpdator({ c: undefined, r: undefined, w: undefined, s: undefined, p: undefined, i: undefined }); - expect(() => { require('../src/index.js') }).not.toThrowError() + expect(() => { require('../../src/indexUrlReplacer.js') }).not.toThrowError() expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -30,7 +30,7 @@ describe('Validate index.js unit tests', () => { expect(mockConsoleLog).not.toBeCalled(); expect(mockConsoleLog).toMatchSnapshot(); - await expect(async () => { await require('../src/index.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + await expect(async () => { await require('../../src/indexUrlReplacer.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() expect(mockProcessExit).toBeCalled(); expect(mockConsoleError).toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -42,7 +42,7 @@ describe('Validate index.js unit tests', () => { it('Should show help if -c argument is missing', async () => { resetAndReimportUrlUpdator({ c: undefined, r: "{{baseURL}}/{{path}}", w: "new_collection.json", s: undefined, p: undefined, i: undefined }); - expect(() => { require('../src/index.js') }).not.toThrowError() + expect(() => { require('../../src/indexUrlReplacer.js') }).not.toThrowError() expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -50,7 +50,7 @@ describe('Validate index.js unit tests', () => { expect(mockConsoleLog).not.toBeCalled(); expect(mockConsoleLog).toMatchSnapshot(); - await expect(async () => { await require('../src/index.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + await expect(async () => { await require('../../src/indexUrlReplacer.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() expect(mockProcessExit).toBeCalled(); expect(mockConsoleError).toBeCalled(); @@ -63,7 +63,7 @@ describe('Validate index.js unit tests', () => { it('Should show help if -r argument is missing', async () => { resetAndReimportUrlUpdator({ c: "test/collection/collection.json", r: undefined, w: "new_collection.json", s: undefined, p: undefined, i: undefined }); - expect(() => { require('../src/index.js') }).not.toThrowError() + expect(() => { require('../../src/indexUrlReplacer.js') }).not.toThrowError() expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -71,7 +71,7 @@ describe('Validate index.js unit tests', () => { expect(mockConsoleLog).not.toBeCalled(); expect(mockConsoleLog).toMatchSnapshot(); - await expect(async () => { await require('../src/index.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + await expect(async () => { await require('../../src/indexUrlReplacer.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() expect(mockProcessExit).toBeCalled(); expect(mockConsoleError).toBeCalled(); @@ -84,7 +84,7 @@ describe('Validate index.js unit tests', () => { it('Should show help if -w argument is missing', async () => { resetAndReimportUrlUpdator({ c: "test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: undefined, s: "new_collection.json", p: undefined, i: undefined }); - expect(() => { require('../src/index.js') }).not.toThrowError() + expect(() => { require('../../src/indexUrlReplacer.js') }).not.toThrowError() expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -92,7 +92,7 @@ describe('Validate index.js unit tests', () => { expect(mockConsoleLog).not.toBeCalled(); expect(mockConsoleLog).toMatchSnapshot(); - await expect(async () => { await require('../src/index.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() + await expect(async () => { await require('../../src/indexUrlReplacer.js').createNewCollection() }).rejects.toThrowErrorMatchingSnapshot() expect(mockProcessExit).toBeCalled(); expect(mockConsoleError).toBeCalled(); @@ -104,7 +104,7 @@ describe('Validate index.js unit tests', () => { it('Should show file not found error if collection doesnt exists', async () => { resetAndReimportUrlUpdator({ c: "test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "new_collection.json", p: undefined, i: undefined }); - postman_url_updater = require('../src/index.js') + postman_url_updater = require('../../src/indexUrlReplacer.js') expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -122,8 +122,8 @@ describe('Validate index.js unit tests', () => { }); it('Should show file saved message correctly with default path', async () => { - resetAndReimportUrlUpdator({ c: "__test__/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: undefined, p: undefined, i: undefined }); - postman_url_updater = require('../src/index.js') + resetAndReimportUrlUpdator({ c: "__test__/url_replacer_test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: undefined, p: undefined, i: undefined }); + postman_url_updater = require('../../src/indexUrlReplacer.js') expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -136,12 +136,12 @@ describe('Validate index.js unit tests', () => { expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); expect(mockConsoleError).toMatchSnapshot(); - expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./__test__/collection/new_collection.json')}`); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./__test__/url_replacer_test/collection/new_collection.json')}`); }); it('Should show file saved message correctly with custom path', async () => { - resetAndReimportUrlUpdator({ c: "__test__/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "__test__/collection/output/new_collection.json", p: undefined, i: undefined }); - postman_url_updater = require('../src/index.js') + resetAndReimportUrlUpdator({ c: "__test__/url_replacer_test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "__test__/url_replacer_test/collection/output/new_collection.json", p: undefined, i: undefined }); + postman_url_updater = require('../../src/indexUrlReplacer.js') expect(mockProcessExit).not.toBeCalled(); expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); @@ -154,12 +154,12 @@ describe('Validate index.js unit tests', () => { expect(mockConsoleError).not.toBeCalled(); expect(mockProcessExit).toMatchSnapshot(); expect(mockConsoleError).toMatchSnapshot(); - expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./__test__/collection/output/new_collection.json')}`); + expect(mockConsoleLog).toBeCalledWith(`File saved to: ${path.resolve('./__test__/url_replacer_test/collection/output/new_collection.json')}`); }); it('Should throw error if exception thrown doesnt contain error code ENOENT', async () => { - resetAndReimportUrlUpdator({ c: "__test__/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "new_collection.json", p: undefined, i: undefined }); - postman_url_updater = require('../src/index.js') + resetAndReimportUrlUpdator({ c: "__test__/url_replacer_test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "new_collection.json", p: undefined, i: undefined }); + postman_url_updater = require('../../src/indexUrlReplacer.js') jest.clearAllMocks() mockConsoleLog.mockImplementation(() => { throw new CustomError(256) }); await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot() @@ -167,8 +167,8 @@ describe('Validate index.js unit tests', () => { }); it('Should throw invalid collection if a valid collection is not provided', async () => { - resetAndReimportUrlUpdator({ c: "__test__/__snapshots__/test-cli-unit.test.js.snap", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "new_collection.json", p: undefined, i: undefined }); - postman_url_updater = require('../src/index.js') + resetAndReimportUrlUpdator({ c: "__test__/collection_aggregator_test/__snapshots__/collection_aggregator_test-cli-unit.test.js.snap", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "new_collection.json", p: undefined, i: undefined }); + postman_url_updater = require('../../src/indexUrlReplacer.js') jest.clearAllMocks() await expect(postman_url_updater.createNewCollection).rejects.toThrowErrorMatchingSnapshot() expect(console.error).toBeCalledWith(`Invalid/corrupted collection provided. Please provide path to valid source collection`); @@ -187,33 +187,31 @@ describe('Validate index.js unit tests', () => { }) it('Should call inquirer if i not provided', async () => { - let inquirerSpy = resetAndReimportUrlUpdator({ c: "__test__/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "__test__/collection/output/new_collection.json", p: undefined, i: true }); - await require('../src/index.js').createNewCollection(); + let inquirerSpy = resetAndReimportUrlUpdator({ c: "__test__/url_replacer_test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "__test__/url_replacer_test/collection/output/new_collection.json", p: undefined, i: true }); + await require('../../src/indexUrlReplacer.js').createNewCollection(); expect(inquirerSpy).toHaveBeenCalled() }); it('Should not call inquirer if i not provided', async () => { - let inquirerSpy = resetAndReimportUrlUpdator({ c: "__test__/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "__test__/collection/output/new_collection.json", p: undefined, i: false }); - await require('../src/index.js').createNewCollection(); + let inquirerSpy = resetAndReimportUrlUpdator({ c: "__test__/url_replacer_test/collection/collection.json", r: "{{baseURL}}/{{path}}", w: "{{baseURL}}/{{path}}", s: "__test__/url_replacer_test/collection/output/new_collection.json", p: undefined, i: false }); + await require('../../src/indexUrlReplacer.js').createNewCollection(); expect(inquirerSpy).not.toHaveBeenCalled() }); }) describe('Validate collection changes', () => { - let collectionPath = '__test__/collection/collection.json', - outputCollectionPath = '__test__/collection/output/new_unit.json'; + let collectionPath = '__test__/url_replacer_test/collection/collection.json', + outputCollectionPath = '__test__/url_replacer_test/collection/output/new_unit.json'; it('validate no changes happens when there is no match', async () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "https://localhost:23456/api/v1/{{path}}", w: "{{baseURL}}/{{path}}", s: outputCollectionPath, p: undefined, i: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + removeID(sourceCollection); + removeID(outputCollection); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate change happens only for urls other properties remains the same', async () => { @@ -231,18 +229,19 @@ describe('Validate index.js unit tests', () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "https://www.testdomain0.ie", w: "{{baseURL}}/{{path}}", s: outputCollectionPath, p: undefined, i: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); + + + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0], 'n', 1); updatedRequestObject(sourceCollection.item[2], 0, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate change protocol is shown if not removed', async () => { @@ -260,18 +259,17 @@ describe('Validate index.js unit tests', () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "www.testdomain0.ie", w: "{{baseURL}}/{{path}}", s: outputCollectionPath, p: undefined, i: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0], 'n', 1); updatedRequestObject(sourceCollection.item[2], 0, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -289,16 +287,15 @@ describe('Validate index.js unit tests', () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "www.testdomain0.ie/testpath/:pathvariable1-1", w: "{{baseURL}}/{{path}}", s: outputCollectionPath, p: undefined, i: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -321,16 +318,15 @@ describe('Validate index.js unit tests', () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "/:pathvariable1-1/path/request1-1?query1-1-0", w: "/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0-0&test", s: outputCollectionPath, p: undefined, i: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -354,18 +350,16 @@ describe('Validate index.js unit tests', () => { r: "https://www.testdomain0.ie/testpath/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0&query1-1-1=queryvalue1-1-1", w: "{{protocol}}://{{baseURL}}/v1/{{path}}", s: outputCollectionPath, p: undefined, i: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); //expect only first request is modified updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate query parameters are updated using regex if p flag used ', async () => { @@ -379,9 +373,11 @@ describe('Validate index.js unit tests', () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "^(.*?)(?:\\?(.*))?$", w: "$1?querynew=valuenew&$2", s: outputCollectionPath, p: true }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); //expect that new query parameter is added as first parameter updatedRequestObject(sourceCollection.item[0].item[0]); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0]); @@ -394,28 +390,20 @@ describe('Validate index.js unit tests', () => { "value": null, }) - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); - expect(outputCollection.item[4].request).toStrictEqual(sourceCollection.item[4].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate regex have no effect if p flag is not used ', async () => { const sourceCollection = new sdk.Collection(JSON.parse(fs.readFileSync(collectionPath).toString())).toJSON(); resetAndReimportUrlUpdator({ c: collectionPath, r: "^(.*?)(?:\\?(.*))?$", w: "$1?querynew=valuenew&$2", s: outputCollectionPath, p: undefined }); - await require('../src/index.js').createNewCollection(); + await require('../../src/indexUrlReplacer.js').createNewCollection(); const outputCollection = new sdk.Collection(JSON.parse(fs.readFileSync(outputCollectionPath).toString())).toJSON(); //expect source and output are the same - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); - expect(outputCollection.item[4].request).toStrictEqual(sourceCollection.item[4].request); + removeID(sourceCollection); + removeID(outputCollection); + expect(outputCollection).toStrictEqual(sourceCollection); }); }) diff --git a/__test__/test-cli.system.test.js b/__test__/url_replacer_test/url_replacer_test-cli.system.test.js similarity index 69% rename from __test__/test-cli.system.test.js rename to __test__/url_replacer_test/url_replacer_test-cli.system.test.js index 7060b07..fc6f356 100644 --- a/__test__/test-cli.system.test.js +++ b/__test__/url_replacer_test/url_replacer_test-cli.system.test.js @@ -1,8 +1,10 @@ +const { removeID } = require('./utils/helperMethods'); + const exec = require('shelljs').exec, SDK = require('postman-collection'), FS = require('fs'); -describe('Validate index.js system test', () => { +describe('Validate url_updator system test', () => { describe('Validate cli output messages', () => { it('Should show help if arguments are missing', async () => { const commandResponse = exec('npx postman-collection-url-updater ', { silent: true }); @@ -34,32 +36,30 @@ describe('Validate index.js system test', () => { }); it('Should show file saved message correctly with default path', async () => { - const commandResponse = exec('npx postman-collection-url-updater -c "__test__/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}"', { silent: true }); + const commandResponse = exec('npx postman-collection-url-updater -c "__test__/url_replacer_test/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}"', { silent: true }); expect(commandResponse.stderr).toMatch(''); - expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]collection[\\|\/]new_collection.json/g); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]url_replacer_test[\\|\/]collection[\\|\/]new_collection.json/g); }); it('Should show file saved message correctly with custom path', async () => { - const commandResponse = exec('npx postman-collection-url-updater -c "__test__/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "__test__/collection/output/new.json"', { silent: true }); + const commandResponse = exec('npx postman-collection-url-updater -c "__test__/url_replacer_test/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "__test__/url_replacer_test/collection/output/new.json"', { silent: true }); expect(commandResponse.stderr).toMatch(''); - expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]collection[\\|\/]output[\\|\/]new\.json/g); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]url_replacer_test[\\|\/]collection[\\|\/]output[\\|\/]new\.json/g); }); }) describe('Validate collection changes', () => { - let collectionPath = '__test__/collection/collection.json', - outputCollectionPath = '__test__/collection/output/new.json'; + let collectionPath = '__test__/url_replacer_test/collection/collection.json', + outputCollectionPath = '__test__/url_replacer_test/collection/output/new.json'; it('validate no changes happens when there is no match', async () => { const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); const commandResponse = exec(`npx postman-collection-url-updater -c "${collectionPath}" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + removeID(sourceCollection); + removeID(outputCollection); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate change happens only for urls other properties remains the same', async () => { @@ -80,15 +80,14 @@ describe('Validate index.js system test', () => { const commandResponse = exec(`npx postman-collection-url-updater -c "${collectionPath}" -r "https://www.testdomain0.ie" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0], 'n', 1); updatedRequestObject(sourceCollection.item[2], 0, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate change protocol is shown if not removed', async () => { @@ -107,16 +106,15 @@ describe('Validate index.js system test', () => { const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); const commandResponse = exec(`npx postman-collection-url-updater -c "${collectionPath}" -r "www.testdomain0.ie" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + + removeID(sourceCollection); + removeID(outputCollection); updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0], 'n', 1); updatedRequestObject(sourceCollection.item[2], 0, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -136,13 +134,12 @@ describe('Validate index.js system test', () => { const commandResponse = exec(`npx postman-collection-url-updater -c "${collectionPath}" -r "www.testdomain0.ie/testpath/:pathvariable1-1" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -167,13 +164,12 @@ describe('Validate index.js system test', () => { const commandResponse = exec(`npx postman-collection-url-updater -c "${collectionPath}" -r "/:pathvariable1-1/path/request1-1?query1-1-0" -w "/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0-0&test" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -195,13 +191,12 @@ describe('Validate index.js system test', () => { const commandResponse = exec(`npx postman-collection-url-updater -c "${collectionPath}" -r "https://www.testdomain0.ie/testpath/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0&query1-1-1=queryvalue1-1-1" -w "{{protocol}}://{{baseURL}}/v1/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); }) diff --git a/__test__/test-cli.test.js b/__test__/url_replacer_test/url_replacer_test-cli.test.js similarity index 50% rename from __test__/test-cli.test.js rename to __test__/url_replacer_test/url_replacer_test-cli.test.js index 84a4d8f..cbf9385 100644 --- a/__test__/test-cli.test.js +++ b/__test__/url_replacer_test/url_replacer_test-cli.test.js @@ -1,65 +1,65 @@ +const { removeID } = require('./utils/helperMethods.js'); + const exec = require('shelljs').exec, SDK = require('postman-collection'), FS = require('fs'); -describe('Validate main.js test', () => { +describe('Validate url_updator main.js test', () => { describe('Validate cli output messages', () => { it('Should show help if arguments are missing', async () => { - const commandResponse = exec('node "bin/main.js"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js"', { silent: true }); expect(commandResponse.stderr).toMatchSnapshot(); }); it('Should show help if -c argument is missing', async () => { - const commandResponse = exec('node "bin/main.js" -r "test" -w "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js" -r "test" -w "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); expect(commandResponse.stderr).toMatchSnapshot(); expect(commandResponse.stdout).toMatchSnapshot(); }); it('Should show help if -r argument is missing', async () => { - const commandResponse = exec('node "bin/main.js" -c "test/collection/collection.json" -w "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js" -c "test/collection/collection.json" -w "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); expect(commandResponse.stderr).toMatchSnapshot(); expect(commandResponse.stdout).toMatchSnapshot(); }); it('Should show help if -w argument is missing', async () => { - const commandResponse = exec('node "bin/main.js" -c "test/collection/collection.json" -r "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js" -c "test/collection/collection.json" -r "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); expect(commandResponse.stderr).toMatchSnapshot(); expect(commandResponse.stdout).toMatchSnapshot(); }); it('Should show file not found error if collection doesnt exists', async () => { - const commandResponse = exec('node "bin/main.js" -c "test/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js" -c "test/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "new_collection.json"', { silent: true }); expect(commandResponse.stderr).toMatchSnapshot(); expect(commandResponse.stdout).toMatchSnapshot(); }); it('Should show file saved message correctly with default path', async () => { - const commandResponse = exec('node "bin/main.js" -c "__test__/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js" -c "__test__/url_replacer_test/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}"', { silent: true }); expect(commandResponse.stderr).toMatch(''); - expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]collection[\\|\/]new_collection.json/g); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]url_replacer_test[\\|\/]collection[\\|\/]new_collection.json/g); }); it('Should show file saved message correctly with custom path', async () => { - const commandResponse = exec('node "bin/main.js" -c "__test__/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "__test__/collection/output/new.json"', { silent: true }); + const commandResponse = exec('node "bin/mainUrlUpdater.js" -c "__test__/url_replacer_test/collection/collection.json" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "__test__/url_replacer_test/collection/output/new.json"', { silent: true }); expect(commandResponse.stderr).toMatch(''); - expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]collection[\\|\/]output[\\|\/]new\.json/g); + expect(commandResponse.stdout).toMatch(/File saved to: .*[\\|\/]__test__[\\|\/]url_replacer_test[\\|\/]collection[\\|\/]output[\\|\/]new\.json/g); }); }) describe('Validate collection changes', () => { - let collectionPath = '__test__/collection/collection.json', - outputCollectionPath = '__test__/collection/output/new.json'; + let collectionPath = '__test__/url_replacer_test/collection/collection.json', + outputCollectionPath = '__test__/url_replacer_test/collection/output/new.json'; it('validate no changes happens when there is no match', async () => { const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); - const commandResponse = exec(`node "bin/main.js" -c "${collectionPath}" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); + const commandResponse = exec(`node "bin/mainUrlUpdater.js" -c "${collectionPath}" -r "https://localhost:23456/api/v1/{{path}}" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + removeID(sourceCollection); + removeID(outputCollection); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate change happens only for urls other properties remains the same', async () => { @@ -77,18 +77,17 @@ describe('Validate main.js test', () => { } const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); - const commandResponse = exec(`node "bin/main.js" -c "${collectionPath}" -r "https://www.testdomain0.ie" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); + const commandResponse = exec(`node "bin/mainUrlUpdater.js" -c "${collectionPath}" -r "https://www.testdomain0.ie" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0], 'n', 1); updatedRequestObject(sourceCollection.item[2], 0, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); it('validate change protocol is shown if not removed', async () => { @@ -105,18 +104,17 @@ describe('Validate main.js test', () => { } const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); - const commandResponse = exec(`node "bin/main.js" -c "${collectionPath}" -r "www.testdomain0.ie" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); + const commandResponse = exec(`node "bin/mainUrlUpdater.js" -c "${collectionPath}" -r "www.testdomain0.ie" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); updatedRequestObject(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0], 'n', 1); updatedRequestObject(sourceCollection.item[2], 0, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -133,16 +131,15 @@ describe('Validate main.js test', () => { } const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); - const commandResponse = exec(`node "bin/main.js" -c "${collectionPath}" -r "www.testdomain0.ie/testpath/:pathvariable1-1" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); + const commandResponse = exec(`node "bin/mainUrlUpdater.js" -c "${collectionPath}" -r "www.testdomain0.ie/testpath/:pathvariable1-1" -w "{{baseURL}}/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -164,16 +161,15 @@ describe('Validate main.js test', () => { } const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); - const commandResponse = exec(`node "bin/main.js" -c "${collectionPath}" -r "/:pathvariable1-1/path/request1-1?query1-1-0" -w "/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0-0&test" -s "${outputCollectionPath}"`, { silent: true }); + const commandResponse = exec(`node "bin/mainUrlUpdater.js" -c "${collectionPath}" -r "/:pathvariable1-1/path/request1-1?query1-1-0" -w "/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0-0&test" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + + removeID(sourceCollection); + removeID(outputCollection); updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); }); @@ -192,16 +188,16 @@ describe('Validate main.js test', () => { } const sourceCollection = new SDK.Collection(JSON.parse(FS.readFileSync(collectionPath).toString())).toJSON(); - const commandResponse = exec(`node "bin/main.js" -c "${collectionPath}" -r "https://www.testdomain0.ie/testpath/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0&query1-1-1=queryvalue1-1-1" -w "{{protocol}}://{{baseURL}}/v1/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); + const commandResponse = exec(`node "bin/mainUrlUpdater.js" -c "${collectionPath}" -r "https://www.testdomain0.ie/testpath/:pathvariable1-1/path/request1-1?query1-1-0=queryvalue1-1-0&query1-1-1=queryvalue1-1-1" -w "{{protocol}}://{{baseURL}}/v1/{{path}}" -s "${outputCollectionPath}"`, { silent: true }); const outputCollection = new SDK.Collection(JSON.parse(FS.readFileSync(outputCollectionPath).toString())).toJSON(); + removeID(sourceCollection); + removeID(outputCollection); + updatedRequestObject(sourceCollection.item[0].item[0], 1, 1); - expect(outputCollection.item[0].item[0].request).toStrictEqual(sourceCollection.item[0].item[0].request); - expect(outputCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request) - .toStrictEqual(sourceCollection.item[1].item[0].item[0].item[0].item[0].item[0].item[0].item[0].request); - expect(outputCollection.item[2].request).toStrictEqual(sourceCollection.item[2].request); - expect(outputCollection.item[3].request).toStrictEqual(sourceCollection.item[3].request); + expect(outputCollection).toStrictEqual(sourceCollection); + }); }) diff --git a/__test__/utils/helperMethods.js b/__test__/url_replacer_test/utils/helperMethods.js similarity index 75% rename from __test__/utils/helperMethods.js rename to __test__/url_replacer_test/utils/helperMethods.js index ea262bb..f5d4625 100644 --- a/__test__/utils/helperMethods.js +++ b/__test__/url_replacer_test/utils/helperMethods.js @@ -25,4 +25,13 @@ class CustomError extends Error { }; -module.exports = { resetAndReimportUrlUpdator, CustomError }; \ No newline at end of file +function removeID(obj) { + for (prop in obj) { + if (prop === 'id' || prop === '_id') + delete obj[prop]; + else if (typeof obj[prop] === 'object') + removeID(obj[prop]); + } +} + +module.exports = { resetAndReimportUrlUpdator, CustomError, removeID }; \ No newline at end of file diff --git a/bin/main.js b/bin/main.js deleted file mode 100644 index d425740..0000000 --- a/bin/main.js +++ /dev/null @@ -1,3 +0,0 @@ -#! /usr/bin/env node -let { createNewCollection } = require('../src/index.js') -createNewCollection() diff --git a/bin/mainCollectionAggregator.js b/bin/mainCollectionAggregator.js new file mode 100644 index 0000000..6bafe8c --- /dev/null +++ b/bin/mainCollectionAggregator.js @@ -0,0 +1,3 @@ +#! /usr/bin/env node +let { createNewCollection } = require('../src/indexAggregator.js') +createNewCollection() diff --git a/bin/mainUrlUpdater.js b/bin/mainUrlUpdater.js new file mode 100644 index 0000000..7ffe3b0 --- /dev/null +++ b/bin/mainUrlUpdater.js @@ -0,0 +1,3 @@ +#! /usr/bin/env node +let { createNewCollection } = require('../src/indexUrlReplacer.js') +createNewCollection() diff --git a/package.json b/package.json index e18c3ab..9bd4eb6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "postman-collection-url-updater", - "version": "2.0.7", - "description": "Postman collection url updater is a command line utility project that can update urls across multiple postman requests in your postman collection. It allows to update postman request urls in bulk inside the postman collection", + "version": "3.0.0", + "description": "Postman collection url updater is a command line utility project that can update urls across multiple postman requests in your postman collection. It allows to update postman request urls in bulk inside the postman collection. it also support migrating multiple collection into single collection", "scripts": { "test": "jest" }, @@ -16,7 +16,8 @@ "yargs": "^17.3.1" }, "bin": { - "postman-collection-url-updater": "./bin/main.js" + "postman-collection-url-updater": "./bin/mainUrlUpdater.js", + "postman-collection-aggregator": "./bin/mainCollectionAggregator.js" }, "files": [ "src", @@ -57,7 +58,8 @@ "verbose": true, "maxWorkers": 1, "collectCoverageFrom": [ - "src/**/index.js" + "src/**/indexAggregator.js", + "src/**/indexUrlReplacer.js" ] } } diff --git a/src/helper/constant.js b/src/helper/constant.js index b1166f2..c5dbef5 100644 --- a/src/helper/constant.js +++ b/src/helper/constant.js @@ -7,7 +7,7 @@ function validate(answer, message) { return true; } -module.exports = (defaults) => { +exports.urlReplacerQuestionaire = (defaults) => { let questions = [ { name: 'collection_path', @@ -51,3 +51,51 @@ module.exports = (defaults) => { return questions }; + +exports.collectionAggregatorQuestionaire = (defaults) => { + let questions = [ + { + name: 'new_collection_name', + message: 'Please provided the name for new collection', + type: 'string', + suffix: " [Example: aggregated_collection]", + validate: (answer) => validate(answer, "Please provided a name") + }, + { + name: 'using_collection_directory', + message: 'Do you want to provide directory containing all collections or manually provide the path to each collection file', + type:'list', + choices: ['Providing directory', 'Manually entring path'], + + }, + { + when : function ( answers ) { + return answers.using_collection_directory === 'Manually entring path'; + }, + name: 'collection_list', + message: 'Provide relative or absolute collection file paths separated by comma', + suffix: "[Example: test/collection_name1.json,test/collection_name2.json,test/collection name3.json]", + filter: answer => answer.split(',') + + }, + { + when : function ( answers ) { + return answers.using_collection_directory === 'Providing directory'; + }, + name: 'collection_directory', + message: 'Directory containing all collection files', + type: 'string', + suffix: " [Example: www.test.com/path1/path2]", + validate: (answer) => validate(answer, "Please provide a string to replace"), + }, + { + name: 'save_as', + message: 'Please provide a custom path to save the new output collection', + type: 'string', + default: defaults.save_as, + suffix: " [Example: output/new_collection_name.json]" + }, + ]; + return questions +}; + diff --git a/src/indexAggregator.js b/src/indexAggregator.js new file mode 100644 index 0000000..9743b78 --- /dev/null +++ b/src/indexAggregator.js @@ -0,0 +1,79 @@ +let sourceCollection; + +const yargs = require('yargs'), + fs = require('fs-extra'), + sdk = require('postman-collection'), + inquirer = require('inquirer'), + path = require('path'), + chalk = require('chalk'), + DEFAULTS = { + save_as: 'currentDirectory/.collection.json', + new_collection_name: "Aggregated_collection" + }, + COLLECTION_AGGREGATOR_QUESTIONS = require('./helper/constant').collectionAggregatorQuestionaire(DEFAULTS); + +let OPTIONS = yargs + .usage('\nUsage: -n "new_collection" -l "path/collection1.json" "path/collection1.json" "path/collection1.json"') + .usage('\nor\n\nUsage: -i') + .usage('\nor\n\nUsage: -d "./collection_directory" -n "new_collection" ') + .strict() + .option('i', { alias: 'interactive', describe: 'Pass -i to enter Interactive mode', type: 'boolean', default: false }) + .option('n', { alias: 'new_collection_name', describe: 'Name of the new collection', type: 'string', default: DEFAULTS.new_collection_name }) + .option('l', { alias: 'collection_list', describe: 'Pass relative or absolute collection file paths', type: 'array' }) + .option('d', { alias: 'collection_directory', describe: 'Directory containing all collection files', type: 'string' }) + .option('s', { alias: 'save_as', describe: 'path to save new collection', type: 'string', default: DEFAULTS.save_as }) + .example([ + ['postman-collection-aggregator -n "new_collection" -l "path/collection1.json" "path/collection1.json" "path/collection1.json"', '- Using collection list'], + ['postman-collection-aggregator -d "./collection_directory"', '- Using collection directory'] + ]) + +async function startConvert() { + await setOptions() + sourceCollection = new sdk.Collection({ "name": OPTIONS.new_collection_name }); + + try { + let collection_list = OPTIONS.collection_directory ? fs.readdirSync(OPTIONS.collection_directory).filter(file => file.endsWith('.json')) : OPTIONS.collection_list; + + collection_list.map(filePath => { + sourceCollection.items.add(new sdk.ItemGroup(JSON.parse(fs.readFileSync(OPTIONS.collection_directory ? + OPTIONS.collection_directory + '/' + filePath : + filePath).toString() + ))) + + new sdk.Collection(JSON.parse(fs.readFileSync(OPTIONS.collection_directory ? + OPTIONS.collection_directory + '/' + filePath : + filePath).toString() + )).variables.each(variable => { + sourceCollection.variables.append( + variable.toJSON() + ); + }) + }) + + DESTINATIONPATH = path.resolve(OPTIONS.save_as === DEFAULTS.save_as ? `${OPTIONS.new_collection_name}.collection.json` : OPTIONS.save_as); + fs.outputFileSync(DESTINATIONPATH, JSON.stringify(sourceCollection.toJSON(), null, 2)) + console.log(chalk.green('File saved to: ') + chalk.yellowBright(DESTINATIONPATH)) + } catch (e) { + if (!(e.code === 'ENOENT' || e.code === 'ENOTDIR') + && + !(e.stack && e.stack.includes("at JSON.parse"))) throw e; + + console.error(chalk.red((e.stack && e.stack.includes("at JSON.parse")) ? "Invalid/corrupted collection provided. Please provide path to valid source collection" + : (e.message))) + process.exit() + } +} + +async function setOptions() { + OPTIONS.check((argv) => { + if (!(argv.l || argv.d) && !argv.i) throw Error(`Please provide either collection_directory or collection_list +[Missing required property -l or -d]`) + return true + }); + + if ((OPTIONS.argv.l && OPTIONS.argv.d) && !OPTIONS.argv.i) console.log(chalk.yellowBright(`[Warning] Both -d and -l was provided. Will be using Using -d`)); + OPTIONS = OPTIONS.argv.i ? await inquirer.prompt(COLLECTION_AGGREGATOR_QUESTIONS) : OPTIONS.argv; +} + +module.exports = { createNewCollection: startConvert } + diff --git a/src/index.js b/src/indexUrlReplacer.js similarity index 95% rename from src/index.js rename to src/indexUrlReplacer.js index ec791ee..cffd38b 100644 --- a/src/index.js +++ b/src/indexUrlReplacer.js @@ -11,7 +11,7 @@ const yargs = require('yargs'), save_as: '/new_.json', use_regex_pattern: false }, - QUESTIONS = require('./helper/constant')(DEFAULTS); + URL_REPLACER_QUESTIONS = require('./helper/constant').urlReplacerQuestionaire(DEFAULTS); let OPTIONS = yargs .usage('\nUsage: -c "root/collection_name.json" -r "{{Baseurl}}/path1/path2" -w "{{Baseurl}}/{{path}}" -s "root/new_collection_name.json"') @@ -30,7 +30,7 @@ if (!OPTIONS.parse().i) { async function startConvert() { - OPTIONS = OPTIONS.argv.i ? await inquirer.prompt(QUESTIONS) : OPTIONS.argv; + OPTIONS = OPTIONS.argv.i ? await inquirer.prompt(URL_REPLACER_QUESTIONS) : OPTIONS.argv; const COLLECTIONFILE = path.parse(OPTIONS.collection_path).base, COLLECTIONDIR = path.resolve(path.parse(OPTIONS.collection_path).dir),