browserstack-cypress-cli 1.25.3 → 1.26.1

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.
Files changed (42) hide show
  1. package/.nyc_output/4de31829-b694-4567-a64d-b9f2a39aad8f.json +1 -0
  2. package/.nyc_output/5bfb514c-7f4c-4d7d-a340-aea45b6df22a.json +1 -0
  3. package/.nyc_output/6560b7ed-7bb3-4356-8e02-8e3b87e338df.json +1 -0
  4. package/.nyc_output/7bd0aff0-4e4e-48e2-a4b4-5759ca2809a1.json +1 -0
  5. package/.nyc_output/9026361d-cf67-46f1-be8c-1cca46df290c.json +1 -0
  6. package/.nyc_output/96b48768-47a7-4ce2-a594-f8cce51372d0.json +1 -0
  7. package/.nyc_output/981ac816-df8a-44d0-a0c4-492f9866d7ae.json +1 -0
  8. package/.nyc_output/ad567238-328d-4698-917f-a91539e16070.json +1 -0
  9. package/.nyc_output/ad864605-6250-44da-a38d-e3fc5d9d3d7d.json +1 -0
  10. package/.nyc_output/c6e6f4da-56a6-437e-b5f0-82d29d9536e6.json +1 -0
  11. package/.nyc_output/cb28d15a-b052-44a2-89d1-184cdf7a4ffc.json +1 -0
  12. package/.nyc_output/dc944854-f4c9-49a2-a907-b8eacbe61ea2.json +1 -0
  13. package/.nyc_output/e93ac7d5-aca6-473c-b715-9b11594cd0ff.json +1 -0
  14. package/.nyc_output/e97f3f73-9ecb-4391-aa1a-8afe1fd3895b.json +1 -0
  15. package/.nyc_output/processinfo/4de31829-b694-4567-a64d-b9f2a39aad8f.json +1 -0
  16. package/.nyc_output/processinfo/5bfb514c-7f4c-4d7d-a340-aea45b6df22a.json +1 -0
  17. package/.nyc_output/processinfo/6560b7ed-7bb3-4356-8e02-8e3b87e338df.json +1 -0
  18. package/.nyc_output/processinfo/7bd0aff0-4e4e-48e2-a4b4-5759ca2809a1.json +1 -0
  19. package/.nyc_output/processinfo/9026361d-cf67-46f1-be8c-1cca46df290c.json +1 -0
  20. package/.nyc_output/processinfo/96b48768-47a7-4ce2-a594-f8cce51372d0.json +1 -0
  21. package/.nyc_output/processinfo/981ac816-df8a-44d0-a0c4-492f9866d7ae.json +1 -0
  22. package/.nyc_output/processinfo/ad567238-328d-4698-917f-a91539e16070.json +1 -0
  23. package/.nyc_output/processinfo/ad864605-6250-44da-a38d-e3fc5d9d3d7d.json +1 -0
  24. package/.nyc_output/processinfo/c6e6f4da-56a6-437e-b5f0-82d29d9536e6.json +1 -0
  25. package/.nyc_output/processinfo/cb28d15a-b052-44a2-89d1-184cdf7a4ffc.json +1 -0
  26. package/.nyc_output/processinfo/dc944854-f4c9-49a2-a907-b8eacbe61ea2.json +1 -0
  27. package/.nyc_output/processinfo/e93ac7d5-aca6-473c-b715-9b11594cd0ff.json +1 -0
  28. package/.nyc_output/processinfo/e97f3f73-9ecb-4391-aa1a-8afe1fd3895b.json +1 -0
  29. package/.nyc_output/processinfo/index.json +1 -0
  30. package/bin/accessibility-automation/constants.js +1 -0
  31. package/bin/accessibility-automation/cypress/index.js +140 -0
  32. package/bin/accessibility-automation/helper.js +218 -0
  33. package/bin/accessibility-automation/plugin/index.js +43 -0
  34. package/bin/commands/runs.js +16 -0
  35. package/bin/helpers/buildArtifacts.js +13 -3
  36. package/bin/helpers/capabilityHelper.js +17 -0
  37. package/bin/helpers/constants.js +3 -1
  38. package/bin/helpers/helper.js +305 -0
  39. package/bin/helpers/utils.js +35 -14
  40. package/bin/testObservability/helper/helper.js +7 -231
  41. package/log/usage.log +7 -0
  42. package/package.json +1 -1
