browserstack-cypress-cli 1.34.0 → 1.35.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.
Files changed (72) hide show
  1. package/bin/accessibility-automation/cypress/index.js +16 -19
  2. package/bin/accessibility-automation/plugin/index.js +50 -0
  3. package/bin/commands/runs.js +11 -8
  4. package/bin/helpers/helper.js +11 -0
  5. package/bin/helpers/utils.js +10 -10
  6. package/bin/testObservability/helper/helper.js +9 -9
  7. package/bin/testObservability/reporter/index.js +85 -8
  8. package/bin/testhub/constants.js +10 -0
  9. package/bin/testhub/testhubHandler.js +135 -0
  10. package/bin/testhub/utils.js +286 -0
  11. package/package.json +2 -1
  12. package/.claude/settings.local.json +0 -13
  13. package/.nyc_output/1c1b6051-514d-4847-bd2a-d03b2d537cfb.json +0 -1
  14. package/.nyc_output/20afa9bb-5b9f-42e2-adfe-9dbf55591bb8.json +0 -1
  15. package/.nyc_output/22e511c5-8971-4265-b783-553560573bdc.json +0 -1
  16. package/.nyc_output/2d21e700-0ac9-4ac9-8f8c-322a5cbefe8d.json +0 -1
  17. package/.nyc_output/3c54171a-9bf6-478d-a4c0-28ec402806cf.json +0 -1
  18. package/.nyc_output/52675bfd-ff62-4f5b-944c-e3f48af2972c.json +0 -1
  19. package/.nyc_output/5766c03a-3d68-4298-89f7-c298c025e176.json +0 -1
  20. package/.nyc_output/625adc06-9859-4c11-8892-0498922cc2aa.json +0 -1
  21. package/.nyc_output/730f797e-97d0-44a8-b5d0-7fd3f8c06d75.json +0 -1
  22. package/.nyc_output/73501809-7c04-439e-8c09-9a1bff7962c6.json +0 -1
  23. package/.nyc_output/77484870-1b25-4c2d-a361-2ac51c0951bc.json +0 -1
  24. package/.nyc_output/8098fa2d-312d-4762-ad96-3e9827eaef09.json +0 -1
  25. package/.nyc_output/87357e21-685f-4861-9a6f-4c6b62f85ac0.json +0 -1
  26. package/.nyc_output/8fcd9f27-af41-43f7-bdf8-7bea2efd7abb.json +0 -1
  27. package/.nyc_output/9f8ad8fd-775b-4a99-ba77-c6142e7df5e9.json +0 -1
  28. package/.nyc_output/a1de1cdd-5eed-409d-a528-1c7cf16d56b5.json +0 -1
  29. package/.nyc_output/a25237ac-032d-4a27-af09-fb32326b539a.json +0 -1
  30. package/.nyc_output/a5d38a55-372c-4676-b4bc-c6def0669c0d.json +0 -1
  31. package/.nyc_output/a67d3cbf-0548-4fcb-8aad-2af60b532670.json +0 -1
  32. package/.nyc_output/aa2117b0-10c0-4f5b-9d8d-1f96375f0240.json +0 -1
  33. package/.nyc_output/ac17471f-3f16-45ab-b53e-ba8956afd5d4.json +0 -1
  34. package/.nyc_output/bbbe672a-8524-4850-b6b3-b725aa2b6c16.json +0 -1
  35. package/.nyc_output/c7289c09-7047-47cb-9737-f11fe7fc9628.json +0 -1
  36. package/.nyc_output/ceeeac29-3ca3-40af-b779-12c0408cf05d.json +0 -1
  37. package/.nyc_output/d08d37a4-6abc-41a7-98bd-de074a1fca7f.json +0 -1
  38. package/.nyc_output/d1dbecb0-8458-41bc-86c8-9d2470b60415.json +0 -1
  39. package/.nyc_output/d7245fa2-3732-4790-831b-44dbcba15a16.json +0 -1
  40. package/.nyc_output/e184572f-281b-4bd6-81e3-58842eac98ee.json +0 -1
  41. package/.nyc_output/efd98bd9-1699-472b-ab98-0808e5d39899.json +0 -1
  42. package/.nyc_output/processinfo/1c1b6051-514d-4847-bd2a-d03b2d537cfb.json +0 -1
  43. package/.nyc_output/processinfo/20afa9bb-5b9f-42e2-adfe-9dbf55591bb8.json +0 -1
  44. package/.nyc_output/processinfo/22e511c5-8971-4265-b783-553560573bdc.json +0 -1
  45. package/.nyc_output/processinfo/2d21e700-0ac9-4ac9-8f8c-322a5cbefe8d.json +0 -1
  46. package/.nyc_output/processinfo/3c54171a-9bf6-478d-a4c0-28ec402806cf.json +0 -1
  47. package/.nyc_output/processinfo/52675bfd-ff62-4f5b-944c-e3f48af2972c.json +0 -1
  48. package/.nyc_output/processinfo/5766c03a-3d68-4298-89f7-c298c025e176.json +0 -1
  49. package/.nyc_output/processinfo/625adc06-9859-4c11-8892-0498922cc2aa.json +0 -1
  50. package/.nyc_output/processinfo/730f797e-97d0-44a8-b5d0-7fd3f8c06d75.json +0 -1
  51. package/.nyc_output/processinfo/73501809-7c04-439e-8c09-9a1bff7962c6.json +0 -1
  52. package/.nyc_output/processinfo/77484870-1b25-4c2d-a361-2ac51c0951bc.json +0 -1
  53. package/.nyc_output/processinfo/8098fa2d-312d-4762-ad96-3e9827eaef09.json +0 -1
  54. package/.nyc_output/processinfo/87357e21-685f-4861-9a6f-4c6b62f85ac0.json +0 -1
  55. package/.nyc_output/processinfo/8fcd9f27-af41-43f7-bdf8-7bea2efd7abb.json +0 -1
  56. package/.nyc_output/processinfo/9f8ad8fd-775b-4a99-ba77-c6142e7df5e9.json +0 -1
  57. package/.nyc_output/processinfo/a1de1cdd-5eed-409d-a528-1c7cf16d56b5.json +0 -1
  58. package/.nyc_output/processinfo/a25237ac-032d-4a27-af09-fb32326b539a.json +0 -1
  59. package/.nyc_output/processinfo/a5d38a55-372c-4676-b4bc-c6def0669c0d.json +0 -1
  60. package/.nyc_output/processinfo/a67d3cbf-0548-4fcb-8aad-2af60b532670.json +0 -1
  61. package/.nyc_output/processinfo/aa2117b0-10c0-4f5b-9d8d-1f96375f0240.json +0 -1
  62. package/.nyc_output/processinfo/ac17471f-3f16-45ab-b53e-ba8956afd5d4.json +0 -1
  63. package/.nyc_output/processinfo/bbbe672a-8524-4850-b6b3-b725aa2b6c16.json +0 -1
  64. package/.nyc_output/processinfo/c7289c09-7047-47cb-9737-f11fe7fc9628.json +0 -1
  65. package/.nyc_output/processinfo/ceeeac29-3ca3-40af-b779-12c0408cf05d.json +0 -1
  66. package/.nyc_output/processinfo/d08d37a4-6abc-41a7-98bd-de074a1fca7f.json +0 -1
  67. package/.nyc_output/processinfo/d1dbecb0-8458-41bc-86c8-9d2470b60415.json +0 -1
  68. package/.nyc_output/processinfo/d7245fa2-3732-4790-831b-44dbcba15a16.json +0 -1
  69. package/.nyc_output/processinfo/e184572f-281b-4bd6-81e3-58842eac98ee.json +0 -1
  70. package/.nyc_output/processinfo/efd98bd9-1699-472b-ab98-0808e5d39899.json +0 -1
  71. package/.nyc_output/processinfo/index.json +0 -1
  72. package/log/usage.log +0 -393
