browserstack-cypress-cli 1.14.1 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -97,6 +97,11 @@ module.exports = function run(args, rawArgs) {
97
97
  // set record feature caps
98
98
  utils.setRecordCaps(bsConfig, args);
99
99
 
100
+ // set build tag caps
101
+ utils.setBuildTags(bsConfig, args);
102
+ // set node version
103
+ utils.setNodeVersion(bsConfig, args);
104
+
100
105
  //set browsers
101
106
  await utils.setBrowsers(bsConfig, args);
102
107
 
@@ -254,6 +254,9 @@ const validate = (bsConfig, args) => {
254
254
  }
255
255
  }
256
256
 
257
+ if (!Utils.isUndefined(bsConfig.run_settings.nodeVersion) && typeof(bsConfig.run_settings.nodeVersion) === 'string' && !bsConfig.run_settings.nodeVersion.match(/^(\d+\.)?(\d+\.)?(\*|\d+)$/))
258
+ logger.warn(Constants.validationMessages.NODE_VERSION_PARSING_ERROR);
259
+
257
260
  resolve(cypressJson);
258
261
  });
259
262
  }
@@ -1,72 +1,115 @@
1
1
  let config = require("./config");
2
- let chalk = require('chalk');
2
+ let chalk = require("chalk");
3
3
 
4
4
  const syncCLI = {
5
- FAILED_SPEC_DETAILS_COL_HEADER: ['Spec', 'Status', 'Browser', 'BrowserStack Session ID'],
5
+ FAILED_SPEC_DETAILS_COL_HEADER: [
6
+ "Spec",
7
+ "Status",
8
+ "Browser",
9
+ "BrowserStack Session ID",
10
+ ],
6
11
  LOGS: {
7
- INIT_LOG: "All tests:"
12
+ INIT_LOG: "All tests:",
8
13
  },
9
14
  INITIAL_DELAY_MULTIPLIER: 10,
10
- DEFAULT_LINE_SEP: "\n--------------------------------------------------------------------------------",
11
- STARTUP_MESSAGE: "BrowserStack machines are now setting up Cypress with the specified npm dependencies for running your tests. It might take some time before your tests start runnning and showing up below..."
15
+ DEFAULT_LINE_SEP:
16
+ "\n--------------------------------------------------------------------------------",
17
+ STARTUP_MESSAGE:
18
+ "BrowserStack machines are now setting up Cypress with the specified npm dependencies for running your tests. It might take some time before your tests start runnning and showing up below...",
12
19
  };
13
20
 