@@ -0,0 +1,218 @@
1
+ const logger = require("../helpers/logger").winstonLogger;
2
+ const { API_URL } = require('./constants');
3
+ const utils = require('../helpers/utils');
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const request = require('request');
7
+ const os = require('os');
8
+ const glob = require('glob');
9
+ const helper = require('../helpers/helper');
10
+ const { CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS } = require('../helpers/constants');
11
+ const supportFileContentMap = {}
12
+
13
+ exports.checkAccessibilityPlatform = (user_config) => {
14
+ let accessibility = false;
15
+ try {
16
+ user_config.browsers.forEach(browser => {
17
+ if (browser.accessibility) {
18
+ accessibility = true;
19
+ }
20
+ })
21
+ } catch {}
22
+
23
+ return accessibility;
24
+ }
25
+
26
+ exports.setAccessibilityCypressCapabilities = async (user_config, accessibilityResponse) => {
27
+ if (utils.isUndefined(user_config.run_settings.accessibilityOptions)) {
28
+ user_config.run_settings.accessibilityOptions = {}
29
+ }
30
+ user_config.run_settings.accessibilityOptions["authToken"] = accessibilityResponse.data.accessibilityToken;
31
+ user_config.run_settings.accessibilityOptions["auth"] = accessibilityResponse.data.accessibilityToken;
32
+ user_config.run_settings.accessibilityOptions["scannerVersion"] = accessibilityResponse.data.scannerVersion;
33
+ user_config.run_settings.system_env_vars.push(`ACCESSIBILITY_AUTH=${accessibilityResponse.data.accessibilityToken}`)
34
+ user_config.run_settings.system_env_vars.push(`ACCESSIBILITY_SCANNERVERSION=${accessibilityResponse.data.scannerVersion}`)
35
+ }
36
+
37
+ exports.isAccessibilitySupportedCypressVersion = (cypress_config_filename) => {
38
+ const extension = cypress_config_filename.split('.').pop();
39
+ return CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS.includes(extension);
40
+ }
41
+
42
+ exports.createAccessibilityTestRun = async (user_config, framework) => {
43
+
44
+ try {
45
+ if (!this.isAccessibilitySupportedCypressVersion(user_config.run_settings.cypress_config_file) ){
46
+ logger.warn(`Accessibility Testing is not supported on Cypress version 9 and below.`)
47
+ process.env.BROWSERSTACK_TEST_ACCESSIBILITY = 'false';
48
+ user_config.run_settings.accessibility = false;
49
+ return;
50
+ }
51
+ const userName = user_config["auth"]["username"];
52
+ const accessKey = user_config["auth"]["access_key"];
53
+ let settings = utils.isUndefined(user_config.run_settings.accessibilityOptions) ? {} : user_config.run_settings.accessibilityOptions
54
+
55
+ const {
56
+ buildName,
57
+ projectName,
58
+ buildDescription
59
+ } = helper.getBuildDetails(user_config);
60
+
61
+ const data = {
62
+ 'projectName': projectName,
63
+ 'buildName': buildName,
64
+ 'startTime': (new Date()).toISOString(),
65
+ 'description': buildDescription,
66
+ 'source': {
67
+ frameworkName: "Cypress",
68
+ frameworkVersion: helper.getPackageVersion('cypress', user_config),
69
+ sdkVersion: helper.getAgentVersion()
70
+ },
71
+ 'settings': settings,
72
+ 'versionControl': await helper.getGitMetaData(),
73
+ 'ciInfo': helper.getCiInfo(),
74
+ 'hostInfo': {
75
+ hostname: os.hostname(),
76
+ platform: os.platform(),
77
+ type: os.type(),
78
+ version: os.version(),
79
+ arch: os.arch()
80
+ },
81
+ 'browserstackAutomation': process.env.BROWSERSTACK_AUTOMATION === 'true'
82
+ };
83
+
84
+ const config = {
85
+ auth: {
86
+ user: userName,
87
+ pass: accessKey
88
+ },
89
+ headers: {
90
+ 'Content-Type': 'application/json'
91
+ }
92
+ };
93
+
94
+ const response = await nodeRequest(
95
+ 'POST', 'test_runs', data, config, API_URL
96
+ );
97
+ if(!utils.isUndefined(response.data)) {
98
+ process.env.BS_A11Y_JWT = response.data.data.accessibilityToken;
99
+ process.env.BS_A11Y_TEST_RUN_ID = response.data.data.id;
100
+ }
101
+ if (process.env.BS_A11Y_JWT) {
102
+ process.env.BROWSERSTACK_TEST_ACCESSIBILITY = 'true';
103
+ }
104
+ logger.debug(`BrowserStack Accessibility Automation Test Run ID: ${response.data.data.id}`);
105
+
106
+ this.setAccessibilityCypressCapabilities(user_config, response.data);
107
+ setAccessibilityEventListeners();
108
+ helper.setBrowserstackCypressCliDependency(user_config);
109
+
110
+ } catch (error) {
111
+ if (error.response) {
112
+ logger.error(
113
+ `Exception while creating test run for BrowserStack Accessibility Automation: ${
114
+ error.response.status
115
+ } ${error.response.statusText} ${JSON.stringify(error.response.data)}`
116
+ );
117
+ } else {
118
+ if(error.message === 'Invalid configuration passed.') {
119
+ logger.error(
120
+ `Exception while creating test run for BrowserStack Accessibility Automation: ${
121
+ error.message || error.stack
122
+ }`
123
+ );
124
+ for(const errorkey of error.errors){
125
+ logger.error(errorkey.message);
126
+ }
127
+
128
+ } else {
129
+ logger.error(
130
+ `Exception while creating test run for BrowserStack Accessibility Automation: ${
131
+ error.message || error.stack
132
+ }`
133
+ );
134
+ }
135
+ // since create accessibility session failed
136
+ process.env.BROWSERSTACK_TEST_ACCESSIBILITY = 'false';
137
+ user_config.run_settings.accessibility = false;
138
+ }
139
+ }
140
+ }
141
+
142
+ const nodeRequest = (type, url, data, config) => {
143
+ return new Promise(async (resolve, reject) => {
144
+ const options = {...config,...{
145
+ method: type,
146
+ url: `${API_URL}/${url}`,
147
+ body: data,
148
+ json: config.headers['Content-Type'] === 'application/json',
149
+ }};
150
+
151
+ request(options, function callback(error, response, body) {
152
+ if(error) {
153
+ logger.info("error in nodeRequest", error);
154
+ reject(error);
155
+ } else if(!(response.statusCode == 201 || response.statusCode == 200)) {
156
+ logger.info("response.statusCode in nodeRequest", response.statusCode);
157
+ reject(response && response.body ? response.body : `Received response from BrowserStack Server with status : ${response.statusCode}`);
158
+ } else {
159
+ try {
160
+ if(typeof(body) !== 'object') body = JSON.parse(body);
161
+ } catch(e) {
162
+ if(!url.includes('/stop')) {
163
+ reject('Not a JSON response from BrowserStack Server');
164
+ }
165
+ }
166
+ resolve({
167
+ data: body
168
+ });
169
+ }
170
+ });
171
+ });
172
+ }
173
+
174
+ exports.supportFileCleanup = () => {
175
+ logger.debug("Cleaning up support file changes added for accessibility. ")
176
+ Object.keys(supportFileContentMap).forEach(file => {
177
+ try {
178
+ fs.writeFileSync(file, supportFileContentMap[file], {encoding: 'utf-8'});
179
+ } catch(e) {
180
+ logger.debug(`Error while replacing file content for ${file} with it's original content with error : ${e}`, true, e);
181
+ }
182
+ });
183
+ }
184
+
185
+ const getAccessibilityCypressCommandEventListener = () => {
186
+ return (
187
+ `require('browserstack-cypress-cli/bin/accessibility-automation/cypress');`
188
+ );
189
+ }
190
+
191
+ const setAccessibilityEventListeners = () => {
192
+ try {
193
+ const cypressCommandEventListener = getAccessibilityCypressCommandEventListener();
194
+ glob(process.cwd() + '/cypress/support/*.js', {}, (err, files) => {
195
+ if(err) return logger.debug('EXCEPTION IN BUILD START EVENT : Unable to parse cypress support files');
196
+ files.forEach(file => {
197
+ try {
198
+ if(!file.includes('commands.js')) {
199
+ const defaultFileContent = fs.readFileSync(file, {encoding: 'utf-8'});
200
+
201
+ if(!defaultFileContent.includes(cypressCommandEventListener)) {
202
+ let newFileContent = defaultFileContent +
203
+ '\n' +
204
+ cypressCommandEventListener +
205
+ '\n'
206
+ fs.writeFileSync(file, newFileContent, {encoding: 'utf-8'});
207
+ supportFileContentMap[file] = defaultFileContent;
208
+ }
209
+ }
210
+ } catch(e) {
211
+ logger.debug(`Unable to modify file contents for ${file} to set event listeners with error ${e}`, true, e);
212
+ }
213
+ });
214
+ });
215
+ } catch(e) {
216
+ logger.debug(`Unable to parse support files to set event listeners with error ${e}`, true, e);
217
+ }
218
+ }
@@ -0,0 +1,43 @@
1
+
2
+ const path = require("node:path");
3
+
4
+ const browserstackAccessibility = (on, config) => {
5
+ let browser_validation = true;
6
+ on('before:browser:launch', (browser = {}, launchOptions) => {
7
+ try {
8
+
9
+ if (process.env.ACCESSIBILITY_EXTENSION_PATH !== undefined) {
10
+ if (browser.name !== 'chrome') {
11
+ console.log(`Accessibility Automation will run only on Chrome browsers.`);
12
+ browser_validation = false;
13
+ }
14
+ if (browser.name === 'chrome' && browser.majorVersion <= 94) {
15
+ console.log(`Accessibility Automation will run only on Chrome browser version greater than 94.`);
16
+ browser_validation = false;
17
+ }
18
+ if (browser.isHeadless === true) {
19
+ console.log(`Accessibility Automation will not run on legacy headless mode. Switch to new headless mode or avoid using headless mode.`);
20
+ browser_validation = false;
21
+ }
22
+ if (browser_validation) {
23
+ const ally_path = path.dirname(process.env.ACCESSIBILITY_EXTENSION_PATH)
24
+ launchOptions.extensions.push(ally_path);
25
+ return launchOptions
26
+ }
27
+ }
28
+ } catch(err) {}
29
+
30
+ })
31
+ config.env.ACCESSIBILITY_EXTENSION_PATH = process.env.ACCESSIBILITY_EXTENSION_PATH
32
+ config.env.OS_VERSION = process.env.OS_VERSION
33
+ config.env.OS = process.env.OS
34
+
35
+ config.env.IS_ACCESSIBILITY_EXTENSION_LOADED = browser_validation.toString()
36
+
37
+ config.env.INCLUDE_TAGS_FOR_ACCESSIBILITY = process.env.ACCESSIBILITY_INCLUDETAGSINTESTINGSCOPE
38
+ config.env.EXCLUDE_TAGS_FOR_ACCESSIBILITY = process.env.ACCESSIBILITY_EXCLUDETAGSINTESTINGSCOPE
39
+
40
+ return config;
41
+ }
42
+
43
+ module.exports = browserstackAccessibility;
@@ -30,6 +30,13 @@ const {
30
30
  printBuildLink
31
31
  } = require('../testObservability/helper/helper');
