browserstack-cypress-cli 1.26.2 → 1.28.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.
@@ -38,6 +38,11 @@ module.exports = function info(args, rawArgs) {
38
38
  'User-Agent': utils.getUserAgent(),
39
39
  },
40
40
  };
41
+
42
+ if (Constants.turboScaleObj.enabled) {
43
+ options.url = `${config.turboScaleBuildsUrl}/${buildId}`;
44
+ }
45
+
41
46
  request.get(options, function (err, resp, body) {
42
47
  let message = null;
43
48
  let messageType = null;
@@ -36,6 +36,7 @@ const {
36
36
  checkAccessibilityPlatform,
37
37
  supportFileCleanup
38
38
  } = require('../accessibility-automation/helper');
39
+ const { isTurboScaleSession, getTurboScaleGridDetails, patchCypressConfigFileContent, atsFileCleanup } = require('../helpers/atsHelper');
39
40
 
40
41
  module.exports = function run(args, rawArgs) {
41
42
 
@@ -66,6 +67,8 @@ module.exports = function run(args, rawArgs) {
66
67
  const [isTestObservabilitySession, isBrowserstackInfra] = setTestObservabilityFlags(bsConfig);
67
68
  const checkAccessibility = checkAccessibilityPlatform(bsConfig);
68
69
  const isAccessibilitySession = bsConfig.run_settings.accessibility || checkAccessibility;
70
+ const turboScaleSession = isTurboScaleSession(bsConfig);
71
+ Constants.turboScaleObj.enabled = turboScaleSession;
69
72
 
70
73
  utils.setUsageReportingFlag(bsConfig, args.disableUsageReporting);
71
74
 
@@ -77,7 +80,7 @@ module.exports = function run(args, rawArgs) {
77
80
  // accept the access key from command line or env variable if provided
78
81
  utils.setAccessKey(bsConfig, args);
79
82
 
80
- let buildReportData = !isBrowserstackInfra ? null : await getInitialDetails(bsConfig, args, rawArgs);
83
+ let buildReportData = (turboScaleSession || !isBrowserstackInfra) ? null : await getInitialDetails(bsConfig, args, rawArgs);
81
84
 
82
85
  // accept the build name from command line if provided
83
86
  utils.setBuildName(bsConfig, args);
@@ -111,7 +114,10 @@ module.exports = function run(args, rawArgs) {
111
114
  /*
112
115
  Send build start to Observability
113
116
  */
114
- if(isTestObservabilitySession) await launchTestSession(bsConfig, bsConfigPath);
117
+ if(isTestObservabilitySession) {
118
+ await launchTestSession(bsConfig, bsConfigPath);
119
+ utils.setO11yProcessHooks(null, bsConfig, args, null, buildReportData);
120
+ }
115
121
 
116
122
  // accept the system env list from bsconf and set it
117
123
  utils.setSystemEnvs(bsConfig);
@@ -144,6 +150,29 @@ module.exports = function run(args, rawArgs) {
144
150
  if (isAccessibilitySession && isBrowserstackInfra) {
145
151
  await createAccessibilityTestRun(bsConfig);
146
152
  }
153
+
154
+ if (turboScaleSession) {
155
+ // Local is only required in case user is running on trial grid and wants to access private website.
156
+ // Even then, it will be spawned separately via browserstack-cli ats connect-grid command and not via browserstack-cypress-cli
157
+ // Hence whenever running on ATS, need to make local as false
158
+ bsConfig.connection_settings.local = false;
159
+
160
+ const gridDetails = await getTurboScaleGridDetails(bsConfig, args, rawArgs);
161
+
162
+ if (gridDetails && Object.keys(gridDetails).length > 0) {
163
+ Constants.turboScaleObj.gridDetails = gridDetails;
164
+ Constants.turboScaleObj.gridUrl = gridDetails.cypressUrl;
165
+ Constants.turboScaleObj.uploadUrl = gridDetails.cypressUrl + '/upload';
166
+ Constants.turboScaleObj.buildUrl = gridDetails.cypressUrl + '/build';
167
+
168
+ logger.debug(`Automate TurboScale Grid URL set to ${gridDetails.url}`);
169
+
170
+ patchCypressConfigFileContent(bsConfig);
171
+ } else {
172
+ process.exitCode = Constants.ERROR_EXIT_CODE;
173
+ return;
174
+ }
175
+ }
147
176
  }
148
177
 
149
178
  const { packagesInstalled } = !isBrowserstackInfra ? false : await packageInstaller.packageSetupAndInstaller(bsConfig, config.packageDirName, {markBlockStart, markBlockEnd});
@@ -183,10 +212,10 @@ module.exports = function run(args, rawArgs) {
183
212
 
184
213
  //get the number of spec files
185
214
  markBlockStart('getNumberOfSpecFiles');
186
- let specFiles = utils.getNumberOfSpecFiles(bsConfig, args, cypressConfigFile);
215
+ let specFiles = utils.getNumberOfSpecFiles(bsConfig, args, cypressConfigFile, turboScaleSession);
187
216
  markBlockEnd('getNumberOfSpecFiles');
188
217
 
189
- bsConfig['run_settings']['video_config'] = utils.getVideoConfig(cypressConfigFile);
218
+ bsConfig['run_settings']['video_config'] = utils.getVideoConfig(cypressConfigFile, bsConfig);
190
219
 
191
220
  // return the number of parallels user specified
192
221
  let userSpecifiedParallels = utils.getParallels(bsConfig, args);
@@ -248,6 +277,19 @@ module.exports = function run(args, rawArgs) {
248
277
  if (process.env.BROWSERSTACK_TEST_ACCESSIBILITY === 'true') {
249
278
  supportFileCleanup();
250
279
  }
280
+
281
+ if (turboScaleSession) {
282
+ atsFileCleanup(bsConfig);
283
+ }
284
+
285
+ // Set config args for enforce_settings
286
+ if ( !utils.isUndefinedOrFalse(bsConfig.run_settings.enforce_settings) ) {
287
+ markBlockStart('setEnforceSettingsConfig');
288
+ logger.debug('Started setting the configs');
289
+ utils.setEnforceSettingsConfig(bsConfig);
290
+ logger.debug('Completed setting the configs');
291
+ markBlockEnd('setEnforceSettingsConfig');
292
+ }
251
293
  // Create build
252
294
  //setup Local Testing
253
295
  markBlockStart('localSetup');
@@ -264,6 +306,9 @@ module.exports = function run(args, rawArgs) {
264
306
  markBlockEnd('createBuild');
265
307
  markBlockEnd('total');
266
308
  utils.setProcessHooks(data.build_id, bsConfig, bs_local, args, buildReportData);
309
+ if(isTestObservabilitySession) {
310
+ utils.setO11yProcessHooks(data.build_id, bsConfig, bs_local, args, buildReportData);
311
+ }
267
312
  let message = `${data.message}! ${Constants.userMessages.BUILD_CREATED} with build id: ${data.build_id}`;
268
313
  let dashboardLink = `${Constants.userMessages.VISIT_DASHBOARD} ${data.dashboard_url}`;
269
314
  buildReportData = { 'build_id': data.build_id, 'parallels': userSpecifiedParallels, ...buildReportData }
@@ -296,13 +341,13 @@ module.exports = function run(args, rawArgs) {
296
341
  logger.debug("Completed polling of build status");
297
342
 
298
343
  // stop the Local instance
299
- await utils.stopLocalBinary(bsConfig, bs_local, args, rawArgs, buildReportData);
344
+ if (!turboScaleSession) await utils.stopLocalBinary(bsConfig, bs_local, args, rawArgs, buildReportData);
300
345
 
301
346
  // waiting for 5 secs for upload to complete (as a safety measure)
302
347
  await new Promise(resolve => setTimeout(resolve, 5000));
303
348
 
304
349
  // download build artifacts
305
- if (exitCode != Constants.BUILD_FAILED_EXIT_CODE) {
350
+ if (exitCode != Constants.BUILD_FAILED_EXIT_CODE && !turboScaleSession) {
306
351
  if (utils.nonEmptyArray(bsConfig.run_settings.downloads)) {
307
352
  logger.debug("Downloading build artifacts");
308
353
  await downloadBuildArtifacts(bsConfig, data.build_id, args, rawArgs, buildReportData);
@@ -314,7 +359,7 @@ module.exports = function run(args, rawArgs) {
314
359
  markBlockEnd('postBuild');
315
360
  utils.handleSyncExit(exitCode, data.dashboard_url);
316
361
  });
317
- } else {
362
+ } else if(!turboScaleSession){
318
363
  let stacktraceUrl = getStackTraceUrl();
319
364
  downloadBuildStacktrace(stacktraceUrl).then((message) => {
320
365
  utils.sendUsageReport(bsConfig, args, message, Constants.messageTypes.SUCCESS, null, buildReportData, rawArgs);
@@ -330,7 +375,7 @@ module.exports = function run(args, rawArgs) {
330
375
  });
331
376
  }
332
377
  });
333
- } else if (utils.nonEmptyArray(bsConfig.run_settings.downloads)) {
378
+ } else if (utils.nonEmptyArray(bsConfig.run_settings.downloads && !turboScaleSession)) {
334
379
  logger.info(Constants.userMessages.ASYNC_DOWNLOADS.replace('<build-id>', data.build_id));
335
380
  }
336
381
 
@@ -19,17 +19,19 @@ module.exports = function stop(args, rawArgs) {
19
19
  // accept the access key from command line if provided
20
20
  utils.setAccessKey(bsConfig, args);
21
21
 
22
- let buildReportData = await getInitialDetails(bsConfig, args, rawArgs);
23
-
24
22
  utils.setUsageReportingFlag(bsConfig, args.disableUsageReporting);
25
23
 
26
24
  // set cypress config filename
27
25
  utils.setCypressConfigFilename(bsConfig, args);
28
26
 
29
27
  let buildId = args._[1];
28
+ let buildReportData = null;
30
29
 
31
- await utils.stopBrowserStackBuild(bsConfig, args, buildId, rawArgs, buildReportData);
30
+ if (!Constants.turboScaleObj.enabled) {
31
+ buildReportData = await getInitialDetails(bsConfig, args, rawArgs);
32
+ }
32
33
 
34
+ await utils.stopBrowserStackBuild(bsConfig, args, buildId, rawArgs, buildReportData);
33
35
  }).catch(function (err) {
34
36
  logger.error(err);
35
37
  utils.setUsageReportingFlag(null, args.disableUsageReporting);
@@ -0,0 +1,118 @@
1
+ const path = require('path');
2
+ const fs = require('fs')
3
+
4
+ const request = require('request'),
5
+ logger = require('./logger').winstonLogger,
6
+ utils = require('./utils'),
7
+ config = require('./config');
8
+ Constants = require('./constants');
9
+
10
+ exports.isTurboScaleSession = (bsConfig) => {
11
+ // env var will override config
12
+ if (process.env.BROWSERSTACK_TURBOSCALE && process.env.BROWSERSTACK_TURBOSCALE === 'true') {
13
+ return true;
14
+ }
15
+
16
+ if (bsConfig.run_settings && bsConfig.run_settings.turboScale) {
17
+ return true;
18
+ }
19
+
20
+ return false;
21
+ };
22
+
23
+ exports.getTurboScaleOptions = (bsConfig) => {
24
+ if (bsConfig.run_settings && bsConfig.run_settings.turboScaleOptions) {
25
+ return bsConfig.run_settings.turboScaleOptions;
26
+ }
27
+
28
+ return {};
29
+ };
30
+
31
+ exports.getTurboScaleGridName = (bsConfig) => {
32
+ // env var will override config
33
+ if (process.env.BROWSERSTACK_TURBOSCALE_GRID_NAME) {
34
+ return process.env.BROWSERSTACK_TURBOSCALE_GRID_NAME;
35
+ }
36
+
37
+ if (bsConfig.run_settings && bsConfig.run_settings.turboScaleOptions && bsConfig.run_settings.turboScaleOptions.gridName) {
38
+ return bsConfig.run_settings.turboScaleOptions.gridName;
39
+ }
40
+
41
+ return 'NO_GRID_NAME_PASSED';
42
+ };
43
+
44
+ exports.getTurboScaleGridDetails = async (bsConfig, args, rawArgs) => {
45
+ try {
46
+ const gridName = this.getTurboScaleGridName(bsConfig);
47
+
48
+ return new Promise((resolve, reject) => {
49
+ let options = {
50
+ url: `${config.turboScaleAPIUrl}/grids/${gridName}`,
51
+ auth: {
52
+ username: bsConfig.auth.username,
53
+ password: bsConfig.auth.access_key,
54
+ },
55
+ headers: {
56
+ 'User-Agent': utils.getUserAgent(),
57
+ }
58
+ };
59
+ let responseData = {};
60
+ request.get(options, function (err, resp, data) {
61
+ if(err) {
62
+ logger.warn(utils.formatRequest(err, resp, data));
63
+ utils.sendUsageReport(bsConfig, args, err, Constants.messageTypes.ERROR, 'get_ats_details_failed', null, rawArgs);
64
+ resolve({});
65
+ } else {
66
+ try {
67
+ responseData = JSON.parse(data);
68
+ } catch (e) {
69
+ responseData = {};
70
+ }
71
+ if(resp.statusCode != 200) {
72
+ logger.warn(`Warn: Get Automate TurboScale Details Request failed with status code ${resp.statusCode}`);
73
+ utils.sendUsageReport(bsConfig, args, responseData["error"], Constants.messageTypes.ERROR, 'get_ats_details_failed', null, rawArgs);
74
+ resolve({});
75
+ }
76
+ resolve(responseData);
77
+ }
78
+ });
79
+ });
80
+ } catch (err) {
81
+ logger.error(`Failed to find TurboScale Grid: ${err}: ${err.stack}`);
82
+ }
83
+ };
84
+
85
+ exports.patchCypressConfigFileContent = (bsConfig) => {
86
+ try {
87
+ let cypressConfigFileData = fs.readFileSync(path.resolve(bsConfig.run_settings.cypress_config_file)).toString();
88
+ const patchedConfigFileData = cypressConfigFileData + '\n\n' + `
89
+ let originalFunction = module.exports.e2e.setupNodeEvents;
90
+
91
+ module.exports.e2e.setupNodeEvents = (on, config) => {
92
+ const bstackOn = require("./cypressPatch.js")(on);
93
+ if (originalFunction !== null && originalFunction !== undefined) {
94
+ originalFunction(bstackOn, config);
95
+ }
96
+ }
97
+ `
98
+
99
+ let confPath = bsConfig.run_settings.cypress_config_file;
100
+ let patchedConfPathList = confPath.split(path.sep);
101
+ patchedConfPathList[patchedConfPathList.length - 1] = 'patched_ats_config_file.js'
102
+ const patchedConfPath = patchedConfPathList.join(path.sep);
103
+
104
+ bsConfig.run_settings.patched_cypress_config_file = patchedConfPath;
105
+
106
+ fs.writeFileSync(path.resolve(bsConfig.run_settings.patched_cypress_config_file), patchedConfigFileData);
107
+ } catch(e) {
108
+ logger.error(`Encountered an error when trying to patch ATS Cypress Config File ${e}`);
109
+ return {};
110
+ }
111
+ }
112
+
113
+ exports.atsFileCleanup = (bsConfig) => {
114
+ const filePath = path.resolve(bsConfig.run_settings.patched_cypress_config_file);
115
+ if(fs.existsSync(filePath)){
116
+ fs.unlinkSync(filePath);
117
+ }
118
+ }
@@ -23,6 +23,10 @@ const createBuild = (bsConfig, zip) => {
23
23
  body: data
24
24
  }
25
25
 
26
+ if (Constants.turboScaleObj.enabled) {
27
+ options.url = Constants.turboScaleObj.buildUrl;
28
+ }
29
+
26
30
  request.post(options, function (err, resp, body) {
27
31
  if (err) {
28
32
  logger.error(utils.formatRequest(err, resp, body));
@@ -184,6 +184,10 @@ const validate = (bsConfig, args) => {
184
184
  reject(Constants.validationMessages.EMPTY_CYPRESS_CONFIG_FILE);
185
185
  }
186
186
 
187
+ if ( bsConfig && bsConfig.run_settings && bsConfig.run_settings.enforce_settings && bsConfig.run_settings.enforce_settings.toString() === 'true' && Utils.isUndefined(bsConfig.run_settings.specs) ) {
188
+ reject(Constants.validationMessages.EMPTY_SPECS_IN_BROWSERSTACK_JSON);
189
+ }
190
+
187
191
  // validate parallels specified in browserstack.json if parallels are not specified via arguments
188
192
  if (!Utils.isUndefined(args) && Utils.isUndefined(args.parallels) && !Utils.isParallelValid(bsConfig.run_settings.parallels)) reject(Constants.validationMessages.INVALID_PARALLELS_CONFIGURATION);
189
193
 
@@ -214,7 +218,8 @@ const validate = (bsConfig, args) => {
214
218
 
215
219
  logger.debug(`Validating ${bsConfig.run_settings.cypress_config_filename}`);
216
220
  try {
217
- if (bsConfig.run_settings.cypress_config_filename !== 'false') {
221
+ // Not reading cypress config file upon enforce_settings
222
+ if (Utils.isUndefinedOrFalse(bsConfig.run_settings.enforce_settings) && bsConfig.run_settings.cypress_config_filename !== 'false') {
218
223
  if (bsConfig.run_settings.cypressTestSuiteType === Constants.CYPRESS_V10_AND_ABOVE_TYPE) {
219
224
  const completeCypressConfigFile = readCypressConfigFile(bsConfig)
220
225
  if (!Utils.isUndefined(completeCypressConfigFile)) {
@@ -234,6 +239,11 @@ const validate = (bsConfig, args) => {
234
239
  // Detect if the user is not using the right directory structure, and throw an error
235
240
  if (!Utils.isUndefined(cypressConfigFile.integrationFolder) && !Utils.isCypressProjDirValid(bsConfig.run_settings.cypressProjectDir,cypressConfigFile.integrationFolder)) reject(Constants.validationMessages.INCORRECT_DIRECTORY_STRUCTURE);
236
241
  }
242
+ else {
243
+ logger.debug("Validating baseurl and integrationFolder in browserstack.json");
244
+ if (!Utils.isUndefined(bsConfig.run_settings.baseUrl) && bsConfig.run_settings.baseUrl.includes("localhost") && !Utils.getLocalFlag(bsConfig.connection_settings)) reject(Constants.validationMessages.LOCAL_NOT_SET.replace("<baseUrlValue>", bsConfig.run_settings.baseUrl));
245
+ if (!Utils.isUndefined(bsConfig.run_settings.integrationFolder) && !Utils.isCypressProjDirValid(bsConfig.run_settings.cypressProjectDir,bsConfig.run_settings.integrationFolder)) reject(Constants.validationMessages.INCORRECT_DIRECTORY_STRUCTURE);
246
+ }
237
247
  } catch(error){
238
248
  reject(Constants.validationMessages.INVALID_CYPRESS_JSON)
239
249
  }
@@ -121,6 +121,10 @@ const checkUploadedMd5 = (bsConfig, args, instrumentBlocks) => {
121
121
  body: JSON.stringify(data)
122
122
  };
123
123
 
124
+ if (Constants.turboScaleObj.enabled) {
125
+ options.url = config.turboScaleMd5Sum;
126
+ }
127
+
124
128
  instrumentBlocks.markBlockStart("checkAlreadyUploaded.railsCheck");
125
129
  request.post(options, function (err, resp, body) {
126
130
  if (err) {
@@ -24,7 +24,11 @@ config.packageFileName = "bstackPackages.tar.gz";
24
24
  config.packageDirName = "tmpBstackPackages";
25
25
  config.retries = 5;
26
26
  config.networkErrorExitCode = 2;
27
- config.compiledConfigJsDirName = 'tmpBstackCompiledJs'
28
- config.configJsonFileName = 'tmpCypressConfig.json'
27
+ config.compiledConfigJsDirName = 'tmpBstackCompiledJs';
28
+ config.configJsonFileName = 'tmpCypressConfig.json';
29
+
30
+ // turboScale
31
+ config.turboScaleMd5Sum = `${config.turboScaleUrl}/md5sumcheck`;
32
+ config.turboScaleBuildsUrl = `${config.turboScaleUrl}/builds`;
29
33
 
30
34
  module.exports = config;
@@ -3,5 +3,7 @@
3
3
  "rails_host": "https://api.browserstack.com",
4
4
  "dashboardUrl": "https://automate.browserstack.com/dashboard/v2/builds/",
5
5
  "usageReportingUrl": "https://eds.browserstack.com:443/send_event_cy_internal",
6
- "localTestingListUrl": "https://www.browserstack.com/local/v1/list"
6
+ "localTestingListUrl": "https://www.browserstack.com/local/v1/list",
7
+ "turboScaleUrl": "https://grid.browserstack.com/packages/cypress",
8
+ "turboScaleAPIUrl": "https://api.browserstack.com/automate-turboscale/v1"
7
9
  }
@@ -72,6 +72,8 @@ const userMessages = {
72
72
  UPLOADING_NPM_PACKAGES_SUCCESS: "Uploaded node_modules successfully",
73
73
  SKIP_UPLOADING_TESTS:
74
74
  "Skipping zip upload since BrowserStack already has your test suite that has not changed since the last run.",
75
+ SKIP_NPM_INSTALL:
76
+ "Skipping NPM Install as the enforce_settings has been passed.",
75
77
  SKIP_UPLOADING_NPM_PACKAGES:
76
78
  "Skipping the upload of node_modules since BrowserStack has already cached your npm dependencies that have not changed since the last run.",
77
79
  LOCAL_TRUE: "you will now be able to test localhost / private URLs",
@@ -134,8 +136,10 @@ const validationMessages = {
134
136
  "cypress_proj_dir is not set in run_settings. See https://www.browserstack.com/docs/automate/cypress/sample-tutorial to learn more.",
135
137
  EMPTY_CYPRESS_CONFIG_FILE:
136
138
  "cypress_config_file is not set in run_settings. See https://www.browserstack.com/docs/automate/cypress/configuration-file to learn more.",
139
+ EMPTY_SPECS_IN_BROWSERSTACK_JSON:
140
+ "specs is required when enforce_settings is true in run_settings of browserstack.json",
137
141
  VALIDATED: "browserstack.json file is validated",
138
- NOT_VALID: "browerstack.json is not valid",
142
+ NOT_VALID: "browserstack.json is not valid",
139
143
  NOT_VALID_JSON: "browerstack.json is not a valid json",
140
144
  INVALID_EXTENSION: "Invalid files, please remove these files and try again.",
141
145
  INVALID_PARALLELS_CONFIGURATION:
@@ -437,6 +441,8 @@ const CYPRESS_CONFIG_FILE_NAMES = Object.keys(CYPRESS_CONFIG_FILE_MAPPING);
437
441
 
438
442
  const CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS = ['js', 'ts', 'cjs', 'mjs']
439
443
 
444
+ const turboScaleObj = {};
445
+
440
446
  module.exports = Object.freeze({
441
447
  syncCLI,
442
448
  userMessages,
@@ -449,6 +455,7 @@ module.exports = Object.freeze({
449
455
  hashingOptions,
450
456
  packageInstallerOptions,
451
457
  specFileTypes,
458
+ turboScaleObj,
452
459
  DEFAULT_CYPRESS_SPEC_PATH,
453
460
  DEFAULT_CYPRESS_10_SPEC_PATH,
454
461
  SPEC_TOTAL_CHAR_LIMIT,
@@ -133,7 +133,11 @@ const packageSetupAndInstaller = (bsConfig, packageDir, instrumentBlocks) => {
133
133
  let obj = {
134
134
  packagesInstalled: false
135
135
  };
136
-
136
+ if (bsConfig && bsConfig.run_settings && bsConfig.run_settings.enforce_settings && bsConfig.run_settings.enforce_settings.toString() === 'true' ) {
137
+ logger.info("Enforce_settings is enabled in run_settings");
138
+ logger.debug(Constants.userMessages.SKIP_NPM_INSTALL);
139
+ return resolve(obj);
140
+ }
137
141
  logger.info(Constants.userMessages.NPM_INSTALL);
138
142
  instrumentBlocks.markBlockStart("packageInstaller.folderSetup");
139
143
  logger.debug("Started setting up package folder");
@@ -0,0 +1,203 @@
1
+ const Constants = require('./constants');
2
+
3
+ const usernameOptions = {
4
+ 'u': {
5
+ alias: 'username',
6
+ describe: Constants.cliMessages.COMMON.USERNAME,
7
+ type: "string",
8
+ default: undefined
9
+ },
10
+ }
11
+
12
+ const accessKeyOptions = {
13
+ 'k': {
14
+ alias: 'key',
15
+ describe: Constants.cliMessages.COMMON.ACCESS_KEY,
16
+ type: "string",
17
+ default: undefined
18
+ },
19
+ }
20
+
21
+ const configFileOptions = {
22
+ 'cf': {
23
+ alias: 'config-file',
24
+ describe: Constants.cliMessages.COMMON.CONFIG_FILE_PATH,
25
+ default: 'browserstack.json',
26
+ type: 'string',
27
+ nargs: 1,
28
+ demand: true,
29
+ demand: Constants.cliMessages.COMMON.CONFIG_DEMAND
30
+ },
31
+ }
32
+
33
+ const debugModeOptions = {
34
+ 'cli-debug': {
35
+ default: false,
36
+ describe: Constants.cliMessages.COMMON.DEBUG,
37
+ type: "boolean"
38
+ },
39
+ }
40
+
41
+ exports.disableUsageReportingOptions = {
42
+ 'disable-usage-reporting': {
43
+ default: undefined,
44
+ description: Constants.cliMessages.COMMON.DISABLE_USAGE_REPORTING,
45
+ type: "boolean"
46
+ },
47
+ }
48
+
49
+ exports.commonBuildOptions = {
50
+ ...configFileOptions,
51
+ ...this.disableUsageReportingOptions,
52
+ ...usernameOptions,
53
+ ...accessKeyOptions,
54
+ ...debugModeOptions,
55
+ }
56
+
57
+ exports.runOptions = {
58
+ ...this.commonBuildOptions,
59
+ 'ccf': {
60
+ alias: 'cypress-config-file',
61
+ describe: Constants.cliMessages.RUN.CYPRESS_DESC,
62
+ default: './cypress.json',
63
+ type: 'string',
64
+ nargs: 1,
65
+ demand: true,
66
+ demand: Constants.cliMessages.RUN.CYPRESS_CONFIG_DEMAND
67
+ },
68
+ 'gl': {
69
+ alias: 'geolocation',
70
+ describe: Constants.cliMessages.RUN.CYPRESS_GEO_LOCATION,
71
+ default: undefined,
72
+ type: 'string'
73
+ },
74
+ 'p': {
75
+ alias: ['parallels', 'parallel'],
76
+ describe: Constants.cliMessages.RUN.PARALLEL_DESC,
77
+ type: "number",
78
+ default: undefined
79
+ },
80
+ 'b': {
81
+ alias: ['build-name', 'ci-build-id'],
82
+ describe: Constants.cliMessages.RUN.BUILD_NAME,
83
+ type: "string",
84
+ default: undefined
85
+ },
86
+ 'e': {
87
+ alias: 'exclude',
88
+ describe: Constants.cliMessages.RUN.EXCLUDE,
89
+ type: "string",
90
+ default: undefined
91
+ },
92
+ 's': {
93
+ alias: ['specs', 'spec'],
94
+ describe: Constants.cliMessages.RUN.SPECS_DESCRIPTION,
95
+ type: "string",
96
+ default: undefined
97
+ },
98
+ 'env': {
99
+ describe: Constants.cliMessages.RUN.ENV_DESCRIPTION,
100
+ type: "string",
101
+ default: undefined
102
+ },
103
+ 't': {
104
+ alias: ['specTimeout'],
105
+ default: undefined,
106
+ describe: Constants.cliMessages.RUN.SPEC_TIMEOUT,
107
+ type: "string"
108
+ },
109
+ 'disable-npm-warning': {
110
+ default: false,
111
+ description: Constants.cliMessages.COMMON.NO_NPM_WARNING,
112
+ type: "boolean"
113
+ },
114
+ 'sync': {
115
+ default: true,
116
+ describe: Constants.cliMessages.RUN.SYNC_DESCRIPTION,
117
+ type: "boolean"
118
+ },
119
+ 'async': {
120
+ default: false,
121
+ describe: Constants.cliMessages.RUN.ASYNC_DESCRIPTION,
122
+ type: "boolean"
123
+ },
124
+ 'force-upload': {
125
+ default: false,
126
+ describe: Constants.cliMessages.COMMON.FORCE_UPLOAD,
127
+ type: "boolean"
128
+ },
129
+ 'headed': {
130
+ default: false,
131
+ describe: Constants.cliMessages.RUN.HEADED,
132
+ type: "boolean"
133
+ },
134
+ 'local': {
135
+ describe: Constants.cliMessages.RUN.LOCAL,
136
+ type: "boolean"
137
+ },
138
+ 'local-identifier': {
139
+ describe: Constants.cliMessages.RUN.LOCAL_IDENTIFIER,
140
+ type: "string"
141
+ },
142
+ 'local-mode': {
143
+ describe: Constants.cliMessages.RUN.LOCAL_MODE,
144
+ type: "string"
145
+ },
146
+ 'local-config-file': {
147
+ describe: Constants.cliMessages.RUN.LOCAL_CONFIG_FILE,
148
+ type: "string"
149
+ },
150
+ 'no-wrap': {
151
+ default: false,
152
+ describe: Constants.cliMessages.RUN.SYNC_NO_WRAP,
153
+ type: "boolean"
154
+ },
155
+ 'browser': {
156
+ describe: Constants.cliMessages.RUN.BROWSER_DESCRIPTION,
157
+ type: "string",
158
+ default: undefined
159
+ },
160
+ 'c': {
161
+ alias: 'config',
162
+ describe: Constants.cliMessages.RUN.CONFIG_DESCRIPTION,
163
+ type: "string",
164
+ default: undefined
165
+ },
166
+ 'r': {
167
+ alias: 'reporter',
168
+ default: undefined,
169
+ describe: Constants.cliMessages.RUN.REPORTER,
170
+ type: "string"
171
+ },
172
+ 'o': {
173
+ alias: 'reporter-options',
174
+ default: undefined,
175
+ describe: Constants.cliMessages.RUN.REPORTER_OPTIONS,
176
+ type: "string"
177
+ },
178
+ 'record': {
179
+ describe: Constants.cliMessages.RUN.RECORD,
180
+ type: "boolean"
181
+ },
182
+ 'record-key': {
183
+ default: undefined,
184
+ describe: Constants.cliMessages.RUN.RECORD_KEY,
185
+ type: "string"
186
+ },
187
+ 'projectId': {
188
+ default: undefined,
189
+ describe: Constants.cliMessages.RUN.PROJECT_ID,
190
+ type: "string"
191
+ },
192
+ 'nv': {
193
+ alias: ['node-version', 'nodeVersion'],
194
+ default: undefined,
195
+ describe: Constants.cliMessages.RUN.NODE_VERSION,
196
+ type: "string"
197
+ },
198
+ 'build-tag': {
199
+ default: undefined,
200
+ describe: Constants.cliMessages.RUN.BUILD_TAG,
201
+ type: "string"
202
+ }
203
+ }
@@ -24,8 +24,8 @@ let terminalWidth = (process.stdout.columns) * 0.9;
24
24
  let lineSeparator = Constants.syncCLI.DEFAULT_LINE_SEP;
25
25
  if (!isNaN(terminalWidth)) lineSeparator = "\n" + "-".repeat(terminalWidth);
26
26
 
27
- let getOptions = (auth, build_id) => {
28
- return {
27
+ let getOptions = (auth, build_id) => {
28
+ const options = {
29
29
  url: `${config.buildUrlV2}${build_id}`,
30
30
  auth: {
31
31
  user: auth.username,
@@ -37,6 +37,12 @@ let getOptions = (auth, build_id) => {
37
37
  "User-Agent": utils.getUserAgent()
38
38
  }
39
39
  };
40
+
41
+ if (Constants.turboScaleObj.enabled) {
42
+ options.url = `${config.turboScaleBuildsUrl}/${build_id}`;
43
+ }
44
+
45
+ return options;
40
46
  }
41
47
 
42
48
  let getTableConfig = (termWidth) => {
@@ -22,7 +22,7 @@ const usageReporting = require("./usageReporting"),
22
22
  config = require("../helpers/config"),
23
23
  pkg = require('../../package.json'),
24
24
  transports = require('./logger').transports,
25
- { findGitConfig, printBuildLink, isTestObservabilitySession, isBrowserstackInfra, shouldReRunObservabilityTests } = require('../testObservability/helper/helper'),
25
+ o11yHelpers = require('../testObservability/helper/helper'),
26
26
  { OBSERVABILITY_ENV_VARS, TEST_OBSERVABILITY_REPORTER } = require('../testObservability/helper/constants');
27
27
 
28
28
  const request = require('request');
@@ -434,7 +434,8 @@ exports.setProjectId = (bsConfig, args, cypressConfigFile) => {
434
434
  } else if(!this.isUndefined(bsConfig.run_settings["projectId"])) {
435
435
  return bsConfig.run_settings["projectId"];
436
436
  } else {
437
- if (!this.isUndefined(cypressConfigFile) && !this.isUndefined(cypressConfigFile["projectId"])) {
437
+ // ignore reading cypressconfig if enforce_settings is passed
438
+ if (this.isUndefinedOrFalse(bsConfig.run_settings.enforce_settings) && !this.isUndefined(cypressConfigFile) && !this.isUndefined(cypressConfigFile["projectId"])) {
438
439
  return cypressConfigFile["projectId"];
439
440
  }
440
441
  }
@@ -480,7 +481,7 @@ exports.setNodeVersion = (bsConfig, args) => {
480
481
  // specs can be passed via command line args as a string
481
482
  // command line args takes precedence over config
482
483
  exports.setUserSpecs = (bsConfig, args) => {
483
- if(isBrowserstackInfra() && isTestObservabilitySession() && shouldReRunObservabilityTests()) {
484
+ if(o11yHelpers.isBrowserstackInfra() && o11yHelpers.isTestObservabilitySession() && o11yHelpers.shouldReRunObservabilityTests()) {
484
485
  bsConfig.run_settings.specs = process.env.BROWSERSTACK_RERUN_TESTS;
485
486
  return;
486
487
  }
@@ -580,8 +581,8 @@ exports.setSystemEnvs = (bsConfig) => {
580
581
  envKeys[key] = process.env[key];
581
582
  });
582
583
 
583
- let gitConfigPath = findGitConfig(process.cwd());
584
- if(!isBrowserstackInfra()) process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL = gitConfigPath;
584
+ let gitConfigPath = o11yHelpers.findGitConfig(process.cwd());
585
+ if(!o11yHelpers.isBrowserstackInfra()) process.env.OBSERVABILITY_GIT_CONFIG_PATH_LOCAL = gitConfigPath;
585
586
  if(gitConfigPath) {
586
587
  const relativePathFromGitConfig = path.relative(gitConfigPath, process.cwd());
587
588
  envKeys["OBSERVABILITY_GIT_CONFIG_PATH"] = relativePathFromGitConfig ? relativePathFromGitConfig : 'DEFAULT';
@@ -628,6 +629,8 @@ exports.isPositiveInteger = (str) => {
628
629
 
629
630
  exports.isTrueString = value => (!this.isUndefined(value) && value.toString().toLowerCase() === 'true');
630
631
 
632
+ exports.isUndefinedOrFalse = value => ( this.isUndefined(value) || value.toString().toLowerCase() === 'false');
633
+
631
634
  exports.isFloat = (value) => Number(value) && Number(value) % 1 !== 0;
632
635
 
633
636
  exports.isInteger = (value) => Number.isInteger(value);
@@ -718,6 +721,11 @@ exports.generateUploadParams = (bsConfig, filePath, md5data, fileDetails) => {
718
721
  "User-Agent": exports.getUserAgent(),
719
722
  }
720
723
  }
724
+
725
+ if (Constants.turboScaleObj.enabled) {
726
+ options.url = Constants.turboScaleObj.uploadUrl;
727
+ }
728
+
721
729
  return options
722
730
  }
723
731
 
@@ -965,6 +973,7 @@ exports.setLocalArgs = (bsConfig, args) => {
965
973
  local_args['proxyPort'] = bsConfig["connection_settings"]["proxyPort"];
966
974
  if (bsConfig["connection_settings"]["useCaCertificate"])
967
975
  local_args['useCaCertificate'] = bsConfig["connection_settings"]["useCaCertificate"];
976
+
968
977
  local_args['daemon'] = true;
969
978
  local_args['enable-logging-for-api'] = true
970
979
  local_args['source'] = `cypress:${usageReporting.cli_version_and_path(bsConfig).version}`;
@@ -1067,7 +1076,7 @@ exports.getFilesToIgnore = (runSettings, excludeFiles, logging = true) => {
1067
1076
  return ignoreFiles;
1068
1077
  }
1069
1078
 
1070
- exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig) => {
1079
+ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig, turboScaleSession=false) => {
1071
1080
  let defaultSpecFolder
1072
1081
  let testFolderPath
1073
1082
  let globCypressConfigSpecPatterns = []
@@ -1077,7 +1086,8 @@ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig) => {
1077
1086
  if (bsConfig.run_settings.cypressTestSuiteType === Constants.CYPRESS_V10_AND_ABOVE_TYPE) {
1078
1087
  defaultSpecFolder = Constants.DEFAULT_CYPRESS_10_SPEC_PATH
1079
1088
  testFolderPath = defaultSpecFolder
1080
- if(!this.isUndefined(cypressConfig) && !this.isUndefined(cypressConfig.e2e)) {
1089
+ // Read cypress config if enforce_settings is not present
1090
+ if(this.isUndefinedOrFalse(bsConfig.run_settings.enforce_settings) && !this.isUndefined(cypressConfig) && !this.isUndefined(cypressConfig.e2e)) {
1081
1091
  if(!this.isUndefined(cypressConfig.e2e.specPattern)) {
1082
1092
  globCypressConfigSpecPatterns = Array.isArray(cypressConfig.e2e.specPattern) ?
1083
1093
  cypressConfig.e2e.specPattern : [cypressConfig.e2e.specPattern];
@@ -1141,6 +1151,13 @@ exports.getNumberOfSpecFiles = (bsConfig, args, cypressConfig) => {
1141
1151
  }
1142
1152
 
1143
1153
  logger.debug(`${files ? files.length : 0} spec files found`);
1154
+
1155
+ if (turboScaleSession) {
1156
+ // remove unwanted path prefix for turboscale
1157
+ files = files.map((x) => { return path.join(testFolderPath, x.split(testFolderPath)[1]) })
1158
+ // setting specs for turboScale as we don't have patched API for turboscale so we will rely on info from CLI
1159
+ bsConfig.run_settings.specs = files;
1160
+ }
1144
1161
  return files;
1145
1162
  };
1146
1163
 
@@ -1184,8 +1201,8 @@ exports.handleSyncExit = (exitCode, dashboard_url) => {
1184
1201
  syncCliLogger.info(Constants.userMessages.BUILD_REPORT_MESSAGE);
1185
1202
  syncCliLogger.info(dashboard_url);
1186
1203
  }
1187
- if(isTestObservabilitySession()) {
1188
- printBuildLink(true, exitCode);
1204
+ if(o11yHelpers.isTestObservabilitySession()) {
1205
+ o11yHelpers.printBuildLink(true, exitCode);
1189
1206
  } else {
1190
1207
  process.exit(exitCode);
1191
1208
  }
@@ -1286,9 +1303,53 @@ exports.setConfig = (bsConfig, args) => {
1286
1303
  }
1287
1304
  }
1288
1305
 
1306
+ exports.setVideoCliConfig = (bsConfig, videoConfig) => {
1307
+ // set cli config for video for cypress 13 and above to attain default value of true.
1308
+ if(this.isUndefined(videoConfig) || this.isUndefined(videoConfig.video) || this.isUndefined(videoConfig.videoUploadOnPasses) || this.isUndefined(bsConfig)) return;
1309
+ let user_cypress_version = (bsConfig && bsConfig.run_settings && bsConfig.run_settings.cypress_version) ? bsConfig.run_settings.cypress_version.toString() : undefined;
1310
+ let cypress_major_version = (user_cypress_version && user_cypress_version.match(/^(\d+)/)) ? user_cypress_version.split(".")[0] : undefined;
1311
+ let config_args = (bsConfig && bsConfig.run_settings && bsConfig.run_settings.config) ? bsConfig.run_settings.config : undefined;
1312
+ if(this.isUndefined(user_cypress_version) || this.isUndefined(cypress_major_version) || parseInt(cypress_major_version) >= 13 ) {
1313
+ let video_args = `video=${videoConfig.video},videoUploadOnPasses=${videoConfig.videoUploadOnPasses}`;
1314
+ config_args = this.isUndefined(config_args) ? video_args : config_args + ',' + video_args;
1315
+ logger.debug(`Setting default video true for cypress 13 and above in cli for cypress version ${user_cypress_version} with cli args - ${config_args}`)
1316
+ }
1317
+ if (bsConfig.run_settings && this.isNotUndefined(config_args)) bsConfig["run_settings"]["config"] = config_args;
1318
+ }
1319
+
1320
+ // set configs if enforce_settings is passed
1321
+ exports.setEnforceSettingsConfig = (bsConfig) => {
1322
+ if ( this.isUndefined(bsConfig) || this.isUndefined(bsConfig.run_settings) ) return;
1323
+ let config_args = (bsConfig && bsConfig.run_settings && bsConfig.run_settings.config) ? bsConfig.run_settings.config : undefined;
1324
+ if ( this.isUndefined(config_args) || !config_args.includes("video") ) {
1325
+ let video_args = (this.isUndefined(bsConfig.run_settings.video_config) || this.isUndefined(bsConfig.run_settings.video_config.video) || !bsConfig.run_settings.video_config.video ) ? 'video=false' : 'video=true' ;
1326
+ video_args += (this.isUndefined(bsConfig.run_settings.video_config) || this.isUndefined(bsConfig.run_settings.video_config.videoUploadOnPasses) || !bsConfig.run_settings.video_config.videoUploadOnPasses ) ? ',videoUploadOnPasses=false' : ',videoUploadOnPasses=true';
1327
+ config_args = this.isUndefined(config_args) ? video_args : config_args + ',' + video_args;
1328
+ logger.debug(`Setting video_args for enforce_settings to ${video_args}`);
1329
+ }
1330
+ if ( (bsConfig && bsConfig.run_settings && bsConfig.run_settings.baseUrl) && (this.isUndefined(config_args) || !config_args.includes("baseUrl")) ) {
1331
+ let base_url_args = 'baseUrl='+bsConfig.run_settings.baseUrl;
1332
+ config_args = this.isUndefined(config_args) ? base_url_args : config_args + ',' + base_url_args;
1333
+ logger.debug(`Setting base_url_args for enforce_settings to ${base_url_args}`);
1334
+ }
1335
+ // set specs in config of specpattern to override cypress config
1336
+ if( this.isNotUndefined(bsConfig.run_settings.specs) && bsConfig.run_settings.cypressTestSuiteType === Constants.CYPRESS_V10_AND_ABOVE_TYPE && (this.isUndefined(config_args) || !config_args.includes("specPattern")) ) {
1337
+ // doing this only for cypress 10 and above as --spec is given precedence for cypress 9.
1338
+ let specConfigs = bsConfig.run_settings.specs;
1339
+ // if multiple specs are passed, convert it into an array.
1340
+ if(specConfigs && specConfigs.includes(',')) {
1341
+ specConfigs = JSON.stringify(specConfigs.split(','));
1342
+ }
1343
+ let spec_pattern_args = `specPattern=${specConfigs}`;
1344
+ config_args = this.isUndefined(config_args) ? spec_pattern_args : config_args + ',' + spec_pattern_args;
1345
+ }
1346
+ if ( this.isNotUndefined(config_args) ) bsConfig["run_settings"]["config"] = config_args;
1347
+ logger.debug(`Setting conifg_args for enforce_settings to ${config_args}`);
1348
+ }
1349
+
1289
1350
  // blindly send other passed configs with run_settings and handle at backend
1290
1351
  exports.setOtherConfigs = (bsConfig, args) => {
1291
- if(isTestObservabilitySession() && process.env.BS_TESTOPS_JWT) {
1352
+ if(o11yHelpers.isTestObservabilitySession() && process.env.BS_TESTOPS_JWT) {
1292
1353
  bsConfig["run_settings"]["reporter"] = TEST_OBSERVABILITY_REPORTER;
1293
1354
  return;
1294
1355
  }
@@ -1382,6 +1443,11 @@ exports.stopBrowserStackBuild = async (bsConfig, args, buildId, rawArgs, buildRe
1382
1443
  'User-Agent': that.getUserAgent(),
1383
1444
  },
1384
1445
  };
1446
+
1447
+ if (Constants.turboScaleObj.enabled) {
1448
+ options.url = `${config.turboScaleBuildsUrl}/${buildId}/stop`;
1449
+ }
1450
+
1385
1451
  let message = null;
1386
1452
  let messageType = null;
1387
1453
  let errorCode = null;
@@ -1453,14 +1519,37 @@ exports.setProcessHooks = (buildId, bsConfig, bsLocal, args, buildReportData) =>
1453
1519
  process.on('uncaughtException', processExitHandler.bind(this, bindData));
1454
1520
  }
1455
1521
 
1522
+ exports.setO11yProcessHooks = (() => {
1523
+ let bindData = {};
1524
+ let handlerAdded = false;
1525
+ return (buildId, bsConfig, bsLocal, args, buildReportData) => {
1526
+ bindData.buildId = buildId;
1527
+ bindData.bsConfig = bsConfig;
1528
+ bindData.bsLocal = bsLocal;
1529
+ bindData.args = args;
1530
+ bindData.buildReportData = buildReportData;
1531
+ if (handlerAdded) return;
1532
+ handlerAdded = true;
1533
+ process.on('beforeExit', processO11yExitHandler.bind(this, bindData));
1534
+ }
1535
+ })()
1536
+
1456
1537
  async function processExitHandler(exitData){
1457
1538
  logger.warn(Constants.userMessages.PROCESS_KILL_MESSAGE);
1458
1539
  await this.stopBrowserStackBuild(exitData.bsConfig, exitData.args, exitData.buildId, null, exitData.buildReportData);
1459
1540
  await this.stopLocalBinary(exitData.bsConfig, exitData.bsLocalInstance, exitData.args, null, exitData.buildReportData);
1460
- await printBuildLink(true);
1541
+ await o11yHelpers.printBuildLink(true);
1461
1542
  process.exit(0);
1462
1543
  }
1463
1544
 
1545
+ async function processO11yExitHandler(exitData){
1546
+ if (exitData.buildId) {
1547
+ await o11yHelpers.printBuildLink(false);
1548
+ } else {
1549
+ await o11yHelpers.printBuildLink(true);
1550
+ }
1551
+ }
1552
+
1464
1553
  exports.fetchZipSize = (fileName) => {
1465
1554
  try {
1466
1555
  let stats = fs.statSync(fileName)
@@ -1499,14 +1588,23 @@ exports.fetchFolderSize = async (dir) => {
1499
1588
  }
1500
1589
  }
1501
1590
 
1502
- exports.getVideoConfig = (cypressConfig) => {
1591
+ exports.getVideoConfig = (cypressConfig, bsConfig = {}) => {
1503
1592
  let conf = {
1504
1593
  video: true,
1505
1594
  videoUploadOnPasses: true
1506
1595
  }
1507
- if (!this.isUndefined(cypressConfig.video)) conf.video = cypressConfig.video;
1508
- if (!this.isUndefined(cypressConfig.videoUploadOnPasses)) conf.videoUploadOnPasses = cypressConfig.videoUploadOnPasses;
1596
+ // Reading bsconfig in case of enforce_settings
1597
+ if ( this.isUndefined(bsConfig.run_settings) || this.isUndefinedOrFalse(bsConfig.run_settings.enforce_settings) ) {
1598
+ if (!this.isUndefined(cypressConfig.video)) conf.video = cypressConfig.video;
1599
+ if (!this.isUndefined(cypressConfig.videoUploadOnPasses)) conf.videoUploadOnPasses = cypressConfig.videoUploadOnPasses;
1600
+ }
1601
+ else {
1602
+ if (!this.isUndefined(bsConfig.run_settings) && !this.isUndefined(bsConfig.run_settings.video)) conf.video = bsConfig.run_settings.video;
1603
+ if (!this.isUndefined(bsConfig.run_settings) && !this.isUndefined(bsConfig.run_settings.videoUploadOnPasses)) conf.videoUploadOnPasses = bsConfig.run_settings.videoUploadOnPasses;
1604
+ }
1509
1605
 
1606
+ // set video in cli config in case of cypress 13 or above as default value is false there.
1607
+ this.setVideoCliConfig(bsConfig,conf);
1510
1608
  logger.debug(`Setting video = ${conf.video}`);
1511
1609
  logger.debug(`Setting videoUploadOnPasses = ${conf.videoUploadOnPasses}`);
1512
1610
  return conf;
package/bin/runner.js CHANGED
@@ -2,63 +2,10 @@
2
2
  'use strict';
3
3
  const yargs = require('yargs'),
4
4
  logger = require("./helpers/logger").winstonLogger,
5
- Constants = require('./helpers/constants');
5
+ Constants = require('./helpers/constants'),
6
+ { disableUsageReportingOptions, commonBuildOptions, runOptions } = require('./helpers/runnerArgs');
6
7
 
7
8
 
8
- const disableUsageReportingOptions = {
9
- 'disable-usage-reporting': {
10
- default: undefined,
11
- description: Constants.cliMessages.COMMON.DISABLE_USAGE_REPORTING,
12
- type: "boolean"
13
- },
14
- }
15
-
16
- const usernameOptions = {
17
- 'u': {
18
- alias: 'username',
19
- describe: Constants.cliMessages.COMMON.USERNAME,
20
- type: "string",
21
- default: undefined
22
- },
23
- }
24
-
25
- const accessKeyOptions = {
26
- 'k': {
27
- alias: 'key',
28
- describe: Constants.cliMessages.COMMON.ACCESS_KEY,
29
- type: "string",
30
- default: undefined
31
- },
32
- }
33
-
34
- const configFileOptions = {
35
- 'cf': {
36
- alias: 'config-file',
37
- describe: Constants.cliMessages.COMMON.CONFIG_FILE_PATH,
38
- default: 'browserstack.json',
39
- type: 'string',
40
- nargs: 1,
41
- demand: true,
42
- demand: Constants.cliMessages.COMMON.CONFIG_DEMAND
43
- },
44
- }
45
-
46
- const debugModeOptions = {
47
- 'cli-debug': {
48
- default: false,
49
- describe: Constants.cliMessages.COMMON.DEBUG,
50
- type: "boolean"
51
- },
52
- }
53
-
54
- const commonBuildOptions = {
55
- ...configFileOptions,
56
- ...disableUsageReportingOptions,
57
- ...usernameOptions,
58
- ...accessKeyOptions,
59
- ...debugModeOptions,
60
- }
61
-
62
9
  function checkCommands(yargs, argv, numRequired) {
63
10
  if (argv._.length < numRequired) {
64
11
  yargs.showHelp()
@@ -132,151 +79,7 @@ var argv = yargs
132
79
  argv = yargs
133
80
  .usage('usage: $0 run <options>')
134
81
  .options({
135
- ...commonBuildOptions,
136
- 'ccf': {
137
- alias: 'cypress-config-file',
138
- describe: Constants.cliMessages.RUN.CYPRESS_DESC,
139
- default: './cypress.json',
140
- type: 'string',
141
- nargs: 1,
142
- demand: true,
143
- demand: Constants.cliMessages.RUN.CYPRESS_CONFIG_DEMAND
144
- },
145
- 'gl': {
146
- alias: 'geolocation',
147
- describe: Constants.cliMessages.RUN.CYPRESS_GEO_LOCATION,
148
- default: undefined,
149
- type: 'string'
150
- },
151
- 'p': {
152
- alias: ['parallels', 'parallel'],
153
- describe: Constants.cliMessages.RUN.PARALLEL_DESC,
154
- type: "number",
155
- default: undefined
156
- },
157
- 'b': {
158
- alias: ['build-name', 'ci-build-id'],
159
- describe: Constants.cliMessages.RUN.BUILD_NAME,
160
- type: "string",
161
- default: undefined
162
- },
163
- 'e': {
164
- alias: 'exclude',
165
- describe: Constants.cliMessages.RUN.EXCLUDE,
166
- type: "string",
167
- default: undefined
168
- },
169
- 's': {
170
- alias: ['specs', 'spec'],
171
- describe: Constants.cliMessages.RUN.SPECS_DESCRIPTION,
172
- type: "string",
173
- default: undefined
174
- },
175
- 'env': {
176
- describe: Constants.cliMessages.RUN.ENV_DESCRIPTION,
177
- type: "string",
178
- default: undefined
179
- },
180
- 't': {
181
- alias: ['specTimeout'],
182
- default: undefined,
183
- describe: Constants.cliMessages.RUN.SPEC_TIMEOUT,
184
- type: "string"
185
- },
186
- 'disable-npm-warning': {
187
- default: false,
188
- description: Constants.cliMessages.COMMON.NO_NPM_WARNING,
189
- type: "boolean"
190
- },
191
- 'sync': {
192
- default: true,
193
- describe: Constants.cliMessages.RUN.SYNC_DESCRIPTION,
194
- type: "boolean"
195
- },
196
- 'async': {
197
- default: false,
198
- describe: Constants.cliMessages.RUN.ASYNC_DESCRIPTION,
199
- type: "boolean"
200
- },
201
- 'force-upload': {
202
- default: false,
203
- describe: Constants.cliMessages.COMMON.FORCE_UPLOAD,
204
- type: "boolean"
205
- },
206
- 'headed': {
207
- default: false,
208
- describe: Constants.cliMessages.RUN.HEADED,
209
- type: "boolean"
210
- },
211
- 'local': {
212
- describe: Constants.cliMessages.RUN.LOCAL,
213
- type: "boolean"
214
- },
215
- 'local-identifier': {
216
- describe: Constants.cliMessages.RUN.LOCAL_IDENTIFIER,
217
- type: "string"
218
- },
219
- 'local-mode': {
220
- describe: Constants.cliMessages.RUN.LOCAL_MODE,
221
- type: "string"
222
- },
223
- 'local-config-file': {
224
- describe: Constants.cliMessages.RUN.LOCAL_CONFIG_FILE,
225
- type: "string"
226
- },
227
- 'no-wrap': {
228
- default: false,
229
- describe: Constants.cliMessages.RUN.SYNC_NO_WRAP,
230
- type: "boolean"
231
- },
232
- 'browser': {
233
- describe: Constants.cliMessages.RUN.BROWSER_DESCRIPTION,
234
- type: "string",
235
- default: undefined
236
- },
237
- 'c': {
238
- alias: 'config',
239
- describe: Constants.cliMessages.RUN.CONFIG_DESCRIPTION,
240
- type: "string",
241
- default: undefined
242
- },
243
- 'r': {
244
- alias: 'reporter',
245
- default: undefined,
246
- describe: Constants.cliMessages.RUN.REPORTER,
247
- type: "string"
248
- },
249
- 'o': {
250
- alias: 'reporter-options',
251
- default: undefined,
252
- describe: Constants.cliMessages.RUN.REPORTER_OPTIONS,
253
- type: "string"
254
- },
255
- 'record': {
256
- describe: Constants.cliMessages.RUN.RECORD,
257
- type: "boolean"
258
- },
259
- 'record-key': {
260
- default: undefined,
261
- describe: Constants.cliMessages.RUN.RECORD_KEY,
262
- type: "string"
263
- },
264
- 'projectId': {
265
- default: undefined,
266
- describe: Constants.cliMessages.RUN.PROJECT_ID,
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"
279
- }
82
+ ...runOptions,
280
83
  })
281
84
  .help('help')
282
85
  .wrap(null)
@@ -9,6 +9,7 @@ const { promisify } = require('util');
9
9
  const gitconfig = require('gitconfiglocal');
10
10
  const { spawn, execSync } = require('child_process');
11
11
  const glob = require('glob');
12
+ const { runOptions } = require('../../helpers/runnerArgs')
12
13
 
13
14
  const pGitconfig = promisify(gitconfig);
14
15
 
@@ -64,8 +65,11 @@ const supportFileCleanup = () => {
64
65
  });
65
66
  }
66
67
 
68
+ exports.buildStopped = false;
69
+
67
70
  exports.printBuildLink = async (shouldStopSession, exitCode = null) => {
68
- if(!this.isTestObservabilitySession()) return;
71
+ if(!this.isTestObservabilitySession() || exports.buildStopped) return;
72
+ exports.buildStopped = true;
69
73
  try {
70
74
  if(shouldStopSession) {
71
75
  supportFileCleanup();
@@ -766,13 +770,45 @@ const getLocalSessionReporter = () => {
766
770
  }
767
771
 
768
772
  const cleanupTestObservabilityFlags = (rawArgs) => {
769
- const newRawArgs = [];
770
- for(let idx=0; idx<rawArgs.length; idx++) {
771
- if(!['--disable-browserstack-automation', '--disable-test-observability'].includes(rawArgs[idx])) {
772
- newRawArgs.push(rawArgs[idx]);
773
+ const newArgs = [];
774
+ const aliasMap = Object.keys(runOptions).reduce( (acc, key) => {
775
+ const curr = runOptions[key];
776
+ if (curr.alias) {
777
+ const aliases = Array.isArray(curr.alias) ? curr.alias : [curr.alias]
778
+ for (const alias of aliases) {
779
+ acc[alias] = curr;
780
+ }
781
+ }
782
+ return acc;
783
+ }, {})
784
+
785
+ const cliArgs = {
786
+ ...runOptions,
787
+ ...aliasMap
788
+ }
789
+
790
+ // these flags are present in cypress too, but in some the same cli and
791
+ // cypress flags have different meaning. In that case, we assume user has
792
+ // given cypress related args
793
+ const retain = ['c', 'p', 'b', 'o', 's', 'specs', 'spec']
794
+
795
+ for (let i = 0;i < rawArgs.length;i++) {
796
+ const arg = rawArgs[i];
797
+ if (arg.startsWith('-')) {
798
+ const argName = arg.length > 1 && arg[1] == '-' ? arg.slice(2) : arg.slice(1);
799
+ // If this flag belongs to cli, we omit it and its value
800
+ if (cliArgs[argName] && !retain.includes(argName)) {
801
+ const nextArg = i + 1 < rawArgs.length ? rawArgs[i+1] : ''
802
+ // if the flag is bound to have a value, we ignore it
803
+ if (cliArgs[argName].type && cliArgs[argName].type !== 'boolean' && !nextArg.startsWith('-')) {
804
+ i++;
805
+ }
806
+ continue;
807
+ }
773
808
  }
809
+ newArgs.push(rawArgs[i]);
774
810
  }
775
- return newRawArgs;
811
+ return newArgs;
776
812
  }
777
813
 
778
814
  exports.runCypressTestsLocally = (bsConfig, args, rawArgs) => {
@@ -71,6 +71,7 @@ class MyReporter {
71
71
  this._paths = new PathHelper({ cwd: process.cwd() }, this._testEnv.location_prefix);
72
72
  this.currentTestSteps = [];
73
73
  this.currentTestCucumberSteps = [];
74
+ this.hooksStarted = {};
74
75
  this.beforeHooks = [];
75
76
  this.platformDetailsMap = {};
76
77
  this.runStatusMarkedHash = {};
@@ -110,6 +111,9 @@ class MyReporter {
110
111
  } else {
111
112
  this.runStatusMarkedHash[hook.hookAnalyticsId] = true;
112
113
  }
114
+
115
+ // Remove hooks added at hook start
116
+ delete this.hooksStarted[hook.hookAnalyticsId];
113
117
  await this.sendTestRunEvent(hook,undefined,false,"HookRunFinished");
114
118
  }
115
119
  }
@@ -152,12 +156,14 @@ class MyReporter {
152
156
  })
153
157
 
154
158
  .on(EVENT_TEST_BEGIN, async (test) => {
159
+ if (test.isSkipped) return;
155
160
  if(this.testObservability == true) {
156
161
  await this.testStarted(test);
157
162
  }
158
163
  })
159
164
 
160
165
  .on(EVENT_TEST_END, async (test) => {
166
+ if (test.isSkipped) return;
161
167
  if(this.testObservability == true) {
162
168
  if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
163
169
  if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
@@ -435,6 +441,38 @@ class MyReporter {
435
441
  };
436
442
  await uploadEventData(buildUpdateData);
437
443
  }
444
+
445
+ // Add started hooks to the hash
446
+ if(eventType === 'HookRunStarted' && ['BEFORE_EACH', 'AFTER_EACH', 'BEFORE_ALL'].includes(testData['hook_type'])) {
447
+ this.hooksStarted[testData.uuid] = uploadData;
448
+ }
449
+
450
+ // Send pending hook finsihed events for hook starts
451
+ if (eventType === 'TestRunFinished') {
452
+ Object.values(this.hooksStarted).forEach(async hookData => {
453
+ hookData['event_type'] = 'HookRunFinished';
454
+ hookData['hook_run'] = {
455
+ ...hookData['hook_run'],
456
+ result: uploadData['test_run'].result,
457
+ failure: uploadData['test_run'].failure,
458
+ failure_type: uploadData['test_run'].failure_type,
459
+ failure_reason: uploadData['test_run'].failure_reason,
460
+ failure_reason_expanded: uploadData['test_run'].failure_reason_expanded,
461
+ failure_backtrace: uploadData['test_run'].failure_backtrace
462
+
463
+ }
464
+
465
+ if (hookData['hook_run']['hook_type'] === 'BEFORE_ALL') {
466
+ hookData['hook_run'].finished_at = uploadData['test_run'].finished_at;
467
+ hookData['hook_run'].duration_in_ms = new Date(hookData['hook_run'].finished_at).getTime() - new Date(hookData['hook_run'].started_at).getTime();
468
+ } else {
469
+ hookData['hook_run'].finished_at = hookData['hook_run'].started_at;
470
+ hookData['hook_run'].duration_in_ms = 0;
471
+ }
472
+ await uploadEventData(hookData);
473
+ })
474
+ this.hooksStarted = {};
475
+ }
438
476
  } catch(error) {
439
477
  debug(`Exception in populating test data for event ${eventType} with error : ${error}`, true, error);
440
478
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browserstack-cypress-cli",
3
- "version": "1.26.2",
3
+ "version": "1.28.0",
4
4
  "description": "BrowserStack Cypress CLI for Cypress integration with BrowserStack's remote devices.",
5
5
  "main": "index.js",
6
6
  "scripts": {