14
21
  const userMessages = {
15
22
  BUILD_FAILED: "Build creation failed.",
16
- BUILD_GENERATE_REPORT_FAILED: "Generating report for the build <build-id> failed.",
23
+ BUILD_GENERATE_REPORT_FAILED:
24
+ "Generating report for the build <build-id> failed.",
17
25
  BUILD_CREATED: "Build created",
18
26
  BUILD_INFO_FAILED: "Failed to get build info.",
19
27
  BUILD_STOP_FAILED: "Failed to stop build.",
20
28
  BUILD_REPORT_MESSAGE: "See the entire build report here:",
21
- ZIP_UPLOADER_NOT_REACHABLE: "Could not reach BrowserStack APIs. Please check your network or see if you need to whitelist *.browserstack.com",
29
+ ZIP_UPLOADER_NOT_REACHABLE:
30
+ "Could not reach BrowserStack APIs. Please check your network or see if you need to whitelist *.browserstack.com",
22
31
  ZIP_UPLOAD_FAILED: "Zip Upload failed.",
23
- ZIP_UPLOAD_LIMIT_EXCEEDED: "The directory size which contains the cypress config file is more than 200 MB. For more info, check out https://www.browserstack.com/docs/automate/cypress/exclude-files",
24
- NODE_MODULES_LIMIT_EXCEEDED: "node_modules upload failed as the size %SIZE% MB is not supported. Dependencies will be installed in runtime. This will have a negative impact on build performance. Reach out to us at browserstack.com/support if you see this warning.",
25
- CONFIG_FILE_CREATED: "BrowserStack Config File created, you can now run browserstack-cypress --config-file run",
26
- CONFIG_FILE_EXISTS: "File already exists, delete the browserstack.json file manually. skipping...",
27
- DIR_NOT_FOUND: "Given path does not exist. Failed to create browserstack.json in %s",
28
- MD5_CHECK_FAILED: "There was some issue while checking if zip is already uploaded.",
32
+ ZIP_UPLOAD_LIMIT_EXCEEDED:
33
+ "The directory size which contains the cypress config file is more than 200 MB. For more info, check out https://www.browserstack.com/docs/automate/cypress/exclude-files",
34
+ NODE_MODULES_LIMIT_EXCEEDED:
35
+ "node_modules upload failed as the size %SIZE% MB is not supported. Dependencies will be installed in runtime. This will have a negative impact on build performance. Reach out to us at browserstack.com/support if you see this warning.",
36
+ CONFIG_FILE_CREATED:
37
+ "BrowserStack Config File created, you can now run browserstack-cypress --config-file run",
38
+ CONFIG_FILE_EXISTS:
39
+ "File already exists, delete the browserstack.json file manually. skipping...",
40
+ DIR_NOT_FOUND:
41
+ "Given path does not exist. Failed to create browserstack.json in %s",
42
+ MD5_CHECK_FAILED:
43
+ "There was some issue while checking if zip is already uploaded.",
29
44
  ZIP_DELETE_FAILED: "Could not delete tests.zip successfully.",
30
45
  ZIP_DELETED: "Deleted tests.zip successfully.",
31
- NPM_INSTALL_AND_UPLOAD: "Installing required dependencies and building the package to upload to BrowserStack",
46
+ NPM_INSTALL_AND_UPLOAD:
47
+ "Installing required dependencies and building the package to upload to BrowserStack",
32
48
  NPM_DELETE_FAILED: "Could not delete the dependency packages.",
33
49
  NPM_DELETED: "Deleted dependency packages successfully.",
34
- API_DEPRECATED: "This version of API is deprecated, please use latest version of API.",
50
+ API_DEPRECATED:
51
+ "This version of API is deprecated, please use latest version of API.",
35
52
  FAILED_TO_ZIP: "Failed to zip files.",
36
- FAILED_CREATE_NPM_ARCHIVE: "CLI execution failed due to some issue in npm setup. Please retry.",
37
- FAILED_MD5_CHECK: "Something went wrong - you can retry running browserstack-cypress with ‘--force-upload’ parameter, or contact BrowserStack Support.",
53
+ FAILED_CREATE_NPM_ARCHIVE:
54
+ "CLI execution failed due to some issue in npm setup. Please retry.",
55
+ FAILED_MD5_CHECK:
56
+ "Something went wrong - you can retry running browserstack-cypress with ‘--force-upload’ parameter, or contact BrowserStack Support.",
38
57
  VISIT_DASHBOARD: "Visit the Automate dashboard for real-time test reporting:",
39
- CONFLICTING_INIT_ARGUMENTS: "Conflicting arguments given. You can use --path only with a file name, and not with a file path.",
40
- NO_PARALLELS: "Your specs will run sequentially on a single machine. Read more about running your specs in parallel here: https://www.browserstack.com/docs/automate/cypress/run-tests-in-parallel",
41
- NO_NPM_DEPENDENCIES: "No npm dependencies specified - your specs might fail if they need any packages to be installed before running.",
42
- NO_NPM_DEPENDENCIES_READ_MORE: "Read more about npm dependencies here: https://www.browserstack.com/docs/automate/cypress/npm-packages. You can suppress this warning by using --disable-npm-warning flag.",
58
+ CONFLICTING_INIT_ARGUMENTS:
59
+ "Conflicting arguments given. You can use --path only with a file name, and not with a file path.",
60
+ NO_PARALLELS:
61
+ "Your specs will run sequentially on a single machine. Read more about running your specs in parallel here: https://www.browserstack.com/docs/automate/cypress/run-tests-in-parallel",
62
+ NO_NPM_DEPENDENCIES:
63
+ "No npm dependencies specified - your specs might fail if they need any packages to be installed before running.",
64
+ NO_NPM_DEPENDENCIES_READ_MORE:
65
+ "Read more about npm dependencies here: https://www.browserstack.com/docs/automate/cypress/npm-packages. You can suppress this warning by using --disable-npm-warning flag.",
43
66
  VALIDATING_CONFIG: "Validating the config",
44
67
  UPLOADING_TESTS: "Uploading the tests to BrowserStack",
45
68
  UPLOADING_TESTS_SUCCESS: "Uploaded tests successfully",
46
69
  UPLOADING_NPM_PACKAGES: "Uploading required node_modules to BrowserStack",
47
70
  UPLOADING_NPM_PACKAGES_SUCCESS: "Uploaded node_modules successfully",
48
- SKIP_UPLOADING_TESTS: "Skipping zip upload since BrowserStack already has your test suite that has not changed since the last run.",
49
- SKIP_UPLOADING_NPM_PACKAGES: "Skipping the upload of node_modules since BrowserStack has already cached your npm dependencies that have not changed since the last run.",
71
+ SKIP_UPLOADING_TESTS:
72
+ "Skipping zip upload since BrowserStack already has your test suite that has not changed since the last run.",
73
+ SKIP_UPLOADING_NPM_PACKAGES:
74
+ "Skipping the upload of node_modules since BrowserStack has already cached your npm dependencies that have not changed since the last run.",
50
75
  LOCAL_TRUE: "you will now be able to test localhost / private URLs",
51
76
  LOCAL_FALSE: "you won't be able to test localhost / private URLs",
52
- EXIT_SYNC_CLI_MESSAGE: "Exiting the CLI, but your build is still running. You can use the --sync option to keep getting test updates. You can also use the build-info <build-id> command now.",
77
+ EXIT_SYNC_CLI_MESSAGE:
78
+ "Exiting the CLI, but your build is still running. You can use the --sync option to keep getting test updates. You can also use the build-info <build-id> command now.",
53
79
  FATAL_NETWORK_ERROR: `fatal: unable to access '${config.buildUrl}': Could not resolve host: ${config.rails_host}`,
54
80
  RETRY_LIMIT_EXCEEDED: `Max retries exceeded trying to connect to the host (retries: ${config.retries})`,
55
81
  CHECK_DASHBOARD_AT: "Please check the build status at: ",
56
- CYPRESS_VERSION_CHANGED: "Your build will run using Cypress <actualVersion> instead of Cypress <preferredVersion>.<frameworkUpgradeMessage> Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
82
+ CYPRESS_VERSION_CHANGED:
83
+ "Your build will run using Cypress <actualVersion> instead of Cypress <preferredVersion>.<frameworkUpgradeMessage> Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
57
84
  LOCAL_START_FAILED: "Local Testing setup failed.",
58
85
  LOCAL_STOP_FAILED: "Local Binary stop failed.",
59
- INVALID_LOCAL_MODE_WARNING: "Invalid value specified for local_mode. local_mode: (\"always-on\" | \"on-demand\"). For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
60
- LOCAL_BINARY_ALREADY_RUNNING: "We found an existing BrowserStack Local connection running from your account. Using the existing connection for this build. If you wish to use a new Local connection for your build, please specify a value for 'local_identifier' within 'connection_settings' in your browserstack.json config.",
61
- SPEC_LIMIT_WARNING: "You might not see all your results on the dashboard because of high spec count, please consider reducing the number of spec files in this folder.",
62
- DOWNLOAD_BUILD_ARTIFACTS_FAILED: "Downloading build artifacts for the build <build-id> failed for <machine-count> machines.",
63
- ASYNC_DOWNLOADS: "Test artifacts as specified under 'downloads' can be downloaded after the build has completed its run, using 'browserstack-cypress generate-downloads <build-id>'",
64
- DOWNLOAD_BUILD_ARTIFACTS_SUCCESS: "Your build artifact(s) have been successfully downloaded in '<user-path>/build_artifacts/<build-id>' directory",
65
- LATEST_SYNTAX_TO_ACTUAL_VERSION_MESSAGE: "Your build will run using Cypress <actualVersion> as you had specified <latestSyntaxVersion>.<frameworkUpgradeMessage> Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
66
- PROCESS_KILL_MESSAGE: "Stopping the CLI and the execution of the build on BrowserStack",
67
- BUILD_FAILED_ERROR: "The above stacktrace has been thrown by Cypress when we tried to run your build. If your test suite requires npm dependencies then please specify them on browserstack.json. Read more at " + chalk.blueBright("https://www.browserstack.com/docs/automate/cypress/npm-packages") + ". Also, we recommend you to try running the build locally using ‘cypress run’ and if it works fine then please reach out to support at " + chalk.blueBright("https://www.browserstack.com/contact#technical-support"),
68
- SPEC_TIMEOUT_LIMIT_WARNING: "Value for the 'spec_timeout' key not in the 1-120 range. Going ahead with 30 mins as the default spec timeout. Read more about how to specify the option in https://browserstack.com/docs/automate/cypress/spec-timeout",
69
- SPEC_LIMIT_SUCCESS_MESSAGE: "Spec timeout specified as <x> minutes. If any of your specs exceed the specified time limit, it would be forcibly killed by BrowserStack"
86
+ INVALID_LOCAL_MODE_WARNING:
87
+ 'Invalid value specified for local_mode. local_mode: ("always-on" | "on-demand"). For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference',
88
+ LOCAL_BINARY_ALREADY_RUNNING:
89
+ "We found an existing BrowserStack Local connection running from your account. Using the existing connection for this build. If you wish to use a new Local connection for your build, please specify a value for 'local_identifier' within 'connection_settings' in your browserstack.json config.",
90
+ SPEC_LIMIT_WARNING:
91
+ "You might not see all your results on the dashboard because of high spec count, please consider reducing the number of spec files in this folder.",
92
+ DOWNLOAD_BUILD_ARTIFACTS_FAILED:
93
+ "Downloading build artifacts for the build <build-id> failed for <machine-count> machines.",
94
+ ASYNC_DOWNLOADS:
95
+ "Test artifacts as specified under 'downloads' can be downloaded after the build has completed its run, using 'browserstack-cypress generate-downloads <build-id>'",
96
+ DOWNLOAD_BUILD_ARTIFACTS_SUCCESS:
97
+ "Your build artifact(s) have been successfully downloaded in '<user-path>/build_artifacts/<build-id>' directory",
98
+ LATEST_SYNTAX_TO_ACTUAL_VERSION_MESSAGE:
99
+ "Your build will run using Cypress <actualVersion> as you had specified <latestSyntaxVersion>.<frameworkUpgradeMessage> Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
100
+ PROCESS_KILL_MESSAGE:
101
+ "Stopping the CLI and the execution of the build on BrowserStack",
102
+ BUILD_FAILED_ERROR:
103
+ "The above stacktrace has been thrown by Cypress when we tried to run your build. If your test suite requires npm dependencies then please specify them on browserstack.json. Read more at " +
104
+ chalk.blueBright(
105
+ "https://www.browserstack.com/docs/automate/cypress/npm-packages"
106
+ ) +
107
+ ". Also, we recommend you to try running the build locally using ‘cypress run’ and if it works fine then please reach out to support at " +
108
+ chalk.blueBright("https://www.browserstack.com/contact#technical-support"),
109
+ SPEC_TIMEOUT_LIMIT_WARNING:
110
+ "Value for the 'spec_timeout' key not in the 1-120 range. Going ahead with 30 mins as the default spec timeout. Read more about how to specify the option in https://browserstack.com/docs/automate/cypress/spec-timeout",
111
+ SPEC_LIMIT_SUCCESS_MESSAGE:
112
+ "Spec timeout specified as <x> minutes. If any of your specs exceed the specified time limit, it would be forcibly killed by BrowserStack",
70
113
  };
71
114
 