32
32
 
33
+
34
+ const {
35
+ createAccessibilityTestRun,
36
+ checkAccessibilityPlatform,
37
+ supportFileCleanup
38
+ } = require('../accessibility-automation/helper');
39
+
33
40
  module.exports = function run(args, rawArgs) {
34
41
 
35
42
  markBlockStart('preBuild');
@@ -57,6 +64,8 @@ module.exports = function run(args, rawArgs) {
57
64
  Set testObservability & browserstackAutomation flags
58
65
  */
59
66
  const [isTestObservabilitySession, isBrowserstackInfra] = setTestObservabilityFlags(bsConfig);
67
+ const checkAccessibility = checkAccessibilityPlatform(bsConfig);
68
+ const isAccessibilitySession = bsConfig.run_settings.accessibility || checkAccessibility;
60
69
 
61
70
  utils.setUsageReportingFlag(bsConfig, args.disableUsageReporting);
62
71
 
@@ -131,6 +140,10 @@ module.exports = function run(args, rawArgs) {
131
140
 
132
141
  // add cypress dependency if missing
133
142
  utils.setCypressNpmDependency(bsConfig);
143
+
144
+ if (isAccessibilitySession && isBrowserstackInfra) {
145
+ await createAccessibilityTestRun(bsConfig);
146
+ }
134
147
  }
135
148
 
136
149
  const { packagesInstalled } = !isBrowserstackInfra ? false : await packageInstaller.packageSetupAndInstaller(bsConfig, config.packageDirName, {markBlockStart, markBlockEnd});
@@ -232,6 +245,9 @@ module.exports = function run(args, rawArgs) {
232
245
  markBlockEnd('zip.zipUpload');
233
246
  markBlockEnd('zip');
234
247
 
248
+ if (process.env.BROWSERSTACK_TEST_ACCESSIBILITY === 'true') {
249
+ supportFileCleanup();
250
+ }
235
251
  // Create build
236
252
  //setup Local Testing
237
253
  markBlockStart('localSetup');
@@ -15,7 +15,7 @@ const decompress = require('decompress');
15
15
  let BUILD_ARTIFACTS_TOTAL_COUNT = 0;
16
16
  let BUILD_ARTIFACTS_FAIL_COUNT = 0;
17
17
 
18
- const parseAndDownloadArtifacts = async (buildId, data) => {
18
+ const parseAndDownloadArtifacts = async (buildId, data, bsConfig, args, rawArgs, buildReportData) => {
19
19
  return new Promise(async (resolve, reject) => {
20
20
  let all_promises = [];
21
21
  let combs = Object.keys(data);
@@ -28,7 +28,14 @@ const parseAndDownloadArtifacts = async (buildId, data) => {
28
28
  let fileName = 'build_artifacts.zip';
29
29
  BUILD_ARTIFACTS_TOTAL_COUNT += 1;
30
30
  all_promises.push(downloadAndUnzip(filePath, fileName, data[comb][sessionId]).catch((error) => {
31
- BUILD_ARTIFACTS_FAIL_COUNT += 1;
31
+ if (error === Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND) {
32
+ // Don't consider build artifact 404 error as a failure
33
+ let warningMessage = Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND.replace('<session-id>', sessionId);
34
+ logger.warn(warningMessage);
35
+ utils.sendUsageReport(bsConfig, args, warningMessage, Constants.messageTypes.ERROR, 'build_artifacts_not_found', buildReportData, rawArgs);
36
+ } else {
37
+ BUILD_ARTIFACTS_FAIL_COUNT += 1;
38
+ }
32
39
  // delete malformed zip if present
33
40
  let tmpFilePath = path.join(filePath, fileName);
34
41
  if(fs.existsSync(tmpFilePath)){
@@ -99,6 +106,9 @@ const downloadAndUnzip = async (filePath, fileName, url) => {
99
106
  request.get(url).on('response', function(response) {
100
107
 
101
108
  if(response.statusCode != 200) {
109
+ if (response.statusCode === 404) {
110
+ reject(Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND);
111
+ }
102
112
  reject();
103
113
  } else {
104
114
  //ensure that the user can call `then()` only when the file has
@@ -220,7 +230,7 @@ exports.downloadBuildArtifacts = async (bsConfig, buildId, args, rawArgs, buildR
220
230
  process.exitCode = Constants.ERROR_EXIT_CODE;
221
231
  } else {
222
232
  await createDirectories(buildId, buildDetails);
223
- await parseAndDownloadArtifacts(buildId, buildDetails);
233
+ await parseAndDownloadArtifacts(buildId, buildDetails, bsConfig, args, rawArgs, buildReportData);
224
234
  if (BUILD_ARTIFACTS_FAIL_COUNT > 0) {
225
235
  messageType = Constants.messageTypes.ERROR;
226
236
  message = Constants.userMessages.DOWNLOAD_BUILD_ARTIFACTS_FAILED.replace('<build-id>', buildId).replace('<machine-count>', BUILD_ARTIFACTS_FAIL_COUNT);
@@ -121,6 +121,10 @@ const caps = (bsConfig, zip) => {
121
121
  logger.info(`Running your tests in headless mode. Use --headed arg to run in headful mode.`);
122
122
  }
123
123
 
124
+ if (process.env.BROWSERSTACK_TEST_ACCESSIBILITY === 'true') {
125
+ bsConfig.run_settings["accessibilityPlatforms"] = getAccessibilityPlatforms(bsConfig);
126
+ }
127
+
124
128
  // send run_settings as is for other capabilities
125
129
  obj.run_settings = JSON.stringify(bsConfig.run_settings);
126
130
  }
@@ -138,9 +142,22 @@ const caps = (bsConfig, zip) => {
138
142
  if (obj.parallels) logger.info(`Parallels limit specified: ${obj.parallels}`);
139
143
 
140
144
  var data = JSON.stringify(obj);
145
+
141
146
  resolve(data);
142
147
  })
143
148
  }
149
+ const getAccessibilityPlatforms = (bsConfig) => {
150
+ const browserList = bsConfig.browsers;
151
+ const accessibilityPlatforms = Array(browserList.length).fill(false);
152
+ let rootLevelAccessibility = false;
153
+ if (!Utils.isUndefined(bsConfig.run_settings.accessibility)) {
154
+ rootLevelAccessibility = bsConfig.run_settings.accessibility.toString() === 'true'
155
+ }
156
+ browserList.forEach((browserDetails, idx) => {
157
+ accessibilityPlatforms[idx] = (browserDetails.accessibility === undefined) ? rootLevelAccessibility : browserDetails.accessibility
158
+ });
159
+ return accessibilityPlatforms;
160
+ }
144
161
 
145
162
  const addCypressZipStartLocation = (runSettings) => {
146
163
  let resolvedHomeDirectoryPath = path.resolve(runSettings.home_directory);
@@ -94,7 +94,9 @@ const userMessages = {
94
94
  SPEC_LIMIT_WARNING:
95
95
  "You might not see all your results on the dashboard because of high spec count, please consider reducing the number of spec files in this folder.",
96
96
  DOWNLOAD_BUILD_ARTIFACTS_FAILED:
97
- "Downloading build artifacts for the build <build-id> failed for <machine-count> machines.",
97
+ "Downloading build artifact(s) for the build <build-id> failed for <machine-count> machines.",
98
+ DOWNLOAD_BUILD_ARTIFACTS_NOT_FOUND:
99
+ "Build artifact(s) for the session <session-id> was either not generated or not uploaded.",
98
100
  ASYNC_DOWNLOADS:
99
101
  "Test artifacts as specified under 'downloads' can be downloaded after the build has completed its run, using 'browserstack-cypress generate-downloads <build-id>'",
100
102
  DOWNLOAD_BUILD_ARTIFACTS_SUCCESS: