browserstack-cypress-cli 1.10.1 → 1.12.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.
@@ -1,4 +1,5 @@
1
1
  let config = require("./config");
2
+ let chalk = require('chalk');
2
3
 
3
4
  const syncCLI = {
4
5
  FAILED_SPEC_DETAILS_COL_HEADER: ['Spec', 'Status', 'Browser', 'BrowserStack Session ID'],
@@ -7,6 +8,7 @@ const syncCLI = {
7
8
  },
8
9
  INITIAL_DELAY_MULTIPLIER: 10,
9
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..."
10
12
  };
11
13
 
12
14
  const userMessages = {
@@ -25,8 +27,12 @@ const userMessages = {
25
27
  MD5_CHECK_FAILED: "There was some issue while checking if zip is already uploaded.",
26
28
  ZIP_DELETE_FAILED: "Could not delete tests.zip successfully.",
27
29
  ZIP_DELETED: "Deleted tests.zip successfully.",
30
+ NPM_INSTALL_AND_UPLOAD: "Installing required dependencies and building the package to upload to BrowserStack",
31
+ NPM_DELETE_FAILED: "Could not delete the dependency packages.",
32
+ NPM_DELETED: "Deleted dependency packages successfully.",
28
33
  API_DEPRECATED: "This version of API is deprecated, please use latest version of API.",
29
34
  FAILED_TO_ZIP: "Failed to zip files.",
35
+ FAILED_CREATE_NPM_ARCHIVE: "CLI execution failed due to some issue in npm setup. Please retry.",
30
36
  FAILED_MD5_CHECK: "Something went wrong - you can retry running browserstack-cypress with ‘--force-upload’ parameter, or contact BrowserStack Support.",
31
37
  VISIT_DASHBOARD: "Visit the Automate dashboard for real-time test reporting:",
32
38
  CONFLICTING_INIT_ARGUMENTS: "Conflicting arguments given. You can use --path only with a file name, and not with a file path.",
@@ -35,13 +41,18 @@ const userMessages = {
35
41
  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.",
36
42
  VALIDATING_CONFIG: "Validating the config",
37
43
  UPLOADING_TESTS: "Uploading the tests to BrowserStack",
44
+ UPLOADING_TESTS_SUCCESS: "Uploaded tests successfully",
45
+ UPLOADING_NPM_PACKAGES: "Uploading required node_modules to BrowserStack",
46
+ UPLOADING_NPM_PACKAGES_SUCCESS: "Uploaded node_modules successfully",
47
+ SKIP_UPLOADING_TESTS: "Skipping zip upload since BrowserStack already has your test suite that has not changed since the last run.",
48
+ 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.",
38
49
  LOCAL_TRUE: "you will now be able to test localhost / private URLs",
39
50
  LOCAL_FALSE: "you won't be able to test localhost / private URLs",
40
51
  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.",
41
52
  FATAL_NETWORK_ERROR: `fatal: unable to access '${config.buildUrl}': Could not resolve host: ${config.rails_host}`,
42
53
  RETRY_LIMIT_EXCEEDED: `Max retries exceeded trying to connect to the host (retries: ${config.retries})`,
43
54
  CHECK_DASHBOARD_AT: "Please check the build status at: ",
44
- CYPRESS_VERSION_CHANGED: "Your build will run using Cypress <actualVersion> instead of Cypress <preferredVersion>. Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
55
+ 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",
45
56
  LOCAL_START_FAILED: "Local Testing setup failed.",
46
57
  LOCAL_STOP_FAILED: "Local Binary stop failed.",
47
58
  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",
@@ -49,7 +60,9 @@ const userMessages = {
49
60
  DOWNLOAD_BUILD_ARTIFACTS_FAILED: "Downloading build artifacts for the build <build-id> failed for <machine-count> machines.",
50
61
  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>'",
51
62
  DOWNLOAD_BUILD_ARTIFACTS_SUCCESS: "Your build artifact(s) have been successfully downloaded in '<user-path>/build_artifacts/<build-id>' directory",
52
- LATEST_SYNTAX_TO_ACTUAL_VERSION_MESSAGE: "Your build will run using Cypress <actualVersion> as you had specified <latestSyntaxVersion>. Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions"
63
+ 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",
64
+ PROCESS_KILL_MESSAGE: "Stopping the CLI and the execution of the build on BrowserStack",
65
+ 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")
53
66
  };
54
67
 
55
68
  const validationMessages = {
@@ -74,7 +87,16 @@ const validationMessages = {
74
87
  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",
75
88
  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",
76
89
  INVALID_LOCAL_IDENTIFIER: "Invalid value specified for local_identifier. For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
77
- INVALID_BROWSER_ARGS: "Aborting as an unacceptable value was passed for --browser. Read more at https://www.browserstack.com/docs/automate/cypress/cli-reference"
90
+ INVALID_BROWSER_ARGS: "Aborting as an unacceptable value was passed for --browser. Read more at https://www.browserstack.com/docs/automate/cypress/cli-reference",
91
+ INVALID_LOCAL_ASYNC_ARGS: "Cannot run in --async mode when local is set to true. Please run the build after removing --async",
92
+ 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",
93
+ 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.",
94
+ 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.",
95
+ 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.",
96
+ NOT_ALLOWED_GEO_LOCATION_AND_LOCAL_MODE: "IP Geolocation feature is not available in conjunction with BrowserStack Local.",
97
+ HOME_DIRECTORY_NOT_FOUND: "Specified home directory could not be found. Please make sure the path of the home directory is correct.",
98
+ HOME_DIRECTORY_NOT_A_DIRECTORY: "Specified home directory is not a directory. The home directory can only be a directory and not a file.",
99
+ 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."
78
100
  };
79
101
 
80
102
  const cliMessages = {
@@ -96,7 +118,7 @@ const cliMessages = {
96
118
  },
97
119
  RUN: {
98
120
  PARALLEL_DESC: "The maximum number of parallels to use to run your test suite",
99
- INFO: "Run your tests on BrowserStack.",
121
+ INFO: "Run your tests on BrowserStack. For more help: `browserstack-cypress run --help`.",
100
122
  CYPRESS_DESC: "Path to Cypress config file",
101
123
  CYPRESS_CONFIG_DEMAND: "Cypress config file is required",
102
124
  BUILD_NAME: "The build name you want to use to name your test runs",
@@ -105,6 +127,7 @@ const cliMessages = {
105
127
  SPECS_DESCRIPTION: "Specify the spec files to run",
106
128
  ENV_DESCRIPTION: "Specify the environment variables for your spec files",
107
129
  SYNC_DESCRIPTION: "Makes the run command in sync",
130
+ ASYNC_DESCRIPTION: "Makes the run command in async",
108
131
  BUILD_REPORT_MESSAGE: "See the entire build report here",
109
132
  HEADED: "Run your tests in a headed browser instead of a headless browser",
110
133
  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",
@@ -116,6 +139,7 @@ const cliMessages = {
116
139
  CONFIG_DESCRIPTION: "Set configuration values. Separate multiple values with a comma. The values set here override any values set in your configuration file.",
117
140
  REPORTER: "Specify the custom reporter to use",
118
141
  REPORTER_OPTIONS: "Specify reporter options for custom reporter",
142
+ CYPRESS_GEO_LOCATION: "Enterprise feature to simulate website and mobile behavior from different locations."
119
143
  },
120
144
  COMMON: {
121
145
  DISABLE_USAGE_REPORTING: "Disable usage reporting",
@@ -143,7 +167,7 @@ const messageTypes = {
143
167
  NULL: null
144
168
  }
145
169
 
146
- 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'];
170
+ 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'];
147
171
 
148
172
  const filesToIgnoreWhileUploading = [
149
173
  '**/node_modules/**',
@@ -156,6 +180,8 @@ const filesToIgnoreWhileUploading = [
156
180
  '.idea/**',
157
181
  '.vscode/**',
158
182
  '.npm/**',
183
+ 'bstackPackages.tar.gz',
184
+ 'tmpBstackPackages/**',
159
185
  '.yarn/**',
160
186
  'build_artifacts/**'
161
187
  ];
@@ -175,6 +201,15 @@ const hashingOptions = {
175
201
  encoding: 'hex',
176
202
  };
177
203
 
204
+ const packageInstallerOptions = {
205
+ npmLoad: {
206
+ loglevel: 'silent',
207
+ only: 'dev',
208
+ 'save-dev': true,
209
+ 'only-dev': true,
210
+ }
211
+ }
212
+
178
213
  const specFileTypes = ['js', 'ts', 'feature', 'jsx', 'coffee', 'cjsx'];
179
214
 
180
215
  const DEFAULT_CYPRESS_SPEC_PATH = "cypress/integration"
@@ -188,6 +223,16 @@ const usageReportingConstants = {
188
223
 
189
224
  const LATEST_VERSION_SYNTAX_REGEX = /\d*.latest(.\d*)?/gm
190
225
 
226
+ const AUTH_REGEX = /"auth" *: *{[\s\S]*?}/g
227
+
228
+ const ERROR_EXIT_CODE = 1;
229
+
230
+ const BUILD_FAILED_EXIT_CODE = 3;
231
+
232
+ const REDACTED = "[REDACTED]";
233
+
234
+ const REDACTED_AUTH =`auth: { "username": ${REDACTED}, "access_key": ${REDACTED} }`;
235
+
191
236
  module.exports = Object.freeze({
192
237
  syncCLI,
193
238
  userMessages,
@@ -198,10 +243,15 @@ module.exports = Object.freeze({
198
243
  filesToIgnoreWhileUploading,
199
244
  readDirOptions,
200
245
  hashingOptions,
246
+ packageInstallerOptions,
201
247
  specFileTypes,
202
248
  DEFAULT_CYPRESS_SPEC_PATH,
203
249
  SPEC_TOTAL_CHAR_LIMIT,
204
250
  METADATA_CHAR_BUFFER_PER_SPEC,
205
251
  usageReportingConstants,
206
- LATEST_VERSION_SYNTAX_REGEX
252
+ LATEST_VERSION_SYNTAX_REGEX,
253
+ ERROR_EXIT_CODE,
254
+ AUTH_REGEX,
255
+ REDACTED_AUTH,
256
+ BUILD_FAILED_EXIT_CODE
207
257
  });
@@ -0,0 +1,29 @@
1
+ 'use strict'
2
+ const request = require('request');
3
+
4
+ const downloadBuildStacktrace = async (url) => {
5
+ return new Promise(async (resolve, reject) => {
6
+ request.get(url).on('response', function (response) {
7
+ if(response.statusCode == 200) {
8
+ response.pipe(process.stdout);
9
+ let error = null;
10
+ process.stdout.on('error', (err) => {
11
+ error = err;
12
+ process.stdout.close();
13
+ reject(response.statusCode);
14
+ });
15
+ process.stdout.on('close', async () => {
16
+ if(!error) {
17
+ resolve("Build stacktrace downloaded successfully");
18
+ }
19
+ });
20
+ } else {
21
+ reject(response.statusCode);
22
+ }
23
+ }).on('end', () => {
24
+ resolve("Build stacktrace downloaded successfully");
25
+ });
26
+ });
27
+ };
28
+
29
+ exports.downloadBuildStacktrace = downloadBuildStacktrace;
@@ -4,6 +4,7 @@ const fs = require('fs-extra'),
4
4
 
5
5
  const logger = require('./logger').winstonLogger,
6
6
  Constants = require('../helpers/constants'),
7
+ process = require('process'),
7
8
  config = require('../helpers/config');
8
9
 
9
10
  exports.write = function (f, message, args, cb) {
@@ -35,6 +36,19 @@ exports.deleteZip = () => {
35
36
  }
36
37
  };
37
38
 
39
+ exports.deletePackageArchieve = (logging = true) => {
40
+ try {
41
+ delete process.env.CYPRESS_INSTALL_BINARY;
42
+ fs.removeSync(config.packageFileName);
43
+ fs.removeSync(config.packageDirName);
44
+ if (logging) logger.info(Constants.userMessages.NPM_DELETED);
45
+ return 0;
46
+ } catch (err) {
47
+ if (logging) logger.info(Constants.userMessages.NPM_DELETE_FAILED);
48
+ return 1;
49
+ }
50
+ };
51
+
38
52
  exports.dirExists = function (filePath, cb) {
39
53
  let exists = false;
40
54
  if (fs.existsSync(path.dirname(filePath), cb)) {
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+ const archiver = require("archiver"),
3
+ path = require('path'),
4
+ fs = require('fs-extra'),
5
+ fileHelpers = require('./fileHelpers'),
6
+ logger = require("./logger").winstonLogger,
7
+ Constants = require('./constants'),
8
+ process = require('process'),
9
+ utils = require('./utils'),
10
+ { spawn } = require('child_process');
11
+
12
+ let nodeProcess;
13
+
14
+ const setupPackageFolder = (runSettings, directoryPath) => {
15
+ return new Promise(function (resolve, reject) {
16
+ fileHelpers.deletePackageArchieve(false);
17
+ fs.mkdir(directoryPath, function (err) {
18
+ try {
19
+ if (err) {
20
+ return reject(err);
21
+ }
22
+ let packageJSON = {};
23
+ if (typeof runSettings.package_config_options === 'object') {
24
+ Object.assign(packageJSON, runSettings.package_config_options);
25
+ }
26
+
27
+ if (typeof runSettings.npm_dependencies === 'object') {
28
+ Object.assign(packageJSON, {
29
+ devDependencies: runSettings.npm_dependencies,
30
+ });
31
+ }
32
+
33
+ if (Object.keys(packageJSON).length > 0) {
34
+ let packageJSONString = JSON.stringify(packageJSON);
35
+ let packagePath = path.join(directoryPath, "package.json");
36
+ fs.writeFileSync(packagePath, packageJSONString);
37
+ let cypressFolderPath = path.dirname(runSettings.cypressConfigFilePath);
38
+ let sourceNpmrc = path.join(cypressFolderPath, ".npmrc");
39
+ let destNpmrc = path.join(directoryPath, ".npmrc");
40
+ if (fs.existsSync(sourceNpmrc)) {
41
+ fs.copyFileSync(sourceNpmrc, destNpmrc);
42
+ }
43
+ return resolve("Package file created");
44
+ }
45
+ return reject("Nothing in package file");
46
+ } catch(error) {
47
+ return reject(error);
48
+ }
49
+ })
50
+ })
51
+ };
52
+
53
+ const packageInstall = (packageDir) => {
54
+ return new Promise(function (resolve, reject) {
55
+ const nodeProcessCloseCallback = (code) => {
56
+ if(code == 0) {
57
+ resolve('Packages were installed successfully.');
58
+ } else {
59
+ reject('Packages were not installed successfully.');
60
+ }
61
+ };
62
+ const nodeProcessErrorCallback = (error) => {
63
+ logger.error(`Some error occurred while installing packages: ${error}`);
64
+ reject(`Packages were not installed successfully.`);
65
+ };
66
+ nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install'], {cwd: packageDir});
67
+ nodeProcess.on('close', nodeProcessCloseCallback);
68
+ nodeProcess.on('error', nodeProcessErrorCallback);
69
+ });
70
+ };
71
+
72
+ const packageArchiver = (packageDir, packageFile) => {
73
+ return new Promise(function (resolve, reject) {
74
+ let output = fs.createWriteStream(packageFile);
75
+ let archive = archiver('tar', {
76
+ gzip: true
77
+ });
78
+ archive.on('warning', function (err) {
79
+ if (err.code === 'ENOENT') {
80
+ logger.info(err);
81
+ } else {
82
+ reject(err);
83
+ }
84
+ });
85
+
86
+ output.on('close', function () {
87
+ resolve('Zipping completed');
88
+ });
89
+
90
+ output.on('end', function () {
91
+ logger.info('Data has been drained');
92
+ });
93
+
94
+ archive.on('error', function (err) {
95
+ reject(err);
96
+ });
97
+
98
+ archive.pipe(output);
99
+ archive.directory(packageDir, false);
100
+ archive.finalize();
101
+ })
102
+ }
103
+
104
+ const packageWrapper = (bsConfig, packageDir, packageFile, md5data, instrumentBlocks) => {
105
+ return new Promise(function (resolve) {
106
+ let obj = {
107
+ packageArchieveCreated: false
108
+ };
109
+ if (md5data.packageUrlPresent || !utils.isTrueString(bsConfig.run_settings.cache_dependencies)) {
110
+ return resolve(obj);
111
+ }
112
+ logger.info(Constants.userMessages.NPM_INSTALL_AND_UPLOAD);
113
+ instrumentBlocks.markBlockStart("packageInstaller.folderSetup");
114
+ return setupPackageFolder(bsConfig.run_settings, packageDir).then((_result) => {
115
+ process.env.CYPRESS_INSTALL_BINARY = 0
116
+ instrumentBlocks.markBlockEnd("packageInstaller.folderSetup");
117
+ instrumentBlocks.markBlockStart("packageInstaller.packageInstall");
118
+ return packageInstall(packageDir);
119
+ }).then((_result) => {
120
+ instrumentBlocks.markBlockEnd("packageInstaller.packageInstall");
121
+ instrumentBlocks.markBlockStart("packageInstaller.packageArchive");
122
+ return packageArchiver(packageDir, packageFile);
123
+ }).then((_result) => {
124
+ instrumentBlocks.markBlockEnd("packageInstaller.packageArchive");
125
+ Object.assign(obj, { packageArchieveCreated: true });
126
+ return resolve(obj);
127
+ }).catch((err) => {
128
+ obj.error = err.stack ? err.stack.toString().substring(0,100) : err.toString().substring(0,100);
129
+ return resolve(obj);
130
+ })
131
+ })
132
+ }
133
+
134
+ exports.packageWrapper = packageWrapper;
@@ -4,8 +4,7 @@ const fs = require('fs'),
4
4
  logger = require('./logger').winstonLogger,
5
5
  utils = require("./utils"),
6
6
  Constants = require('./constants'),
7
- config = require("./config"),
8
- axios = require("axios");
7
+ config = require("./config");
9
8
 
10
9
  let templatesDir = path.join(__dirname, '../', 'templates');
11
10
 
@@ -89,7 +88,7 @@ function buildSpecStats(specMeta) {
89
88
  return specStats;
90
89
  }
91
90
 
92
- let reportGenerator = (bsConfig, buildId, args, cb) => {
91
+ let reportGenerator = (bsConfig, buildId, args, rawArgs, cb) => {
93
92
  let options = {
94
93
  url: `${config.buildUrl}${buildId}/custom_report`,
95
94
  auth: {
@@ -115,7 +114,7 @@ let reportGenerator = (bsConfig, buildId, args, cb) => {
115
114
  logger.error('Generating the build report failed.');
116
115
  logger.error(message);
117
116
 
118
- utils.sendUsageReport(bsConfig, args, message, messageType, errorCode);
117
+ utils.sendUsageReport(bsConfig, args, message, messageType, errorCode, null, rawArgs);
119
118
  return;
120
119
  } else {
121
120
  try {
@@ -167,7 +166,7 @@ let reportGenerator = (bsConfig, buildId, args, cb) => {
167
166
  await renderReportHTML(build);
168
167
  logger.info(message);
169
168
  }
170
- utils.sendUsageReport(bsConfig, args, message, messageType, errorCode);
169
+ utils.sendUsageReport(bsConfig, args, message, messageType, errorCode, null, rawArgs);
171
170
  if (cb){
172
171
  cb();
173
172
  }
@@ -235,24 +234,74 @@ async function cypressReportData(report_data) {
235
234
  return report_data;
236
235
  }
237
236
 
237
+ function getConfigJsonResponse(combination) {
238
+ 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
+ }
262
+
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]);
271
+ } 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
+
238
289
  function generateCypressCombinationSpecReportDataWithConfigJson(combination){
239
290
  return new Promise(async (resolve, reject) => {
240
291
  try {
241
292
  let configJsonError, resultsJsonError;
242
- let [configJsonResponse, resultsJsonResponse] = await axios.all([
243
- axios.get(combination.tests.config_json).catch(function (error) {
244
- configJsonError = true;
245
- }),
246
- axios.get(combination.tests.result_json).catch(function(error){
247
- resultsJsonError = true;
248
- })
249
- ]);
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
+
250
301
  if(resultsJsonError || configJsonError){
251
302
  resolve();
252
303
  }
253
304
  let tests = {};
254
- let configJson = configJsonResponse.data;
255
- let resultsJson = resultsJsonResponse.data;
256
305
  if(utils.isUndefined(configJson.tests) || utils.isUndefined(resultsJson.tests)){
257
306
  resolve();
258
307
  }
@@ -277,21 +326,25 @@ function generateCypressCombinationSpecReportDataWithConfigJson(combination){
277
326
  });
278
327
  combination.tests = sessionTests;
279
328
  resolve(combination.tests);
280
- } catch (error) { reject(error) }
329
+ } catch (error) {
330
+ process.exitCode = Constants.ERROR_EXIT_CODE;
331
+ reject(error);
332
+ }
281
333
  })
282
334
  }
283
335
 
284
336
  function generateCypressCombinationSpecReportDataWithoutConfigJson(combination){
285
337
  return new Promise(async (resolve, reject) => {
286
338
  try {
287
- let resultsJsonError;
288
- let resultsJsonResponse = await axios.get(combination.tests.result_json).catch(function(error){
289
- resultsJsonError = true;
290
- });
339
+ let resultsJson ,resultsJsonError;
340
+ await getResultsJsonResponse(combination).then(function (successResult) {
341
+ [resultsJson, resultsJsonError] = successResult
342
+ }).catch( function (failureResult) {
343
+ [resultsJson, resultsJsonError] = failureResult
344
+ })
291
345
  if(resultsJsonError || utils.isUndefined(resultsJsonResponse)){
292
346
  resolve();
293
347
  }
294
- let resultsJson = resultsJsonResponse.data;
295
348
  let sessionTests = [];
296
349
  if(utils.isUndefined(resultsJson.tests)){
297
350
  resolve();
@@ -308,7 +361,10 @@ function generateCypressCombinationSpecReportDataWithoutConfigJson(combination){
308
361
  });
309
362
  combination.tests = sessionTests;
310
363
  resolve(combination.tests);
311
- } catch (error) { reject(error) }
364
+ } catch (error) {
365
+ process.exitCode = Constants.ERROR_EXIT_CODE;
366
+ reject(error);
367
+ }
312
368
  })
313
369
  }
314
370
 
@@ -3,13 +3,15 @@ const request = require("request"),
3
3
  config = require("../config"),
4
4
  utils = require("../utils"),
5
5
  logger = require("../logger").syncCliLogger,
6
+ winstonLogger = require("../logger").winstonLogger,
6
7
  async = require('async'),
7
8
  Constants = require("../constants"),
8
9
  tableStream = require('table').createStream,
9
10
  chalk = require('chalk');
10
11
 
11
- let whileLoop = true, whileTries = config.retries, options, timeout = 3000, n = 2, tableConfig, stream, endTime, startTime = Date.now();
12
+ let whileLoop = true, whileTries = config.retries, options, timeout = 3000, n = 2, tableConfig, stream, endTime, startTime = Date.now(), buildStarted = false;
12
13
  let specSummary = {
14
+ "buildError": null,
13
15
  "specs": [],
14
16
  "duration": null
15
17
  }
@@ -89,7 +91,7 @@ let setNoWrapParams = () => {
89
91
  }
90
92
  };
91
93
 
92
- let printSpecsStatus = (bsConfig, buildDetails) => {
94
+ let printSpecsStatus = (bsConfig, buildDetails, rawArgs) => {
93
95
  setNoWrapParams();
94
96
  return new Promise((resolve, reject) => {
95
97
  options = getOptions(bsConfig.auth, buildDetails.build_id)
@@ -105,11 +107,15 @@ let printSpecsStatus = (bsConfig, buildDetails) => {
105
107
  },
106
108
  function(err, result) { // when loop ends
107
109
  if (err) {
108
- utils.sendUsageReport(bsConfig, {}, `buildId: ${buildDetails.build_id}`, 'error', 'sync_cli_error', err);
110
+ if(err.status == 204) {
111
+ reject(specSummary.exitCode);
112
+ } else {
113
+ utils.sendUsageReport(bsConfig, {}, `buildId: ${buildDetails.build_id}`, 'error', 'sync_cli_error', err, rawArgs);
114
+ }
109
115
  }
110
116
  logger.info(lineSeparator);
111
117
  specSummary.duration = endTime - startTime
112
- resolve(specSummary)
118
+ resolve(specSummary);
113
119
  }
114
120
  );
115
121
  });
@@ -144,7 +150,8 @@ let whileProcess = (whilstCallback) => {
144
150
  whileLoop = false;
145
151
  endTime = Date.now();
146
152
  showSpecsStatus(body);
147
- return whilstCallback(null, body);
153
+ return specSummary.exitCode == Constants.BUILD_FAILED_EXIT_CODE ?
154
+ whilstCallback({ status: 204, message: "No specs ran in the build"} ) : whilstCallback(null, body);
148
155
  default:
149
156
  whileLoop = false;
150
157
  return whilstCallback({ status: response.statusCode, message: body });
@@ -152,18 +159,31 @@ let whileProcess = (whilstCallback) => {
152
159
  });
153
160
  }
154
161
 
162
+ let getStackTraceUrl = () => {
163
+ return specSummary.buildError
164
+ }
165
+
155
166
  let showSpecsStatus = (data) => {
156
167
  let specData = JSON.parse(data);
157
168
  specData.forEach(specDetails => {
158
169
  if (specDetails == "created") {
159
- printInitialLog();
170
+ return;
171
+ } else if (specDetails["stacktrace_url"]) {
172
+ specSummary.exitCode = Constants.BUILD_FAILED_EXIT_CODE;
173
+ specSummary.buildError = specDetails["stacktrace_url"]
174
+ winstonLogger.error(chalk.red(specDetails["message"]));
160
175
  } else {
161
- printSpecData(JSON.parse(specDetails))
176
+ if(!buildStarted) {
177
+ buildStarted = true
178
+ printInitialLog();
179
+ }
180
+ printSpecData(JSON.parse(specDetails));
162
181
  }
163
182
  });
164
183
  }
165
184
 
166
185
  let printInitialLog = () => {
186
+ winstonLogger.info(Constants.syncCLI.STARTUP_MESSAGE);
167
187
  logger.info(`\n${Constants.syncCLI.LOGS.INIT_LOG}`)
168
188
  logger.info(lineSeparator);
169
189
  n = Constants.syncCLI.INITIAL_DELAY_MULTIPLIER
@@ -206,3 +226,4 @@ let getStatus = (status) => {
206
226
  }
207
227
 
208
228
  exports.printSpecsStatus = printSpecsStatus;
229
+ exports.getStackTraceUrl = getStackTraceUrl;