72
115
  const validationMessages = {
@@ -75,36 +118,62 @@ const validationMessages = {
75
118
  EMPTY_TEST_SUITE: "Test suite is empty",
76
119
  EMPTY_BROWSERSTACK_JSON: "Empty browserstack.json",
77
120
  EMPTY_RUN_SETTINGS: "Empty run settings",
78
- EMPTY_CYPRESS_PROJ_DIR: "cypress_proj_dir is not set in run_settings. See https://www.browserstack.com/docs/automate/cypress/sample-tutorial to learn more.",
121
+ EMPTY_CYPRESS_PROJ_DIR:
122
+ "cypress_proj_dir is not set in run_settings. See https://www.browserstack.com/docs/automate/cypress/sample-tutorial to learn more.",
79
123
  VALIDATED: "browserstack.json file is validated",
80
124
  NOT_VALID: "browerstack.json is not valid",
81
125
  NOT_VALID_JSON: "browerstack.json is not a valid json",
82
126
  INVALID_EXTENSION: "Invalid files, please remove these files and try again.",
83
- INVALID_PARALLELS_CONFIGURATION: "Invalid value specified for parallels to use. Maximum parallels to use should be a number greater than 0.",
127
+ INVALID_PARALLELS_CONFIGURATION:
128
+ "Invalid value specified for parallels to use. Maximum parallels to use should be a number greater than 0.",
84
129
  INVALID_CYPRESS_CONFIG_FILE: "Invalid cypress_config_file",
85
- CYPRESS_JSON_NOT_FOUND: "cypress.json file is not found at cypress_proj_dir path ",
130
+ CYPRESS_JSON_NOT_FOUND:
131
+ "cypress.json file is not found at cypress_proj_dir path ",
86
132
  INVALID_CYPRESS_JSON: "cypress.json is not a valid json",
87
- INVALID_DEFAULT_AUTH_PARAMS: "Your username and access key are required to run your tests on BrowserStack. Learn more at https://www.browserstack.com/docs/automate/cypress/authentication",
88
- LOCAL_NOT_SET: "To test <baseUrlValue> on BrowserStack, you will have to set up Local testing. Read more here: https://www.browserstack.com/docs/automate/cypress/local-testing",
89
- INCORRECT_DIRECTORY_STRUCTURE: "No tests to run. Note that your Cypress tests should be in the same directory where the cypress.json exists.",
90
- INVALID_CLI_LOCAL_IDENTIFIER: "When using --local-identifier, a value needs to be supplied. \n--local-identifier <String>.\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
91
- INVALID_LOCAL_MODE: "When using --local-mode, a value needs to be supplied. \n--local-mode (\"always-on\" | \"on-demand\").\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
92
- INVALID_LOCAL_CONFIG_FILE: "Using --local-config-file requires an input of the form /path/to/config-file.yml.\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
93
- INVALID_LOCAL_IDENTIFIER: "Invalid value specified for local_identifier. For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
94
- INVALID_BROWSER_ARGS: "Aborting as an unacceptable value was passed for --browser. Read more at https://www.browserstack.com/docs/automate/cypress/cli-reference",
95
- INVALID_LOCAL_ASYNC_ARGS: "Cannot run in --async mode when local is set to true. Please run the build after removing --async",
96
- INVALID_GEO_LOCATION: "[BROWSERSTACK_INVALID_COUNTRY_CODE] The country code specified for 'geolocation' is invalid. For list of supported countries, refer to - https://www.browserstack.com/ip-geolocation",
97
- NOT_SUPPORTED_GEO_LOCATION: "The country code you have passed for IP Geolocation is currently not supported. Please refer the link https://www.browserstack.com/ip-geolocation for a list of supported countries.",
98
- NOT_AVAILABLE_GEO_LOCATION: "The country code you have passed for IP Geolocation is not available at the moment. Please try again in a few hours.",
99
- ACCESS_DENIED_GEO_LOCATION: "'geolocation' (IP Geolocation feature) capability is not supported in your account. It is only available under Enterprise plans, refer https://www.browserstack.com/ip-geolocation for more details.",
100
- NOT_ALLOWED_GEO_LOCATION_AND_LOCAL_MODE: "IP Geolocation feature is not available in conjunction with BrowserStack Local.",
101
- HOME_DIRECTORY_NOT_FOUND: "Specified home directory could not be found. Please make sure the path of the home directory is correct.",
102
- HOME_DIRECTORY_NOT_A_DIRECTORY: "Specified home directory is not a directory. The home directory can only be a directory and not a file.",
103
- CYPRESS_CONFIG_FILE_NOT_PART_OF_HOME_DIRECTORY: "Could not find cypress.json within the specified home directory. Please make sure cypress.json resides within the home directory.",
104
- SPEC_TIMEOUT_LIMIT_ERROR: "The maximum allowed value of 'spec_timeout' is 120. Read more on https://browserstack.com/docs/automate/cypress/spec-timeout ",
105
- SPEC_TIMEOUT_NOT_PASSED_ERROR: "'spec_timeout' key not specified. Going ahead with 30 mins as the default spec timeout. Read more about how to specify the option in https://browserstack.com/docs/automate/cypress/spec-timeout ",
106
- PROJECT_ID_MISSING: "You have specified '--record' flag but you've not provided the 'projectId' in cypress.json or in browserstack.json. Your record functionality on cypress.io dashboard might not work as it needs both the key and the projectId",
107
- RECORD_KEY_MISSING: "You have specified '--record' flag but you've not provided the '--record-key' and we could not find any value in 'CYPRESS_RECORD_KEY' environment variable. Your record functionality on cypress.io dashboard might not work as it needs the key and projectId"
133
+ INVALID_DEFAULT_AUTH_PARAMS:
134
+ "Your username and access key are required to run your tests on BrowserStack. Learn more at https://www.browserstack.com/docs/automate/cypress/authentication",
135
+ LOCAL_NOT_SET:
136
+ "To test <baseUrlValue> on BrowserStack, you will have to set up Local testing. Read more here: https://www.browserstack.com/docs/automate/cypress/local-testing",
137
+ INCORRECT_DIRECTORY_STRUCTURE:
138
+ "No tests to run. Note that your Cypress tests should be in the same directory where the cypress.json exists.",
139
+ INVALID_CLI_LOCAL_IDENTIFIER:
140
+ "When using --local-identifier, a value needs to be supplied. \n--local-identifier <String>.\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
141
+ INVALID_LOCAL_MODE:
142
+ 'When using --local-mode, a value needs to be supplied. \n--local-mode ("always-on" | "on-demand").\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference',
143
+ INVALID_LOCAL_CONFIG_FILE:
144
+ "Using --local-config-file requires an input of the form /path/to/config-file.yml.\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
145
+ INVALID_LOCAL_IDENTIFIER:
146
+ "Invalid value specified for local_identifier. For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
147
+ INVALID_BROWSER_ARGS:
148
+ "Aborting as an unacceptable value was passed for --browser. Read more at https://www.browserstack.com/docs/automate/cypress/cli-reference",
149
+ INVALID_LOCAL_ASYNC_ARGS:
150
+ "Cannot run in --async mode when local is set to true. Please run the build after removing --async",
151
+ INVALID_GEO_LOCATION:
152
+ "[BROWSERSTACK_INVALID_COUNTRY_CODE] The country code specified for 'geolocation' is invalid. For list of supported countries, refer to - https://www.browserstack.com/ip-geolocation",
153
+ NOT_SUPPORTED_GEO_LOCATION:
154
+ "The country code you have passed for IP Geolocation is currently not supported. Please refer the link https://www.browserstack.com/ip-geolocation for a list of supported countries.",
155
+ NOT_AVAILABLE_GEO_LOCATION:
156
+ "The country code you have passed for IP Geolocation is not available at the moment. Please try again in a few hours.",
157
+ ACCESS_DENIED_GEO_LOCATION:
158
+ "'geolocation' (IP Geolocation feature) capability is not supported in your account. It is only available under Enterprise plans, refer https://www.browserstack.com/ip-geolocation for more details.",
159
+ NOT_ALLOWED_GEO_LOCATION_AND_LOCAL_MODE:
160
+ "IP Geolocation feature is not available in conjunction with BrowserStack Local.",
161
+ HOME_DIRECTORY_NOT_FOUND:
162
+ "Specified home directory could not be found. Please make sure the path of the home directory is correct.",
163
+ HOME_DIRECTORY_NOT_A_DIRECTORY:
164
+ "Specified home directory is not a directory. The home directory can only be a directory and not a file.",
165
+ CYPRESS_CONFIG_FILE_NOT_PART_OF_HOME_DIRECTORY:
166
+ "Could not find cypress.json within the specified home directory. Please make sure cypress.json resides within the home directory.",
167
+ SPEC_TIMEOUT_LIMIT_ERROR:
168
+ "The maximum allowed value of 'spec_timeout' is 120. Read more on https://browserstack.com/docs/automate/cypress/spec-timeout ",
169
+ SPEC_TIMEOUT_NOT_PASSED_ERROR:
170
+ "'spec_timeout' key not specified. Going ahead with 30 mins as the default spec timeout. Read more about how to specify the option in https://browserstack.com/docs/automate/cypress/spec-timeout ",
171
+ PROJECT_ID_MISSING:
172
+ "You have specified '--record' flag but you've not provided the 'projectId' in cypress.json or in browserstack.json. Your record functionality on cypress.io dashboard might not work as it needs both the key and the projectId",
173
+ RECORD_KEY_MISSING:
174
+ "You have specified '--record' flag but you've not provided the '--record-key' and we could not find any value in 'CYPRESS_RECORD_KEY' environment variable. Your record functionality on cypress.io dashboard might not work as it needs the key and projectId",
175
+ NODE_VERSION_PARSING_ERROR:
176
+ "We weren't able to successfully parse the specified nodeVersion. We will be using the default nodeVersion to run your tests.",
108
177
  };
109
178
 
110
179
  const cliMessages = {
@@ -125,37 +194,48 @@ const cliMessages = {
125
194
  STOP_MESSAGE: "Stopping build with given buildId ",
126
195
  },
127
196
  RUN: {
128
- PARALLEL_DESC: "The maximum number of parallels to use to run your test suite",
197
+ PARALLEL_DESC:
198
+ "The maximum number of parallels to use to run your test suite",
129
199
  INFO: "Run your tests on BrowserStack. For more help: `browserstack-cypress run --help`.",
130
200
  CYPRESS_DESC: "Path to Cypress config file",
131
201
  CYPRESS_CONFIG_DEMAND: "Cypress config file is required",
132
202
  BUILD_NAME: "The build name you want to use to name your test runs",
133
203
  EXCLUDE: "Exclude files matching a pattern from zipping and uploading",
134
- DEFAULT_PARALLEL_MESSAGE: "Here goes the number of parallels you want to run",
204
+ DEFAULT_PARALLEL_MESSAGE:
205
+ "Here goes the number of parallels you want to run",
135
206
  SPECS_DESCRIPTION: "Specify the spec files to run",
136
207
  ENV_DESCRIPTION: "Specify the environment variables for your spec files",
137
208
  SYNC_DESCRIPTION: "Makes the run command in sync",
138
209
  ASYNC_DESCRIPTION: "Makes the run command in async",
139
210
  BUILD_REPORT_MESSAGE: "See the entire build report here",
140
211
  HEADED: "Run your tests in a headed browser instead of a headless browser",
141
- LOCAL: "Accepted values: (true | false) - create a local testing connection to let you test staging and localhost websites, or sites behind proxies; learn more at browserstack.com/local-testing",
142
- LOCAL_MODE: 'Accepted values: ("always-on" | "on-demand") - if you choose to keep the binary "always-on", it will speed up your tests by keeping the Local connection warmed up in the background; otherwise, you can choose to have it spawn and killed for every build',
143
- LOCAL_IDENTIFIER: "Accepted values: String - assign an identifier to your Local process instance",
144
- LOCAL_CONFIG_FILE: "Accepted values: String - path to local config-file to your Local process instance. Learn more at https://www.browserstack.com/local-testing/binary-params",
145
- SYNC_NO_WRAP: "Wrap the spec names in --sync mode in case of smaller terminal window size pass --no-wrap",
212
+ LOCAL:
213
+ "Accepted values: (true | false) - create a local testing connection to let you test staging and localhost websites, or sites behind proxies; learn more at browserstack.com/local-testing",
214
+ LOCAL_MODE:
215
+ 'Accepted values: ("always-on" | "on-demand") - if you choose to keep the binary "always-on", it will speed up your tests by keeping the Local connection warmed up in the background; otherwise, you can choose to have it spawn and killed for every build',
216
+ LOCAL_IDENTIFIER:
217
+ "Accepted values: String - assign an identifier to your Local process instance",
218
+ LOCAL_CONFIG_FILE:
219
+ "Accepted values: String - path to local config-file to your Local process instance. Learn more at https://www.browserstack.com/local-testing/binary-params",
220
+ SYNC_NO_WRAP:
221
+ "Wrap the spec names in --sync mode in case of smaller terminal window size pass --no-wrap",
146
222
  BROWSER_DESCRIPTION: "Specify the browsers you need to run your tests on.",
147
- CONFIG_DESCRIPTION: "Set configuration values. Separate multiple values with a comma. The values set here override any values set in your configuration file.",
223
+ CONFIG_DESCRIPTION:
224
+ "Set configuration values. Separate multiple values with a comma. The values set here override any values set in your configuration file.",
148
225
  REPORTER: "Specify the custom reporter to use",
149
226
  REPORTER_OPTIONS: "Specify reporter options for custom reporter",
150
227
  CYPRESS_GEO_LOCATION: "Enterprise feature to simulate website and mobile behavior from different locations.",
151
228
  SPEC_TIMEOUT: "Specify a value for a hard timeout for each spec execution in the 1-120 mins range. Read https://browserstack.com/docs/automate/cypress/spec-timeout for more details.",
152
229
  RECORD: "Pass the --record flag to record your Cypress runs on Cypress.io dashboard. Note: You also need to specify '--record-key' and '--projectId' arguments either in CLI or in browserstack.json.",
153
230
  RECORD_KEY: "You can specify the 'key' that is needed to record your runs on Cypress.io dashboard using the '--record-key' argument. Alternatively, you can also pass it on browserstack.json",
154
- PROJECT_ID: "You can pass the 'projectId' of your Cypress.io project where you want to record your runs if specifying the '--record' key. You can also specify this in your cypress.json or in your browserstack.json."
231
+ PROJECT_ID: "You can pass the 'projectId' of your Cypress.io project where you want to record your runs if specifying the '--record' key. You can also specify this in your cypress.json or in your browserstack.json.",
232
+ NODE_VERSION: "Pass the node version that you want BrowserStack to use to run your Cypress tests on.",
233
+ BUILD_TAG: "Add a tag to your build to filter builds based on tag values on the Dashboard."
155
234
  },
156
235
  COMMON: {
157
236
  DISABLE_USAGE_REPORTING: "Disable usage reporting",
158
- FORCE_UPLOAD: "Force the upload of your test files even if BrowserStack has detected no changes in your suite since you last ran",
237
+ FORCE_UPLOAD:
238
+ "Force the upload of your test files even if BrowserStack has detected no changes in your suite since you last ran",
159
239
  USERNAME: "Your BrowserStack username",
160
240
  ACCESS_KEY: "Your BrowserStack access key",
161
241
  NO_NPM_WARNING: "No NPM warning if npm_dependencies is empty",
@@ -164,10 +244,10 @@ const cliMessages = {
164
244
  DEBUG: "Use this option to get debug logs on the CLI console.",
165
245
  },
166
246
  GENERATE_REPORT: {
167
- INFO: "Generates the build report"
247
+ INFO: "Generates the build report",
168
248
  },
169
249
  GENERATE_DOWNLOADS: {
170
- INFO: "Downloads the build artifacts"
250
+ INFO: "Downloads the build artifacts",
171
251
  },
172
252
  };
173
253
 
@@ -177,70 +257,112 @@ const messageTypes = {
177
257
  INFO: "info",
178
258
  WARNING: "warning",
179
259
  UNKNOWN: "unknown",
180
- NULL: null
181
- }
260
+ NULL: null,
261
+ };
182
262
 
183
- const allowedFileTypes = ['js', 'json', 'txt', 'ts', 'feature', 'features', 'pdf', 'jpg', 'jpeg', 'png', 'zip', 'npmrc', 'xml', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'jsx', 'coffee', 'cjsx', 'csv', 'tsv', 'yml', 'yaml', 'env', 'mov', 'mp4', 'mp3', 'wav', 'gz', 'tgz', 'tiff', 'bmp', 'msg', 'gif', 'sql'];
263
+ const allowedFileTypes = [
264
+ "js",
265
+ "json",
266
+ "txt",
267
+ "ts",
268
+ "feature",
269
+ "features",
270
+ "pdf",
271
+ "jpg",
272
+ "jpeg",
273
+ "png",
274
+ "zip",
275
+ "npmrc",
276
+ "xml",
277
+ "doc",
278
+ "docx",
279
+ "ppt",
280
+ "pptx",
281
+ "xls",
282
+ "xlsx",
283
+ "jsx",
284
+ "coffee",
285
+ "cjsx",
286
+ "csv",
287
+ "tsv",
288
+ "yml",
289
+ "yaml",
290
+ "env",
291
+ "mov",
292
+ "mp4",
293
+ "mp3",
294
+ "wav",
295
+ "gz",
296
+ "tgz",
297
+ "tiff",
298
+ "bmp",
299
+ "msg",
300
+ "gif",
301
+ "sql",
302
+ "pmc",
303
+ "pmp",
304
+ "max",
305
+ ];
184
306
 
185
307
  const filesToIgnoreWhileUploading = [
186
- '**/node_modules/**',
187
- 'node_modules/**',
188
- 'package-lock.json',
189
- 'package.json',
190
- 'browserstack-package.json',
191
- 'tests.zip',
192
- 'cypress.json',
193
- '.idea/**',
194
- '.vscode/**',
195
- '.npm/**',
196
- 'bstackPackages.tar.gz',
197
- 'tmpBstackPackages/**',
198
- '.yarn/**',
199
- 'build_artifacts/**'
308
+ "**/node_modules/**",
309
+ "node_modules/**",
310
+ "package-lock.json",
311
+ "package.json",
312
+ "browserstack-package.json",
313
+ "tests.zip",
314
+ "cypress.json",
315
+ ".idea/**",
316
+ ".vscode/**",
317
+ ".npm/**",
318
+ "bstackPackages.tar.gz",
319
+ "tmpBstackPackages/**",
320
+ ".yarn/**",
321
+ "build_artifacts/**",
200
322
  ];
201
323
 
202
324
  const readDirOptions = {
203
- cwd: '.',
325
+ cwd: ".",
204
326
  matchBase: true,
205
327
  ignore: [],
206
328
  dot: true,
207
329
  stat: true,
208
- pattern: ''
209
- }
330
+ pattern: "",
331
+ };
210
332
 
