browserstack-cypress-cli 1.33.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.
@@ -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);
@@ -1812,6 +1812,215 @@ exports.decodeJWTToken = (token) => {
1812
1812
  }
1813
1813
  }
1814
1814
 
1815
+ exports.validateAutoImportConflict = (runSettings) => {
1816
+ const constants = require('./constants');
1817
+
1818
+ // Validate auto_import_dev_dependencies type
1819
+ if (runSettings.auto_import_dev_dependencies !== undefined &&
1820
+ typeof runSettings.auto_import_dev_dependencies !== 'boolean') {
1821
+ throw new Error(constants.validationMessages.AUTO_IMPORT_INVALID_TYPE);
1822
+ }
1823
+
1824
+ // Skip validation if auto_import_dev_dependencies is not enabled
1825
+ if (!runSettings.auto_import_dev_dependencies) {
1826
+ return;
1827
+ }
1828
+
1829
+ // Check if any manual npm dependency configurations have values
1830
+ const hasNpmDeps = runSettings.npm_dependencies &&
1831
+ typeof runSettings.npm_dependencies === 'object' &&
1832
+ Object.keys(runSettings.npm_dependencies).length > 0;
1833
+
1834
+ const hasWinDeps = runSettings.win_npm_dependencies &&
1835
+ typeof runSettings.win_npm_dependencies === 'object' &&
1836
+ Object.keys(runSettings.win_npm_dependencies).length > 0;
1837
+
1838
+ const hasMacDeps = runSettings.mac_npm_dependencies &&
1839
+ typeof runSettings.mac_npm_dependencies === 'object' &&
1840
+ Object.keys(runSettings.mac_npm_dependencies).length > 0;
1841
+
1842
+ if (hasNpmDeps || hasWinDeps || hasMacDeps) {
1843
+ throw new Error(constants.validationMessages.AUTO_IMPORT_CONFLICT_ERROR);
1844
+ }
1845
+ };
1846
+
1847
+ exports.readPackageJsonDevDependencies = (projectDir) => {
1848
+ const fs = require('fs');
1849
+ const path = require('path');
1850
+ const constants = require('./constants');
1851
+
1852
+ const packageJsonPath = path.join(projectDir, 'package.json');
1853
+
1854
+ try {
1855
+ const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf8');
1856
+
1857
+ // Remove BOM if present
1858
+ const cleanedContent = packageJsonContent.replace(/^\ufeff/, '');
1859
+
1860
+ if (!cleanedContent.trim()) {
1861
+ throw new Error(constants.validationMessages.PACKAGE_JSON_MALFORMED);
1862
+ }
1863
+
1864
+ let packageJson;
1865
+ try {
1866
+ packageJson = JSON.parse(cleanedContent);
1867
+ } catch (parseError) {
1868
+ throw new Error(constants.validationMessages.PACKAGE_JSON_MALFORMED);
1869
+ }
1870
+
1871
+ if (typeof packageJson !== 'object' || packageJson === null || Array.isArray(packageJson)) {
1872
+ throw new Error(constants.validationMessages.PACKAGE_JSON_NOT_OBJECT);
1873
+ }
1874
+
1875
+ // Handle missing devDependencies field
1876
+ if (packageJson.devDependencies === undefined) {
1877
+ return {};
1878
+ }
1879
+
1880
+ // Validate devDependencies format
1881
+ if (typeof packageJson.devDependencies !== 'object' ||
1882
+ packageJson.devDependencies === null ||
1883
+ Array.isArray(packageJson.devDependencies)) {
1884
+ throw new Error(constants.validationMessages.DEVDEPS_INVALID_FORMAT);
1885
+ }
1886
+
1887
+ return packageJson.devDependencies;
1888
+
1889
+ } catch (error) {
1890
+ if (error.code === 'ENOENT') {
1891
+ throw new Error(constants.validationMessages.PACKAGE_JSON_NOT_FOUND);
1892
+ } else if (error.code === 'EACCES') {
1893
+ throw new Error(constants.validationMessages.PACKAGE_JSON_PERMISSION_DENIED);
1894
+ } else if (error.message.includes(constants.validationMessages.PACKAGE_JSON_MALFORMED) ||
1895
+ error.message.includes(constants.validationMessages.PACKAGE_JSON_NOT_OBJECT) ||
1896
+ error.message.includes(constants.validationMessages.DEVDEPS_INVALID_FORMAT)) {
1897
+ throw error;
1898
+ } else {
1899
+ throw new Error(`Cannot read package.json: ${error.message}`);
1900
+ }
1901
+ }
1902
+ };
1903
+
1904
+ exports.filterDependenciesWithRegex = (dependencies, excludePatterns) => {
1905
+ const constants = require('./constants');
1906
+
1907
+ // Validate dependencies parameter
1908
+ if (!dependencies || typeof dependencies !== 'object' || Array.isArray(dependencies)) {
1909
+ throw new Error(constants.validationMessages.DEPENDENCIES_PARAM_INVALID);
1910
+ }
1911
+
1912
+ // Return all dependencies if no exclusion patterns
1913
+ if (!excludePatterns) {
1914
+ return dependencies;
1915
+ }
1916
+
1917
+ // Validate excludePatterns parameter
1918
+ if (!Array.isArray(excludePatterns)) {
1919
+ throw new Error(constants.validationMessages.EXCLUDE_DEPS_INVALID_TYPE);
1920
+ }
1921
+
1922
+ // Validate all patterns are strings
1923
+ for (const pattern of excludePatterns) {
1924
+ if (typeof pattern !== 'string') {
1925
+ throw new Error(constants.validationMessages.EXCLUDE_DEPS_INVALID_PATTERNS);
1926
+ }
1927
+ }
1928
+
1929
+ // If no patterns, return all dependencies
1930
+ if (excludePatterns.length === 0) {
1931
+ return dependencies;
1932
+ }
1933
+
1934
+ const filteredDependencies = {};
1935
+
1936
+ for (const [packageName, version] of Object.entries(dependencies)) {
1937
+ let shouldExclude = false;
1938
+
1939
+ for (const pattern of excludePatterns) {
1940
+ // Skip empty patterns
1941
+ if (!pattern) {
1942
+ continue;
1943
+ }
1944
+
1945
+ try {
1946
+ const regex = new RegExp(pattern);
1947
+ if (regex.test(packageName)) {
1948
+ shouldExclude = true;
1949
+ break;
1950
+ }
1951
+ } catch (regexError) {
1952
+ const errorMsg = constants.validationMessages.INVALID_REGEX_PATTERN.replace('{pattern}', pattern);
1953
+ throw new Error(errorMsg);
1954
+ }
1955
+ }
1956
+
1957
+ if (!shouldExclude) {
1958
+ filteredDependencies[packageName] = version;
1959
+ }
1960
+ }
1961
+
1962
+ return filteredDependencies;
1963
+ };
1964
+
1965
+ exports.ensureBrowserstackCypressCliDependency = (npmDependencies) => {
1966
+ // Validate npmDependencies parameter
1967
+ if (npmDependencies === undefined || npmDependencies === null ||
1968
+ typeof npmDependencies !== 'object' || Array.isArray(npmDependencies)) {
1969
+ return;
1970
+ }
1971
+
1972
+ // Check if browserstack-cypress-cli already exists
1973
+ if ("browserstack-cypress-cli" in npmDependencies) {
1974
+ return;
1975
+ }
1976
+
1977
+ logger.warn("Missing browserstack-cypress-cli not found in npm_dependencies");
1978
+
1979
+ // Get version from package.json (similar to getAgentVersion)
1980
+ let version = "latest";
1981
+ try {
1982
+ const packageJsonPath = path.join(__dirname, '../../package.json');
1983
+ if (fs.existsSync(packageJsonPath)) {
1984
+ version = require(packageJsonPath).version;
1985
+ }
1986
+ } catch (err) {
1987
+ logger.debug("Could not read package.json version, using 'latest'");
1988
+ }
1989
+
1990
+ npmDependencies['browserstack-cypress-cli'] = version;
1991
+ logger.warn(`Adding browserstack-cypress-cli version ${version} in npm_dependencies`);
1992
+ };
1993
+
1994
+ exports.processAutoImportDependencies = (runSettings) => {
1995
+ // Always run validation first
1996
+ exports.validateAutoImportConflict(runSettings);
1997
+
1998
+ // Skip processing if auto_import_dev_dependencies is not enabled
1999
+ if (!runSettings.auto_import_dev_dependencies) {
2000
+ return;
2001
+ }
2002
+
2003
+ // Determine project directory using battle-tested logic
2004
+ let projectDir;
2005
+ if (runSettings.home_directory) {
2006
+ projectDir = runSettings.home_directory;
2007
+ } else {
2008
+ const path = require('path');
2009
+ projectDir = path.dirname(runSettings.cypressConfigFilePath);
2010
+ }
2011
+
2012
+ // Read devDependencies from package.json
2013
+ const devDependencies = exports.readPackageJsonDevDependencies(projectDir);
2014
+
2015
+ // Apply exclusion filters
2016
+ const filteredDependencies = exports.filterDependenciesWithRegex(devDependencies, runSettings.exclude_dependencies);
2017
+
2018
+ // Set the npm_dependencies in runSettings
2019
+ runSettings.npm_dependencies = filteredDependencies;
2020
+
2021
+ // Ensure browserstack-cypress-cli dependency is present when auto import is enabled
2022
+ exports.ensureBrowserstackCypressCliDependency(runSettings.npm_dependencies);
2023
+ };
1815
2024
  exports.normalizeTestReportingEnvVars = () => {
1816
2025
  if (!this.isUndefined(process.env.BROWSERSTACK_TEST_REPORTING)){
1817
2026
  process.env.BROWSERSTACK_TEST_OBSERVABILITY = process.env.BROWSERSTACK_TEST_REPORTING;
@@ -59,6 +59,8 @@ module.exports = function () {
59
59
  "parallels": "Number of parallels you want to run",
60
60
  "npm_dependencies": {
61
61
  },
62
+ "auto_import_dev_dependencies": false,
63
+ "exclude_dependencies": [],
62
64
  "package_config_options": {
63
65
  },
64
66
  "headless": true
@@ -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,11 +414,11 @@ 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);
421
- if(this.isBrowserstackInfra()) helper.setBrowserstackCypressCliDependency(user_config);
420
+ exports.setEnvironmentVariablesForRemoteReporter(response.data.jwt, response.data.build_hashed_id, response.data.allow_screenshots, data.observability_version.sdkVersion);
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) {
424
424
  if (error.response) {
@@ -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;