@zohodesk/testinglibrary 0.0.5 → 0.0.6-n20-experimental

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 (136) hide show
  1. package/.babelrc +24 -0
  2. package/.eslintrc.js +31 -0
  3. package/.gitlab-ci.yml +206 -0
  4. package/.prettierrc +6 -0
  5. package/README.md +189 -18
  6. package/bin/cli.js +2 -2
  7. package/bin/postinstall.js +1 -16
  8. package/build/common/data-generator/steps/DataGenerator.spec.js +19 -0
  9. package/build/common/data-generator/steps/DataGeneratorStepsHelper.js +19 -0
  10. package/build/common/multi-actor/steps/multiActorHandling.spec.js +26 -0
  11. package/build/common/searchFake/helpers/rpcRequestHelper.js +52 -0
  12. package/build/common/searchFake/steps/searchFake.spec.js +77 -0
  13. package/build/core/dataGenerator/DataGenerator.js +108 -0
  14. package/build/core/dataGenerator/DataGeneratorError.js +50 -0
  15. package/build/core/dataGenerator/DataGeneratorHelper.js +49 -0
  16. package/{src → build}/core/jest/preprocessor/jsPreprocessor.js +7 -9
  17. package/{src → build}/core/jest/runner/jest-runner.js +46 -44
  18. package/build/core/jest/setup/index.js +3 -0
  19. package/build/core/playwright/builtInFixtures/actorContext.js +75 -0
  20. package/build/core/playwright/builtInFixtures/addTags.js +19 -0
  21. package/build/core/playwright/builtInFixtures/cacheLayer.js +13 -0
  22. package/build/core/playwright/builtInFixtures/context.js +32 -0
  23. package/build/core/playwright/builtInFixtures/executionContext.js +17 -0
  24. package/build/core/playwright/builtInFixtures/i18N.js +41 -0
  25. package/build/core/playwright/builtInFixtures/index.js +46 -0
  26. package/build/core/playwright/builtInFixtures/page.js +38 -0
  27. package/build/core/playwright/builtInFixtures/unauthenticatedPage.js +18 -0
  28. package/build/core/playwright/clear-caches.js +49 -0
  29. package/build/core/playwright/codegen.js +55 -0
  30. package/build/core/playwright/configuration/Configuration.js +25 -0
  31. package/build/core/playwright/configuration/ConfigurationHelper.js +43 -0
  32. package/build/core/playwright/configuration/UserArgs.js +12 -0
  33. package/build/core/playwright/constants/browserTypes.js +12 -0
  34. package/build/core/playwright/constants/fileMutexConfig.js +9 -0
  35. package/build/core/playwright/custom-commands.js +7 -0
  36. package/build/core/playwright/env-initializer.js +43 -0
  37. package/build/core/playwright/fixtures.js +24 -0
  38. package/build/core/playwright/helpers/additionalProfiles.js +25 -0
  39. package/build/core/playwright/helpers/auth/accountLogin.js +21 -0
  40. package/build/core/playwright/helpers/auth/checkAuthCookies.js +41 -0
  41. package/build/core/playwright/helpers/auth/getUrlOrigin.js +13 -0
  42. package/build/core/playwright/helpers/auth/getUsers.js +118 -0
  43. package/build/core/playwright/helpers/auth/index.js +76 -0
  44. package/build/core/playwright/helpers/auth/loginDefaultStepsHelper.js +54 -0
  45. package/build/core/playwright/helpers/auth/loginSteps.js +51 -0
  46. package/build/core/playwright/helpers/checkAuthDirectory.js +27 -0
  47. package/build/core/playwright/helpers/configFileNameProvider.js +31 -0
  48. package/build/core/playwright/helpers/customFixturesHelper.js +58 -0
  49. package/build/core/playwright/helpers/fileMutex.js +72 -0
  50. package/build/core/playwright/helpers/getUserFixtures.js +23 -0
  51. package/build/core/playwright/helpers/mergeObjects.js +13 -0
  52. package/build/core/playwright/helpers/parseUserArgs.js +10 -0
  53. package/build/core/playwright/index.js +24 -0
  54. package/build/core/playwright/readConfigFile.js +148 -0
  55. package/build/core/playwright/report-generator.js +42 -0
  56. package/build/core/playwright/runner/Runner.js +22 -0
  57. package/build/core/playwright/runner/RunnerHelper.js +43 -0
  58. package/build/core/playwright/runner/RunnerTypes.js +17 -0
  59. package/build/core/playwright/runner/SpawnRunner.js +113 -0
  60. package/build/core/playwright/setup/Project.js +35 -0
  61. package/build/core/playwright/setup/ProjectConfiguration.js +80 -0
  62. package/build/core/playwright/setup/config-creator.js +89 -0
  63. package/build/core/playwright/setup/config-utils.js +188 -0
  64. package/build/core/playwright/setup/custom-reporter.js +136 -0
  65. package/build/core/playwright/setup/qc-custom-reporter.js +291 -0
  66. package/build/core/playwright/tagProcessor.js +69 -0
  67. package/build/core/playwright/test-runner.js +118 -0
  68. package/build/core/playwright/types.js +44 -0
  69. package/build/core/playwright/validateFeature.js +28 -0
  70. package/build/decorators.d.ts +1 -0
  71. package/build/decorators.js +16 -0
  72. package/build/index.d.ts +78 -0
  73. package/build/index.js +105 -0
  74. package/build/lib/cli.js +78 -0
  75. package/build/lib/post-install.js +25 -0
  76. package/build/lint/index.js +4 -0
  77. package/build/parser/parser.js +205 -0
  78. package/build/parser/sample.feature +34 -0
  79. package/build/parser/sample.spec.js +37 -0
  80. package/build/parser/verifier.js +130 -0
  81. package/build/setup-folder-structure/helper.js +37 -0
  82. package/build/setup-folder-structure/reportEnhancement/addonScript.html +25 -0
  83. package/build/setup-folder-structure/reportEnhancement/reportAlteration.js +25 -0
  84. package/build/setup-folder-structure/samples/accountLogin-sample.js +19 -0
  85. package/build/setup-folder-structure/samples/actors-index.js +2 -0
  86. package/build/setup-folder-structure/samples/auth-setup-sample.js +15 -0
  87. package/build/setup-folder-structure/samples/editions-index.js +3 -0
  88. package/build/setup-folder-structure/samples/free-sample.json +25 -0
  89. package/build/setup-folder-structure/samples/git-ignore.sample.js +37 -0
  90. package/build/setup-folder-structure/samples/settings.json +7 -0
  91. package/build/setup-folder-structure/samples/testSetup-sample.js +14 -0
  92. package/build/setup-folder-structure/samples/uat-config-sample.js +46 -0
  93. package/build/setup-folder-structure/setupProject.js +122 -0
  94. package/build/test/core/playwright/__tests__/tagProcessor.test.js +94 -0
  95. package/build/test/core/playwright/__tests__/validateFeature.test.js +69 -0
  96. package/build/test/core/playwright/buildInFixtures/__tests__/executionContext.test.js +27 -0
  97. package/build/test/core/playwright/configuration/__tests__/Configuration.test.js +53 -0
  98. package/build/test/core/playwright/helpers/__tests__/additionalProfiles.test.js +45 -0
  99. package/build/test/core/playwright/helpers/__tests__/configFileNameProvider.test.js +34 -0
  100. package/build/test/core/playwright/helpers/__tests__/customFixturesHelper.test.js +51 -0
  101. package/build/test/core/playwright/helpers/__tests__/fileMutex.test.js +79 -0
  102. package/build/test/core/playwright/helpers/__tests__/getUsers_ListOfActors.test.js +80 -0
  103. package/build/test/core/playwright/runner/__tests__/RunnerHelper.test.js +16 -0
  104. package/build/test/core/playwright/runner/__tests__/SpawnRunner.test.js +27 -0
  105. package/{src → build}/utils/cliArgsToObject.js +72 -63
  106. package/build/utils/commonUtils.js +17 -0
  107. package/build/utils/fileUtils.js +109 -0
  108. package/build/utils/getFilePath.js +11 -0
  109. package/build/utils/logger.js +28 -0
  110. package/build/utils/rootPath.js +53 -0
  111. package/build/utils/stepDefinitionsFormatter.js +11 -0
  112. package/changelog.md +167 -25
  113. package/jest.config.js +81 -63
  114. package/npm-shrinkwrap.json +11894 -5772
  115. package/package.json +61 -31
  116. package/playwright.config.js +62 -112
  117. package/test-results/.last-run.json +4 -0
  118. package/unit_reports/unit-report.html +260 -0
  119. package/src/core/jest/setup/index.js +0 -165
  120. package/src/core/playwright/codegen.js +0 -60
  121. package/src/core/playwright/custom-commands.js +0 -3
  122. package/src/core/playwright/env-initializer.js +0 -24
  123. package/src/core/playwright/index.js +0 -82
  124. package/src/core/playwright/readConfigFile.js +0 -63
  125. package/src/core/playwright/report-generator.js +0 -45
  126. package/src/core/playwright/setup/config-creator.js +0 -77
  127. package/src/core/playwright/test-runner.js +0 -67
  128. package/src/index.js +0 -9
  129. package/src/lib/cli.js +0 -42
  130. package/src/setup-folder-structure/env-config-sample.json +0 -17
  131. package/src/setup-folder-structure/setupProject.js +0 -99
  132. package/src/setup-folder-structure/uat-config-sample.js +0 -22
  133. package/src/setup-folder-structure/user-example.json +0 -3
  134. package/src/utils/getFilePath.js +0 -9
  135. package/src/utils/logger.js +0 -28
  136. package/src/utils/rootPath.js +0 -51
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _fs = require("fs");
5
+ var _path = _interopRequireDefault(require("path"));
6
+ var _configFileNameProvider = require("../../../../../core/playwright/helpers/configFileNameProvider");
7
+ jest.mock('fs');
8
+ jest.mock('path');
9
+ const mockCwd = '/mock/current/directory';
10
+ _path.default.resolve = jest.fn();
11
+ process.cwd = jest.fn(() => mockCwd);
12
+ describe('getUATFileName', () => {
13
+ beforeEach(() => {
14
+ jest.clearAllMocks();
15
+ });
16
+ test('return the pipeline matched config files for pipeline matched files exists', () => {
17
+ const mode = 'cd';
18
+ const mockPath = `${mockCwd}/uat/conf/${mode}/uat.config.js`;
19
+ _fs.existsSync.mockReturnValue(true);
20
+ _path.default.resolve.mockImplementation((...args) => args.join('/'));
21
+ const result = (0, _configFileNameProvider.getUATFileName)(mode);
22
+ expect(_fs.existsSync).toHaveBeenCalledWith(mockPath);
23
+ expect(result).toBe(mockPath);
24
+ });
25
+ test('return the default config files for pipeline matched files not exists', () => {
26
+ const mode = 'ci';
27
+ const defaultPath = `${mockCwd}/uat/conf/default/uat.config.js`;
28
+ _fs.existsSync.mockReturnValue(false);
29
+ _path.default.resolve.mockImplementation((...args) => args.join('/'));
30
+ const result = (0, _configFileNameProvider.getUATFileName)(mode);
31
+ expect(_fs.existsSync).toHaveBeenCalledWith(`${mockCwd}/uat/conf/${mode}/uat.config.js`);
32
+ expect(result).toBe(defaultPath);
33
+ });
34
+ });
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+
3
+ var _customFixturesHelper = require("../../../../../core/playwright/helpers/customFixturesHelper");
4
+ var _logger = require("../../../../../utils/logger");
5
+ var _getUsers = require("../../../../../core/playwright/helpers/auth/getUsers");
6
+ jest.mock('../../../../../core/playwright/helpers/auth/getUsers', () => ({
7
+ getUserForSelectedEditionAndProfile: jest.fn((edition, profile, betaFeature, portalInfo) => ({
8
+ email: 'manager.m@zohotest.com',
9
+ id: '1',
10
+ edition: edition || 'enterprise',
11
+ orgName: 'orgName',
12
+ profile: profile || 'admin',
13
+ betaFeature: betaFeature || null,
14
+ portalInfo: portalInfo || null
15
+ })),
16
+ getDefaultActor: jest.fn(() => ({
17
+ edition: 'enterprise',
18
+ profile: 'admin'
19
+ }))
20
+ }));
21
+ jest.mock('../../../../../utils/logger', () => ({
22
+ Logger: {
23
+ log: jest.fn(),
24
+ FAILURE_TYPE: 'FAILURE'
25
+ }
26
+ }));
27
+ const mockTags = ['@profile_admin', '@edition_enterprise', '@beta_feature', '@portal_clientuat'];
28
+ describe('getCustomAccountDetails', () => {
29
+ beforeEach(() => {
30
+ jest.clearAllMocks();
31
+ });
32
+ test('returns selected user when any tag info is present', () => {
33
+ const result = (0, _customFixturesHelper.getCustomAccountDetails)(mockTags);
34
+ expect(_getUsers.getUserForSelectedEditionAndProfile).toHaveBeenCalledWith('enterprise', 'admin', 'feature', 'clientuat');
35
+ expect(result).toHaveProperty('email', 'manager.m@zohotest.com');
36
+ });
37
+ test('logs and returns undefined if getCustomAccountDetails function throws', () => {
38
+ const error = new Error('failed to get user');
39
+ _getUsers.getUserForSelectedEditionAndProfile.mockImplementation(() => {
40
+ throw error;
41
+ });
42
+ const result = (0, _customFixturesHelper.getCustomAccountDetails)(mockTags);
43
+ expect(_logger.Logger.log).toHaveBeenCalledWith(_logger.Logger.FAILURE_TYPE, 'Error while getting accounts details:', error);
44
+ expect(result).toBeUndefined();
45
+ });
46
+ test('returns default actor when no tag info is not provided', () => {
47
+ const result = (0, _customFixturesHelper.getCustomAccountDetails)([]);
48
+ expect(_getUsers.getDefaultActor).toHaveBeenCalledTimes(1);
49
+ expect(result).toEqual((0, _getUsers.getDefaultActor)());
50
+ });
51
+ });
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _fileMutex = _interopRequireDefault(require("../../../../../core/playwright/helpers/fileMutex"));
5
+ var _path = _interopRequireDefault(require("path"));
6
+ var _fs = require("fs");
7
+ jest.mock('fs');
8
+ describe('FileMutex', () => {
9
+ const directory = '/tmp/locks';
10
+ const lockFileName = 'test-lock';
11
+ const fileDeletionTimeoutConfig = {
12
+ timeout: 1000
13
+ };
14
+ const lockFilePath = _path.default.resolve(directory, lockFileName + '.lock');
15
+ let fileMutex;
16
+ beforeEach(() => {
17
+ jest.clearAllMocks();
18
+ fileMutex = new _fileMutex.default(directory, lockFileName, fileDeletionTimeoutConfig);
19
+ });
20
+ describe('acquire', () => {
21
+ it('should create the lock file if it does not exist', async () => {
22
+ _fs.writeFileSync.mockImplementation(() => {});
23
+ await fileMutex.acquire();
24
+ expect(_fs.writeFileSync).toHaveBeenCalledWith(fileMutex.lockFilePath, 'locked');
25
+ });
26
+ it('should wait for lock file deletion if it exists', async () => {
27
+ _fs.existsSync.mockImplementation(filePath => filePath === fileMutex.lockFilePath);
28
+ _fs.watch.mockImplementation((dir, callback) => {
29
+ setTimeout(() => {
30
+ _fs.existsSync.mockImplementation(() => false);
31
+ callback('rename', fileMutex.lockFileName);
32
+ }, fileDeletionTimeoutConfig);
33
+ return {
34
+ close: jest.fn()
35
+ };
36
+ });
37
+ await fileMutex.acquire();
38
+ expect(_fs.watch).toHaveBeenCalledWith(directory, expect.any(Function));
39
+ });
40
+ it('should reject if watch timeout exceeds', async () => {
41
+ _fs.existsSync.mockImplementation(filePath => filePath === lockFilePath);
42
+ _fs.watch.mockImplementation(() => {
43
+ return {
44
+ close: jest.fn()
45
+ };
46
+ });
47
+ await expect(fileMutex.acquire()).rejects.toThrow('Watch timeout exceeded');
48
+ });
49
+ });
50
+ describe('release', () => {
51
+ it('should delete the lock file if it exists', async () => {
52
+ _fs.existsSync.mockReturnValue(true);
53
+ _fs.unlinkSync.mockImplementation(() => {});
54
+ await fileMutex.release();
55
+ expect(_fs.existsSync).toHaveBeenCalledWith(lockFilePath);
56
+ expect(_fs.unlinkSync).toHaveBeenCalledWith(lockFilePath);
57
+ });
58
+ it('should release lock by deleting lock file', async () => {
59
+ _fs.existsSync.mockReturnValue(true);
60
+ _fs.unlinkSync.mockImplementation(() => {});
61
+ await fileMutex.release();
62
+ expect(_fs.unlinkSync).toHaveBeenCalledWith(lockFilePath);
63
+ });
64
+ it('should not attempt to delete the lock file if it does not exist', async () => {
65
+ _fs.existsSync.mockReturnValue(false);
66
+ await fileMutex.release();
67
+ expect(_fs.existsSync).toHaveBeenCalledWith(lockFilePath);
68
+ expect(_fs.unlinkSync).not.toHaveBeenCalled();
69
+ });
70
+ it('should log an error if deleting the lock file fails', async () => {
71
+ const errorMessage = 'Error deleting lock file';
72
+ _fs.existsSync.mockReturnValue(true);
73
+ _fs.unlinkSync.mockImplementation(() => {
74
+ throw new Error(errorMessage);
75
+ });
76
+ await expect(fileMutex.release()).rejects.toThrow(errorMessage);
77
+ });
78
+ });
79
+ });
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _fs = require("fs");
5
+ var _path = _interopRequireDefault(require("path"));
6
+ jest.mock('fs');
7
+ jest.mock('path');
8
+ jest.mock('../../../../../core/playwright/readConfigFile', () => ({
9
+ generateConfigFromFile: jest.fn(() => ({
10
+ uatDirectory: '/test/directory'
11
+ })),
12
+ getRunMode: jest.fn(() => 'dev')
13
+ }));
14
+ const {
15
+ getListOfActors
16
+ } = require('../../../../../core/playwright/helpers/auth/getUsers');
17
+ describe('getListOfActors', () => {
18
+ beforeEach(() => {
19
+ jest.clearAllMocks();
20
+ _path.default.join.mockImplementation((...args) => args.join('/'));
21
+ });
22
+ test('throws an error when config file cannot be loaded', () => {
23
+ _fs.existsSync.mockReturnValueOnce(true); // Main config file exists
24
+
25
+ jest.mock('/test/directory/conf/dev/actors/index.js', () => {
26
+ throw new Error('Loading error');
27
+ }, {
28
+ virtual: true
29
+ });
30
+ expect(() => getListOfActors()).toThrow('Error loading actor configuration from /test/directory/conf/dev/actors/index.js');
31
+ });
32
+ test('throws an error when beta feature config does not exist', () => {
33
+ _fs.existsSync.mockReturnValueOnce(true) // Main config file exists
34
+ .mockReturnValueOnce(false); // Beta feature config does not exist in either path
35
+
36
+ const betaFeature = 'nonExistentFeature';
37
+ expect(() => getListOfActors(betaFeature)).toThrow(`There is no beta feature configured with the name "${betaFeature}"`);
38
+ });
39
+ test('loads main configuration when betaFeature is not provided and main config file exists', () => {
40
+ _fs.existsSync.mockReturnValueOnce(true);
41
+ jest.doMock('/test/directory/conf/dev/actors/index.js', () => ({
42
+ actors: []
43
+ }), {
44
+ virtual: true
45
+ });
46
+ const result = getListOfActors();
47
+ expect(result).toEqual({
48
+ actors: []
49
+ });
50
+ });
51
+ test('falls back to default configuration if main config file does not exist', () => {
52
+ _fs.existsSync.mockReturnValueOnce(false).mockReturnValueOnce(true);
53
+ jest.doMock('/test/directory/conf/default/actors/index.js', () => ({
54
+ actors: []
55
+ }), {
56
+ virtual: true
57
+ });
58
+ const result = getListOfActors();
59
+ expect(result).toEqual({
60
+ actors: []
61
+ });
62
+ });
63
+ test('loads beta feature configuration when betaFeature is provided', () => {
64
+ _fs.existsSync.mockReturnValueOnce(true) // Main config file exists
65
+ .mockReturnValueOnce(true); // Beta feature config exists
66
+
67
+ const betaFeature = 'parentchild';
68
+ const betaFeaturePath = `/test/directory/conf/dev/actors/beta/${betaFeature}/index.js`;
69
+ jest.doMock(betaFeaturePath, () => ({
70
+ betaActors: []
71
+ }), {
72
+ virtual: true
73
+ });
74
+ const result = getListOfActors(betaFeature);
75
+ expect(result).toEqual({
76
+ betaActors: []
77
+ });
78
+ expect(_path.default.join).toHaveBeenCalledWith('/test/directory', `conf/dev/actors/beta/${betaFeature}/index.js`);
79
+ });
80
+ });
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _RunnerHelper = _interopRequireDefault(require("../../../../../core/playwright/runner/RunnerHelper"));
5
+ var _SpawnRunner = _interopRequireDefault(require("../../../../../core/playwright/runner/SpawnRunner"));
6
+ describe('RunnerHelper', () => {
7
+ describe('createRunner', () => {
8
+ it('should throw error on invalid runner type', () => {
9
+ expect(() => _RunnerHelper.default.createRunner('invalid-type', {})).toThrow("Invalid runner type");
10
+ });
11
+ it('should create a valid runner class', () => {
12
+ const runnerInstance = _RunnerHelper.default.createRunner('spawn', {});
13
+ expect(runnerInstance).toBeInstanceOf(_SpawnRunner.default); // Directly pass the result
14
+ });
15
+ });
16
+ });
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ var _RunnerHelper = _interopRequireDefault(require("../../../../../core/playwright/runner/RunnerHelper"));
5
+ var _Runner = _interopRequireDefault(require("../../../../../core/playwright/runner/Runner"));
6
+ var _Configuration = _interopRequireDefault(require("../../../../../core/playwright/configuration/Configuration"));
7
+ jest.mock('child_process');
8
+ jest.mock('../../../../../utils/logger');
9
+ describe('SpawnRunner', () => {
10
+ let spawnRunner;
11
+ const runnerObj = new _Runner.default();
12
+ beforeEach(() => {
13
+ const config = new _Configuration.default({});
14
+ config.add("bddMode", true);
15
+ runnerObj.setConfig(config);
16
+ runnerObj.setTagArgs(["--headed"]);
17
+ spawnRunner = _RunnerHelper.default.createRunner('spawn', runnerObj);
18
+ });
19
+ describe('run', () => {
20
+ it('should call runPreprocessing when bddMode is true', () => {
21
+ const runPreprocessingSpy = jest.spyOn(spawnRunner, 'runPreprocessing').mockResolvedValue();
22
+ const runPlaywrightSpy = jest.spyOn(spawnRunner, 'runPlaywright').mockResolvedValue();
23
+ spawnRunner.run();
24
+ expect(runPreprocessingSpy).toHaveBeenCalled();
25
+ });
26
+ });
27
+ });
@@ -1,63 +1,72 @@
1
- /**
2
- * Converts an array of command-line arguments into an object.
3
- *
4
- * @param {string[]} cliArgs - An array of command-line arguments.
5
- * @param {boolean} [isKeyNeedToBeAdded=true] - Indicates whether the keys should be added to the resulting object.
6
- * @returns {Object} An object representing the command-line arguments, where keys are argument names (without '--') and values are argument values.
7
- * If `isKeyNeedToBeAdded` is set to `false`, only values are included in the object with numeric indexes as keys.
8
- *
9
- * @example
10
- * // Example usage:
11
- * const args = ['--port=8080', '--verbose', 'input.txt'];
12
- * const result = cliArgsToObject(args);
13
- * // result will be: { port: '8080', verbose: true }
14
- */
15
- function cliArgsToObject(cliArgs, isKeyNeedToBeAdded) {
16
- const processEnv = {};
17
- cliArgs.forEach(option => {
18
- if (/^--./.test(option)) {
19
- const equIndex = option.indexOf('=');
20
- let key = option.slice(2, equIndex);
21
- let value = option.slice(equIndex + 1);
22
- if (equIndex === -1) {
23
- key = option.slice(2);
24
- value = true;
25
- }
26
- processEnv[key] = value;
27
- }
28
- });
29
- return processEnv;
30
- }
31
-
32
-
33
- /**
34
- * Converts an object to an array of command-line arguments.
35
- *
36
- * @param {Object} objectToBeConverted - The object to be converted to command-line arguments.
37
- * @param {(string|function(string): boolean)} [isKeyNeedToBeAdded=true] - A string representing a key, or a function that determines whether a key should be added to the resulting array.
38
- * @returns {string[]} An array of command-line arguments generated from the object's key-value pairs. Keys are transformed into argument names (with '--') and values are added as argument values.
39
- *
40
- * @example
41
- * // Example usage:
42
- * const options = { port: 8080, verbose: true, input: 'input.txt' };
43
- * const args = objectToCliArgs(options);
44
- * // args will be: ['--port=8080', '--verbose', '--input=input.txt']
45
- */
46
- function objectToCliArgs(objectToBeConverted, isKeyNeedToBeAdded) {
47
- const argsArray = [];
48
-
49
- Object.keys(objectToBeConverted).forEach(key => {
50
- if (isKeyNeedToBeAdded(key)) {
51
- if (typeof objectToBeConverted[key] === 'boolean' && objectToBeConverted[key]) {
52
- argsArray.push(`--${key}`)
53
- } else {
54
- argsArray.push(`--${key}=${objectToBeConverted[key]}`)
55
- }
56
- }
57
- })
58
-
59
- return argsArray;
60
- }
61
-
62
-
63
- module.exports = { cliArgsToObject, objectToCliArgs };
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.cliArgsToObject = cliArgsToObject;
7
+ exports.objectToCliArgs = objectToCliArgs;
8
+ function isMatchForOption(option) {
9
+ return /^--./.test(option);
10
+ }
11
+
12
+ /**
13
+ * Converts an array of command-line arguments into an object.
14
+ *
15
+ * @param {string[]} cliArgs - An array of command-line arguments.
16
+ * @param {boolean} [isKeyNeedToBeAdded=true] - Indicates whether the keys should be added to the resulting object.
17
+ * @returns {Object} An object representing the command-line arguments, where keys are argument names (without '--') and values are argument values.
18
+ * If `isKeyNeedToBeAdded` is set to `false`, only values are included in the object with numeric indexes as keys.
19
+ *
20
+ * @example
21
+ * // Example usage:
22
+ * const args = ['--port=8080', '--verbose', 'input.txt'];
23
+ * const result = cliArgsToObject(args);
24
+ * // result will be: { port: '8080', verbose: true }
25
+ */
26
+ // eslint-disable-next-line no-unused-vars
27
+ function cliArgsToObject(cliArgs, isKeyNeedToBeAdded) {
28
+ const processEnv = {};
29
+ cliArgs.forEach(option => {
30
+ if (isMatchForOption(option)) {
31
+ const equIndex = option.indexOf('=');
32
+ let key = option.slice(2, equIndex);
33
+ let value = option.slice(equIndex + 1);
34
+ if (equIndex === -1) {
35
+ key = option.slice(2);
36
+ value = true;
37
+ }
38
+ processEnv[key] = value;
39
+ if (!isNaN(parseInt(value))) {
40
+ processEnv[key] = parseInt(value);
41
+ }
42
+ }
43
+ });
44
+ return processEnv;
45
+ }
46
+
47
+ /**
48
+ * Converts an object to an array of command-line arguments.
49
+ *
50
+ * @param {Object} objectToBeConverted - The object to be converted to command-line arguments.
51
+ * @param {(string|function(string): boolean)} [isKeyNeedToBeAdded=true] - A string representing a key, or a function that determines whether a key should be added to the resulting array.
52
+ * @returns {string[]} An array of command-line arguments generated from the object's key-value pairs. Keys are transformed into argument names (with '--') and values are added as argument values.
53
+ *
54
+ * @example
55
+ * // Example usage:
56
+ * const options = { port: 8080, verbose: true, input: 'input.txt' };
57
+ * const args = objectToCliArgs(options);
58
+ * // args will be: ['--port=8080', '--verbose', '--input=input.txt']
59
+ */
60
+ function objectToCliArgs(objectToBeConverted, isKeyNeedToBeAdded) {
61
+ const argsArray = [];
62
+ Object.keys(objectToBeConverted).forEach(key => {
63
+ if (isKeyNeedToBeAdded(key)) {
64
+ if (typeof objectToBeConverted[key] === 'boolean' && objectToBeConverted[key]) {
65
+ argsArray.push(`--${key}`);
66
+ } else {
67
+ argsArray.push(`--${key}=${objectToBeConverted[key]}`);
68
+ }
69
+ }
70
+ });
71
+ return argsArray;
72
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.copyCommonSpecs = copyCommonSpecs;
8
+ var _fileUtils = require("./fileUtils");
9
+ var _path = _interopRequireDefault(require("path"));
10
+ function copyCommonSpecs() {
11
+ const libraryPath = require.resolve("@zohodesk/testinglibrary");
12
+ // libraryPath will be build/index.js to go to the common specs we need to go one level up
13
+ const commonSpecPath = _path.default.resolve(libraryPath, '../', 'common');
14
+ const destDirectory = _path.default.resolve(process.cwd(), 'uat', 'modules', '.testingLib-common');
15
+ (0, _fileUtils.deleteFolder)(destDirectory);
16
+ (0, _fileUtils.copyDirectory)(commonSpecPath, destDirectory);
17
+ }
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.checkIfFileExists = checkIfFileExists;
8
+ exports.checkIfFolderExistsWithPattern = checkIfFolderExistsWithPattern;
9
+ exports.copyDirectory = copyDirectory;
10
+ exports.deleteFile = deleteFile;
11
+ exports.deleteFolder = deleteFolder;
12
+ exports.readFileContents = readFileContents;
13
+ exports.writeFileContents = writeFileContents;
14
+ var _fs = _interopRequireDefault(require("fs"));
15
+ var _path = _interopRequireDefault(require("path"));
16
+ var _logger = require("./logger");
17
+ var glob = _interopRequireWildcard(require("glob"));
18
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
19
+ function checkIfFileExists(file) {
20
+ try {
21
+ _fs.default.accessSync(file, _fs.default.constants.F_OK);
22
+ return true;
23
+ } catch (err) {
24
+ _logger.Logger.error(err);
25
+ return false;
26
+ }
27
+ }
28
+ function readFileContents(filePath) {
29
+ try {
30
+ let fileContents = _fs.default.readFileSync(filePath, 'utf-8');
31
+ return fileContents;
32
+ } catch (err) {
33
+ _logger.Logger.error(err);
34
+ return null;
35
+ }
36
+ }
37
+ function writeFileContents(filePath, content, writeOptions = {}) {
38
+ const directoryPath = _path.default.dirname(filePath);
39
+
40
+ // Check if the directory exists
41
+ if (!_fs.default.existsSync(directoryPath)) {
42
+ _fs.default.mkdirSync(directoryPath, {
43
+ recursive: true
44
+ });
45
+ }
46
+ try {
47
+ _fs.default.writeFileSync(`${filePath}`, content, writeOptions);
48
+ } catch (err) {
49
+ _logger.Logger.error(err);
50
+ throw new Error(err);
51
+ }
52
+ }
53
+ function deleteFile(filePath) {
54
+ if (checkIfFileExists(filePath)) {
55
+ try {
56
+ _fs.default.unlinkSync(filePath);
57
+ } catch (err) {
58
+ _logger.Logger.error(err);
59
+ throw new Error(`Error while deleting the test data file: ${filePath}`);
60
+ }
61
+ } else {
62
+ _logger.Logger.log(_logger.Logger.INFO_TYPE, `File Does not Exist in the path ${filePath}`);
63
+ }
64
+ }
65
+ function deleteFolder(folderPath) {
66
+ if (_fs.default.existsSync(folderPath)) {
67
+ try {
68
+ _fs.default.rmdirSync(folderPath, {
69
+ recursive: true
70
+ });
71
+ } catch (err) {
72
+ _logger.Logger.error(err);
73
+ throw new Error(`Error while deleting the test data file: ${folderPath}`);
74
+ }
75
+ }
76
+ }
77
+
78
+ // This function uses glob to check if a folder exists with a specific pattern
79
+ // Glob is define patterns for matching file and directory names based on wildcards
80
+ function checkIfFolderExistsWithPattern(folderPath) {
81
+ try {
82
+ if (glob.sync(folderPath).length > 0) {
83
+ return true;
84
+ }
85
+ return false;
86
+ } catch (err) {
87
+ _logger.Logger.error(err);
88
+ return false;
89
+ }
90
+ }
91
+ function copyDirectory(src, dest) {
92
+ if (!_fs.default.existsSync(dest)) {
93
+ _fs.default.mkdirSync(dest, {
94
+ recursive: true
95
+ });
96
+ }
97
+ const entries = _fs.default.readdirSync(src, {
98
+ withFileTypes: true
99
+ });
100
+ for (const entry of entries) {
101
+ const srcPath = _path.default.join(src, entry.name);
102
+ const destPath = _path.default.join(dest, entry.name);
103
+ if (entry.isDirectory()) {
104
+ copyDirectory(srcPath, destPath);
105
+ } else {
106
+ _fs.default.copyFileSync(srcPath, destPath);
107
+ }
108
+ }
109
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = getFilePathWithExtension;
7
+ var _os = require("os");
8
+ const isWindows = (0, _os.platform)().toLowerCase() === 'win32';
9
+ function getFilePathWithExtension(binName) {
10
+ return isWindows ? `${binName}.cmd` : binName;
11
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Logger = void 0;
7
+ class LoggerImpl {
8
+ constructor() {
9
+ this.SUCCESS_TYPE = 'success';
10
+ this.FAILURE_TYPE = 'failure';
11
+ this.INFO_TYPE = 'info';
12
+ this.colors = {
13
+ 'success': ['\x1b[36m', '\x1b[0m'],
14
+ 'failure': ['\x1b[31m', '\x1b[0m'],
15
+ 'info': ['\x1b[33m', '\x1b[0m']
16
+ };
17
+ this.consoleLogger = console;
18
+ }
19
+ error(err) {
20
+ this.consoleLogger.error(err);
21
+ }
22
+ info() {}
23
+ log(type, message) {
24
+ const color = this.colors[type];
25
+ this.consoleLogger.log(`${color[0]}${message}${color[1]}`);
26
+ }
27
+ }
28
+ const Logger = exports.Logger = new LoggerImpl();
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.getBinPath = getBinPath;
8
+ exports.getExecutableBinaryPath = getExecutableBinaryPath;
9
+ exports.getRootNodeModulesPath = getRootNodeModulesPath;
10
+ exports.getRootPath = getRootPath;
11
+ var _path = _interopRequireDefault(require("path"));
12
+ var _fs = _interopRequireDefault(require("fs"));
13
+ var _logger = require("./logger");
14
+ var _getFilePath = _interopRequireDefault(require("./getFilePath"));
15
+ // TODO: Publish and check this change of finding package.json working fine.
16
+ function findPath(directory, pathToFind) {
17
+ const filePath = _path.default.join(directory, pathToFind);
18
+ if (_fs.default.existsSync(filePath)) {
19
+ return filePath;
20
+ }
21
+ const parentDir = _path.default.dirname(directory);
22
+ if (parentDir === directory) {
23
+ return null;
24
+ }
25
+ return findPath(parentDir, pathToFind);
26
+ }
27
+ function findPackageJSON(startDir) {
28
+ return findPath(startDir, 'package.json');
29
+ }
30
+ function findBinaryPath(directory, command) {
31
+ const binaryPath = _path.default.join('.bin', (0, _getFilePath.default)(command));
32
+ return findPath(directory, binaryPath);
33
+ }
34
+ function getRootPath() {
35
+ return findPackageJSON(_path.default.resolve(__dirname));
36
+ }
37
+ function getRootNodeModulesPath() {
38
+ const rootPath = getRootPath();
39
+ return _path.default.resolve(_path.default.dirname(rootPath), 'node_modules');
40
+ }
41
+ function getBinPath(command) {
42
+ const packageNodeModulesPath = getRootNodeModulesPath();
43
+ return findBinaryPath(packageNodeModulesPath, command);
44
+ }
45
+ function getExecutableBinaryPath(command) {
46
+ const binPath = getBinPath(command);
47
+ if (binPath !== null) {
48
+ return binPath;
49
+ } else {
50
+ _logger.Logger.log(_logger.Logger.FAILURE_TYPE, `Error: Could not find executable bin ${command} file. Make sure to npm install before proceeding`);
51
+ process.exit();
52
+ }
53
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.delimiters = void 0;
7
+ exports.findDelimiterFromStep = findDelimiterFromStep;
8
+ const delimiters = exports.delimiters = ["Given", "When", "Then", "And"];
9
+ function findDelimiterFromStep(step) {
10
+ return delimiters.find(delimiter => step.includes(delimiter));
11
+ }