211
333
  const hashingOptions = {
212
334
  parallel: 10,
213
- algo: 'md5',
214
- encoding: 'hex',
335
+ algo: "md5",
336
+ encoding: "hex",
215
337
  };
216
338
 
217
339
  const packageInstallerOptions = {
218
340
  npmLoad: {
219
- loglevel: 'silent',
220
- only: 'dev',
221
- 'save-dev': true,
222
- 'only-dev': true,
223
- }
224
- }
341
+ loglevel: "silent",
342
+ only: "dev",
343
+ "save-dev": true,
344
+ "only-dev": true,
345
+ },
346
+ };
225
347
 
226
- const specFileTypes = ['js', 'ts', 'feature', 'jsx', 'coffee', 'cjsx'];
348
+ const specFileTypes = ["js", "ts", "feature", "jsx", "coffee", "cjsx"];
227
349
 
228
- const DEFAULT_CYPRESS_SPEC_PATH = "cypress/integration"
350
+ const DEFAULT_CYPRESS_SPEC_PATH = "cypress/integration";
229
351
 
230
352
  const SPEC_TOTAL_CHAR_LIMIT = 32243;
231
353
  const METADATA_CHAR_BUFFER_PER_SPEC = 175;
232
354
 
233
355
  const usageReportingConstants = {
234
- GENERATE_DOWNLOADS: 'generate-downloads called',
235
- }
356
+ GENERATE_DOWNLOADS: "generate-downloads called",
357
+ };
236
358
 
237
- const LATEST_VERSION_SYNTAX_REGEX = /\d*.latest(.\d*)?/gm
359
+ const LATEST_VERSION_SYNTAX_REGEX = /\d*.latest(.\d*)?/gm;
238
360
 
239
- const AUTH_REGEX = /"auth" *: *{[\s\S]*?}/g
361
+ const AUTH_REGEX = /"auth" *: *{[\s\S]*?}/g;
240
362
 
241
- const CLI_ARGS_REGEX = /(?<=("u"|"username"|"k"|"key") *: *)"[^,}]*/g
363
+ const CLI_ARGS_REGEX = /(?<=("u"|"username"|"k"|"key") *: *)"[^,}]*/g;
242
364
 
243
- const RAW_ARGS_REGEX = /(?<=("-u"|"-username"|"-k"|"-key") *, *)"[^,\]]*/g
365
+ const RAW_ARGS_REGEX = /(?<=("-u"|"-username"|"-k"|"-key") *, *)"[^,\]]*/g;
244
366
 
245
367
  const ERROR_EXIT_CODE = 1;
246
368
 
@@ -248,9 +370,9 @@ const BUILD_FAILED_EXIT_CODE = 3;
248
370
 
249
371
  const REDACTED = "[REDACTED]";
250
372
 
251
- const REDACTED_AUTH =`auth: { "username": ${REDACTED}, "access_key": ${REDACTED} }`;
373
+ const REDACTED_AUTH = `auth: { "username": ${REDACTED}, "access_key": ${REDACTED} }`;
252
374
 
253
- const SPEC_TIMEOUT_LIMIT = 120 // IN MINS
375
+ const SPEC_TIMEOUT_LIMIT = 120; // IN MINS
254
376
 
255
377
  const CYPRESS_CUSTOM_ERRORS_TO_PRINT_KEY = "custom_errors_to_print";
256
378
 
@@ -279,5 +401,5 @@ module.exports = Object.freeze({
279
401
  REDACTED,
280
402
  BUILD_FAILED_EXIT_CODE,
281
403
  SPEC_TIMEOUT_LIMIT,
282
- CYPRESS_CUSTOM_ERRORS_TO_PRINT_KEY
404
+ CYPRESS_CUSTOM_ERRORS_TO_PRINT_KEY,
283
405
  });
@@ -5,8 +5,9 @@
5
5
  fileHelpers = require('./fileHelpers'),
6
6
  logger = require("./logger").winstonLogger,
7
7
  Constants = require('./constants'),
8
- process = require('process'),
9
8
  utils = require('./utils'),
9
+ { get_version } = require('./usageReporting'),
10
+ process = require('process'),
10
11
  { spawn } = require('child_process'),
11
12
  util = require('util');
12
13
 
@@ -64,7 +65,7 @@ const packageInstall = (packageDir) => {
64
65
  logger.info(`Packages were installed locally successfully.`);
65
66
  resolve('Packages were installed successfully.');
66
67
  } else {
67
- logger.error(`Some error occurred while installing packages. Error code ${code}`);
68
+ logger.error(`Some error occurred while installing packages. Error code ${code}. Please read npm_install_debug.log for more info.`);
68
69
  reject(`Packages were not installed successfully. Error code ${code}`);
69
70
  }
70
71
  };
@@ -72,7 +73,22 @@ const packageInstall = (packageDir) => {
72
73
  logger.error(`Some error occurred while installing packages: %j`, error);
73
74
  reject(`Packages were not installed successfully. Error Description ${util.format('%j', error)}`);
74
75
  };
75
- nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true});
76
+
77
+ let nodeProcess;
78
+ logger.debug(`Fetching npm version and its major version`);
79
+ const npm_version = get_version('npm')
80
+ const npm_major_version = utils.getMajorVersion(npm_version);
81
+ logger.debug(`Fetched npm version: ${npm_version} and its major version: ${npm_major_version}`);
82
+
83
+ // add --legacy-peer-deps flag while installing dependencies for npm v7+
84
+ // For more info please read "Peer Dependencies" section here -> https://github.blog/2021-02-02-npm-7-is-now-generally-available/
85
+ if (parseInt(npm_major_version) >= 7) {
86
+ logger.debug(`Running NPM install command: npm install --legacy-peer-deps --loglevel verbose > ../npm_install_debug.log`);
87
+ nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--legacy-peer-deps', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true});
88
+ } else {
89
+ logger.debug(`Running NPM install command: 'npm install --loglevel verbose > ../npm_install_debug.log'`);
90
+ nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install', '--loglevel', 'verbose', '>', '../npm_install_debug.log', '2>&1'], {cwd: packageDir, shell: true});
91
+ }
76
92
  nodeProcess.on('close', nodeProcessCloseCallback);
