browserstack-cypress-cli 1.8.1 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bin/commands/generateDownloads.js +39 -0
  2. package/bin/commands/generateReport.js +5 -4
  3. package/bin/commands/info.js +4 -3
  4. package/bin/commands/init.js +6 -6
  5. package/bin/commands/runs.js +227 -64
  6. package/bin/commands/stop.js +5 -65
  7. package/bin/helpers/archiver.js +5 -20
  8. package/bin/helpers/buildArtifacts.js +250 -0
  9. package/bin/helpers/capabilityHelper.js +15 -22
  10. package/bin/helpers/checkUploaded.js +153 -0
  11. package/bin/helpers/config.js +3 -0
  12. package/bin/helpers/constants.js +109 -13
  13. package/bin/helpers/fileHelpers.js +14 -0
  14. package/bin/helpers/hashUtil.js +70 -0
  15. package/bin/helpers/packageInstaller.js +134 -0
  16. package/bin/helpers/reporterHTML.js +169 -11
  17. package/bin/helpers/sync/syncSpecsLogs.js +37 -9
  18. package/bin/helpers/timeComponents.js +71 -0
  19. package/bin/helpers/usageReporting.js +35 -6
  20. package/bin/helpers/utils.js +420 -12
  21. package/bin/helpers/zipUpload.js +106 -27
  22. package/bin/runner.js +119 -118
  23. package/package.json +4 -1
  24. package/test/test_files/dummy_bstack.json +0 -0
  25. package/test/test_files/dummy_bstack_2.json +0 -1
  26. package/test/test_files/dummy_bstack_3.json +0 -3
  27. package/test/unit/bin/commands/generateReport.js +0 -112
  28. package/test/unit/bin/commands/info.js +0 -374
  29. package/test/unit/bin/commands/init.js +0 -187
  30. package/test/unit/bin/commands/runs.js +0 -700
  31. package/test/unit/bin/commands/stop.js +0 -388
  32. package/test/unit/bin/helpers/archiver.js +0 -57
  33. package/test/unit/bin/helpers/build.js +0 -210
  34. package/test/unit/bin/helpers/capabilityHelper.js +0 -1049
  35. package/test/unit/bin/helpers/fileHelpers.js +0 -102
  36. package/test/unit/bin/helpers/reporterHTML.js +0 -272
  37. package/test/unit/bin/helpers/sync/failedSpecDetails.js +0 -76
  38. package/test/unit/bin/helpers/sync/specSummary.js +0 -55
  39. package/test/unit/bin/helpers/sync/syncSpecsLogs.js +0 -403
  40. package/test/unit/bin/helpers/usageReporting.js +0 -411
  41. package/test/unit/bin/helpers/utils.js +0 -1770
  42. package/test/unit/bin/helpers/zipUpload.js +0 -205
  43. package/test/unit/support/fixtures/testObjects.js +0 -149
@@ -5,7 +5,9 @@ const syncCLI = {
5
5
  LOGS: {
6
6
  INIT_LOG: "All tests:"
7
7
  },
8
- INITIAL_DELAY_MULTIPLIER: 10
8
+ INITIAL_DELAY_MULTIPLIER: 10,
9
+ DEFAULT_LINE_SEP: "\n--------------------------------------------------------------------------------",
10
+ STARTUP_MESSAGE: "BrowserStack machines are now setting up Cypress with the specified npm dependencies for running your tests. It might take some time before your tests start runnning and showing up below..."
9
11
  };
10
12
 
