browserstack-cypress-cli 1.11.2 → 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.
@@ -16,8 +16,10 @@ const archiver = require("../helpers/archiver"),
16
16
  reportGenerator = require('../helpers/reporterHTML').reportGenerator,
17
17
  {initTimeComponents, instrumentEventTime, markBlockStart, markBlockEnd, getTimeComponents} = require('../helpers/timeComponents'),
18
18
  downloadBuildArtifacts = require('../helpers/buildArtifacts').downloadBuildArtifacts,
19
+ downloadBuildStacktrace = require('../helpers/downloadBuildStacktrace').downloadBuildStacktrace,
19
20
  updateNotifier = require('update-notifier'),
20
21
  pkg = require('../../package.json');
22
+ const { getStackTraceUrl } = require('../helpers/sync/syncSpecsLogs');
21
23
 
22
24
  module.exports = function run(args, rawArgs) {
23
25
  let bsConfigPath = utils.getConfigPath(args.cf);
@@ -48,6 +50,9 @@ module.exports = function run(args, rawArgs) {
48
50
  // set cypress config filename
49
51
  utils.setCypressConfigFilename(bsConfig, args);
50
52
 
53
+ // set cypress geo location
54
+ utils.setGeolocation(bsConfig, args);
55
+
51
56
  // accept the specs list from command line if provided
52
57
  utils.setUserSpecs(bsConfig, args);
53
58
 
@@ -178,15 +183,32 @@ module.exports = function run(args, rawArgs) {
178
183
  await new Promise(resolve => setTimeout(resolve, 5000));
179
184
 
180
185
  // download build artifacts
181
- if (utils.nonEmptyArray(bsConfig.run_settings.downloads)) {
182
- await downloadBuildArtifacts(bsConfig, data.build_id, args, rawArgs);
186
+ if (exitCode != Constants.BUILD_FAILED_EXIT_CODE) {
187
+ if (utils.nonEmptyArray(bsConfig.run_settings.downloads)) {
188
+ await downloadBuildArtifacts(bsConfig, data.build_id, args, rawArgs);
189
+ }
190
+
191
+ // Generate custom report!
192
+ reportGenerator(bsConfig, data.build_id, args, rawArgs, function(){
193
+ utils.sendUsageReport(bsConfig, args, `${message}\n${dashboardLink}`, Constants.messageTypes.SUCCESS, null, buildReportData, rawArgs);
194
+ utils.handleSyncExit(exitCode, data.dashboard_url);
195
+ });
196
+ } else {
197
+ let stacktraceUrl = getStackTraceUrl();
198
+ downloadBuildStacktrace(stacktraceUrl).then((message) => {
199
+ utils.sendUsageReport(bsConfig, args, message, Constants.messageTypes.SUCCESS, null, buildReportData, rawArgs);
200
+ }).catch((err) => {
201
+ let message = `Downloading build stacktrace failed with statuscode: ${err}. Please visit ${data.dashboard_url} for additional details.`;
202
+ logger.error(message);
203
+ utils.sendUsageReport(bsConfig, args, message, Constants.messageTypes.ERROR, null, buildReportData, rawArgs);
204
+ }).finally(() =>{
205
+ let terminalWidth = (process.stdout.columns) * 0.9;
206
+ let lineSeparator = "\n" + "-".repeat(terminalWidth);
207
+ console.log(lineSeparator)
208
+ logger.info(Constants.userMessages.BUILD_FAILED_ERROR)
209
+ process.exitCode = Constants.BUILD_FAILED_EXIT_CODE;
210
+ });
183
211
  }
184
-
185
- // Generate custom report!
186
- reportGenerator(bsConfig, data.build_id, args, rawArgs, function(){
187
- utils.sendUsageReport(bsConfig, args, `${message}\n${dashboardLink}`, Constants.messageTypes.SUCCESS, null, buildReportData, rawArgs);
188
- utils.handleSyncExit(exitCode, data.dashboard_url);
189
- });
190
212
  });
191
213
  } else if (utils.nonEmptyArray(bsConfig.run_settings.downloads)) {
192
214
  logger.info(Constants.userMessages.ASYNC_DOWNLOADS.replace('<build-id>', data.build_id));
@@ -236,6 +258,9 @@ module.exports = function run(args, rawArgs) {
236
258
  utils.sendUsageReport(bsConfig, args, `${message}\n${dashboardLink}`, Constants.messageTypes.SUCCESS, null, buildReportData, rawArgs);
237
259
  return;
238
260
  }).catch(async function (err) {
261
+ if (err && err.includes('browserstack.geoLocation')) {
262
+ err = err.replace(/browserstack.geoLocation/g, 'geolocation');
263
+ }
239
264
  // Build creation failed
240
265
  logger.error(err);
241
266
  // stop the Local instance
@@ -318,9 +343,23 @@ module.exports = function run(args, rawArgs) {
318
343
  utils.sendUsageReport(bsJsonData, args, err.message, Constants.messageTypes.ERROR, utils.getErrorCodeFromErr(err), null, rawArgs);
319
344
  process.exitCode = Constants.ERROR_EXIT_CODE;
320
345
  }).finally(function(){
321
- updateNotifier({
346
+ const notifier = updateNotifier({
322
347
  pkg,
323
348
  updateCheckInterval: 1000 * 60 * 60 * 24 * 7,
324
- }).notify({isGlobal: true});
349
+ });
350
+
351
+ // Checks for update on first run.
352
+ // Set lastUpdateCheck to 0 to spawn the check update process as notifier sets this to Date.now() for preventing
353
+ // the check untill one interval period. It runs once.
354
+ if (!notifier.disabled && Date.now() - notifier.config.get('lastUpdateCheck') < 50) {
355
+ notifier.config.set('lastUpdateCheck', 0);
356
+ notifier.check();
357
+ }
358
+
359
+ // Set the config update as notifier clears this after reading.
360
+ if (notifier.update && notifier.update.current !== notifier.update.latest) {
361
+ notifier.config.set('update', notifier.update);
362
+ notifier.notify({isGlobal: true});
363
+ }
325
364
  });
326
365
  }
@@ -1,11 +1,11 @@
1
1
  'use strict';
2
- const fs = require("fs");
2
+ const fs = require("fs"),
3
+ path = require("path");
3
4
 
4
5
  const archiver = require("archiver"),
5
6
  Constants = require('../helpers/constants'),
6
7
  logger = require("./logger").winstonLogger,
7
- utils = require('../helpers/utils'),
8
- path = require('path');
8
+ utils = require('../helpers/utils');
9
9
 
10
10
  const archiveSpecs = (runSettings, filePath, excludeFiles, md5data) => {
11
11
  return new Promise(function (resolve, reject) {
@@ -14,7 +14,17 @@ const archiveSpecs = (runSettings, filePath, excludeFiles, md5data) => {
14
14
  }
15
15
  var output = fs.createWriteStream(filePath);
16
16
 
17
- var cypressFolderPath = path.dirname(runSettings.cypressConfigFilePath);
17
+ var cypressFolderPath = '';
18
+ let cypressAppendFilesZipLocation = '';
19
+ if (runSettings.home_directory) {
20
+ cypressFolderPath = runSettings.home_directory;
21
+ cypressAppendFilesZipLocation = runSettings.cypressZipStartLocation;
22
+ if (cypressAppendFilesZipLocation !== '') {
23
+ cypressAppendFilesZipLocation += '/';
24
+ }
25
+ } else {
26
+ cypressFolderPath = path.dirname(runSettings.cypressConfigFilePath);
27
+ }
18
28
 
19
29
  logger.info(`Creating tests.zip with files in ${cypressFolderPath}`);
20
30
 
@@ -61,7 +71,7 @@ const archiveSpecs = (runSettings, filePath, excludeFiles, md5data) => {
61
71
 
62
72
  if (Object.keys(packageJSON).length > 0) {
63
73
  let packageJSONString = JSON.stringify(packageJSON, null, 4);
64
- archive.append(packageJSONString, {name: 'browserstack-package.json'});
74
+ archive.append(packageJSONString, {name: `${cypressAppendFilesZipLocation}browserstack-package.json`});
65
75
  }
66
76
 
67
77
  // do not add cypress.json if arg provided is false
@@ -73,7 +83,7 @@ const archiveSpecs = (runSettings, filePath, excludeFiles, md5data) => {
73
83
  fs.readFileSync(runSettings.cypressConfigFilePath)
74
84
  );
75
85
  let cypressJSONString = JSON.stringify(cypressJSON, null, 4);
76
- archive.append(cypressJSONString, {name: 'cypress.json'});
86
+ archive.append(cypressJSONString, {name: `${cypressAppendFilesZipLocation}cypress.json`});
77
87
  }
78
88
 
79
89
  archive.finalize();
@@ -1,7 +1,9 @@
1
+ const fs = require('fs'),
2
+ path = require('path');
3
+
1
4
  const logger = require("./logger").winstonLogger,
2
5
  Constants = require("./constants"),
3
- Utils = require("./utils"),
4
- fs = require('fs');
6
+ Utils = require("./utils");
5
7
 
6
8
  const caps = (bsConfig, zip) => {
7
9
  return new Promise(function (resolve, reject) {
@@ -129,6 +131,13 @@ const caps = (bsConfig, zip) => {
129
131
  })
130
132
  }
131
133
 
134
+ const addCypressZipStartLocation = (runSettings) => {
135
+ let resolvedHomeDirectoryPath = path.resolve(runSettings.home_directory);
136
+ let resolvedCypressConfigFilePath = path.resolve(runSettings.cypressConfigFilePath);
137
+ runSettings.cypressZipStartLocation = path.dirname(resolvedCypressConfigFilePath.split(resolvedHomeDirectoryPath)[1]);
138
+ runSettings.cypressZipStartLocation = runSettings.cypressZipStartLocation.substring(1);
139
+ }
140
+
132
141
  const validate = (bsConfig, args) => {
133
142
  return new Promise(function (resolve, reject) {
134
143
  logger.info(Constants.userMessages.VALIDATING_CONFIG);
@@ -164,6 +173,10 @@ const validate = (bsConfig, args) => {
164
173
 
165
174
  if( Utils.searchForOption('--async') && ( !Utils.isUndefined(args.async) && bsConfig["connection_settings"]["local"])) reject(Constants.validationMessages.INVALID_LOCAL_ASYNC_ARGS);
166
175
 
176
+ if (bsConfig.run_settings.userProvidedGeolocation && !bsConfig.run_settings.geolocation.match(/^[A-Z]{2}$/g)) reject(Constants.validationMessages.INVALID_GEO_LOCATION);
177
+
178
+ if (bsConfig["connection_settings"]["local"] && bsConfig.run_settings.userProvidedGeolocation) reject(Constants.validationMessages.NOT_ALLOWED_GEO_LOCATION_AND_LOCAL_MODE);
179
+
167
180
  // validate if config file provided exists or not when cypress_config_file provided
168
181
  // validate the cypressProjectDir key otherwise.
169
182
  let cypressConfigFilePath = bsConfig.run_settings.cypressConfigFilePath;
@@ -185,11 +198,33 @@ const validate = (bsConfig, args) => {
185
198
  } catch(error){
186
199
  reject(Constants.validationMessages.INVALID_CYPRESS_JSON)
187
200
  }
201
+
202
+ //check if home_directory is present or not in user run_settings
203
+ if (!Utils.isUndefined(bsConfig.run_settings.home_directory)) {
204
+ // check if home_directory exists or not
205
+ if (!fs.existsSync(bsConfig.run_settings.home_directory)) {
206
+ reject(Constants.validationMessages.HOME_DIRECTORY_NOT_FOUND);
207
+ }
208
+
209
+ // check if home_directory is a directory or not
210
+ if (!fs.statSync(bsConfig.run_settings.home_directory).isDirectory()) {
211
+ reject(Constants.validationMessages.HOME_DIRECTORY_NOT_A_DIRECTORY);
212
+ }
213
+
214
+ // check if cypress config file (cypress.json) is a part of home_directory or not
215
+ if (!path.resolve(bsConfig.run_settings.cypressConfigFilePath).includes(path.resolve(bsConfig.run_settings.home_directory))) {
216
+ reject(Constants.validationMessages.CYPRESS_CONFIG_FILE_NOT_PART_OF_HOME_DIRECTORY);
217
+ }
218
+
219
+ addCypressZipStartLocation(bsConfig.run_settings);
220
+ }
221
+
188
222
  resolve(cypressJson);
189
223
  });
190
224
  }
191
225
 
192
226
  module.exports = {
193
227
  caps,
228
+ addCypressZipStartLocation,
194
229
  validate
195
230
  }
@@ -15,7 +15,12 @@ const checkSpecsMd5 = (runSettings, args, instrumentBlocks) => {
15
15
  if (args["force-upload"]) {
16
16
  return resolve("force-upload");
17
17
  }
18
- let cypressFolderPath = path.dirname(runSettings.cypressConfigFilePath);
18
+ let cypressFolderPath = undefined;
19
+ if (runSettings.home_directory) {
20
+ cypressFolderPath = runSettings.home_directory;
21
+ } else {
22
+ cypressFolderPath = path.dirname(runSettings.cypressConfigFilePath);
23
+ }
19
24
  let ignoreFiles = utils.getFilesToIgnore(runSettings, args.exclude, false);
20
25
  let options = {
21
26
  cwd: cypressFolderPath,
@@ -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'],
@@ -61,6 +62,7 @@ const userMessages = {
61
62
  DOWNLOAD_BUILD_ARTIFACTS_SUCCESS: "Your build artifact(s) have been successfully downloaded in '<user-path>/build_artifacts/<build-id>' directory",
62
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",
63
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")
64
66
  };
65
67
 
66
68
  const validationMessages = {
@@ -87,6 +89,14 @@ const validationMessages = {
87
89
  INVALID_LOCAL_IDENTIFIER: "Invalid value specified for local_identifier. For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
88
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",
89
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."
90
100
  };
91
101
 
92
102
  const cliMessages = {
@@ -129,6 +139,7 @@ const cliMessages = {
129
139
  CONFIG_DESCRIPTION: "Set configuration values. Separate multiple values with a comma. The values set here override any values set in your configuration file.",
130
140
  REPORTER: "Specify the custom reporter to use",
131
141
  REPORTER_OPTIONS: "Specify reporter options for custom reporter",
142
+ CYPRESS_GEO_LOCATION: "Enterprise feature to simulate website and mobile behavior from different locations."
132
143
  },
133
144
  COMMON: {
134
145
  DISABLE_USAGE_REPORTING: "Disable usage reporting",
@@ -216,6 +227,8 @@ const AUTH_REGEX = /"auth" *: *{[\s\S]*?}/g
216
227
 
217
228
  const ERROR_EXIT_CODE = 1;
218
229
 
230
+ const BUILD_FAILED_EXIT_CODE = 3;
231
+
219
232
  const REDACTED = "[REDACTED]";
220
233
 
221
234
  const REDACTED_AUTH =`auth: { "username": ${REDACTED}, "access_key": ${REDACTED} }`;
@@ -239,5 +252,6 @@ module.exports = Object.freeze({
239
252
  LATEST_VERSION_SYNTAX_REGEX,
240
253
  ERROR_EXIT_CODE,
241
254
  AUTH_REGEX,
242
- REDACTED_AUTH
255
+ REDACTED_AUTH,
256
+ BUILD_FAILED_EXIT_CODE
243
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;
@@ -63,7 +63,7 @@ const packageInstall = (packageDir) => {
63
63
  logger.error(`Some error occurred while installing packages: ${error}`);
64
64
  reject(`Packages were not installed successfully.`);
65
65
  };
66
- nodeProcess = spawn('npm', ['install'], {cwd: packageDir});
66
+ nodeProcess = spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['install'], {cwd: packageDir});
67
67
  nodeProcess.on('close', nodeProcessCloseCallback);
68
68
  nodeProcess.on('error', nodeProcessErrorCallback);
69
69
  });
@@ -9,8 +9,9 @@ const request = require("request"),
9
9
  tableStream = require('table').createStream,
10
10
  chalk = require('chalk');
11
11
 
12
- 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;
13
13
  let specSummary = {
14
+ "buildError": null,
14
15
  "specs": [],
15
16
  "duration": null
16
17
  }
@@ -106,11 +107,15 @@ let printSpecsStatus = (bsConfig, buildDetails, rawArgs) => {
106
107
  },
107
108
  function(err, result) { // when loop ends
108
109
  if (err) {
110
+ if(err.status == 204) {
111
+ reject(specSummary.exitCode);
112
+ } else {
109
113
  utils.sendUsageReport(bsConfig, {}, `buildId: ${buildDetails.build_id}`, 'error', 'sync_cli_error', err, rawArgs);
114
+ }
110
115
  }
111
116
  logger.info(lineSeparator);
112
117
  specSummary.duration = endTime - startTime
113
- resolve(specSummary)
118
+ resolve(specSummary);
114
119
  }
115
120
  );
116
121
  });
@@ -145,7 +150,8 @@ let whileProcess = (whilstCallback) => {
145
150
  whileLoop = false;
146
151
  endTime = Date.now();
147
152
  showSpecsStatus(body);
148
- 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);
149
155
  default:
150
156
  whileLoop = false;
151
157
  return whilstCallback({ status: response.statusCode, message: body });
@@ -153,13 +159,25 @@ let whileProcess = (whilstCallback) => {
153
159
  });
154
160
  }
155
161
 
162
+ let getStackTraceUrl = () => {
163
+ return specSummary.buildError
164
+ }
165
+
156
166
  let showSpecsStatus = (data) => {
157
167
  let specData = JSON.parse(data);
158
168
  specData.forEach(specDetails => {
159
169
  if (specDetails == "created") {
160
- 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"]));
161
175
  } else {
162
- printSpecData(JSON.parse(specDetails))
176
+ if(!buildStarted) {
177
+ buildStarted = true
178
+ printInitialLog();
179
+ }
180
+ printSpecData(JSON.parse(specDetails));
163
181
  }
164
182
  });
165
183
  }
@@ -208,3 +226,4 @@ let getStatus = (status) => {
208
226
  }
209
227
 
210
228
  exports.printSpecsStatus = printSpecsStatus;
229
+ exports.getStackTraceUrl = getStackTraceUrl;
@@ -85,6 +85,21 @@ exports.getErrorCodeFromMsg = (errMsg) => {
85
85
  case Constants.validationMessages.INVALID_LOCAL_ASYNC_ARGS:
86
86
  errorCode = 'invalid_local_async_args';
87
87
  break;
88
+ case Constants.validationMessages.INVALID_GEO_LOCATION:
89
+ errorCode = 'invalid_geo_location';
90
+ break;
91
+ case Constants.validationMessages.NOT_ALLOWED_GEO_LOCATION_AND_LOCAL_MODE:
92
+ errorCode = 'not_allowed_geo_location_and_local_mode';
93
+ break;
94
+ case Constants.validationMessages.HOME_DIRECTORY_NOT_FOUND:
95
+ errorCode = 'home_directory_not_found';
96
+ break;
97
+ case Constants.validationMessages.HOME_DIRECTORY_NOT_A_DIRECTORY:
98
+ errorCode = 'home_directory_not_a_directory';
99
+ break;
100
+ case Constants.validationMessages.CYPRESS_CONFIG_FILE_NOT_PART_OF_HOME_DIRECTORY:
101
+ errorCode = 'cypress_config_file_not_part_of_home_directory';
102
+ break;
88
103
  }
89
104
  if (
90
105
  errMsg.includes("Please use --config-file <path to browserstack.json>.")
@@ -272,6 +287,28 @@ exports.setCypressConfigFilename = (bsConfig, args) => {
272
287
  }
273
288
  }
274
289
 
290
+ exports.verifyGeolocationOption = () => {
291
+ let glOptionsSet = (this.searchForOption('-gl') || this.searchForOption('--gl'));
292
+ let geoHyphenLocationOptionsSet = (this.searchForOption('-geo-location') || this.searchForOption('--geo-location'));
293
+ let geoLocationOptionsSet = (this.searchForOption('-geolocation') || this.searchForOption('--geolocation'));
294
+ return (glOptionsSet || geoHyphenLocationOptionsSet || geoLocationOptionsSet);
295
+ }
296
+
297
+ exports.setGeolocation = (bsConfig, args) => {
298
+ let userProvidedGeolocation = this.verifyGeolocationOption();
299
+ bsConfig.run_settings.userProvidedGeolocation = (userProvidedGeolocation || (!this.isUndefined(bsConfig.run_settings.geolocation)));
300
+
301
+ if (userProvidedGeolocation && !this.isUndefined(args.geolocation)) {
302
+ bsConfig.run_settings.geolocation = args.geolocation;
303
+ }
304
+
305
+ if (this.isUndefined(bsConfig.run_settings.geolocation)){
306
+ bsConfig.run_settings.geolocation = null;
307
+ } else {
308
+ bsConfig.run_settings.geolocation = bsConfig.run_settings.geolocation.toUpperCase();
309
+ }
310
+ }
311
+
275
312
  // specs can be passed from bstack configuration file
276
313
  // specs can be passed via command line args as a string
277
314
  // command line args takes precedence over config
@@ -10,9 +10,18 @@ const config = require("./config"),
10
10
  Constants = require("./constants"),
11
11
  utils = require("./utils");
12
12
 
13
- const uploadSuits = (bsConfig, filePath, opts) => {
13
+
14
+ const purgeUploadBar = (obj) => {
15
+ obj.bar1.update(100, {
16
+ speed: ((obj.size / (Date.now() - obj.startTime)) / 125).toFixed(2) //kbits per sec
17
+ });
18
+ obj.bar1.stop();
19
+ clearInterval(obj.zipInterval);
20
+ }
21
+
22
+ const uploadSuits = (bsConfig, filePath, opts, obj) => {
14
23
  return new Promise(function (resolve, reject) {
15
- let startTime = Date.now();
24
+ obj.startTime = Date.now();
16
25
 
17
26
  if (opts.urlPresent) {
18
27
  return resolve({ [opts.md5ReturnKey]: opts.url });
@@ -21,28 +30,26 @@ const uploadSuits = (bsConfig, filePath, opts) => {
21
30
  return resolve({});
22
31
  }
23
32
 
24
- let size = fs.lstatSync(filePath).size;
33
+ let size = obj.size;
25
34
 
26
35
  // create new progress bar
27
- let bar1 = new cliProgress.SingleBar({
28
- format: `${filePath} [{bar}] {percentage}% | ETA: {eta}s | Speed: {speed} kbps | Duration: {duration}s [${(size / 1000000).toFixed(2)} MB]`,
29
- hideCursor: true,
36
+ obj.bar1 = new cliProgress.SingleBar({
37
+ format: `${filePath} [{bar}] {percentage}% | ETA: {eta}s | Speed: {speed} kbps | Duration: {duration}s [${(size / 1000000).toFixed(2)} MB]`
30
38
  });
31
39
 
32
- bar1.start(100, 0, {
40
+ obj.bar1.start(100, 0, {
33
41
  speed: "N/A"
34
42
  });
35
43
 
36
- bar1.on('start', () => {
44
+ obj.bar1.on('start', () => {
37
45
  });
38
46
 
39
- bar1.on('stop', () => {
47
+ obj.bar1.on('stop', () => {
40
48
  });
41
49
 
42
50
  let options = utils.generateUploadParams(bsConfig, filePath, opts.md5Data, opts.fileDetails)
43
51
  let responseData = null;
44
52
  var r = request.post(options, function (err, resp, body) {
45
- clearInterval(q);
46
53
 
47
54
  if (err) {
48
55
  reject(err);
@@ -55,7 +62,7 @@ const uploadSuits = (bsConfig, filePath, opts) => {
55
62
  if (resp.statusCode != 200) {
56
63
  if (resp.statusCode == 401) {
57
64
  if (responseData && responseData["error"]) {
58
- responseData["time"] = Date.now() - startTime;
65
+ responseData["time"] = Date.now() - obj.startTime;
59
66
  return reject(responseData["error"]);
60
67
  } else {
61
68
  return reject(Constants.validationMessages.INVALID_DEFAULT_AUTH_PARAMS);
@@ -65,7 +72,7 @@ const uploadSuits = (bsConfig, filePath, opts) => {
65
72
  return resolve({});
66
73
  }
67
74
  if(responseData && responseData["error"]){
68
- responseData["time"] = Date.now() - startTime;
75
+ responseData["time"] = Date.now() - obj.startTime;
69
76
  reject(responseData["error"]);
70
77
  } else {
71
78
  if (resp.statusCode == 413) {
@@ -75,30 +82,26 @@ const uploadSuits = (bsConfig, filePath, opts) => {
75
82
  }
76
83
  }
77
84
  } else {
78
- bar1.update(100, {
79
- speed: ((size / (Date.now() - startTime)) / 125).toFixed(2) //kbits per sec
80
- });
81
- bar1.stop();
85
+ purgeUploadBar(obj);
82
86
  logger.info(`${opts.messages.uploadingSuccess} (${responseData[opts.md5ReturnKey]})`);
83
87
  opts.cleanupMethod();
84
- responseData["time"] = Date.now() - startTime;
88
+ responseData["time"] = Date.now() - obj.startTime;
85
89
  resolve(responseData);
86
90
  }
87
91
  }
88
92
  });
89
93
 
90
- var q = setInterval(function () {
94
+ obj.zipInterval = setInterval(function () {
91
95
  let dispatched = r.req.connection._bytesDispatched;
92
96
  let percent = dispatched * 100.0 / size;
93
- bar1.update(percent, {
94
- speed: ((dispatched / (Date.now() - startTime)) / 125).toFixed(2) //kbits per sec
97
+ obj.bar1.update(percent, {
98
+ speed: ((dispatched / (Date.now() - obj.startTime)) / 125).toFixed(2) //kbits per sec
95
99
  });
96
100
  }, 150);
97
101
 
98
102
  });
99
103
  }
100
104
 
101
-
102
105
  const uploadCypressZip = (bsConfig, md5data, packageData) => {
103
106
  return new Promise(function (resolve, reject) {
104
107
  let obj = {}
@@ -116,8 +119,22 @@ const uploadCypressZip = (bsConfig, md5data, packageData) => {
116
119
  logger.info(npmOptions.messages.uploading);
117
120
  }
118
121
 
119
- let zipUpload = uploadSuits(bsConfig, config.fileName, zipOptions);
120
- let npmPackageUpload = uploadSuits(bsConfig, config.packageFileName, npmOptions);
122
+ var testZipUploadObj = {
123
+ bar1: null,
124
+ zipInterval: null,
125
+ size: fs.existsSync(config.fileName) ? fs.lstatSync(config.fileName).size : 0,
126
+ startTime: null
127
+ }
128
+
129
+ var npmPackageZipUploadObj = {
130
+ bar1: null,
131
+ zipInterval: null,
132
+ size: fs.existsSync(config.packageFileName) ? fs.lstatSync(config.packageFileName).size : 0,
133
+ startTime: null
134
+ }
135
+
136
+ let zipUpload = uploadSuits(bsConfig, config.fileName, zipOptions, testZipUploadObj);
137
+ let npmPackageUpload = uploadSuits(bsConfig, config.packageFileName, npmOptions, npmPackageZipUploadObj);
121
138
  Promise.all([zipUpload, npmPackageUpload]).then(function (uploads) {
122
139
  uploads.forEach(upload => {
123
140
  if(upload.zip_url && upload.time) {
@@ -130,6 +147,8 @@ const uploadCypressZip = (bsConfig, md5data, packageData) => {
130
147
  });
131
148
  return resolve(obj);
132
149
  }).catch((error) => {
150
+ purgeUploadBar(testZipUploadObj);
151
+ purgeUploadBar(npmPackageZipUploadObj);
133
152
  return reject(error);
134
153
  })
135
154
  })
package/bin/runner.js CHANGED
@@ -133,6 +133,12 @@ var argv = yargs
133
133
  demand: true,
134
134
  demand: Constants.cliMessages.RUN.CYPRESS_CONFIG_DEMAND
135
135
  },
136
+ 'gl': {
137
+ alias: 'geolocation',
138
+ describe: Constants.cliMessages.RUN.CYPRESS_GEO_LOCATION,
139
+ default: undefined,
140
+ type: 'string'
141
+ },
136
142
  'p': {
137
143
  alias: ['parallels', 'parallel'],
138
144
  describe: Constants.cliMessages.RUN.PARALLEL_DESC,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browserstack-cypress-cli",
3
- "version": "1.11.2",
3
+ "version": "1.12.0",
4
4
  "description": "BrowserStack Cypress CLI for Cypress integration with BrowserStack's remote devices.",
5
5
  "main": "index.js",
6
6
  "scripts": {