browserstack-cypress-cli 1.23.1 → 1.24.2

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.
@@ -0,0 +1,996 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const http = require('http');
4
+ const https = require('https');
5
+ const request = require('request');
6
+ var gitLastCommit = require('git-last-commit');
7
+ const { v4: uuidv4 } = require('uuid');
8
+ const os = require('os');
9
+ const { promisify } = require('util');
10
+ const getRepoInfo = require('git-repo-info');
11
+ const gitconfig = require('gitconfiglocal');
12
+ const { spawn, execSync } = require('child_process');
13
+ const glob = require('glob');
14
+
15
+ const pGitconfig = promisify(gitconfig);
16
+
17
+ const logger = require("../../helpers/logger").winstonLogger;
18
+ const utils = require('../../helpers/utils');
19
+ const CrashReporter = require('../crashReporter');
20
+
21
+ // Getting global packages path
22
+ const GLOBAL_MODULE_PATH = execSync('npm root -g').toString().trim();
23
+
24
+ const { name, version } = require('../../../package.json');
25
+
26
+ const { CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS } = require('../../helpers/constants');
27
+ const { consoleHolder, API_URL, TEST_OBSERVABILITY_REPORTER } = require('./constants');
28
+ exports.pending_test_uploads = {
29
+ count: 0
30
+ };
31
+
32
+ exports.debug = (text, shouldReport = false, throwable = null) => {
33
+ if (process.env.BROWSERSTACK_OBSERVABILITY_DEBUG === "true" || process.env.BROWSERSTACK_OBSERVABILITY_DEBUG === "1") {
34
+ logger.info(`[ OBSERVABILITY ] ${text}`);
35
+ }
36
+ if(shouldReport) {
37
+ CrashReporter.getInstance().uploadCrashReport(text, throwable ? throwable && throwable.stack : null);
38
+ }
39
+ }
40
+
41
+ const supportFileContentMap = {};
42
+
43
+ exports.httpsKeepAliveAgent = new https.Agent({
44
+ keepAlive: true,
45
+ timeout: 60000,
46
+ maxSockets: 2,
47
+ maxTotalSockets: 2
48
+ });
49
+
50
+ const httpsScreenshotsKeepAliveAgent = new https.Agent({
51
+ keepAlive: true,
52
+ timeout: 60000,
53
+ maxSockets: 2,
54
+ maxTotalSockets: 2
55
+ });
56
+
57
+ const supportFileCleanup = () => {
58
+ Object.keys(supportFileContentMap).forEach(file => {
59
+ try {
60
+ fs.writeFileSync(file, supportFileContentMap[file], {encoding: 'utf-8'});
61
+ } catch(e) {
62
+ exports.debug(`Error while replacing file content for ${file} with it's original content with error : ${e}`, true, e);
63
+ }
64
+ });
65
+ }
66
+
67
+ exports.printBuildLink = async (shouldStopSession, exitCode = null) => {
68
+ if(!this.isTestObservabilitySession()) return;
69
+ try {
70
+ if(shouldStopSession) {
71
+ supportFileCleanup();
72
+ await this.stopBuildUpstream();
73
+ }
74
+ try {
75
+ if(process.env.BS_TESTOPS_BUILD_HASHED_ID
76
+ && process.env.BS_TESTOPS_BUILD_HASHED_ID != "null"
77
+ && process.env.BS_TESTOPS_BUILD_HASHED_ID != "undefined") {
78
+ console.log();
79
+ logger.info(`Visit https://observability.browserstack.com/builds/${process.env.BS_TESTOPS_BUILD_HASHED_ID} to view build report, insights, and many more debugging information all at one place!\n`);
80
+ }
81
+ } catch(err) {
82
+ exports.debug('Build Not Found');
83
+ }
84
+ } catch(err) {
85
+ exports.debug(`Error while stopping build with error : ${err}`, true, err);
86
+ }
87
+ if(exitCode) process.exit(exitCode);
88
+ }
89
+
90
+ const nodeRequest = (type, url, data, config) => {
91
+ return new Promise(async (resolve, reject) => {
92
+ const options = {...config,...{
93
+ method: type,
94
+ url: `${API_URL}/${url}`,
95
+ body: data,
96
+ json: config.headers['Content-Type'] === 'application/json',
97
+ agent: this.httpsKeepAliveAgent
98
+ }};
99
+
100
+ if(url === exports.requestQueueHandler.screenshotEventUrl) {
101
+ options.agent = httpsScreenshotsKeepAliveAgent;
102
+ }
103
+
104
+ request(options, function callback(error, response, body) {
105
+ if(error) {
106
+ reject(error);
107
+ } else if(response.statusCode != 200) {
108
+ reject(response && response.body ? response.body : `Received response from BrowserStack Server with status : ${response.statusCode}`);
109
+ } else {
110
+ try {
111
+ if(typeof(body) !== 'object') body = JSON.parse(body);
112
+ } catch(e) {
113
+ if(!url.includes('/stop')) {
114
+ reject('Not a JSON response from BrowserStack Server');
115
+ }
116
+ }
117
+ resolve({
118
+ data: body
119
+ });
120
+ }
121
+ });
122
+ });
123
+ }
124
+
125
+ exports.failureData = (errors,tag) => {
126
+ if(!errors) return [];
127
+ try {
128
+ if(tag === 'test') {
129
+ return errors.map((failure) => {
130
+ let {stack, ...expanded} = failure
131
+ let expandedArray = Object.keys(expanded).map((key) => {
132
+ return `${key}: ${expanded[key]}`
133
+ })
134
+ return { backtrace: stack.split(/\r?\n/), expanded: expandedArray }
135
+ })
136
+ } else if(tag === 'err') {
137
+ let failureArr = [], failureChildArr = [];
138
+ Object.keys(errors).forEach((key) => {
139
+ try {
140
+ failureChildArr.push(`${key}: ${errors[key]}`);
141
+ } catch(e) {
142
+ exports.debug(`Exception in populating test failure data with error : ${e.message} : ${e.backtrace}`, true, e);
143
+ }
144
+ })
145
+ failureArr.push({ backtrace: errors.stack.split(/\r?\n/), expanded: failureChildArr });
146
+ return failureArr;
147
+ } else {
148
+ return [];
149
+ }
150
+ } catch(e) {
151
+ exports.debug(`Exception in populating test failure data with error : ${e.message} : ${e.backtrace}`, true, e);
152
+ }
153
+ return [];
154
+ }
155
+
156
+ exports.getTestEnv = () => {
157
+ return {
158
+ "ci": "generic",
159
+ "key": uuidv4(),
160
+ "version": version,
161
+ "collector": `js-${name}`,
162
+ }
163
+ }
164
+
165
+ exports.getFileSeparatorData = () => {
166
+ const fileSeparatorRegex = /^win/.test(process.platform) ? "\\\\" : "/";
167
+ const fileSeparator = /^win/.test(process.platform) ? "\\" : "/";
168
+ return {
169
+ fileSeparator,
170
+ fileSeparatorRegex
171
+ };
172
+ }
173
+
174
+ exports.findGitConfig = (filePath) => {
175
+ const { fileSeparator, fileSeparatorRegex } = exports.getFileSeparatorData();
176
+ if(filePath == null || filePath == '' || filePath == fileSeparator) {
177
+ return null;
178
+ }
179
+ try {
180
+ fs.statSync(filePath + fileSeparator + '.git' + fileSeparator + 'config');
181
+ return filePath;
182
+ } catch(e) {
183
+ let parentFilePath = filePath.split(fileSeparatorRegex);
184
+ parentFilePath.pop();
185
+ return exports.findGitConfig(parentFilePath.join(fileSeparator));
186
+ }
187
+ }
188
+
189
+ const getGitMetaData = () => {
190
+ return new Promise(async (resolve, reject) => {
191
+ try {
192
+ var info = getRepoInfo();
193
+ if(!info.commonGitDir) {
194
+ exports.debug(`Unable to find a Git directory`);
195
+ resolve({});
196
+ }
197
+ if(!info.author && exports.findGitConfig(process.cwd())) {
198
+ /* commit objects are packed */
199
+ gitLastCommit.getLastCommit(async (err, commit) => {
200
+ info["author"] = info["author"] || `${commit["author"]["name"].replace(/[“]+/g, '')} <${commit["author"]["email"].replace(/[“]+/g, '')}>`;
201
+ info["authorDate"] = info["authorDate"] || commit["authoredOn"];
202
+ info["committer"] = info["committer"] || `${commit["committer"]["name"].replace(/[“]+/g, '')} <${commit["committer"]["email"].replace(/[“]+/g, '')}>`;
203
+ info["committerDate"] = info["committerDate"] || commit["committedOn"]
204
+ info["commitMessage"] = info["commitMessage"] || commit["subject"];
205
+
206
+ const { remote } = await pGitconfig(info.commonGitDir);
207
+ const remotes = Object.keys(remote).map(remoteName => ({name: remoteName, url: remote[remoteName]['url']}));
208
+ resolve({
209
+ "name": "git",
210
+ "sha": info["sha"],
211
+ "short_sha": info["abbreviatedSha"],
212
+ "branch": info["branch"],
213
+ "tag": info["tag"],
214
+ "committer": info["committer"],
215
+ "committer_date": info["committerDate"],
216
+ "author": info["author"],
217
+ "author_date": info["authorDate"],
218
+ "commit_message": info["commitMessage"],
219
+ "root": info["root"],
220
+ "common_git_dir": info["commonGitDir"],
221
+ "worktree_git_dir": info["worktreeGitDir"],
222
+ "last_tag": info["lastTag"],
223
+ "commits_since_last_tag": info["commitsSinceLastTag"],
224
+ "remotes": remotes
225
+ });
226
+ }, {dst: exports.findGitConfig(process.cwd())});
227
+ } else {
228
+ const { remote } = await pGitconfig(info.commonGitDir);
229
+ const remotes = Object.keys(remote).map(remoteName => ({name: remoteName, url: remote[remoteName]['url']}));
230
+ resolve({
231
+ "name": "git",
232
+ "sha": info["sha"],
233
+ "short_sha": info["abbreviatedSha"],
234
+ "branch": info["branch"],
235
+ "tag": info["tag"],
236
+ "committer": info["committer"],
237
+ "committer_date": info["committerDate"],
238
+ "author": info["author"],
239
+ "author_date": info["authorDate"],
240
+ "commit_message": info["commitMessage"],
241
+ "root": info["root"],
242
+ "common_git_dir": info["commonGitDir"],
243
+ "worktree_git_dir": info["worktreeGitDir"],
244
+ "last_tag": info["lastTag"],
245
+ "commits_since_last_tag": info["commitsSinceLastTag"],
246
+ "remotes": remotes
247
+ });
248
+ }
249
+ } catch(err) {
250
+ exports.debug(`Exception in populating Git metadata with error : ${err}`, true, err);
251
+ resolve({});
252
+ }
253
+ })
254
+ }
255
+
256
+ const getCiInfo = () => {
257
+ var env = process.env;
258
+ // Jenkins
259
+ if ((typeof env.JENKINS_URL === "string" && env.JENKINS_URL.length > 0) || (typeof env.JENKINS_HOME === "string" && env.JENKINS_HOME.length > 0)) {
260
+ return {
261
+ name: "Jenkins",
262
+ build_url: env.BUILD_URL,
263
+ job_name: env.JOB_NAME,
264
+ build_number: env.BUILD_NUMBER
265
+ }
266
+ }
267
+ // CircleCI
268
+ if (env.CI === "true" && env.CIRCLECI === "true") {
269
+ return {
270
+ name: "CircleCI",
271
+ build_url: env.CIRCLE_BUILD_URL,
272
+ job_name: env.CIRCLE_JOB,
273
+ build_number: env.CIRCLE_BUILD_NUM
274
+ }
275
+ }
276
+ // Travis CI
277
+ if (env.CI === "true" && env.TRAVIS === "true") {
278
+ return {
279
+ name: "Travis CI",
280
+ build_url: env.TRAVIS_BUILD_WEB_URL,
281
+ job_name: env.TRAVIS_JOB_NAME,
282
+ build_number: env.TRAVIS_BUILD_NUMBER
283
+ }
284
+ }
285
+ // Codeship
286
+ if (env.CI === "true" && env.CI_NAME === "codeship") {
287
+ return {
288
+ name: "Codeship",
289
+ build_url: null,
290
+ job_name: null,
291
+ build_number: null
292
+ }
293
+ }
294
+ // Bitbucket
295
+ if (env.BITBUCKET_BRANCH && env.BITBUCKET_COMMIT) {
296
+ return {
297
+ name: "Bitbucket",
298
+ build_url: env.BITBUCKET_GIT_HTTP_ORIGIN,
299
+ job_name: null,
300
+ build_number: env.BITBUCKET_BUILD_NUMBER
301
+ }
302
+ }
303
+ // Drone
304
+ if (env.CI === "true" && env.DRONE === "true") {
305
+ return {
306
+ name: "Drone",
307
+ build_url: env.DRONE_BUILD_LINK,
308
+ job_name: null,
309
+ build_number: env.DRONE_BUILD_NUMBER
310
+ }
311
+ }
312
+ // Semaphore
313
+ if (env.CI === "true" && env.SEMAPHORE === "true") {
314
+ return {
315
+ name: "Semaphore",
316
+ build_url: env.SEMAPHORE_ORGANIZATION_URL,
317
+ job_name: env.SEMAPHORE_JOB_NAME,
318
+ build_number: env.SEMAPHORE_JOB_ID
319
+ }
320
+ }
321
+ // GitLab
322
+ if (env.CI === "true" && env.GITLAB_CI === "true") {
323
+ return {
324
+ name: "GitLab",
325
+ build_url: env.CI_JOB_URL,
326
+ job_name: env.CI_JOB_NAME,
327
+ build_number: env.CI_JOB_ID
328
+ }
329
+ }
330
+ // Buildkite
331
+ if (env.CI === "true" && env.BUILDKITE === "true") {
332
+ return {
333
+ name: "Buildkite",
334
+ build_url: env.BUILDKITE_BUILD_URL,
335
+ job_name: env.BUILDKITE_LABEL || env.BUILDKITE_PIPELINE_NAME,
336
+ build_number: env.BUILDKITE_BUILD_NUMBER
337
+ }
338
+ }
339
+ // Visual Studio Team Services
340
+ if (env.TF_BUILD === "True") {
341
+ return {
342
+ name: "Visual Studio Team Services",
343
+ build_url: `${env.SYSTEM_TEAMFOUNDATIONSERVERURI}${env.SYSTEM_TEAMPROJECTID}`,
344
+ job_name: env.SYSTEM_DEFINITIONID,
345
+ build_number: env.BUILD_BUILDID
346
+ }
347
+ }
348
+ // if no matches, return null
349
+ return null;
350
+ }
351
+
352
+ let packages = {};
353
+
354
+ exports.getPackageVersion = (package_) => {
355
+ if(packages[package_]) return packages[package_];
356
+ return packages[package_] = this.requireModule(`${package_}/package.json`).version;
357
+ }
358
+
359
+ exports.getAgentVersion = () => {
360
+ let _path = path.join(__dirname, '../../../package.json');
361
+ if(fs.existsSync(_path))
362
+ return require(_path).version;
363
+ }
364
+
365
+ const setEnvironmentVariablesForRemoteReporter = (BS_TESTOPS_JWT, BS_TESTOPS_BUILD_HASHED_ID, BS_TESTOPS_ALLOW_SCREENSHOTS, OBSERVABILITY_LAUNCH_SDK_VERSION) => {
366
+ process.env.BS_TESTOPS_JWT = BS_TESTOPS_JWT;
367
+ process.env.BS_TESTOPS_BUILD_HASHED_ID = BS_TESTOPS_BUILD_HASHED_ID;
368
+ process.env.BS_TESTOPS_ALLOW_SCREENSHOTS = BS_TESTOPS_ALLOW_SCREENSHOTS;
369
+ process.env.OBSERVABILITY_LAUNCH_SDK_VERSION = OBSERVABILITY_LAUNCH_SDK_VERSION;
370
+ }
371
+
372
+ const getCypressCommandEventListener = () => {
373
+ return (
374
+ `require('browserstack-cypress-cli/bin/testObservability/cypress');`
375
+ );
376
+ }
377
+
378
+ const setEventListeners = () => {
379
+ try {
380
+ const cypressCommandEventListener = getCypressCommandEventListener();
381
+ glob(process.cwd() + '/cypress/support/*.js', {}, (err, files) => {
382
+ if(err) return exports.debug('EXCEPTION IN BUILD START EVENT : Unable to parse cypress support files');
383
+ files.forEach(file => {
384
+ try {
385
+ if(!file.includes('commands.js')) {
386
+ const defaultFileContent = fs.readFileSync(file, {encoding: 'utf-8'});
387
+
388
+ if(!defaultFileContent.includes(cypressCommandEventListener)) {
389
+ let newFileContent = defaultFileContent +
390
+ '\n' +
391
+ cypressCommandEventListener +
392
+ '\n'
393
+ fs.writeFileSync(file, newFileContent, {encoding: 'utf-8'});
394
+ supportFileContentMap[file] = defaultFileContent;
395
+ }
396
+ }
397
+ } catch(e) {
398
+ exports.debug(`Unable to modify file contents for ${file} to set event listeners with error ${e}`, true, e);
399
+ }
400
+ });
401
+ });
402
+ } catch(e) {
403
+ exports.debug(`Unable to parse support files to set event listeners with error ${e}`, true, e);
404
+ }
405
+ }
406
+
407
+ const getBuildDetails = (bsConfig) => {
408
+ const isTestObservabilityOptionsPresent = !utils.isUndefined(bsConfig["testObservabilityOptions"]);
409
+ let buildName = '',
410
+ projectName = '',
411
+ buildDescription = '',
412
+ buildTags = [];
413
+
414
+ /* Pick from environment variables */
415
+ buildName = process.env.BROWSERSTACK_BUILD_NAME || buildName;
416
+ projectName = process.env.BROWSERSTACK_PROJECT_NAME || projectName;
417
+
418
+ /* Pick from testObservabilityOptions */
419
+ if(isTestObservabilityOptionsPresent) {
420
+ buildName = buildName || bsConfig["testObservabilityOptions"]["buildName"];
421
+ projectName = projectName || bsConfig["testObservabilityOptions"]["projectName"];
422
+ if(!utils.isUndefined(bsConfig["testObservabilityOptions"]["buildTag"])) buildTags = [...buildTags, ...bsConfig["testObservabilityOptions"]["buildTag"]];
423
+ buildDescription = buildDescription || bsConfig["testObservabilityOptions"]["buildDescription"];
424
+ }
425
+
426
+ /* Pick from run settings */
427
+ buildName = buildName || bsConfig["run_settings"]["build_name"];
428
+ projectName = projectName || bsConfig["run_settings"]["project_name"];
429
+ if(!utils.isUndefined(bsConfig["run_settings"]["build_tag"])) buildTags = [...buildTags, bsConfig["run_settings"]["build_tag"]];
430
+
431
+ buildName = buildName || path.basename(path.resolve(process.cwd()));
432
+
433
+ return {
434
+ buildName,
435
+ projectName,
436
+ buildDescription,
437
+ buildTags
438
+ };
439
+ }
440
+
441
+ const setBrowserstackCypressCliDependency = (bsConfig) => {
442
+ const runSettings = bsConfig.run_settings;
443
+ if (runSettings.npm_dependencies !== undefined &&
444
+ Object.keys(runSettings.npm_dependencies).length !== 0 &&
445
+ typeof runSettings.npm_dependencies === 'object') {
446
+ if (!("browserstack-cypress-cli" in runSettings.npm_dependencies)) {
447
+ logger.warn("Missing browserstack-cypress-cli not found in npm_dependencies");
448
+ runSettings.npm_dependencies['browserstack-cypress-cli'] = exports.getAgentVersion() || "latest";
449
+ logger.warn(`Adding browserstack-cypress-cli version ${runSettings.npm_dependencies['browserstack-cypress-cli']} in npm_dependencies`);
450
+ }
451
+ }
452
+ }
453
+
454
+ const getCypressConfigFileContent = (bsConfig, cypressConfigPath) => {
455
+ const cypressConfigFile = require(path.resolve(bsConfig ? bsConfig.run_settings.cypress_config_file : cypressConfigPath));
456
+ if(bsConfig) process.env.OBS_CRASH_REPORTING_CYPRESS_CONFIG_PATH = bsConfig.run_settings.cypress_config_file;
457
+ return cypressConfigFile;
458
+ }
459
+
460
+ exports.setCrashReportingConfigFromReporter = (credentialsStr, bsConfigPath, cypressConfigPath) => {
461
+ try {
462
+ const browserstackConfigFile = utils.readBsConfigJSON(bsConfigPath);
463
+ const cypressConfigFile = getCypressConfigFileContent(null, cypressConfigPath);
464
+
465
+ if(!credentialsStr) {
466
+ credentialsStr = JSON.stringify({
467
+ username: process.env.OBS_CRASH_REPORTING_USERNAME,
468
+ password: process.env.OBS_CRASH_REPORTING_ACCESS_KEY
469
+ });
470
+ }
471
+ CrashReporter.getInstance().setConfigDetails(credentialsStr, browserstackConfigFile, cypressConfigFile);
472
+ } catch(e) {
473
+ exports.debug(`Encountered an error when trying to set Crash Reporting Config from reporter ${e}`);
474
+ }
475
+ }
476
+
477
+ const setCrashReportingConfig = (bsConfig, bsConfigPath) => {
478
+ try {
479
+ const browserstackConfigFile = utils.readBsConfigJSON(bsConfigPath);
480
+ const cypressConfigFile = getCypressConfigFileContent(bsConfig, null);
481
+ const credentialsStr = JSON.stringify({
482
+ username: bsConfig["auth"]["username"],
483
+ password: bsConfig["auth"]["access_key"]
484
+ });
485
+ CrashReporter.getInstance().setConfigDetails(credentialsStr, browserstackConfigFile, cypressConfigFile);
486
+ process.env.OBS_CRASH_REPORTING_USERNAME = bsConfig["auth"]["username"];
487
+ process.env.OBS_CRASH_REPORTING_ACCESS_KEY = bsConfig["auth"]["access_key"];
488
+ process.env.OBS_CRASH_REPORTING_BS_CONFIG_PATH = bsConfigPath ? path.relative(process.cwd(), bsConfigPath) : null;
489
+ } catch(e) {
490
+ exports.debug(`Encountered an error when trying to set Crash Reporting Config ${e}`);
491
+ }
492
+ }
493
+
494
+ exports.launchTestSession = async (user_config, bsConfigPath) => {
495
+ setCrashReportingConfig(user_config, bsConfigPath);
496
+
497
+ const obsUserName = user_config["auth"]["username"];
498
+ const obsAccessKey = user_config["auth"]["access_key"];
499
+
500
+ const BSTestOpsToken = `${obsUserName || ''}:${obsAccessKey || ''}`;
501
+ if(BSTestOpsToken === '') {
502
+ exports.debug('EXCEPTION IN BUILD START EVENT : Missing authentication token', true, null);
503
+ process.env.BS_TESTOPS_BUILD_COMPLETED = false;
504
+ return [null, null];
505
+ } else {
506
+ try {
507
+ const {
508
+ buildName,
509
+ projectName,
510
+ buildDescription,
511
+ buildTags
512
+ } = getBuildDetails(user_config);
513
+ const data = {
514
+ 'format': 'json',
515
+ 'project_name': projectName,
516
+ 'name': buildName,
517
+ 'description': buildDescription,
518
+ 'start_time': (new Date()).toISOString(),
519
+ 'tags': buildTags,
520
+ 'host_info': {
521
+ hostname: os.hostname(),
522
+ platform: os.platform(),
523
+ type: os.type(),
524
+ version: os.version(),
525
+ arch: os.arch()
526
+ },
527
+ 'ci_info': getCiInfo(),
528
+ 'build_run_identifier': process.env.BROWSERSTACK_BUILD_RUN_IDENTIFIER,
529
+ 'failed_tests_rerun': process.env.BROWSERSTACK_RERUN || false,
530
+ 'version_control': await getGitMetaData(),
531
+ 'observability_version': {
532
+ frameworkName: "Cypress",
533
+ frameworkVersion: exports.getPackageVersion('cypress'),
534
+ sdkVersion: exports.getAgentVersion()
535
+ }
536
+ };
537
+ const config = {
538
+ auth: {
539
+ username: obsUserName,
540
+ password: obsAccessKey
541
+ },
542
+ headers: {
543
+ 'Content-Type': 'application/json',
544
+ 'X-BSTACK-TESTOPS': 'true'
545
+ }
546
+ };
547
+
548
+ const response = await nodeRequest('POST','api/v1/builds',data,config);
549
+ exports.debug('Build creation successfull!');
550
+ process.env.BS_TESTOPS_BUILD_COMPLETED = true;
551
+ setEnvironmentVariablesForRemoteReporter(response.data.jwt, response.data.build_hashed_id, response.data.allow_screenshots, data.observability_version.sdkVersion);
552
+ setEventListeners();
553
+ if(this.isBrowserstackInfra()) setBrowserstackCypressCliDependency(user_config);
554
+ } catch(error) {
555
+ if(!error.errorType) {
556
+ if (error.response) {
557
+ exports.debug(`EXCEPTION IN BUILD START EVENT : ${error.response.status} ${error.response.statusText} ${JSON.stringify(error.response.data)}`, true, error);
558
+ } else {
559
+ exports.debug(`EXCEPTION IN BUILD START EVENT : ${error.message || error}`, true, error);
560
+ }
561
+ } else {
562
+ const { errorType, message } = error;
563
+ switch (errorType) {
564
+ case 'ERROR_INVALID_CREDENTIALS':
565
+ logger.error(message);
566
+ break;
567
+ case 'ERROR_ACCESS_DENIED':
568
+ logger.info(message);
569
+ break;
570
+ case 'ERROR_SDK_DEPRECATED':
571
+ logger.error(message);
572
+ break;
573
+ default:
574
+ logger.error(message);
575
+ }
576
+ }
577
+
578
+ process.env.BS_TESTOPS_BUILD_COMPLETED = false;
579
+ setEnvironmentVariablesForRemoteReporter(null, null, null);
580
+ }
581
+ }
582
+ }
583
+
584
+ exports.getHookDetails = (hookTitle) => {
585
+ if(!hookTitle || typeof(hookTitle) != 'string') return [null, null];
586
+ if(hookTitle.indexOf('hook:') !== -1) {
587
+ const hook_details = hookTitle.split('hook:');
588
+ return [hook_details[0].slice(0,-1).split('"')[1], hook_details[1].substring(1)];
589
+ } else if(hookTitle.indexOf('hook') !== -1) {
590
+ const hook_details = hookTitle.split('hook');
591
+ return [hook_details[0].slice(0,-1).split('"')[1], hookTitle];
592
+ } else {
593
+ return [null, null];
594
+ }
595
+ }
596
+
597
+ exports.getHooksForTest = (test) => {
598
+ if(!test || !test.parent) return [];
599
+ const hooksArr = [];
600
+ ['_beforeAll','_afterAll','_beforeEach','_afterEach'].forEach(hookType => {
601
+ let hooks = test.parent[hookType] || []
602
+ hooks.forEach(testHook => {
603
+ if(testHook.hookAnalyticsId) hooksArr.push(testHook.hookAnalyticsId);
604
+ })
605
+ });
606
+ return [...hooksArr,...exports.getHooksForTest(test.parent)];
607
+ }
608
+
609
+ exports.mapTestHooks = (test) => {
610
+ if(!test || !test.parent) return;
611
+ ['_beforeAll','_afterAll','_beforeEach','_afterEach'].forEach(hookType => {
612
+ let hooks = test.parent[hookType] || []
613
+ hooks.forEach(testHook => {
614
+ if(!testHook.hookAnalyticsId) {
615
+ testHook.hookAnalyticsId = uuidv4();
616
+ } else if(testHook.markedStatus && hookType == '_afterEach') {
617
+ testHook.hookAnalyticsId = uuidv4();
618
+ delete testHook.markedStatus;
619
+ }
620
+ testHook['test_run_id'] = testHook['test_run_id'] || test.testAnalyticsId;
621
+ })
622
+ });
623
+ exports.mapTestHooks(test.parent);
624
+ }
625
+
626
+ exports.batchAndPostEvents = async (eventUrl, kind, data) => {
627
+ const config = {
628
+ headers: {
629
+ 'Authorization': `Bearer ${process.env.BS_TESTOPS_JWT}`,
630
+ 'Content-Type': 'application/json',
631
+ 'X-BSTACK-TESTOPS': 'true'
632
+ }
633
+ };
634
+
635
+ try {
636
+ const response = await nodeRequest('POST',eventUrl,data,config);
637
+ if(response.data.error) {
638
+ throw({message: response.data.error});
639
+ } else {
640
+ exports.debug(`${kind} event successfull!`)
641
+ exports.pending_test_uploads.count = Math.max(0,exports.pending_test_uploads.count - data.length);
642
+ }
643
+ } catch(error) {
644
+ if (error.response) {
645
+ exports.debug(`EXCEPTION IN ${kind} REQUEST TO TEST OBSERVABILITY : ${error.response.status} ${error.response.statusText} ${JSON.stringify(error.response.data)}`, true, error);
646
+ } else {
647
+ exports.debug(`EXCEPTION IN ${kind} REQUEST TO TEST OBSERVABILITY : ${error.message || error}`, true, error);
648
+ }
649
+ exports.pending_test_uploads.count = Math.max(0,exports.pending_test_uploads.count - data.length);
650
+ }
651
+ }
652
+
653
+ const RequestQueueHandler = require('./requestQueueHandler');
654
+ exports.requestQueueHandler = new RequestQueueHandler();
655
+
656
+ exports.uploadEventData = async (eventData, run=0) => {
657
+ const log_tag = {
658
+ ['TestRunStarted']: 'Test_Start_Upload',
659
+ ['TestRunFinished']: 'Test_End_Upload',
660
+ ['TestRunSkipped']: 'Test_Skipped_Upload',
661
+ ['LogCreated']: 'Log_Upload',
662
+ ['HookRunStarted']: 'Hook_Start_Upload',
663
+ ['HookRunFinished']: 'Hook_End_Upload',
664
+ ['CBTSessionCreated']: 'CBT_Upload',
665
+ ['BuildUpdate']: 'Build_Update'
666
+ }[eventData.event_type];
667
+
668
+ if(run === 0 && process.env.BS_TESTOPS_JWT != "null") exports.pending_test_uploads.count += 1;
669
+
670
+ if (process.env.BS_TESTOPS_BUILD_COMPLETED === "true") {
671
+ if(process.env.BS_TESTOPS_JWT == "null") {
672
+ exports.debug(`EXCEPTION IN ${log_tag} REQUEST TO TEST OBSERVABILITY : missing authentication token`);
673
+ exports.pending_test_uploads.count = Math.max(0,exports.pending_test_uploads.count-1);
674
+ return {
675
+ status: 'error',
676
+ message: 'Token/buildID is undefined, build creation might have failed'
677
+ };
678
+ } else {
679
+ let data = eventData, event_api_url = 'api/v1/event';
680
+
681
+ exports.requestQueueHandler.start();
682
+ const { shouldProceed, proceedWithData, proceedWithUrl } = exports.requestQueueHandler.add(eventData);
683
+ if(!shouldProceed) {
684
+ return;
685
+ } else if(proceedWithData) {
686
+ data = proceedWithData;
687
+ event_api_url = proceedWithUrl;
688
+ }
689
+
690
+ const config = {
691
+ headers: {
692
+ 'Authorization': `Bearer ${process.env.BS_TESTOPS_JWT}`,
693
+ 'Content-Type': 'application/json',
694
+ 'X-BSTACK-TESTOPS': 'true'
695
+ }
696
+ };
697
+
698
+ try {
699
+ const response = await nodeRequest('POST',event_api_url,data,config);
700
+ if(response.data.error) {
701
+ throw({message: response.data.error});
702
+ } else {
703
+ exports.debug(`${event_api_url !== exports.requestQueueHandler.eventUrl ? log_tag : 'Batch-Queue'}[${run}] event successfull!`)
704
+ exports.pending_test_uploads.count = Math.max(0,exports.pending_test_uploads.count - (event_api_url === 'api/v1/event' ? 1 : data.length));
705
+ return {
706
+ status: 'success',
707
+ message: ''
708
+ };
709
+ }
710
+ } catch(error) {
711
+ if (error.response) {
712
+ exports.debug(`EXCEPTION IN ${event_api_url !== exports.requestQueueHandler.eventUrl ? log_tag : 'Batch-Queue'} REQUEST TO TEST OBSERVABILITY : ${error.response.status} ${error.response.statusText} ${JSON.stringify(error.response.data)}`, true, error);
713
+ } else {
714
+ exports.debug(`EXCEPTION IN ${event_api_url !== exports.requestQueueHandler.eventUrl ? log_tag : 'Batch-Queue'} REQUEST TO TEST OBSERVABILITY : ${error.message || error}`, true, error);
715
+ }
716
+ exports.pending_test_uploads.count = Math.max(0,exports.pending_test_uploads.count - (event_api_url === 'api/v1/event' ? 1 : data.length));
717
+ return {
718
+ status: 'error',
719
+ message: error.message || (error.response ? `${error.response.status}:${error.response.statusText}` : error)
720
+ };
721
+ }
722
+ }
723
+ } else if (run >= 5) {
724
+ exports.debug(`EXCEPTION IN ${log_tag} REQUEST TO TEST OBSERVABILITY : Build Start is not completed and ${log_tag} retry runs exceeded`);
725
+ if(process.env.BS_TESTOPS_JWT != "null") exports.pending_test_uploads.count = Math.max(0,exports.pending_test_uploads.count-1);
726
+ return {
727
+ status: 'error',
728
+ message: 'Retry runs exceeded'
729
+ };
730
+ } else if(process.env.BS_TESTOPS_BUILD_COMPLETED !== "false") {
731
+ setTimeout(function(){ exports.uploadEventData(eventData, run+1) }, 1000);
732
+ }
733
+ }
734
+
735
+ exports.isTestObservabilitySupportedCypressVersion = (cypress_config_filename) => {
736
+ const extension = cypress_config_filename.split('.').pop();
737
+ return CYPRESS_V10_AND_ABOVE_CONFIG_FILE_EXTENSIONS.includes(extension);
738
+ }
739
+
740
+ exports.setTestObservabilityFlags = (bsConfig) => {
741
+ /* testObservability */
742
+ let isTestObservabilitySession = false;
743
+ try {
744
+ if(!utils.isUndefined(bsConfig["testObservability"])) isTestObservabilitySession = ( bsConfig["testObservability"] == true || bsConfig["testObservability"] == 1 );
745
+ if(!utils.isUndefined(process.env.BROWSERSTACK_TEST_OBSERVABILITY)) isTestObservabilitySession = ( process.env.BROWSERSTACK_TEST_OBSERVABILITY == "true" || process.env.BROWSERSTACK_TEST_OBSERVABILITY == "1" );
746
+ if(process.argv.includes('--disable-test-observability')) isTestObservabilitySession = false;
747
+ isTestObservabilitySession = isTestObservabilitySession && this.isTestObservabilitySupportedCypressVersion(bsConfig.run_settings.cypress_config_file);
748
+ } catch(e) {
749
+ isTestObservabilitySession = false;
750
+ exports.debug(`EXCEPTION while parsing testObservability capability with error ${e}`, true, e);
751
+ }
752
+
753
+
754
+ /* browserstackAutomation */
755
+ let isBrowserstackInfra = true;
756
+ try {
757
+ if(!utils.isUndefined(bsConfig["browserstackAutomation"])) isBrowserstackInfra = ( bsConfig["browserstackAutomation"] == true || bsConfig["browserstackAutomation"] == 1 );
758
+ if(!utils.isUndefined(process.env.BROWSERSTACK_AUTOMATION)) isBrowserstackInfra = ( process.env.BROWSERSTACK_AUTOMATION == "true" || process.env.BROWSERSTACK_AUTOMATION == "1" );
759
+ if(process.argv.includes('--disable-browserstack-automation')) isBrowserstackInfra = false;
760
+ } catch(e) {
761
+ isBrowserstackInfra = true;
762
+ exports.debug(`EXCEPTION while parsing browserstackAutomation capability with error ${e}`, true, e);
763
+ }
764
+
765
+
766
+ process.env.BROWSERSTACK_TEST_OBSERVABILITY = isTestObservabilitySession;
767
+ process.env.BROWSERSTACK_AUTOMATION = isBrowserstackInfra;
768
+
769
+ return [isTestObservabilitySession, isBrowserstackInfra];
770
+ }
771
+
772
+ exports.isTestObservabilitySession = () => {
773
+ return ( process.env.BROWSERSTACK_TEST_OBSERVABILITY == "true" );
774
+ }
775
+
776
+ exports.isBrowserstackInfra = () => {
777
+ return ( process.env.BROWSERSTACK_AUTOMATION == "true" );
778
+ }
779
+
780
+ exports.shouldReRunObservabilityTests = () => {
781
+ return (process.env.BROWSERSTACK_RERUN_TESTS && process.env.BROWSERSTACK_RERUN_TESTS !== "null") ? true : false
782
+ }
783
+
784
+ exports.stopBuildUpstream = async () => {
785
+ if (process.env.BS_TESTOPS_BUILD_COMPLETED === "true") {
786
+ if(process.env.BS_TESTOPS_JWT == "null" || process.env.BS_TESTOPS_BUILD_HASHED_ID == "null") {
787
+ exports.debug('EXCEPTION IN stopBuildUpstream REQUEST TO TEST OBSERVABILITY : Missing authentication token');
788
+ return {
789
+ status: 'error',
790
+ message: 'Token/buildID is undefined, build creation might have failed'
791
+ };
792
+ } else {
793
+ const data = {
794
+ 'stop_time': (new Date()).toISOString()
795
+ };
796
+ const config = {
797
+ headers: {
798
+ 'Authorization': `Bearer ${process.env.BS_TESTOPS_JWT}`,
799
+ 'Content-Type': 'application/json',
800
+ 'X-BSTACK-TESTOPS': 'true'
801
+ }
802
+ };
803
+
804
+ try {
805
+ const response = await nodeRequest('PUT',`api/v1/builds/${process.env.BS_TESTOPS_BUILD_HASHED_ID}/stop`,data,config);
806
+ if(response.data && response.data.error) {
807
+ throw({message: response.data.error});
808
+ } else {
809
+ exports.debug(`stopBuildUpstream event successfull!`)
810
+ return {
811
+ status: 'success',
812
+ message: ''
813
+ };
814
+ }
815
+ } catch(error) {
816
+ if (error.response) {
817
+ exports.debug(`EXCEPTION IN stopBuildUpstream REQUEST TO TEST OBSERVABILITY : ${error.response.status} ${error.response.statusText} ${JSON.stringify(error.response.data)}`, true, error);
818
+ } else {
819
+ exports.debug(`EXCEPTION IN stopBuildUpstream REQUEST TO TEST OBSERVABILITY : ${error.message || error}`, true, error);
820
+ }
821
+ return {
822
+ status: 'error',
823
+ message: error.message || error.response ? `${error.response.status}:${error.response.statusText}` : error
824
+ };
825
+ }
826
+ }
827
+ }
828
+ }
829
+
830
+ exports.getHookSkippedTests = (suite) => {
831
+ const subSuitesSkippedTests = suite.suites.reduce((acc, subSuite) => {
832
+ const subSuiteSkippedTests = exports.getHookSkippedTests(subSuite);
833
+ if (subSuiteSkippedTests) {
834
+ acc = acc.concat(subSuiteSkippedTests);
835
+ }
836
+ return acc;
837
+ }, []);
838
+ const tests = suite.tests.filter(test => {
839
+ const isSkippedTest = test.type != 'hook' &&
840
+ !test.markedStatus &&
841
+ test.state != 'passed' &&
842
+ test.state != 'failed' &&
843
+ !test.pending
844
+ return isSkippedTest;
845
+ });
846
+ return tests.concat(subSuitesSkippedTests);
847
+ }
848
+
849
+ const getPlatformName = () => {
850
+ if (process.platform === 'win32') return 'Windows'
851
+ if (process.platform === 'darwin') return 'OS X'
852
+ if (process.platform === "linux") return 'Linux'
853
+ return 'Unknown'
854
+ }
855
+
856
+ const getMacOSVersion = () => {
857
+ return execSync("awk '/SOFTWARE LICENSE AGREEMENT FOR macOS/' '/System/Library/CoreServices/Setup Assistant.app/Contents/Resources/en.lproj/OSXSoftwareLicense.rtf' | awk -F 'macOS ' '{print $NF}' | awk '{print substr($0, 0, length($0)-1)}'").toString().trim()
858
+ }
859
+
860
+ exports.getOSDetailsFromSystem = async (product) => {
861
+ let platformName = getPlatformName();
862
+ let platformVersion = os.release().toString();
863
+
864
+ switch (platformName) {
865
+ case 'OS X':
866
+ platformVersion = getMacOSVersion();
867
+ break;
868
+ case 'Windows':
869
+ try {
870
+ const windowsRelease = (await import('windows-release')).default;
871
+ platformVersion = windowsRelease();
872
+ } catch (e) {
873
+ }
874
+ break
875
+ case 'Linux':
876
+ try {
877
+ const details = await getLinuxDetails();
878
+ if (details.dist) platformName = details.dist;
879
+ if (details.release) platformVersion = details.release.toString();
880
+ } catch (e) {
881
+ }
882
+ break;
883
+ default:
884
+ break;
885
+ }
886
+
887
+ return {
888
+ os: product == 'automate' && platformName == 'Linux' ? 'OS X' : platformName,
889
+ os_version: platformVersion
890
+ };
891
+ }
892
+
893
+ exports.requireModule = (module, internal = false) => {
894
+ logger.debug(`Getting ${module} from ${process.cwd()}`);
895
+ let local_path = "";
896
+ if(process.env["browserStackCwd"]){
897
+ local_path = path.join(process.env["browserStackCwd"], 'node_modules', module);
898
+ } else if(internal) {
899
+ local_path = path.join(process.cwd(), 'node_modules', 'browserstack-cypress-cli', 'node_modules', module);
900
+ } else {
901
+ local_path = path.join(process.cwd(), 'node_modules', module);
902
+ }
903
+ if(!fs.existsSync(local_path)) {
904
+ logger.debug(`${module} doesn\'t exist at ${process.cwd()}`);
905
+ logger.debug(`Getting ${module} from ${GLOBAL_MODULE_PATH}`);
906
+
907
+ let global_path;
908
+ if(['jest-runner', 'jest-runtime'].includes(module))
909
+ global_path = path.join(GLOBAL_MODULE_PATH, 'jest', 'node_modules', module);
910
+ else
911
+ global_path = path.join(GLOBAL_MODULE_PATH, module);
912
+ if(!fs.existsSync(global_path)) {
913
+ throw new Error(`${module} doesn't exist.`);
914
+ }
915
+ return require(global_path);
916
+ }
917
+ return require(local_path);
918
+ }
919
+
920
+ const getReRunSpecs = (rawArgs) => {
921
+ if (this.isTestObservabilitySession() && this.shouldReRunObservabilityTests()) {
922
+ let startIdx = -1, numEle = 0;
923
+ for(let idx=0; idx<rawArgs.length; idx++) {
924
+ if(rawArgs[idx] == '--spec') {
925
+ startIdx = idx;
926
+ } else if(rawArgs[idx].includes('--') && startIdx != -1) {
927
+ break;
928
+ } else if(startIdx != -1) {
929
+ numEle++;
930
+ }
931
+ }
932
+ if(startIdx != -1) rawArgs.splice(startIdx, numEle + 1);
933
+ return [...rawArgs, '--spec', process.env.BROWSERSTACK_RERUN_TESTS];
934
+ } else {
935
+ return rawArgs;
936
+ }
937
+ }
938
+
939
+ const getLocalSessionReporter = () => {
940
+ if(this.isTestObservabilitySession() && process.env.BS_TESTOPS_JWT) {
941
+ return ['--reporter', TEST_OBSERVABILITY_REPORTER];
942
+ } else {
943
+ return [];
944
+ }
945
+ }
946
+
947
+ const cleanupTestObservabilityFlags = (rawArgs) => {
948
+ const newRawArgs = [];
949
+ for(let idx=0; idx<rawArgs.length; idx++) {
950
+ if(!['--disable-browserstack-automation', '--disable-test-observability'].includes(rawArgs[idx])) {
951
+ newRawArgs.push(rawArgs[idx]);
952
+ }
953
+ }
954
+ return newRawArgs;
955
+ }
956
+
957
+ exports.runCypressTestsLocally = (bsConfig, args, rawArgs) => {
958
+ try {
959
+ rawArgs = cleanupTestObservabilityFlags(rawArgs);
960
+ logger.info(`Running npx cypress run ${getReRunSpecs(rawArgs.slice(1)).join(' ')} ${getLocalSessionReporter().join(' ')}`);
961
+ const cypressProcess = spawn(
962
+ 'npx',
963
+ ['cypress', 'run', ...getReRunSpecs(rawArgs.slice(1)), ...getLocalSessionReporter()],
964
+ { stdio: 'inherit', cwd: process.cwd(), env: process.env }
965
+ );
966
+ cypressProcess.on('close', async (code) => {
967
+ logger.info(`Cypress process exited with code ${code}`);
968
+ await this.printBuildLink(true);
969
+ });
970
+
971
+ cypressProcess.on('error', (err) => {
972
+ logger.info(`Cypress process encountered an error ${err}`);
973
+ });
974
+ } catch(e) {
975
+ exports.debug(`Encountered an error when trying to spawn a Cypress test locally ${e}`, true, e);
976
+ }
977
+ }
978
+
979
+ class PathHelper {
980
+ constructor(config, prefix) {
981
+ this.config = config
982
+ this.prefix = prefix
983
+ }
984
+
985
+ relativeTestFilePath(testFilePath) {
986
+ // Based upon https://github.com/facebook/jest/blob/49393d01cdda7dfe75718aa1a6586210fa197c72/packages/jest-reporters/src/relativePath.ts#L11
987
+ const dir = this.config.cwd || this.config.rootDir
988
+ return path.relative(dir, testFilePath)
989
+ }
990
+
991
+ prefixTestPath(testFilePath) {
992
+ const relativePath = this.relativeTestFilePath(testFilePath)
993
+ return this.prefix ? path.join(this.prefix, relativePath) : relativePath
994
+ }
995
+ }
996
+ exports.PathHelper = PathHelper;