11
13
  const userMessages = {
@@ -17,13 +19,20 @@ const userMessages = {
17
19
  BUILD_REPORT_MESSAGE: "See the entire build report here:",
18
20
  ZIP_UPLOADER_NOT_REACHABLE: "Could not reach BrowserStack APIs. Please check your network or see if you need to whitelist *.browserstack.com",
19
21
  ZIP_UPLOAD_FAILED: "Zip Upload failed.",
22
+ ZIP_UPLOAD_LIMIT_EXCEEDED: "The directory size which contains the cypress config file is more than 200 MB. For more info, check out https://www.browserstack.com/docs/automate/cypress/exclude-files",
20
23
  CONFIG_FILE_CREATED: "BrowserStack Config File created, you can now run browserstack-cypress --config-file run",
21
24
  CONFIG_FILE_EXISTS: "File already exists, delete the browserstack.json file manually. skipping...",
22
25
  DIR_NOT_FOUND: "Given path does not exist. Failed to create browserstack.json in %s",
26
+ MD5_CHECK_FAILED: "There was some issue while checking if zip is already uploaded.",
23
27
  ZIP_DELETE_FAILED: "Could not delete tests.zip successfully.",
24
28
  ZIP_DELETED: "Deleted tests.zip successfully.",
29
+ NPM_INSTALL_AND_UPLOAD: "Installing required dependencies and building the package to upload to BrowserStack",
30
+ NPM_DELETE_FAILED: "Could not delete the dependency packages.",
31
+ NPM_DELETED: "Deleted dependency packages successfully.",
25
32
  API_DEPRECATED: "This version of API is deprecated, please use latest version of API.",
26
33
  FAILED_TO_ZIP: "Failed to zip files.",
34
+ FAILED_CREATE_NPM_ARCHIVE: "CLI execution failed due to some issue in npm setup. Please retry.",
35
+ FAILED_MD5_CHECK: "Something went wrong - you can retry running browserstack-cypress with ‘--force-upload’ parameter, or contact BrowserStack Support.",
27
36
  VISIT_DASHBOARD: "Visit the Automate dashboard for real-time test reporting:",
28
37
  CONFLICTING_INIT_ARGUMENTS: "Conflicting arguments given. You can use --path only with a file name, and not with a file path.",
29
38
  NO_PARALLELS: "Your specs will run sequentially on a single machine. Read more about running your specs in parallel here: https://www.browserstack.com/docs/automate/cypress/run-tests-in-parallel",
@@ -31,16 +40,27 @@ const userMessages = {
31
40
  NO_NPM_DEPENDENCIES_READ_MORE: "Read more about npm dependencies here: https://www.browserstack.com/docs/automate/cypress/npm-packages. You can suppress this warning by using --disable-npm-warning flag.",
32
41
  VALIDATING_CONFIG: "Validating the config",
33
42
  UPLOADING_TESTS: "Uploading the tests to BrowserStack",
43
+ UPLOADING_TESTS_SUCCESS: "Uploaded tests successfully",
44
+ UPLOADING_NPM_PACKAGES: "Uploading required node_modules to BrowserStack",
45
+ UPLOADING_NPM_PACKAGES_SUCCESS: "Uploaded node_modules successfully",
46
+ SKIP_UPLOADING_TESTS: "Skipping zip upload since BrowserStack already has your test suite that has not changed since the last run.",
47
+ SKIP_UPLOADING_NPM_PACKAGES: "Skipping the upload of node_modules since BrowserStack has already cached your npm dependencies that have not changed since the last run.",
34
48
  LOCAL_TRUE: "you will now be able to test localhost / private URLs",
35
49
  LOCAL_FALSE: "you won't be able to test localhost / private URLs",
36
50
  EXIT_SYNC_CLI_MESSAGE: "Exiting the CLI, but your build is still running. You can use the --sync option to keep getting test updates. You can also use the build-info <build-id> command now.",
37
51
  FATAL_NETWORK_ERROR: `fatal: unable to access '${config.buildUrl}': Could not resolve host: ${config.rails_host}`,
38
52
  RETRY_LIMIT_EXCEEDED: `Max retries exceeded trying to connect to the host (retries: ${config.retries})`,
39
53
  CHECK_DASHBOARD_AT: "Please check the build status at: ",
40
- CYPRESS_VERSION_CHANGED: "Your build will run using Cypress <actualVersion> instead of Cypress <preferredVersion>. Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
54
+ CYPRESS_VERSION_CHANGED: "Your build will run using Cypress <actualVersion> instead of Cypress <preferredVersion>.<frameworkUpgradeMessage> Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
41
55
  LOCAL_START_FAILED: "Local Testing setup failed.",
42
56
  LOCAL_STOP_FAILED: "Local Binary stop failed.",
43
- INVALID_LOCAL_MODE_WARNING: "Invalid value specified for local_mode. local_mode: (\"always-on\" | \"on-demand\"). For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference"
57
+ INVALID_LOCAL_MODE_WARNING: "Invalid value specified for local_mode. local_mode: (\"always-on\" | \"on-demand\"). For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
58
+ SPEC_LIMIT_WARNING: "You might not see all your results on the dashboard because of high spec count, please consider reducing the number of spec files in this folder.",
59
+ DOWNLOAD_BUILD_ARTIFACTS_FAILED: "Downloading build artifacts for the build <build-id> failed for <machine-count> machines.",
60
+ ASYNC_DOWNLOADS: "Test artifacts as specified under 'downloads' can be downloaded after the build has completed its run, using 'browserstack-cypress generate-downloads <build-id>'",
61
+ DOWNLOAD_BUILD_ARTIFACTS_SUCCESS: "Your build artifact(s) have been successfully downloaded in '<user-path>/build_artifacts/<build-id>' directory",
62
+ LATEST_SYNTAX_TO_ACTUAL_VERSION_MESSAGE: "Your build will run using Cypress <actualVersion> as you had specified <latestSyntaxVersion>.<frameworkUpgradeMessage> Read more about supported versions here: http://browserstack.com/docs/automate/cypress/supported-versions",
63
+ PROCESS_KILL_MESSAGE: "Stopping the CLI and the execution of the build on BrowserStack",
44
64
  };
45
65
 
46
66
  const validationMessages = {
@@ -64,7 +84,9 @@ const validationMessages = {
64
84
  INVALID_CLI_LOCAL_IDENTIFIER: "When using --local-identifier, a value needs to be supplied. \n--local-identifier <String>.\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
65
85
  INVALID_LOCAL_MODE: "When using --local-mode, a value needs to be supplied. \n--local-mode (\"always-on\" | \"on-demand\").\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
66
86
  INVALID_LOCAL_CONFIG_FILE: "Using --local-config-file requires an input of the form /path/to/config-file.yml.\nFor more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
67
- INVALID_LOCAL_IDENTIFIER: "Invalid value specified for local_identifier. For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference"
87
+ INVALID_LOCAL_IDENTIFIER: "Invalid value specified for local_identifier. For more info, check out https://www.browserstack.com/docs/automate/cypress/cli-reference",
88
+ INVALID_BROWSER_ARGS: "Aborting as an unacceptable value was passed for --browser. Read more at https://www.browserstack.com/docs/automate/cypress/cli-reference",
89
+ INVALID_LOCAL_ASYNC_ARGS: "Cannot run in --async mode when local is set to true. Please run the build after removing --async",
68
90
  };
69
91
 
70
92
  const cliMessages = {
@@ -81,17 +103,13 @@ const cliMessages = {
81
103
  INFO: "Check status of your build.",
82
104
  STOP: "Stop your build.",
83
105
  DEMAND: "Requires a build id.",
84
- DESC: "Path to BrowserStack config",
85
- CONFIG_DEMAND: "config file is required",
86
106
  INFO_MESSAGE: "Getting information for buildId ",
87
107
  STOP_MESSAGE: "Stopping build with given buildId ",
88
108
  },
89
109
  RUN: {
90
110
  PARALLEL_DESC: "The maximum number of parallels to use to run your test suite",
91
- INFO: "Run your tests on BrowserStack.",
92
- DESC: "Path to BrowserStack config",
111
+ INFO: "Run your tests on BrowserStack. For more help: `browserstack-cypress run --help`.",
93
112
  CYPRESS_DESC: "Path to Cypress config file",
94
- CONFIG_DEMAND: "config file is required",
95
113
  CYPRESS_CONFIG_DEMAND: "Cypress config file is required",
96
114
  BUILD_NAME: "The build name you want to use to name your test runs",
97
115
  EXCLUDE: "Exclude files matching a pattern from zipping and uploading",
@@ -99,22 +117,34 @@ const cliMessages = {
99
117
  SPECS_DESCRIPTION: "Specify the spec files to run",
100
118
  ENV_DESCRIPTION: "Specify the environment variables for your spec files",
101
119
  SYNC_DESCRIPTION: "Makes the run command in sync",
120
+ ASYNC_DESCRIPTION: "Makes the run command in async",
102
121
  BUILD_REPORT_MESSAGE: "See the entire build report here",
103
122
  HEADED: "Run your tests in a headed browser instead of a headless browser",
104
123
  LOCAL: "Accepted values: (true | false) - create a local testing connection to let you test staging and localhost websites, or sites behind proxies; learn more at browserstack.com/local-testing",
105
124
  LOCAL_MODE: 'Accepted values: ("always-on" | "on-demand") - if you choose to keep the binary "always-on", it will speed up your tests by keeping the Local connection warmed up in the background; otherwise, you can choose to have it spawn and killed for every build',
106
125
  LOCAL_IDENTIFIER: "Accepted values: String - assign an identifier to your Local process instance",
107
- LOCAL_CONFIG_FILE: "Accepted values: String - path to local config-file to your Local process instance. Learn more at https://www.browserstack.com/local-testing/binary-params"
126
+ LOCAL_CONFIG_FILE: "Accepted values: String - path to local config-file to your Local process instance. Learn more at https://www.browserstack.com/local-testing/binary-params",
127
+ SYNC_NO_WRAP: "Wrap the spec names in --sync mode in case of smaller terminal window size pass --no-wrap",
128
+ BROWSER_DESCRIPTION: "Specify the browsers you need to run your tests on.",
129
+ CONFIG_DESCRIPTION: "Set configuration values. Separate multiple values with a comma. The values set here override any values set in your configuration file.",
130
+ REPORTER: "Specify the custom reporter to use",
131
+ REPORTER_OPTIONS: "Specify reporter options for custom reporter",
108
132
  },
109
133
  COMMON: {
110
134
  DISABLE_USAGE_REPORTING: "Disable usage reporting",
135
+ FORCE_UPLOAD: "Force the upload of your test files even if BrowserStack has detected no changes in your suite since you last ran",
111
136
  USERNAME: "Your BrowserStack username",
112
137
  ACCESS_KEY: "Your BrowserStack access key",
113
138
  NO_NPM_WARNING: "No NPM warning if npm_dependencies is empty",
139
+ CONFIG_DEMAND: "config file is required",
140
+ CONFIG_FILE_PATH: "Path to BrowserStack config",
114
141
  },
115
142
  GENERATE_REPORT: {
116
143
  INFO: "Generates the build report"
117
144
  },
145
+ GENERATE_DOWNLOADS: {
146
+ INFO: "Downloads the build artifacts"
147
+ },
118
148
  };
119
149
 
120
150
  const messageTypes = {
@@ -126,14 +156,70 @@ const messageTypes = {
126
156
  NULL: null
127
157
  }
128
158
 
129
- const allowedFileTypes = ['js', 'json', 'txt', 'ts', 'feature', 'features', 'pdf', 'jpg', 'jpeg', 'png', 'zip', 'npmrc', 'xml', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'jsx', 'coffee', 'cjsx', 'csv', 'tsv'];
159
+ const allowedFileTypes = ['js', 'json', 'txt', 'ts', 'feature', 'features', 'pdf', 'jpg', 'jpeg', 'png', 'zip', 'npmrc', 'xml', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'jsx', 'coffee', 'cjsx', 'csv', 'tsv', 'yml', 'yaml', 'env', 'mov', 'mp4', 'mp3', 'wav'];
160
+
161
+ const filesToIgnoreWhileUploading = [
162
+ '**/node_modules/**',
163
+ 'node_modules/**',
164
+ 'package-lock.json',
165
+ 'package.json',
166
+ 'browserstack-package.json',
167
+ 'tests.zip',
168
+ 'cypress.json',
169
+ '.idea/**',
170
+ '.vscode/**',
171
+ '.npm/**',
172
+ 'bstackPackages.tar.gz',
173
+ 'tmpBstackPackages/**',
174
+ '.yarn/**',
175
+ 'build_artifacts/**'
176
+ ];
177
+
178
+ const readDirOptions = {
179
+ cwd: '.',
180
+ matchBase: true,
181
+ ignore: [],
182
+ dot: true,
183
+ stat: true,
184
+ pattern: ''
185
+ }
186
+
187
+ const hashingOptions = {
188
+ parallel: 10,
189
+ algo: 'md5',
190
+ encoding: 'hex',
191
+ };
130
192
 
131
- const filesToIgnoreWhileUploading = ['**/node_modules/**', 'node_modules/**', 'package-lock.json', 'package.json', 'browserstack-package.json', 'tests.zip', 'cypress.json']
193
+ const packageInstallerOptions = {
194
+ npmLoad: {
195
+ loglevel: 'silent',
196
+ only: 'dev',
197
+ 'save-dev': true,
198
+ 'only-dev': true,
199
+ }
200
+ }
132
201
 
133
202
  const specFileTypes = ['js', 'ts', 'feature', 'jsx', 'coffee', 'cjsx'];
134
203
 
135
204
  const DEFAULT_CYPRESS_SPEC_PATH = "cypress/integration"
136
205
 
206
+ const SPEC_TOTAL_CHAR_LIMIT = 32243;
207
+ const METADATA_CHAR_BUFFER_PER_SPEC = 175;
208
+
209
+ const usageReportingConstants = {
210
+ GENERATE_DOWNLOADS: 'generate-downloads called',
211
+ }
212
+
213
+ const LATEST_VERSION_SYNTAX_REGEX = /\d*.latest(.\d*)?/gm
214
+
215
+ const AUTH_REGEX = /"auth" *: *{[\s\S]*?}/g
216
+
217
+ const ERROR_EXIT_CODE = 1;
218
+
219
+ const REDACTED = "[REDACTED]";
220
+
221
+ const REDACTED_AUTH =`auth: { "username": ${REDACTED}, "access_key": ${REDACTED} }`;
222
+
137
223
  module.exports = Object.freeze({
138
224
  syncCLI,
139
225
  userMessages,
@@ -142,6 +228,16 @@ module.exports = Object.freeze({
142
228
  messageTypes,
143
229
  allowedFileTypes,
144
230
  filesToIgnoreWhileUploading,
231
+ readDirOptions,
232
+ hashingOptions,
233
+ packageInstallerOptions,
145
234
  specFileTypes,
146
- DEFAULT_CYPRESS_SPEC_PATH
235
+ DEFAULT_CYPRESS_SPEC_PATH,
236
+ SPEC_TOTAL_CHAR_LIMIT,
237
+ METADATA_CHAR_BUFFER_PER_SPEC,
238
+ usageReportingConstants,
239
+ LATEST_VERSION_SYNTAX_REGEX,
240
+ ERROR_EXIT_CODE,
241
+ AUTH_REGEX,
242
+ REDACTED_AUTH
147
243
  });
@@ -4,6 +4,7 @@ const fs = require('fs-extra'),
4
4
 
5
5
  const logger = require('./logger').winstonLogger,
6
6
  Constants = require('../helpers/constants'),
7
+ process = require('process'),
7
8
  config = require('../helpers/config');
8
9
 
9
10
  exports.write = function (f, message, args, cb) {
@@ -35,6 +36,19 @@ exports.deleteZip = () => {
35
36
  }
36
37
  };
37
38
 
39
+ exports.deletePackageArchieve = (logging = true) => {
40
+ try {
41
+ delete process.env.CYPRESS_INSTALL_BINARY;
42
+ fs.removeSync(config.packageFileName);
43
+ fs.removeSync(config.packageDirName);
44
+ if (logging) logger.info(Constants.userMessages.NPM_DELETED);
45
+ return 0;
46
+ } catch (err) {
47
+ if (logging) logger.info(Constants.userMessages.NPM_DELETE_FAILED);
48
+ return 1;
49
+ }
50
+ };
51
+
38
52
  exports.dirExists = function (filePath, cb) {
39
53
  let exists = false;
40
54
  if (fs.existsSync(path.dirname(filePath), cb)) {
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+ const glob = require('readdir-glob'),
3
+ Constants = require('./constants'),
4
+ crypto = require('crypto'),
5
+ fs = require('fs');
6
+
7
+ const hashWrapper = (options, instrumentBlocks) => {
8
+ instrumentBlocks.markBlockStart("checkAlreadyUploaded.md5Stats");
9
+ return folderStats(options).then((files) => {
10
+ instrumentBlocks.markBlockEnd("checkAlreadyUploaded.md5Stats");
11
+ instrumentBlocks.markBlockStart("checkAlreadyUploaded.md5Batch");
12
+ return batchHashFile(files);
13
+ }).then((hashes) => {
14
+ const combinedHash = crypto.createHash(Constants.hashingOptions.algo);
15
+ hashes.forEach((hash) => combinedHash.update(hash));
16
+ instrumentBlocks.markBlockEnd("checkAlreadyUploaded.md5Batch");
17
+ return combinedHash.digest(Constants.hashingOptions.encoding);
18
+ });
19
+ }
20
+
21
+ const folderStats = (options) => {
22
+ return new Promise((resolve, reject) => {
23
+ let readDirOptions = {};
24
+ Object.assign(readDirOptions, Constants.readDirOptions, options)
25
+ let globber = glob(readDirOptions.cwd || '.', readDirOptions);
26
+ let files = [];
27
+ globber.on('match', (fileMatch) => {
28
+ files.push({relativePath: fileMatch.relative, absolutePath: fileMatch.absolute, stats: fileMatch.stat})
29
+ });
30
+ globber.on('error', (_err) => {
31
+ reject("Error in getting files.");
32
+ });
33
+ globber.on('end', (_) => {
34
+ resolve(files);
35
+ });
36
+ });
37
+ }
38
+
39
+ const batchHashFile = (fileBatch) => {
40
+ return Promise.resolve(fileBatch).then((files) => {
41
+ files = Array(Math.ceil(files.length / Constants.hashingOptions.parallel)).fill([]).map((_, index) => index * Constants.hashingOptions.parallel).map(begin => files.slice(begin, begin + Constants.hashingOptions.parallel));
42
+ files = files.map((batch) => {
43
+ return (res) => Promise.all(batch.map(hashFile)).then((data) => res.concat(data));
44
+ });
45
+ let hash = files.reduce((acc, curr) => acc.then(curr), Promise.resolve([]));
46
+ return hash;
47
+ });
48
+ };
49
+
50
+ const hashFile = (file) => {
51
+ return new Promise((resolve) => {
52
+ let { relativePath, absolutePath, stats } = file;
53
+ const hash = crypto.createHash(Constants.hashingOptions.algo);
54
+ hash.update(relativePath);
55
+ if (stats.isFile()) {
56
+ const f = fs.createReadStream(absolutePath);
57
+ f.on('end', () => {
58
+ const hashedValue = hash.digest(Constants.hashingOptions.encoding);
59
+ return resolve(hashedValue);
60
+ });
61
+ f.pipe(hash, { end: false });
62
+ } else {
63
+ // paths like empty directories.
64
+ const hashedValue = hash.digest(Constants.hashingOptions.encoding);
65
+ return resolve(hashedValue);
66
+ }
67
+ });
68
+ };
69
+
70
+ exports.hashWrapper = hashWrapper;
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+ const archiver = require("archiver"),
3
+ path = require('path'),
4
+ fs = require('fs-extra'),
5
+ fileHelpers = require('./fileHelpers'),
6
+ logger = require("./logger").winstonLogger,
7
+ Constants = require('./constants'),
8
+ process = require('process'),
9
+ utils = require('./utils'),
10
+ { spawn } = require('child_process');
11
+
12
+ let nodeProcess;
13
+
14
+ const setupPackageFolder = (runSettings, directoryPath) => {
15
+ return new Promise(function (resolve, reject) {
16
+ fileHelpers.deletePackageArchieve(false);
17
+ fs.mkdir(directoryPath, function (err) {
18
+ try {
19
+ if (err) {
20
+ return reject(err);
21
+ }
22
+ let packageJSON = {};
23
+ if (typeof runSettings.package_config_options === 'object') {
24
+ Object.assign(packageJSON, runSettings.package_config_options);
25
+ }
26
+
27
+ if (typeof runSettings.npm_dependencies === 'object') {
28
+ Object.assign(packageJSON, {
29
+ devDependencies: runSettings.npm_dependencies,
30
+ });
31
+ }
32
+
33
+ if (Object.keys(packageJSON).length > 0) {
34
+ let packageJSONString = JSON.stringify(packageJSON);
35
+ let packagePath = path.join(directoryPath, "package.json");
36
+ fs.writeFileSync(packagePath, packageJSONString);
37
+ let cypressFolderPath = path.dirname(runSettings.cypressConfigFilePath);
38
+ let sourceNpmrc = path.join(cypressFolderPath, ".npmrc");
39
+ let destNpmrc = path.join(directoryPath, ".npmrc");
40
+ if (fs.existsSync(sourceNpmrc)) {
41
+ fs.copyFileSync(sourceNpmrc, destNpmrc);
42
+ }
43
+ return resolve("Package file created");
44
+ }
45
+ return reject("Nothing in package file");
46
+ } catch(error) {
47
+ return reject(error);
48
+ }
49
+ })
50
+ })
51
+ };
52
+
53
+ const packageInstall = (packageDir) => {
54
+ return new Promise(function (resolve, reject) {
55
+ const nodeProcessCloseCallback = (code) => {
56
+ if(code == 0) {
57
+ resolve('Packages were installed successfully.');
58
+ } else {
59
+ reject('Packages were not installed successfully.');
60
+ }
61
+ };
62
+ const nodeProcessErrorCallback = (error) => {
63
+ logger.error(`Some error occurred while installing packages: ${error}`);
64
+ reject(`Packages were not installed successfully.`);
65
+ };
66
+ nodeProcess = spawn('npm', ['install'], {cwd: packageDir});
67
+ nodeProcess.on('close', nodeProcessCloseCallback);
68
+ nodeProcess.on('error', nodeProcessErrorCallback);
69
+ });
70
+ };
71
+
72
+ const packageArchiver = (packageDir, packageFile) => {
73
+ return new Promise(function (resolve, reject) {
74
+ let output = fs.createWriteStream(packageFile);
75
+ let archive = archiver('tar', {
76
+ gzip: true
77
+ });
78
+ archive.on('warning', function (err) {
79
+ if (err.code === 'ENOENT') {
80
+ logger.info(err);
81
+ } else {
82
+ reject(err);
83
+ }
84
+ });
85
+
86
+ output.on('close', function () {
87
+ resolve('Zipping completed');
88
+ });
89
+
90
+ output.on('end', function () {
91
+ logger.info('Data has been drained');
92
+ });
93
+
94
+ archive.on('error', function (err) {
95
+ reject(err);
96
+ });
97
+
98
+ archive.pipe(output);
99
+ archive.directory(packageDir, false);
100
+ archive.finalize();
101
+ })
102
+ }
103
+
104
+ const packageWrapper = (bsConfig, packageDir, packageFile, md5data, instrumentBlocks) => {
105
+ return new Promise(function (resolve) {
106
+ let obj = {
107
+ packageArchieveCreated: false
108
+ };
109
+ if (md5data.packageUrlPresent || !utils.isTrueString(bsConfig.run_settings.cache_dependencies)) {
110
+ return resolve(obj);
111
+ }
112
+ logger.info(Constants.userMessages.NPM_INSTALL_AND_UPLOAD);
113
+ instrumentBlocks.markBlockStart("packageInstaller.folderSetup");
114
+ return setupPackageFolder(bsConfig.run_settings, packageDir).then((_result) => {
115
+ process.env.CYPRESS_INSTALL_BINARY = 0
116
+ instrumentBlocks.markBlockEnd("packageInstaller.folderSetup");
117
+ instrumentBlocks.markBlockStart("packageInstaller.packageInstall");
118
+ return packageInstall(packageDir);
119
+ }).then((_result) => {
120
+ instrumentBlocks.markBlockEnd("packageInstaller.packageInstall");
121
+ instrumentBlocks.markBlockStart("packageInstaller.packageArchive");
122
+ return packageArchiver(packageDir, packageFile);
123
+ }).then((_result) => {
124
+ instrumentBlocks.markBlockEnd("packageInstaller.packageArchive");
125
+ Object.assign(obj, { packageArchieveCreated: true });
126
+ return resolve(obj);
127
+ }).catch((err) => {
128
+ obj.error = err.stack.substring(0,100);
129
+ return resolve(obj);
130
+ })
131
+ })
132
+ }
133
+
134
+ exports.packageWrapper = packageWrapper;
@@ -88,7 +88,7 @@ function buildSpecStats(specMeta) {
88
88
  return specStats;
89
89
  }
90
90
 
91
- let reportGenerator = (bsConfig, buildId, args, cb) => {
91
+ let reportGenerator = (bsConfig, buildId, args, rawArgs, cb) => {
92
92
  let options = {
93
93
  url: `${config.buildUrl}${buildId}/custom_report`,
94
94
  auth: {
@@ -100,7 +100,7 @@ let reportGenerator = (bsConfig, buildId, args, cb) => {
100
100
  },
101
101
  };
102
102
 
103
- return request.get(options, function (err, resp, body) {
103
+ return request.get(options, async function (err, resp, body) {
104
104
  let message = null;
105
105
  let messageType = null;
106
106
  let errorCode = null;
@@ -114,7 +114,7 @@ let reportGenerator = (bsConfig, buildId, args, cb) => {
114
114
  logger.error('Generating the build report failed.');
115
115
  logger.error(message);
116
116
 
117
- utils.sendUsageReport(bsConfig, args, message, messageType, errorCode);
117
+ utils.sendUsageReport(bsConfig, args, message, messageType, errorCode, null, rawArgs);
118
118
  return;
119
119
  } else {
120
120
  try {
@@ -163,17 +163,17 @@ let reportGenerator = (bsConfig, buildId, args, cb) => {
163
163
  } else {
164
164
  messageType = Constants.messageTypes.SUCCESS;
165
165
  message = `Report for build: ${buildId} was successfully created.`;
166
- renderReportHTML(build);
166
+ await renderReportHTML(build);
167
167
  logger.info(message);
168
168
  }
169
- utils.sendUsageReport(bsConfig, args, message, messageType, errorCode);
169
+ utils.sendUsageReport(bsConfig, args, message, messageType, errorCode, null, rawArgs);
170
170
  if (cb){
171
171
  cb();
172
172
  }
173
173
  });
174
174
  }
175
175
 
176
- function renderReportHTML(report_data) {
176
+ async function renderReportHTML(report_data) {
177
177
  let resultsDir = 'results';
178
178
  let metaCharSet = `<meta charset="utf-8">`;
179
179
  let metaViewPort = `<meta name="viewport" content="width=device-width, initial-scale=1"> `;
@@ -194,12 +194,17 @@ function renderReportHTML(report_data) {
194
194
  }
195
195
 
196
196
  // Writing the JSON used in creating the HTML file.
197
- fs.writeFileSync(`${resultsDir}/browserstack-cypress-report.json`, JSON.stringify(report_data), () => {
198
- if(err) {
199
- return logger.error(err);
197
+ let reportData = await cypressReportData(report_data);
198
+ fs.writeFileSync(
199
+ `${resultsDir}/browserstack-cypress-report.json`,
200
+ JSON.stringify(reportData),
201
+ () => {
202
+ if (err) {
203
+ return logger.error(err);
204
+ }
205
+ logger.info("The JSON file is saved");
200
206
  }
201
- logger.info("The JSON file is saved");
202
- });
207
+ );
203
208
 
204
209
  // Writing the HTML file generated from the JSON data.
205
210
  fs.writeFileSync(`${resultsDir}/browserstack-cypress-report.html`, html, () => {
@@ -210,4 +215,157 @@ function renderReportHTML(report_data) {
210
215
  });
211
216
  }
212
217
 
218
+ async function cypressReportData(report_data) {
219
+ specFiles = Object.keys(report_data.rows);
220
+ combinationPromises = [];
221
+ for (let spec of specFiles) {
222
+ let specSessions = report_data.rows[spec]["sessions"];
223
+ if (specSessions.length > 0) {
224
+ for (let combination of specSessions) {
225
+ if(utils.isUndefined(report_data.cypress_version) || report_data.cypress_version < "6"){
226
+ combinationPromises.push(generateCypressCombinationSpecReportDataWithoutConfigJson(combination));
227
+ }else{
228
+ combinationPromises.push(generateCypressCombinationSpecReportDataWithConfigJson(combination));
229
+ }
230
+ }
231
+ }
232
+ }
233
+ await Promise.all(combinationPromises);
234
+ return report_data;
235
+ }
236
+
237
+ function getConfigJsonResponse(combination) {
238
+ return new Promise(async (resolve, reject) => {
239
+ configJsonResponse = null;
240
+ configJsonError = false
241
+ request.get(combination.tests.config_json , function(err, resp, body) {
242
+ if(err) {
243
+ configJsonError = true;
244
+ reject([configJsonResponse, configJsonError]);
245
+ } else {
246
+ if(resp.statusCode != 200) {
247
+ configJsonError = true;
248
+ reject([configJsonResponse, configJsonError]);
249
+ } else {
250
+ try {
251
+ configJsonResponse = JSON.parse(body);
252
+ } catch (err) {
253
+ configJsonError = true
254
+ reject([configJsonResponse, configJsonError]);
255
+ }
256
+ }
257
+ }
258
+ resolve([configJsonResponse, configJsonError]);
259
+ });
260
+ });
261
+ }
262
+
263
+ function getResultsJsonResponse(combination) {
264
+ return new Promise(async (resolve, reject) => {
265
+ resultsJsonResponse = null
266
+ resultsJsonError = false;
267
+ request.get(combination.tests.result_json , function(err, resp, body) {
268
+ if(err) {
269
+ resultsJsonError = true;
270
+ reject([resultsJsonResponse, resultsJsonError]);
271
+ } else {
272
+ if(resp.statusCode != 200) {
273
+ resultsJsonError = true;
274
+ reject([resultsJsonResponse, resultsJsonError]);
275
+ } else {
276
+ try {
277
+ resultsJsonResponse = JSON.parse(body);
278
+ } catch (err) {
279
+ resultsJsonError = true
280
+ reject([resultsJsonResponse, resultsJsonError]);
281
+ }
282
+ }
283
+ }
284
+ resolve([resultsJsonResponse, resultsJsonError]);
285
+ });
286
+ });
287
+ }
288
+
289
+ function generateCypressCombinationSpecReportDataWithConfigJson(combination){
290
+ return new Promise(async (resolve, reject) => {
291
+ try {
292
+ let configJsonError, resultsJsonError;
293
+ let configJson, resultsJson;
294
+
295
+ await Promise.all([getConfigJsonResponse(combination), getResultsJsonResponse(combination)]).then(function (successResult) {
296
+ [[configJson, configJsonError], [resultsJson, resultsJsonError]] = successResult;
297
+ }).catch(function (failureResult) {
298
+ [[configJson, configJsonError], [resultsJson, resultsJsonError]] = failureResult;
299
+ });
300
+
301
+ if(resultsJsonError || configJsonError){
302
+ resolve();
303
+ }
304
+ let tests = {};
305
+ if(utils.isUndefined(configJson.tests) || utils.isUndefined(resultsJson.tests)){
306
+ resolve();
307
+ }
308
+ configJson.tests.forEach((test) => {
309
+ tests[test["clientId"]] = test;
310
+ });
311
+ resultsJson.tests.forEach((test) => {
312
+ tests[test["clientId"]] = Object.assign(
313
+ tests[test["clientId"]],
314
+ test
315
+ );
316
+ });
317
+ let sessionTests = [];
318
+ Object.keys(tests).forEach((testId) => {
319
+ sessionTests.push({
320
+ name: tests[testId]["title"].pop(),
321
+ status: tests[testId]["state"],
322
+ duration: parseFloat(
323
+ tests[testId]["attempts"].pop()["wallClockDuration"] / 1000
324
+ ).toFixed(2),
325
+ });
326
+ });
327
+ combination.tests = sessionTests;
328
+ resolve(combination.tests);
329
+ } catch (error) {
330
+ process.exitCode = Constants.ERROR_EXIT_CODE;
331
+ reject(error);
332
+ }
333
+ })
334
+ }
335
+
336
+ function generateCypressCombinationSpecReportDataWithoutConfigJson(combination){
337
+ return new Promise(async (resolve, reject) => {
338
+ try {
339
+ let resultsJson ,resultsJsonError;
340
+ await getResultsJsonResponse(combination).then(function (successResult) {
341
+ [resultsJson, resultsJsonError] = successResult
342
+ }).catch( function (failureResult) {
343
+ [resultsJson, resultsJsonError] = failureResult
344
+ })
345
+ if(resultsJsonError || utils.isUndefined(resultsJsonResponse)){
346
+ resolve();
347
+ }
348
+ let sessionTests = [];
349
+ if(utils.isUndefined(resultsJson.tests)){
350
+ resolve();
351
+ }
352
+ resultsJson.tests.forEach((test) => {
353
+ durationKey = utils.isUndefined(test["attempts"]) ? test : test["attempts"].pop()
354
+ sessionTests.push({
355
+ name: test["title"].pop(),
356
+ status: test["state"],
357
+ duration: parseFloat(
358
+ durationKey["wallClockDuration"] / 1000
359
+ ).toFixed(2)
360
+ })
361
+ });
362
+ combination.tests = sessionTests;
363
+ resolve(combination.tests);
364
+ } catch (error) {
365
+ process.exitCode = Constants.ERROR_EXIT_CODE;
366
+ reject(error);
367
+ }
368
+ })
369
+ }
370
+
213
371
  exports.reportGenerator = reportGenerator;