77
93
  nodeProcess.on('error', nodeProcessErrorCallback);
78
94
  });
@@ -1,93 +1,12 @@
1
1
  const fs = require('fs'),
2
2
  path = require('path'),
3
3
  request = require('request'),
4
+ unzipper = require('unzipper'),
4
5
  logger = require('./logger').winstonLogger,
5
6
  utils = require("./utils"),
6
7
  Constants = require('./constants'),
7
8
  config = require("./config");
8
9
 
9
- let templatesDir = path.join(__dirname, '../', 'templates');
10
-
11
- function loadInlineCss() {
12
- return loadFile(path.join(templatesDir, 'assets', 'browserstack-cypress-report.css'));
13
- }
14
-
15
- function loadFile(fileName) {
16
- return fs.readFileSync(fileName, 'utf8');
17
- }
18
-
19
- function createBodyBuildHeader(report_data){
20
- let projectNameSpan = `<span class='project-name'> ${report_data.project_name} </span>`;
21
- let buildNameSpan = `<span class='build-name'> ${report_data.build_name} </span>`;
22
- let buildMeta = `<div class='build-meta'> ${buildNameSpan} ${projectNameSpan} </div>`;
23
- let buildLink = `<div class='build-link'> <a href='${report_data.build_url}' rel='noreferrer noopener' target='_blank'> View on BrowserStack </a> </div>`;
24
- let buildHeader = `<div class='build-header'> ${buildMeta} ${buildLink} </div>`;
25
- return buildHeader;
26
- }
27
-
28
- function createBodyBuildTable(report_data) {
29
- let specs = Object.keys(report_data.rows),
30
- specRow = '',
31
- specSessions = '',
32
- sessionBlocks = '',
33
- specData,
34
- specNameSpan,
35
- specPathSpan,
36
- specStats,
37
- specStatsSpan,
38
- specMeta,
39
- sessionStatus,
40
- sessionClass,
41
- sessionStatusIcon,
42
- sessionLink;
43
-
44
- specs.forEach((specName) => {
45
- specData = report_data.rows[specName];
46
-
47
- specNameSpan = `<span class='spec-name'> ${specName} </span>`;
48
- specPathSpan = `<span class='spec-path'> ${specData.path} </span>`;
49
-
50
- specStats = buildSpecStats(specData.meta);
51
- specStatsSpan = `<span class='spec-stats ${specStats.cssClass}'> ${specStats.label} </span>`;
52
-
53
- specMeta = `<div class='spec-meta'> ${specNameSpan} ${specPathSpan} ${specStatsSpan} </div>`;
54
- sessionBlocks = '';
55
- specData.sessions.forEach((specSession) => {
56
-
57
- sessionStatus = specSession.status;
58
- sessionClass = sessionStatus === 'passed' ? 'session-passed' : 'session-failed';
59
- sessionStatusIcon = sessionStatus === 'passed' ? "&#10004; " : "&#x2717; ";
60
-
61
- sessionLink = `<a href="${specSession.link}" rel="noreferrer noopener" target="_blank"> ${sessionStatusIcon} ${specSession.name} </a>`;
62
-
63
- sessionDetail = `<div class="session-detail ${sessionClass}"> ${sessionLink} </div>`;
64
- sessionBlocks = `${sessionBlocks} ${sessionDetail}`;
65
- });
66
- specSessions = `<div class='spec-sessions'> ${sessionBlocks} </div>`;
67
- specRow = `${specRow} <div class='spec-row'> ${specMeta} ${specSessions} </div>`;
68
- });
69
-
70
-
71
- return `<div class='build-table'> ${specRow} </div>`;
72
- }
73
-
74
- function buildSpecStats(specMeta) {
75
- let failedSpecs = specMeta.failed,
76
- passedSpecs = specMeta.passed,
77
- totalSpecs = specMeta.total,
78
- specStats = {};
79
-
80
- if (failedSpecs) {
81
- specStats.label = `${failedSpecs}/${totalSpecs} FAILED`;
82
- specStats.cssClass = 'spec-stats-failed';
83
- } else {
84
- specStats.label = `${passedSpecs}/${totalSpecs} PASSED`;
85
- specStats.cssClass = 'spec-stats-passed';
86
- }
87
-
88
- return specStats;
89
- }
90
-
91
10
  let reportGenerator = (bsConfig, buildId, args, rawArgs, buildReportData, cb) => {
92
11
  let options = {
93
12
  url: `${config.buildUrl}${buildId}/custom_report`,
@@ -100,6 +19,8 @@ let reportGenerator = (bsConfig, buildId, args, rawArgs, buildReportData, cb) =>
100
19
  },
101
20
  };
102
21
 
22
+ logger.debug('Started fetching the build json and html reports.');
23
+
103
24
  return request.get(options, async function (err, resp, body) {
104
25
  let message = null;
105
26
  let messageType = null;
@@ -117,6 +38,7 @@ let reportGenerator = (bsConfig, buildId, args, rawArgs, buildReportData, cb) =>
117
38
  utils.sendUsageReport(bsConfig, args, message, messageType, errorCode, buildReportData, rawArgs);
118
39
  return;
119
40
  } else {
41
+ logger.debug('Received reports data from upstream.');
120
42
  try {
121
43
  build = JSON.parse(body);
122
44
  } catch (error) {
@@ -127,7 +49,6 @@ let reportGenerator = (bsConfig, buildId, args, rawArgs, buildReportData, cb) =>
127
49
  if (resp.statusCode == 299) {
128
50
  messageType = Constants.messageTypes.INFO;
129
51
  errorCode = 'api_deprecated';
130
-
131
52
  if (build) {
132
53
  message = build.message;
133
54
  logger.info(message);
@@ -163,9 +84,10 @@ let reportGenerator = (bsConfig, buildId, args, rawArgs, buildReportData, cb) =>
163
84
  } else {
164
85
  messageType = Constants.messageTypes.SUCCESS;
165
86
  message = `Report for build: ${buildId} was successfully created.`;
166
- await renderReportHTML(build);
87
+ await generateCypressBuildReport(build);
167
88
  logger.info(message);
168
89
  }
90
+ logger.debug('Finished fetching the build json and html reports.');
169
91
  utils.sendUsageReport(bsConfig, args, message, messageType, errorCode, buildReportData, rawArgs);
170
92
  if (cb){
171
93
  cb();
@@ -173,199 +95,70 @@ let reportGenerator = (bsConfig, buildId, args, rawArgs, buildReportData, cb) =>
173
95
  });
174
96
  }
175
97
 
176
- async function renderReportHTML(report_data) {
177
- let resultsDir = 'results';
178
- let metaCharSet = `<meta charset="utf-8">`;
179
- let metaViewPort = `<meta name="viewport" content="width=device-width, initial-scale=1"> `;
180
- let pageTitle = `<title> BrowserStack Cypress Report </title>`;
181
- let inlineCss = `<style type="text/css"> ${loadInlineCss()} </style>`;
182
- let head = `<head> ${metaCharSet} ${metaViewPort} ${pageTitle} ${inlineCss} </head>`;
183
- let htmlOpenTag = `<!DOCTYPE HTML><html>`;
184
- let htmlClosetag = `</html>`;
185
- let bodyBuildHeader = createBodyBuildHeader(report_data);
186
- let bodyBuildTable = createBodyBuildTable(report_data);
187
- let bodyReporterContainer = `<div class='report-container'> ${bodyBuildHeader} ${bodyBuildTable} </div>`;
188
- let body = `<body> ${bodyReporterContainer} </body>`;
189
- let html = `${htmlOpenTag} ${head} ${body} ${htmlClosetag}`;
190
-
98
+ async function generateCypressBuildReport(report_data) {
99
+ let resultsDir = path.join('./', 'results');
191
100
 
192
101
  if (!fs.existsSync(resultsDir)){
102
+ logger.debug("Results directory doesn't exists.");
103
+ logger.debug("Creating results directory.");
193
104
  fs.mkdirSync(resultsDir);
194
105
  }
195
-
196
- // Writing the JSON used in creating the HTML file.
197
- let reportData = await cypressReportData(report_data);
198
- fs.writeFileSync(
199
- `${resultsDir}/browserstack-cypress-report.json`,
200
- JSON.stringify(reportData),
201
- () => {
202
- if (err) {
203
- return logger.error(err);
204
- }
205
- logger.info("The JSON file is saved");
206
- }
207
- );
208
-
209
- // Writing the HTML file generated from the JSON data.
210
- fs.writeFileSync(`${resultsDir}/browserstack-cypress-report.html`, html, () => {
211
- if(err) {
212
- return logger.error(err);
213
- }
214
- logger.info("The HTML file was saved!");
215
- });
216
- }
217
-
218
- async function cypressReportData(report_data) {
219
- specFiles = Object.keys(report_data.rows);
220
- combinationPromises = [];
221
- for (let spec of specFiles) {
222
- let specSessions = report_data.rows[spec]["sessions"];
223
- if (specSessions.length > 0) {
224
- for (let combination of specSessions) {
225
- if(utils.isUndefined(report_data.cypress_version) || report_data.cypress_version < "6"){
226
- combinationPromises.push(generateCypressCombinationSpecReportDataWithoutConfigJson(combination));
227
- }else{
228
- combinationPromises.push(generateCypressCombinationSpecReportDataWithConfigJson(combination));
229
- }
230
- }
231
- }
232
- }
233
- await Promise.all(combinationPromises);
234
- return report_data;
106
+ await getReportResponse(resultsDir, 'report.zip', report_data.cypress_custom_report_url);
235
107
  }
236
108
 
237
- function getConfigJsonResponse(combination) {
109
+ function getReportResponse(filePath, fileName, reportJsonUrl) {
110
+ let tmpFilePath = path.join(filePath, fileName);
111
+ const writer = fs.createWriteStream(tmpFilePath);
112
+ logger.debug(`Fetching build reports zip.`)
238
113
  return new Promise(async (resolve, reject) => {
239
- configJsonResponse = null;
240
- configJsonError = false
241
- request.get(combination.tests.config_json , function(err, resp, body) {
242
- if(err) {
243
- configJsonError = true;
244
- reject([configJsonResponse, configJsonError]);
245
- } else {
246
- if(resp.statusCode != 200) {
247
- configJsonError = true;
248
- reject([configJsonResponse, configJsonError]);
249
- } else {
250
- try {
251
- configJsonResponse = JSON.parse(body);
252
- } catch (err) {
253
- configJsonError = true
254
- reject([configJsonResponse, configJsonError]);
255
- }
256
- }
257
- }
258
- resolve([configJsonResponse, configJsonError]);
259
- });
260
- });
261
- }
114
+ request.get(reportJsonUrl).on('response', function(response) {
262
115
 
263
- function getResultsJsonResponse(combination) {
264
- return new Promise(async (resolve, reject) => {
265
- resultsJsonResponse = null
266
- resultsJsonError = false;
267
- request.get(combination.tests.result_json , function(err, resp, body) {
268
- if(err) {
269
- resultsJsonError = true;
270
- reject([resultsJsonResponse, resultsJsonError]);
116
+ if(response.statusCode != 200) {
117
+ let message = `Received non 200 response while fetching reports, code: ${response.statusCode}`;
118
+ reject(message);
271
119
  } else {
272
- if(resp.statusCode != 200) {
273
- resultsJsonError = true;
274
- reject([resultsJsonResponse, resultsJsonError]);
275
- } else {
276
- try {
277
- resultsJsonResponse = JSON.parse(body);
278
- } catch (err) {
279
- resultsJsonError = true
280
- reject([resultsJsonResponse, resultsJsonError]);
281
- }
282
- }
283
- }
284
- resolve([resultsJsonResponse, resultsJsonError]);
285
- });
286
- });
287
- }
288
-
289
- function generateCypressCombinationSpecReportDataWithConfigJson(combination){
290
- return new Promise(async (resolve, reject) => {
291
- try {
292
- let configJsonError, resultsJsonError;
293
- let configJson, resultsJson;
294
-
295
- await Promise.all([getConfigJsonResponse(combination), getResultsJsonResponse(combination)]).then(function (successResult) {
296
- [[configJson, configJsonError], [resultsJson, resultsJsonError]] = successResult;
297
- }).catch(function (failureResult) {
298
- [[configJson, configJsonError], [resultsJson, resultsJsonError]] = failureResult;
299
- });
300
-
301
- if(resultsJsonError || configJsonError){
302
- resolve();
303
- }
304
- let tests = {};
305
- if(utils.isUndefined(configJson.tests) || utils.isUndefined(resultsJson.tests)){
306
- resolve();
307
- }
308
- configJson.tests.forEach((test) => {
309
- tests[test["clientId"]] = test;
120
+ //ensure that the user can call `then()` only when the file has
121
+ //been downloaded entirely.
122
+ response.pipe(writer);
123
+ let error = null;
124
+ writer.on('error', err => {
125
+ error = err;
126
+ writer.close();
127
+ reject(err);
128
+ process.exitCode = Constants.ERROR_EXIT_CODE;
310
129
  });
311
- resultsJson.tests.forEach((test) => {
312
- tests[test["clientId"]] = Object.assign(
313
- tests[test["clientId"]],
314
- test
315
- );
316
- });
317
- let sessionTests = [];
318
- Object.keys(tests).forEach((testId) => {
319
- sessionTests.push({
320
- name: tests[testId]["title"].pop(),
321
- status: tests[testId]["state"],
322
- duration: parseFloat(
323
- tests[testId]["attempts"].pop()["wallClockDuration"] / 1000
324
- ).toFixed(2),
325
- });
130
+ writer.on('close', async () => {
131
+ if (!error) {
132
+ logger.debug("Unzipping downloaded html and json reports.");
133
+ unzipFile(filePath, fileName).then((msg) => {
134
+ logger.debug(msg);
135
+ fs.unlinkSync(tmpFilePath);
136
+ logger.debug("Successfully prepared json and html reports.");
137
+ resolve(true);
138
+ }).catch((err) =>{
139
+ logger.debug(`Unzipping html and json report failed. Error: ${err}`)
140
+ reject(true);
141
+ });
142
+ }
143
+ //no need to call the reject here, as it will have been called in the
144
+ //'error' stream;
326
145
  });
327
- combination.tests = sessionTests;
328
- resolve(combination.tests);
329
- } catch (error) {
330
- process.exitCode = Constants.ERROR_EXIT_CODE;
331
- reject(error);
332
146
  }
333
- })
147
+ });
148
+ });
334
149
  }
335
150
 
336
- function generateCypressCombinationSpecReportDataWithoutConfigJson(combination){
337
- return new Promise(async (resolve, reject) => {
338
- try {
339
- let resultsJson ,resultsJsonError;
340
- await getResultsJsonResponse(combination).then(function (successResult) {
341
- [resultsJson, resultsJsonError] = successResult
342
- }).catch( function (failureResult) {
343
- [resultsJson, resultsJsonError] = failureResult
344
- })
345
- if(resultsJsonError || utils.isUndefined(resultsJsonResponse)){
346
- resolve();
347
- }
348
- let sessionTests = [];
349
- if(utils.isUndefined(resultsJson.tests)){
350
- resolve();
351
- }
352
- resultsJson.tests.forEach((test) => {
353
- durationKey = utils.isUndefined(test["attempts"]) ? test : test["attempts"].pop()
354
- sessionTests.push({
355
- name: test["title"].pop(),
356
- status: test["state"],
357
- duration: parseFloat(
358
- durationKey["wallClockDuration"] / 1000
359
- ).toFixed(2)
360
- })
361
- });
362
- combination.tests = sessionTests;
363
- resolve(combination.tests);
364
- } catch (error) {
151
+ const unzipFile = async (filePath, fileName) => {
152
+ return new Promise( async (resolve, reject) => {
153
+ await unzipper.Open.file(path.join(filePath, fileName))
154
+ .then(d => d.extract({path: filePath, concurrency: 5}))
155
+ .catch((err) => {
156
+ reject(err);
365
157
  process.exitCode = Constants.ERROR_EXIT_CODE;
366
- reject(error);
367
- }
368
- })
158
+ });
159
+ let message = "Unzipped the json and html successfully."
160
+ resolve(message);
161
+ });
369
162
  }
370
163
 
371
164
  exports.reportGenerator = reportGenerator;
@@ -291,4 +291,5 @@ function send(args) {
291
291
  module.exports = {
292
292
  send,
293
293
  cli_version_and_path,
294
+ get_version
294
295
  };
@@ -371,6 +371,36 @@ exports.setRecordCaps = (bsConfig, args) => {
371
371
  bsConfig.run_settings["projectId"] = this.setProjectId(bsConfig, args);
372
372
  }
373
373
 
374
+ exports.verifyNodeVersionOption = () => {
375
+ let nvOptionsSet = (this.searchForOption('-nv') || this.searchForOption('--nv'));
376
+ let nodeVersionHyphenLocationOptionsSet = (this.searchForOption('-node-version') || this.searchForOption('--node-version'));
377
+ let nodeVersionOptionsSet = (this.searchForOption('-nodeVersion') || this.searchForOption('--nodeVersion'));
378
+ return (nvOptionsSet || nodeVersionHyphenLocationOptionsSet || nodeVersionOptionsSet);
379
+ }
380
+
381
+ exports.setNodeVersion = (bsConfig, args) => {
382
+ let userProvidedNodeVersion = this.verifyNodeVersionOption();
383
+ bsConfig.run_settings.userProvidedNodeVersion = (userProvidedNodeVersion || (!this.isUndefined(bsConfig.run_settings.nodeVersion)) || (!this.isUndefined(bsConfig.run_settings.nodeversion)));
384
+
385
+ if (bsConfig.run_settings.userProvidedNodeVersion) {
386
+ if(!this.isUndefined(args.nodeVersion)) {
387
+ bsConfig.run_settings.nodeVersion = args.nodeVersion;
388
+ } else if (!this.isUndefined(bsConfig.run_settings.nodeversion)) {
389
+ bsConfig.run_settings.nodeVersion = bsConfig.run_settings.nodeversion;
390
+ }
391
+ }
392
+
393
+ if (this.isUndefined(bsConfig.run_settings.nodeVersion)) {
394
+ bsConfig.run_settings.nodeVersion = usageReporting.get_version('node') || '';
395
+ }
396
+
397
+ if (bsConfig.run_settings.nodeVersion && typeof(bsConfig.run_settings.nodeVersion) === 'string' && bsConfig.run_settings.nodeVersion.charAt(0).toLowerCase() === 'v') {
398
+ bsConfig.run_settings.nodeVersion = bsConfig.run_settings.nodeVersion.substr(1);
399
+ }
400
+
401
+ logger.debug(`Setting nodeVersion = ${bsConfig.run_settings.nodeVersion}`);
402
+ }
403
+
374
404
  // specs can be passed from bstack configuration file
375
405
  // specs can be passed via command line args as a string
376
406
  // command line args takes precedence over config
@@ -414,6 +444,20 @@ exports.setTestEnvs = (bsConfig, args) => {
414
444
  logger.debug(`Setting env vars = ${bsConfig.run_settings.env}`);
415
445
  }
416
446
 
447
+ exports.setBuildTags = (bsConfig, args) => {
448
+ let buildTag = undefined;
449
+ if(!this.isUndefined(args["build-tag"])) {
450
+ buildTag = args["build-tag"];
451
+ } else {
452
+ buildTag = bsConfig.run_settings.build_tag;
453
+ }
454
+ if(!this.isUndefined(buildTag)) {
455
+ buildTag = buildTag.toString();
456
+ }
457
+ bsConfig.run_settings.build_tag = buildTag;
458
+ logger.debug(`Setting the build tag = ${bsConfig.run_settings.build_tag}`);
459
+ };
460
+
417
461
  exports.setSystemEnvs = (bsConfig) => {
418
462
  let envKeys = {};
419
463
 
@@ -1203,3 +1247,24 @@ exports.getVideoConfig = (cypressJson) => {
1203
1247
  logger.debug(`Setting videoUploadOnPasses = ${conf.videoUploadOnPasses}`);
1204
1248
  return conf;
1205
1249
  }
1250
+
1251
+ exports.getMajorVersion = (version) => {
1252
+ try {
1253
+ if (!version || !version.match(/^(\d+\.)?(\d+\.)?(\*|\d+)$/)) {
1254
+ return null;
1255
+ }
1256
+
1257
+ const matches = version.match(/^(\d+\.)?(\d+\.)?(\*|\d+)$/)
1258
+ if(matches && matches.length >= 2) {
1259
+ if (!matches[1]) {
1260
+ return matches[0];
1261
+ }
1262
+ return matches[1].replace('.','');
1263
+ } else {
1264
+ return null;
1265
+ }
1266
+ } catch(error) {
1267
+ logger.debug(`Some Error occurred while fetching major version of ${version}. Returning null. Error Details: ${error}`)
1268
+ return null;
1269
+ }
1270
+ }
package/bin/runner.js CHANGED
@@ -265,6 +265,17 @@ var argv = yargs
265
265
  default: undefined,
266
266
  describe: Constants.cliMessages.RUN.PROJECT_ID,
267
267
  type: "string"
268
+ },
269
+ 'nv': {
270
+ alias: ['node-version', 'nodeVersion'],
271
+ default: undefined,
272
+ describe: Constants.cliMessages.RUN.NODE_VERSION,
273
+ type: "string"
274
+ },
275
+ 'build-tag': {
276
+ default: undefined,
277
+ describe: Constants.cliMessages.RUN.BUILD_TAG,
278
+ type: "string"
268
279
  }
269
280
  })
270
281
  .help('help')
package/log/usage.log ADDED
@@ -0,0 +1,2 @@
1
+ {"level":"info","message":"Sending {\"event_type\":\"cypress_cli_stats\",\"data\":{\"bstack_json\":\"null\",\"run_settings\":\"\",\"os\":\"darwin\",\"os_version\":\"21.4.0\",\"bstack_json_found_in_pwd\":false,\"cypress_json_found_in_pwd\":false,\"cli_version\":\"1.13.0\",\"cli_path\":\"/Users/rahulnwn/.nvm/versions/node/v12.18.4/lib/node_modules\",\"npm_version\":\"6.14.6\",\"local_cypress_version\":null,\"ci_environment\":null,\"event_timestamp\":\"4/13/2022, 12:39:15 AM\",\"data\":null,\"raw_args\":[\"run\"],\"cli_args\":{\"_\":[\"run\"],\"cf\":\"browserstack.json\",\"config-file\":\"browserstack.json\",\"configFile\":\"browserstack.json\",\"ccf\":\"./cypress.json\",\"cypress-config-file\":\"./cypress.json\",\"cypressConfigFile\":\"./cypress.json\",\"disable-npm-warning\":false,\"disableNpmWarning\":false,\"sync\":true,\"async\":false,\"force-upload\":false,\"forceUpload\":false,\"headed\":false,\"no-wrap\":false,\"noWrap\":false,\"$0\":\"browserstack-cypress\"},\"message_type\":\"error\",\"error_code\":\"bstack_json_invalid_unknown\"}} to http://127.0.0.1:8000/send_event_cy_internal","timestamp":"2022-04-12T19:09:15.315Z"}
2
+ {"level":"info","message":"{\"attempts\":1,\"statusCode\":404}","timestamp":"2022-04-12T19:09:15.365Z"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browserstack-cypress-cli",
3
- "version": "1.14.1",
3
+ "version": "1.17.0",
4
4
  "description": "BrowserStack Cypress CLI for Cypress integration with BrowserStack's remote devices.",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -22,7 +22,7 @@
22
22
  "glob": "7.2.0",
23
23
  "mkdirp": "1.0.4",
24
24
  "request": "2.88.2",
25
- "requestretry": "4.1.2",
25
+ "requestretry": "7.1.0",
26
26
  "table": "5.4.6",
27
27
  "unzipper": "0.10.11",
28
28
  "update-notifier": "5.1.0",