@@ -336,26 +336,23 @@ afterEach(() => {
336
336
  } else if (attributes.prevAttempts && attributes.prevAttempts.length > 0) {
337
337
  filePath = (attributes.prevAttempts[0].invocationDetails && attributes.prevAttempts[0].invocationDetails.relativeFile) || '';
338
338
  }
339
- const payloadToSend = {
340
- "saveResults": shouldScanTestForAccessibility,
341
- "testDetails": {
342
- "name": attributes.title,
343
- "testRunId": '5058', // variable not consumed, shouldn't matter what we send
344
- "filePath": filePath,
345
- "scopeList": [
346
- filePath,
347
- attributes.title
348
- ]
349
- },
350
- "platform": {
351
- "os_name": os_data,
352
- "os_version": Cypress.env("OS_VERSION"),
353
- "browser_name": Cypress.browser.name,
354
- "browser_version": Cypress.browser.version
339
+
340
+ let testRunUuid = null;
341
+ cy.task('get_test_run_uuid', { testIdentifier: attributes.title })
342
+ .then((response) => {
343
+ if (response && response.testRunUuid) {
344
+ testRunUuid = response.testRunUuid;
355
345
  }
356
- };
357
- browserStackLog(`Saving accessibility test results`);
358
- cy.wrap(saveTestResults(win, payloadToSend), {timeout: 30000}).then(() => {
346
+
347
+ const payloadToSend = {
348
+ "thTestRunUuid": testRunUuid,
349
+ "thBuildUuid": Cypress.env("BROWSERSTACK_TESTHUB_UUID"),
350
+ "thJwtToken": Cypress.env("BROWSERSTACK_TESTHUB_JWT")
351
+ };
352
+ browserStackLog(`Payload to send: ${JSON.stringify(payloadToSend)}`);
353
+
354
+ return cy.wrap(saveTestResults(win, payloadToSend), {timeout: 30000});
355
+ }).then(() => {
359
356
  browserStackLog(`Saved accessibility test results`);
360
357
  })
361
358
 
@@ -1,6 +1,7 @@
1
1
  const path = require("node:path");
2
2
  const { decodeJWTToken } = require("../../helpers/utils");
3
3
  const utils = require('../../helpers/utils');
4
+ const http = require('http');
4
5
 
5
6
  const browserstackAccessibility = (on, config) => {
6
7
  let browser_validation = true;
@@ -14,6 +15,51 @@ const browserstackAccessibility = (on, config) => {
14
15
 
15
16
  return null
16
17
  },
18
+ get_test_run_uuid({ testIdentifier, retries = 15, interval = 300 } = {}) {
19
+ return new Promise((resolve) => {
20
+ if(!testIdentifier) return resolve(null);
21
+ const port = process.env.REPORTER_API_PORT_NO;
22
+ let attempt = 0;
23
+ const fetchUuid = () => {
24
+ const options = {
25
+ hostname: '127.0.0.1',
26
+ port,
27
+ path: `/test-uuid?testIdentifier=${encodeURIComponent(testIdentifier)}`,
28
+ method: 'GET',
29
+ timeout: 2000
30
+ };
31
+ const httpModule = http;
32
+ const req = httpModule.request(options, (res) => {
33
+ let data = '';
34
+ res.on('data', (chunk) => data += chunk);
35
+ res.on('end', () => {
36
+ if(res.statusCode === 200) {
37
+ try {
38
+ const json = JSON.parse(data || '{}');
39
+ return resolve({ testRunUuid: json.testRunUuid || null });
40
+ } catch(e) {
41
+ return resolve(null);
42
+ }
43
+ } else if (res.statusCode === 404) {
44
+ // Server up but endpoint not responding as expected – stop retrying.
45
+ return resolve(null);
46
+ } else {
47
+ retryOrResolve();
48
+ }
49
+ });
50
+ });
51
+ req.on('error', () => retryOrResolve());
52
+ req.on('timeout', () => { req.destroy(); retryOrResolve(); });
53
+ req.end();
54
+ };
55
+ const retryOrResolve = () => {
56
+ attempt += 1;
57
+ if(attempt >= retries) return resolve(null);
58
+ setTimeout(fetchUuid, interval);
59
+ };
60
+ fetchUuid();
61
+ });
62
+ }
17
63
  })
18
64
  on('before:browser:launch', (browser = {}, launchOptions) => {
19
65
  try {
@@ -51,6 +97,10 @@ const browserstackAccessibility = (on, config) => {
51
97
  config.env.ACCESSIBILITY_EXTENSION_PATH = process.env.ACCESSIBILITY_EXTENSION_PATH
52
98
  config.env.OS_VERSION = process.env.OS_VERSION
53
99
  config.env.OS = process.env.OS
100
+ config.env.BROWSERSTACK_TESTHUB_UUID = process.env.BROWSERSTACK_TESTHUB_UUID
101
+ config.env.BROWSERSTACK_TESTHUB_JWT = process.env.BROWSERSTACK_TESTHUB_JWT
102
+ config.env.BROWSERSTACK_TESTHUB_API_PORT = process.env.BROWSERSTACK_TESTHUB_API_PORT
103
+ config.env.REPORTER_API_PORT_NO = process.env.REPORTER_API_PORT_NO
54
104
 
55
105
  config.env.IS_ACCESSIBILITY_EXTENSION_LOADED = browser_validation.toString()
56
106
 
@@ -37,7 +37,8 @@ const {
37
37
  supportFileCleanup
38
38
  } = require('../accessibility-automation/helper');
39
39
  const { isTurboScaleSession, getTurboScaleGridDetails, patchCypressConfigFileContent, atsFileCleanup } = require('../helpers/atsHelper');
40
-
40
+ const { shouldProcessEventForTesthub, checkAndSetAccessibility, findAvailablePort } = require('../testhub/utils');
41
+ const TestHubHandler = require('../testhub/testhubHandler');
41
42
 
42
43
  module.exports = function run(args, rawArgs) {
43
44
  utils.normalizeTestReportingEnvVars();
@@ -112,9 +113,15 @@ module.exports = function run(args, rawArgs) {
112
113
  // set build tag caps
113
114
  utils.setBuildTags(bsConfig, args);
114
115
 
116
+ checkAndSetAccessibility(bsConfig, isAccessibilitySession);
117
+
118
+ const preferredPort = 5348;
119
+ const port = await findAvailablePort(preferredPort);
120
+ process.env.REPORTER_API_PORT_NO = port
121
+
115
122
  // Send build start to TEST REPORTING AND ANALYTICS
116
- if(isTestObservabilitySession) {
117
- await launchTestSession(bsConfig, bsConfigPath);
123
+ if(shouldProcessEventForTesthub()) {
124
+ await TestHubHandler.launchBuild(bsConfig, bsConfigPath);
118
125
  utils.setO11yProcessHooks(null, bsConfig, args, null, buildReportData);
119
126
  }
120
127
 
@@ -149,10 +156,6 @@ module.exports = function run(args, rawArgs) {
149
156
  // add cypress dependency if missing
150
157
  utils.setCypressNpmDependency(bsConfig);
151
158
 
152
- if (isAccessibilitySession && isBrowserstackInfra) {
153
- await createAccessibilityTestRun(bsConfig);
154
- }
155
-
156
159
  if (turboScaleSession) {
157
160
  const gridDetails = await getTurboScaleGridDetails(bsConfig, args, rawArgs);
158
161
 
@@ -206,7 +209,7 @@ module.exports = function run(args, rawArgs) {
206
209
  markBlockStart('validateConfig');
207
210
  logger.debug("Started configs validation");
208
211
  return capabilityHelper.validate(bsConfig, args).then(function (cypressConfigFile) {
209
- if(process.env.BROWSERSTACK_TEST_ACCESSIBILITY) {
212
+ if(process.env.BROWSERSTACK_TEST_ACCESSIBILITY === 'true') {
210
213
  setAccessibilityEventListeners(bsConfig);
211
214
  }
212
215
  if(process.env.BS_TESTOPS_BUILD_COMPLETED) {
@@ -182,6 +182,17 @@ exports.getGitMetaData = () => {
182
182
  }
183
183
  })
184
184
  }
185
+
186
+ exports.getHostInfo = () => {
187
+ return {
188
+ hostname: os.hostname(),
189
+ platform: os.platform(),
190
+ type: os.type(),
191
+ version: os.version(),
192
+ arch: os.arch()
193
+ }
194
+ }
195
+
185
196
  exports.getCiInfo = () => {
186
197
  var env = process.env;
187
198
  // Jenkins
@@ -27,6 +27,7 @@ const usageReporting = require("./usageReporting"),
27
27
  { OBSERVABILITY_ENV_VARS, TEST_OBSERVABILITY_REPORTER } = require('../testObservability/helper/constants');
28
28
 
29
29
  const { default: axios } = require("axios");
30
+ const { shouldProcessEventForTesthub } = require("../testhub/utils");
30
31
 
31
32
  exports.validateBstackJson = (bsConfigPath) => {
32
33
  return new Promise(function (resolve, reject) {
@@ -1499,7 +1500,7 @@ exports.splitStringByCharButIgnoreIfWithinARange = (str, splitChar, leftLimiter,
1499
1500
 
1500
1501
  // blindly send other passed configs with run_settings and handle at backend
1501
1502
  exports.setOtherConfigs = (bsConfig, args) => {
1502
- if(o11yHelpers.isTestObservabilitySession() && process.env.BS_TESTOPS_JWT) {
1503
+ if(shouldProcessEventForTesthub()) {
1503
1504
  bsConfig["run_settings"]["reporter"] = TEST_OBSERVABILITY_REPORTER;
1504
1505
  return;
1505
1506
  }
@@ -1754,15 +1755,14 @@ exports.getVideoConfig = (cypressConfig, bsConfig = {}) => {
1754
1755
  video: true,
1755
1756
  videoUploadOnPasses: true
1756
1757
  }
1757
- // Reading bsconfig in case of enforce_settings
1758
- if ( this.isUndefined(bsConfig.run_settings) || this.isUndefinedOrFalse(bsConfig.run_settings.enforce_settings) ) {
1759
- if (!this.isUndefined(cypressConfig.video)) conf.video = cypressConfig.video;
1760
- if (!this.isUndefined(cypressConfig.videoUploadOnPasses)) conf.videoUploadOnPasses = cypressConfig.videoUploadOnPasses;
1761
- }
1762
- else {
1763
- if (!this.isUndefined(bsConfig.run_settings) && !this.isUndefined(bsConfig.run_settings.video)) conf.video = bsConfig.run_settings.video;
1764
- if (!this.isUndefined(bsConfig.run_settings) && !this.isUndefined(bsConfig.run_settings.videoUploadOnPasses)) conf.videoUploadOnPasses = bsConfig.run_settings.videoUploadOnPasses;
1765
- }
1758
+
1759
+ // here if we have enforce_setting: true then cypressConfig will be {} as we are not reading cypress.config.js file in that case
1760
+ if (!this.isUndefined(bsConfig.run_settings) && !this.isUndefined(bsConfig.run_settings.video)) conf.video = bsConfig.run_settings.video;
1761
+ if (!this.isUndefined(bsConfig.run_settings) && !this.isUndefined(bsConfig.run_settings.videoUploadOnPasses)) conf.videoUploadOnPasses = bsConfig.run_settings.videoUploadOnPasses;
1762
+ if (!this.isUndefined(cypressConfig.video)) { conf.video = cypressConfig.video;}
1763
+ if (!this.isUndefined(cypressConfig.videoUploadOnPasses)){ conf.videoUploadOnPasses = cypressConfig.videoUploadOnPasses;}
1764
+ if (!this.isUndefined(cypressConfig.e2e) && !this.isUndefined(cypressConfig.e2e.video)) { conf.video = cypressConfig.e2e.video;}
1765
+ if (!this.isUndefined(cypressConfig.e2e) && !this.isUndefined(cypressConfig.e2e.videoUploadOnPasses)){ conf.videoUploadOnPasses = cypressConfig.e2e.videoUploadOnPasses;}
1766
1766
 
1767
1767
  // set video in cli config in case of cypress 13 or above as default value is false there.
1768
1768
  this.setVideoCliConfig(bsConfig,conf);
@@ -116,7 +116,7 @@ exports.printBuildLink = async (shouldStopSession, exitCode = null) => {
116
116
  if(exitCode) process.exit(exitCode);
117
117
  }
118
118
 
119
- const nodeRequest = (type, url, data, config) => {
119
+ exports.nodeRequest = (type, url, data, config) => {
120
120
  const requestQueueHandler = require('./requestQueueHandler');
121
121
  return new Promise(async (resolve, reject) => {
122
122
  const options = {
@@ -269,7 +269,7 @@ exports.getPackageVersion = (package_, bsConfig = null) => {
269
269
  return packageVersion;
270
270
  }
271
271
 
272
- const setEnvironmentVariablesForRemoteReporter = (BS_TESTOPS_JWT, BS_TESTOPS_BUILD_HASHED_ID, BS_TESTOPS_ALLOW_SCREENSHOTS, OBSERVABILITY_LAUNCH_SDK_VERSION) => {
272
+ exports.setEnvironmentVariablesForRemoteReporter = (BS_TESTOPS_JWT, BS_TESTOPS_BUILD_HASHED_ID, BS_TESTOPS_ALLOW_SCREENSHOTS, OBSERVABILITY_LAUNCH_SDK_VERSION) => {
273
273
  process.env.BS_TESTOPS_JWT = BS_TESTOPS_JWT;
274
274
  process.env.BS_TESTOPS_BUILD_HASHED_ID = BS_TESTOPS_BUILD_HASHED_ID;
275
275
  process.env.BS_TESTOPS_ALLOW_SCREENSHOTS = BS_TESTOPS_ALLOW_SCREENSHOTS;
@@ -343,7 +343,7 @@ exports.setCrashReportingConfigFromReporter = (credentialsStr, bsConfigPath, cyp
343
343
  }
344
344
  }
345
345
 
346
- const setCrashReportingConfig = (bsConfig, bsConfigPath) => {
346
+ exports.setCrashReportingConfig = (bsConfig, bsConfigPath) => {
347
347
  try {
348
348
  const browserstackConfigFile = utils.readBsConfigJSON(bsConfigPath);
349
349
  const cypressConfigFile = getCypressConfigFileContent(bsConfig, null);
@@ -414,10 +414,10 @@ exports.launchTestSession = async (user_config, bsConfigPath) => {
414
414
  }
415
415
  };
416
416
 
417
- const response = await nodeRequest('POST','api/v1/builds',data,config);
417
+ const response = await exports.nodeRequest('POST','api/v1/builds',data,config);
418
418
  exports.debug('Build creation successfull!');
419
419
  process.env.BS_TESTOPS_BUILD_COMPLETED = true;
420
- setEnvironmentVariablesForRemoteReporter(response.data.jwt, response.data.build_hashed_id, response.data.allow_screenshots, data.observability_version.sdkVersion);
420
+ exports.setEnvironmentVariablesForRemoteReporter(response.data.jwt, response.data.build_hashed_id, response.data.allow_screenshots, data.observability_version.sdkVersion);
421
421
  if(this.isBrowserstackInfra() && (user_config.run_settings.auto_import_dev_dependencies != true)) helper.setBrowserstackCypressCliDependency(user_config);
422
422
  } catch(error) {
423
423
  if(!error.errorType) {
@@ -444,7 +444,7 @@ exports.launchTestSession = async (user_config, bsConfigPath) => {
444
444
  }
445
445
 
446
446
  process.env.BS_TESTOPS_BUILD_COMPLETED = false;
447
- setEnvironmentVariablesForRemoteReporter(null, null, null);
447
+ exports.setEnvironmentVariablesForRemoteReporter(null, null, null);
448
448
  }
449
449
  }
450
450
  }
@@ -503,7 +503,7 @@ exports.batchAndPostEvents = async (eventUrl, kind, data) => {
503
503
  try {
504
504
  const eventsUuids = data.map(eventData => `${eventData.event_type}:${eventData.test_run ? eventData.test_run.uuid : (eventData.hook_run ? eventData.hook_run.uuid : null)}`).join(', ');
505
505
  exports.debugOnConsole(`[Request Batch Send] for events:uuids ${eventsUuids}`);
506
- const response = await nodeRequest('POST',eventUrl,data,config);
506
+ const response = await exports.nodeRequest('POST',eventUrl,data,config);
507
507
  exports.debugOnConsole(`[Request Batch Response] for events:uuids ${eventsUuids}`);
508
508
  if(response.data.error) {
509
509
  throw({message: response.data.error});
@@ -570,7 +570,7 @@ exports.uploadEventData = async (eventData, run=0) => {
570
570
  try {
571
571
  const eventsUuids = data.map(eventData => `${eventData.event_type}:${eventData.test_run ? eventData.test_run.uuid : (eventData.hook_run ? eventData.hook_run.uuid : null)}`).join(', ');
572
572
  exports.debugOnConsole(`[Request Send] for events:uuids ${eventsUuids}`);
573
- const response = await nodeRequest('POST',event_api_url,data,config);
573
+ const response = await exports.nodeRequest('POST',event_api_url,data,config);
574
574
  exports.debugOnConsole(`[Request Repsonse] ${util.format(response.data)} for events:uuids ${eventsUuids}`)
575
575
  if(response.data.error) {
576
576
  throw({message: response.data.error});
@@ -681,7 +681,7 @@ exports.stopBuildUpstream = async () => {
681
681
  };
682
682
 
683
683
  try {
684
- const response = await nodeRequest('PUT',`api/v1/builds/${process.env.BS_TESTOPS_BUILD_HASHED_ID}/stop`,data,config);
684
+ const response = await exports.nodeRequest('PUT',`api/v1/builds/${process.env.BS_TESTOPS_BUILD_HASHED_ID}/stop`,data,config);
685
685
  if(response.data && response.data.error) {
686
686
  throw({message: response.data.error});
687
687
  } else {
@@ -11,6 +11,7 @@ const Mocha = requireModule('mocha');
11
11
  // const Runnable = requireModule('mocha/lib/runnable');
12
12
  const Runnable = require('mocha/lib/runnable'); // need to handle as this isn't present in older mocha versions
13
13
  const { v4: uuidv4 } = require('uuid');
14
+ const http = require('http');
14
15
 
15
16
  const { IPC_EVENTS, TEST_REPORTING_ANALYTICS } = require('../helper/constants');
16
17
  const { startIPCServer } = require('../plugin/ipcServer');
@@ -61,6 +62,7 @@ const {
61
62
  } = require('../helper/helper');
62
63
 
63
64
  const { consoleHolder } = require('../helper/constants');
65
+ const { shouldProcessEventForTesthub } = require('../../testhub/utils');
64
66
 
65
67
  // this reporter outputs test results, indenting two spaces per suite
66
68
  class MyReporter {
@@ -70,12 +72,15 @@ class MyReporter {
70
72
  this._testEnv = getTestEnv();
71
73
  this._paths = new PathHelper({ cwd: process.cwd() }, this._testEnv.location_prefix);
72
74
  this.currentTestSteps = [];
75
+ this.httpServer = null;
73
76
  this.currentTestCucumberSteps = [];
74
77
  this.hooksStarted = {};
75
78
  this.beforeHooks = [];
79
+ this.testIdMap = {};
76
80
  this.platformDetailsMap = {};
77
81
  this.runStatusMarkedHash = {};
78
82
  this.haveSentBuildUpdate = false;
83
+ this.startHttpServer();
79
84
  this.registerListeners();
80
85
  setCrashReportingConfigFromReporter(null, process.env.OBS_CRASH_REPORTING_BS_CONFIG_PATH, process.env.OBS_CRASH_REPORTING_CYPRESS_CONFIG_PATH);
81
86
 
@@ -89,7 +94,7 @@ class MyReporter {
89
94
  .on(EVENT_HOOK_BEGIN, async (hook) => {
90
95
  if (this.isInternalHook(hook)) return;
91
96
  debugOnConsole(`[MOCHA EVENT] EVENT_HOOK_BEGIN`);
92
- if(this.testObservability == true) {
97
+ if(shouldProcessEventForTesthub()) {
93
98
  if(!hook.hookAnalyticsId) {
94
99
  hook.hookAnalyticsId = uuidv4();
95
100
  } else if(this.runStatusMarkedHash[hook.hookAnalyticsId]) {
@@ -107,7 +112,7 @@ class MyReporter {
107
112
  .on(EVENT_HOOK_END, async (hook) => {
108
113
  if (this.isInternalHook(hook)) return;
109
114
  debugOnConsole(`[MOCHA EVENT] EVENT_HOOK_END`);
110
- if(this.testObservability == true) {
115
+ if(shouldProcessEventForTesthub()) {
111
116
  if(!this.runStatusMarkedHash[hook.hookAnalyticsId]) {
112
117
  if(!hook.hookAnalyticsId) {
113
118
  /* Hook objects don't maintain uuids in Cypress-Mocha */
@@ -132,7 +137,7 @@ class MyReporter {
132
137
 
133
138
  .on(EVENT_TEST_PASS, async (test) => {
134
139
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PASS`);
135
- if(this.testObservability == true) {
140
+ if(shouldProcessEventForTesthub()) {
136
141
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PASS for uuid: ${test.testAnalyticsId}`);
137
142
  if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
138
143
  if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
@@ -143,7 +148,7 @@ class MyReporter {
143
148
 
144
149
  .on(EVENT_TEST_FAIL, async (test, err) => {
145
150
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_FAIL`);
146
- if(this.testObservability == true) {
151
+ if(shouldProcessEventForTesthub()) {
147
152
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_FAIL for uuid: ${test.testAnalyticsId}`);
148
153
  if((test.testAnalyticsId && !this.runStatusMarkedHash[test.testAnalyticsId]) || (test.hookAnalyticsId && !this.runStatusMarkedHash[test.hookAnalyticsId])) {
149
154
  if(test.testAnalyticsId) {
@@ -159,7 +164,7 @@ class MyReporter {
159
164
 
160
165
  .on(EVENT_TEST_PENDING, async (test) => {
161
166
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PENDING`);
162
- if(this.testObservability == true) {
167
+ if(shouldProcessEventForTesthub()) {
163
168
  if(!test.testAnalyticsId) test.testAnalyticsId = uuidv4();
164
169
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_PENDING for uuid: ${test.testAnalyticsId}`);
165
170
  if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
@@ -172,7 +177,7 @@ class MyReporter {
172
177
  .on(EVENT_TEST_BEGIN, async (test) => {
173
178
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_BEGIN for uuid: ${test.testAnalyticsId}`);
174
179
  if (this.runStatusMarkedHash[test.testAnalyticsId]) return;
175
- if(this.testObservability == true) {
180
+ if(shouldProcessEventForTesthub()) {
176
181
  await this.testStarted(test);
177
182
  }
178
183
  })
@@ -180,7 +185,7 @@ class MyReporter {
180
185
  .on(EVENT_TEST_END, async (test) => {
181
186
  debugOnConsole(`[MOCHA EVENT] EVENT_TEST_BEGIN for uuid: ${test.testAnalyticsId}`);
182
187
  if (this.runStatusMarkedHash[test.testAnalyticsId]) return;
183
- if(this.testObservability == true) {
188
+ if(shouldProcessEventForTesthub()) {
184
189
  if(!this.runStatusMarkedHash[test.testAnalyticsId]) {
185
190
  if(test.testAnalyticsId) this.runStatusMarkedHash[test.testAnalyticsId] = true;
186
191
  await this.sendTestRunEvent(test);
@@ -191,7 +196,7 @@ class MyReporter {
191
196
  .once(EVENT_RUN_END, async () => {
192
197
  try {
193
198
  debugOnConsole(`[MOCHA EVENT] EVENT_RUN_END`);
194
- if(this.testObservability == true) {
199
+ if(shouldProcessEventForTesthub()) {
195
200
  const hookSkippedTests = getHookSkippedTests(this.runner.suite);
196
201
  for(const test of hookSkippedTests) {
197
202
  if(!test.testAnalyticsId) test.testAnalyticsId = uuidv4();
@@ -214,6 +219,66 @@ class MyReporter {
214
219
  return false;
215
220
  }
216
221
 
222
+ async startHttpServer() {
223
+ if(this.httpServer !== null) return;
224
+
225
+ try {
226
+ const httpModule = http;
227
+ this.httpServer = httpModule.createServer(async(req, res) => {
228
+ try {
229
+ // Set CORS headers
230
+ res.setHeader('Access-Control-Allow-Origin', '*');
231
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
232
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
233
+
234
+ if (req.method === 'OPTIONS') {
235
+ res.writeHead(200);
236
+ res.end();
237
+ return;
238
+ }
239
+ const parsedUrl = new URL(req.url, `http://${req.headers.host}`);
240
+ const pathname = parsedUrl.pathname;
241
+ const query = parsedUrl.searchParams;
242
+
243
+ if (pathname === '/test-uuid' && req.method === 'GET') {
244
+ const testIdentifier = query.get('testIdentifier');
245
+
246
+ if (!testIdentifier) {
247
+ res.writeHead(400, { 'Content-Type': 'application/json' });
248
+ res.end(JSON.stringify({
249
+ error: 'testIdentifier parameter is required',
250
+ testRunUuid: null
251
+ }));
252
+ return;
253
+ }
254
+ const testRunUuid = this.getTestId(testIdentifier);
255
+
256
+
257
+ res.writeHead(200, { 'Content-Type': 'application/json' });
258
+ res.end(JSON.stringify({ testRunUuid: testRunUuid }));
259
+ } else {
260
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
261
+ res.end('Not Found');
262
+ }
263
+ } catch (error) {
264
+ debugOnConsole(`Exception in handling HTTP request : ${error}`);
265
+ debug(`Exception in handling HTTP request : ${error}`, true, error);
266
+ res.writeHead(500, { 'Content-Type': 'application/json' });
267
+ res.end(JSON.stringify({ testRunUuid: null }));
268
+ }
269
+ });
270
+
271
+ const port = process.env.REPORTER_API_PORT_NO;
272
+
273
+ this.httpServer.listen(port, '127.0.0.1', async () => {
274
+ console.log(`Reporter HTTP server listening on port ${port}`);
275
+ });
276
+ } catch (error) {
277
+ debugOnConsole(`Exception in starting reporter server : ${error}`);
278
+ debug(`Exception in starting reporter server : ${error}`, true, error);
279
+ }
280
+ }
281
+
217
282
  registerListeners() {
218
283
  startIPCServer(
219
284
  (server) => {
@@ -345,6 +410,8 @@ class MyReporter {
345
410
 
346
411
  debugOnConsole(`${eventType} for uuid: ${testData.uuid}`);
347
412
 
413
+ this.mapTestId(testData, eventType);
414
+
348
415
  if(eventType.match(/TestRunFinished/) || eventType.match(/TestRunSkipped/)) {
349
416
  testData['meta'].steps = JSON.parse(JSON.stringify(this.currentTestCucumberSteps));
350
417
  this.currentTestCucumberSteps = [];
@@ -506,6 +573,16 @@ class MyReporter {
506
573
  }
507
574
  }
508
575
 
576
+ mapTestId = (testData, eventType) => {
577
+ if (!eventType.match(/TestRun/)) {return}
578
+
579
+ this.testIdMap[testData.name] = testData.uuid;
580
+ }
581
+
582
+ getTestId = (testIdentifier) => {
583
+ return this.testIdMap[testIdentifier] || null;
584
+ }
585
+
509
586
  appendTestItemLog = async (log) => {
510
587
  try {
511
588
  if(this.current_hook && ( this.current_hook.hookAnalyticsId && !this.runStatusMarkedHash[this.current_hook.hookAnalyticsId] )) {
@@ -0,0 +1,10 @@
1
+ module.exports = {
2
+ 'TESTHUB_BUILD_API': 'api/v2/builds',
3
+ 'ACCESSIBILITY': 'accessibility',
4
+ 'OBSERVABILITY': 'observability',
5
+ 'ERROR': {
6
+ 'INVALID_CREDENTIALS': 'ERROR_INVALID_CREDENTIALS',
7
+ 'DEPRECATED': 'ERROR_SDK_DEPRECATED',
8
+ 'ACCESS_DENIED': 'ERROR_ACCESS_DENIED'
9
+ },
10
+ };
@@ -0,0 +1,135 @@
1
+ const {
2
+ setCrashReportingConfig,
3
+ isTestObservabilitySession,
4
+ nodeRequest,
5
+ } = require("../testObservability/helper/helper");
6
+ const helper = require("../helpers/helper");
7
+ const testhubUtils = require("../testhub/utils");
8
+ const TESTHUB_CONSTANTS = require("./constants");
9
+ const logger = require('../../bin/helpers/logger').winstonLogger;
10
+
11
+ class TestHubHandler {
12
+ static async launchBuild(user_config, bsConfigPath) {
13
+ setCrashReportingConfig(user_config, bsConfigPath);
14
+
15
+ const obsUserName = user_config["auth"]["username"];
16
+ const obsAccessKey = user_config["auth"]["access_key"];
17
+ const BSTestOpsToken = `${obsUserName || ""}:${obsAccessKey || ""}`;
18
+
19
+ if (BSTestOpsToken === "") {
20
+ // if olly true
21
+ if (isTestObservabilitySession()) {
22
+ logger.debug(
23
+ "EXCEPTION IN BUILD START EVENT : Missing authentication token"
24
+ );
25
+ process.env.BS_TESTOPS_BUILD_COMPLETED = false;
26
+ }
27
+
28
+ if (testhubUtils.isAccessibilityEnabled()) {
29
+ logger.debug(
30
+ "Exception while creating test run for BrowserStack Accessibility Automation: Missing authentication token"
31
+ );
32
+ process.env.BROWSERSTACK_TEST_ACCESSIBILITY = "false";
33
+ }
34
+
35
+ return [null, null];
36
+ }
37
+
38
+ try {
39
+ const data = await this.generateBuildUpstreamData(user_config);
40
+ const config = this.getConfig(obsUserName, obsAccessKey);
41
+ const response = await nodeRequest( "POST", TESTHUB_CONSTANTS.TESTHUB_BUILD_API, data, config);
42
+ const launchData = this.extractDataFromResponse(user_config, data, response, config);
43
+ } catch (error) {
44
+ console.log(error);
45
+ if (error.success === false) { // non 200 response
46
+ testhubUtils.logBuildError(error);
47
+ return;
48
+ }
49
+
50
+ }
51
+ }
52
+
53
+ static async generateBuildUpstreamData(user_config) {
54
+ const { buildName, projectName, buildDescription, buildTags } = helper.getBuildDetails(user_config, true);
55
+ const productMap = testhubUtils.getProductMap(user_config);
56
+ const data = {
57
+ project_name: projectName,
58
+ name: buildName,
59
+ build_identifier: "", // no build identifier in cypress
60
+ description: buildDescription || "",
61
+ started_at: new Date().toISOString(),
62
+ tags: buildTags,
63
+ host_info: helper.getHostInfo(),
64
+ ci_info: helper.getCiInfo(),
65
+ build_run_identifier: process.env.BROWSERSTACK_BUILD_RUN_IDENTIFIER,
66
+ failed_tests_rerun: process.env.BROWSERSTACK_RERUN || false,
67
+ version_control: await helper.getGitMetaData(),
68
+ accessibility: testhubUtils.getAccessibilityOptions(user_config),
69
+ framework_details: testhubUtils.getFrameworkDetails(),
70
+ product_map: productMap,
71
+ browserstackAutomation: productMap["automate"],
72
+ };
73
+
74
+ return data;
75
+ }
76
+
77
+ static async extractDataFromResponse(
78
+ user_config,
79
+ requestData,
80
+ response,
81
+ config
82
+ ) {
83
+ const launchData = {};
84
+
85
+ if (isTestObservabilitySession()) {
86
+ const [jwt, buildHashedId, allowScreenshot] =
87
+ testhubUtils.setTestObservabilityVariables(
88
+ user_config,
89
+ requestData,
90
+ response.data
91
+ );
92
+ if (jwt && buildHashedId) {
93
+ launchData[TESTHUB_CONSTANTS.OBSERVABILITY] = {
94
+ jwt,
95
+ buildHashedId,
96
+ allowScreenshot,
97
+ };
98
+ process.env.BROWSERSTACK_TEST_OBSERVABILITY = "true";
99
+ } else {
100
+ launchData[TESTHUB_CONSTANTS.OBSERVABILITY] = {};
101
+ process.env.BROWSERSTACK_TEST_OBSERVABILITY = "false";
102
+ }
103
+ } else {
104
+ process.env.BROWSERSTACK_TEST_OBSERVABILITY = "false";
105
+ }
106
+
107
+ if(testhubUtils.isAccessibilityEnabled()) {
108
+ testhubUtils.setAccessibilityVariables(user_config, response.data);
109
+ } else {
110
+ process.env.BROWSERSTACK_ACCESSIBILITY = 'false';
111
+ testhubUtils.checkAndSetAccessibility(user_config, false)
112
+ }
113
+
114
+ if (testhubUtils.shouldProcessEventForTesthub()) {
115
+ testhubUtils.setTestHubCommonMetaInfo(user_config, response.data);
116
+ }
117
+
118
+ return launchData;
119
+ }
120
+
121
+ static getConfig(obsUserName, obsAccessKey) {
122
+ return {
123
+ auth: {
124
+ username: obsUserName,
125
+ password: obsAccessKey,
126
+ },
127
+ headers: {
128
+ "Content-Type": "application/json",
129
+ "X-BSTACK-TESTOPS": "true",
130
+ },
131
+ };
132
+ }
133
+ }
134
+
135
+ module.exports = TestHubHandler;