@zohodesk/testinglibrary 3.0.8 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,7 +27,7 @@ function getCustomAccountDetails(tags) {
27
27
  const user = (0, _auth.getUserForSelectedEditionAndProfile)(editionInfo, profileInfo, betaFeature, portalInfo);
28
28
  return user;
29
29
  }
30
- return null;
30
+ return (0, _auth.getDefaultActor)();
31
31
  }
32
32
  const {
33
33
  testSetup
@@ -42,19 +42,9 @@ async function loginSteps(pageDetail) {
42
42
  await page.goto(process.env.domain);
43
43
  }
44
44
  }
45
- async function performDefaultPageSteps({
46
- context,
47
- $tags,
48
- page
49
- }) {
45
+ async function performDefaultPageSteps(testInfo) {
50
46
  if (testSetup.page && typeof testSetup.page === 'function') {
51
- await testSetup.page({
52
- context,
53
- $tags,
54
- page
55
- });
56
- } else {
57
- await page.goto(process.env.domain);
47
+ await testSetup.page(testInfo);
58
48
  }
59
49
  }
60
50
  async function verifyPageIsLoaded(testInfo) {
@@ -68,7 +58,14 @@ var _default = exports.default = {
68
58
  context,
69
59
  $tags,
70
60
  page
71
- }, use) => {
61
+ }, use, testInfo) => {
62
+ let testPortalDetails = getCustomAccountDetails($tags);
63
+ let testDetails = {
64
+ page,
65
+ $tags,
66
+ context,
67
+ ...testPortalDetails
68
+ };
72
69
  try {
73
70
  //This block is used to skip the login process if the @unauthenticated tag is added to the script
74
71
  if ($tags.includes('@unauthenticated')) {
@@ -81,30 +78,18 @@ var _default = exports.default = {
81
78
  if (!isAuthMode) {
82
79
  return;
83
80
  }
84
- const testPortalDetails = getCustomAccountDetails($tags);
85
- if (testPortalDetails) {
81
+ const projectName = testInfo.project.name;
82
+ if (testPortalDetails && projectName !== 'setup' && projectName !== 'cleanup') {
86
83
  await context.clearCookies();
87
- const {
88
- email
89
- } = testPortalDetails;
90
- await (0, _auth.performLoginSteps)({
91
- page,
92
- $tags,
93
- context,
94
- ...testPortalDetails
95
- }, async testInfo => {
84
+ await (0, _auth.performLoginSteps)(testDetails, async testInfo => {
96
85
  return await verifyPageIsLoaded(testInfo);
97
86
  }, loginSteps);
98
87
  process.env.actorInfo = JSON.stringify(testPortalDetails);
99
88
  }
100
- } catch (error) {
101
- console.error('Error during page', error);
89
+ } catch (e) {
90
+ console.error('Error during page', e);
102
91
  } finally {
103
- await performDefaultPageSteps({
104
- context,
105
- $tags,
106
- page
107
- });
92
+ await performDefaultPageSteps(testDetails);
108
93
  await use(page);
109
94
  await context.close();
110
95
  }
@@ -9,6 +9,7 @@ var _path = _interopRequireDefault(require("path"));
9
9
  var _fileUtils = require("../../utils/fileUtils");
10
10
  var _logger = require("../../utils/logger");
11
11
  var _readConfigFile = require("./readConfigFile");
12
+ var _checkAuthDirectory = require("./helpers/checkAuthDirectory");
12
13
  function deleteAuthFiles(authFilePath) {
13
14
  authFilePath = _path.default.resolve(process.cwd(), authFilePath);
14
15
  const authFileFolder = _path.default.dirname(authFilePath);
@@ -24,6 +25,11 @@ function deleteGeneratedFeatures() {
24
25
  _logger.Logger.log(_logger.Logger.INFO_TYPE, `Deleting generated features at ${featuresGenPath}`);
25
26
  (0, _fileUtils.deleteFolder)(featuresGenPath);
26
27
  }
28
+ function deleteLockFiles() {
29
+ const lockFilePath = (0, _checkAuthDirectory.getLockDirectoryPath)();
30
+ _logger.Logger.log(_logger.Logger.INFO_TYPE, `Deleting lock files at ${lockFilePath}`);
31
+ (0, _fileUtils.deleteFolder)(lockFilePath);
32
+ }
27
33
  function clearCaches() {
28
34
  try {
29
35
  const {
@@ -33,6 +39,7 @@ function clearCaches() {
33
39
  deleteAuthFiles(authFilePath);
34
40
  deletePlaywrightReport(reportPath);
35
41
  deleteGeneratedFeatures();
42
+ deleteLockFiles();
36
43
  _logger.Logger.log(_logger.Logger.SUCCESS_TYPE, 'Caches Cleared. Now you can try running npm run uat');
37
44
  } catch (err) {
38
45
  _logger.Logger.error(err);
@@ -3,13 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.LOGIN_MUTEX_TIMEOUT = void 0;
7
- const LOGIN_MUTEX_TIMEOUT = exports.LOGIN_MUTEX_TIMEOUT = {
8
- stale: 100000,
9
- retries: {
10
- retries: 10,
11
- factor: 1,
12
- minTimeout: 10000,
13
- maxTimeout: 20000
14
- }
6
+ exports.fileDeletionTimeoutConfig = void 0;
7
+ const fileDeletionTimeoutConfig = exports.fileDeletionTimeoutConfig = {
8
+ timeout: 45000
15
9
  };
@@ -21,16 +21,13 @@ async function performLoginSteps(testInfo, isLoggedIn, loginSteps) {
21
21
  authFilePrefix = authFilePrefix || email;
22
22
  const authFile = _path.default.resolve(_path.default.join((0, _checkAuthCookies.getAuthFileDirectory)(), `${authFilePrefix}-cookies.json`));
23
23
  const lockFileName = email.replace(/[@.]/g, '_');
24
- const fileMutex = new _fileMutex.default((0, _checkAuthDirectory.getLockDirectoryPath)(), lockFileName, _fileMutexConfig.LOGIN_MUTEX_TIMEOUT);
24
+ const fileMutex = new _fileMutex.default((0, _checkAuthDirectory.getLockDirectoryPath)(), lockFileName, email, authFile, _fileMutexConfig.fileDeletionTimeoutConfig);
25
25
  try {
26
26
  await fileMutex.acquire();
27
27
  await (0, _checkAuthCookies.loadCookiesIfPresent)(page, authFile);
28
- await page.goto(process.env.domain);
29
- await Promise.race([page.waitForNavigation(), page.waitForLoadState('networkidle'), page.waitForTimeout(5000)]);
30
28
  const isAlreadyLoggedIn = await isLoggedIn(testInfo);
31
29
  if (!isAlreadyLoggedIn) {
32
30
  await loginSteps(testInfo);
33
- await page.goto(process.env.domain);
34
31
  await isLoggedIn(testInfo);
35
32
  await page.context().storageState({
36
33
  path: authFile
@@ -39,11 +36,7 @@ async function performLoginSteps(testInfo, isLoggedIn, loginSteps) {
39
36
  } catch (error) {
40
37
  console.error(`Error during login for ${email}:`, error);
41
38
  } finally {
42
- try {
43
- await fileMutex.release();
44
- } catch (releaseError) {
45
- console.error(`Error releasing lock for ${email}:`, releaseError);
46
- }
39
+ await fileMutex.release();
47
40
  }
48
41
  }
49
42
  var _default = exports.default = performLoginSteps;
@@ -16,7 +16,7 @@ function getUATFileName(mode) {
16
16
  if (_fs.default.existsSync(uatConfFilePath)) {
17
17
  return uatConfFilePath;
18
18
  }
19
- return _path.default.resolve(process.cwd(), `uat.config.js`);
19
+ return _path.default.resolve(process.cwd(), `uat/conf/default/uat.config.js`);
20
20
  }
21
21
  function getEnvConfigFilePath(mode) {
22
22
  const confFilePath = _path.default.resolve(process.cwd(), `uat/conf/${mode}/settings.json`);
@@ -6,48 +6,71 @@ Object.defineProperty(exports, "__esModule", {
6
6
  });
7
7
  exports.default = void 0;
8
8
  var _path = _interopRequireDefault(require("path"));
9
- var _properLockfile = _interopRequireDefault(require("proper-lockfile"));
10
9
  var _fs = require("fs");
11
- function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
12
- function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
13
- function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
14
- var _FileMutex_brand = /*#__PURE__*/new WeakSet();
10
+ function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
11
+ function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
12
+ function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
13
+ var _getLockFilePath = /*#__PURE__*/new WeakSet();
15
14
  class FileMutex {
16
- constructor(directory, lockFileName, options = {}) {
17
- _classPrivateMethodInitSpec(this, _FileMutex_brand);
15
+ constructor(directory, lockFileName, email, authFile, fileDeletionTimeoutConfig) {
16
+ _classPrivateMethodInitSpec(this, _getLockFilePath);
18
17
  this.directory = directory;
19
18
  this.lockFileName = lockFileName + ".lock";
20
- this.options = options;
19
+ this.email = email;
20
+ this.authFile = authFile;
21
+ this.fileDeletionTimeout = fileDeletionTimeoutConfig.timeout;
22
+ this.createDirectoryIfNotExist();
23
+ this.lockFilePath = _classPrivateMethodGet(this, _getLockFilePath, _getLockFilePath2).call(this);
21
24
  }
22
25
  async acquire() {
23
- _assertClassBrand(_FileMutex_brand, this, _createDirectoryIfNotExist).call(this);
24
- const lockFilePath = _assertClassBrand(_FileMutex_brand, this, _getLockFilePath).call(this);
25
- try {
26
- if (!(0, _fs.existsSync)(lockFilePath)) {
27
- console.log(`[DEBUG] Creating missing lock file:`, this.lockFileName);
28
- (0, _fs.writeFileSync)(lockFilePath, 'locked');
29
- }
30
- await _properLockfile.default.lock(lockFilePath, this.options);
31
- } catch (err) {
32
- throw new Error(`Failed to acquire lock after ${this.options.retries.retries} attempts: ${err.message}`);
26
+ if ((0, _fs.existsSync)(this.authFile)) {
27
+ console.log(`${this.email} Cookie file exists. Loading cookies...`);
28
+ return;
33
29
  }
30
+ return new Promise((resolve, reject) => {
31
+ if (!(0, _fs.existsSync)(this.lockFilePath)) {
32
+ (0, _fs.writeFileSync)(this.lockFilePath, 'locked');
33
+ console.log(`Lock file created: ${this.lockFilePath}`);
34
+ return resolve();
35
+ }
36
+ const timeout = setTimeout(() => {
37
+ watcher.close();
38
+ reject(new Error('Watch timeout exceeded'));
39
+ }, this.fileDeletionTimeout);
40
+ const watcher = (0, _fs.watch)(this.directory, (eventType, filename) => {
41
+ try {
42
+ if (eventType === 'rename' && filename === this.lockFileName) {
43
+ clearTimeout(timeout);
44
+ console.log(`Lock file deleted! Proceeding...`);
45
+ watcher.close();
46
+ resolve();
47
+ }
48
+ } catch (err) {
49
+ console.error(`Error watching for lock file deletion: ${err.message}`);
50
+ watcher.close();
51
+ }
52
+ });
53
+ });
34
54
  }
35
55
  async release() {
36
56
  try {
37
- await _properLockfile.default.unlock(_assertClassBrand(_FileMutex_brand, this, _getLockFilePath).call(this));
57
+ if ((0, _fs.existsSync)(this.lockFilePath)) {
58
+ (0, _fs.unlinkSync)(this.lockFilePath);
59
+ console.log(`Lock file deleted: ${this.lockFilePath}`);
60
+ }
38
61
  } catch (err) {
39
- throw new Error(`Failed to release lock: ${err.message}`);
62
+ console.error(`Error deleting lock file: ${err.message}`);
63
+ }
64
+ }
65
+ async createDirectoryIfNotExist() {
66
+ if (!(0, _fs.existsSync)(this.directory)) {
67
+ (0, _fs.mkdirSync)(this.directory, {
68
+ recursive: true
69
+ });
40
70
  }
41
71
  }
42
72
  }
43
- function _getLockFilePath() {
73
+ function _getLockFilePath2() {
44
74
  return _path.default.resolve(_path.default.join(this.directory, this.lockFileName));
45
75
  }
46
- function _createDirectoryIfNotExist() {
47
- if (!(0, _fs.existsSync)(this.directory)) {
48
- (0, _fs.mkdirSync)(this.directory, {
49
- recursive: true
50
- });
51
- }
52
- }
53
76
  var _default = exports.default = FileMutex;
@@ -49,7 +49,9 @@ const use = {
49
49
  let reporter = [['html', {
50
50
  outputFolder: reportPath,
51
51
  open: openReportOn
52
- }], ['list'], ['./custom-reporter.js']];
52
+ }], ['list'], ['json', {
53
+ outputFile: _path.default.join(process.cwd(), 'uat', 'test-results', 'test-results.json')
54
+ }], ['./custom-reporter.js']];
53
55
  if (customReporter) {
54
56
  reporter = [customReporter, ...reporter];
55
57
  }
@@ -1,13 +1,23 @@
1
1
  "use strict";
2
2
 
3
3
  var _logger = require("../../utils/logger");
4
- function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
5
- function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
6
- function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
7
- var _TagProcessor_brand = /*#__PURE__*/new WeakSet();
4
+ function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
5
+ function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
6
+ function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
7
+ var _buildTagsString = /*#__PURE__*/new WeakSet();
8
+ var _parseEdition = /*#__PURE__*/new WeakSet();
9
+ var _processSingleEdition = /*#__PURE__*/new WeakSet();
10
+ var _processMultipleEditions = /*#__PURE__*/new WeakSet();
11
+ var _getEditionArgs = /*#__PURE__*/new WeakSet();
12
+ var _buildEditionTags = /*#__PURE__*/new WeakSet();
8
13
  class TagProcessor {
9
14
  constructor(editionOrder) {
10
- _classPrivateMethodInitSpec(this, _TagProcessor_brand);
15
+ _classPrivateMethodInitSpec(this, _buildEditionTags);
16
+ _classPrivateMethodInitSpec(this, _getEditionArgs);
17
+ _classPrivateMethodInitSpec(this, _processMultipleEditions);
18
+ _classPrivateMethodInitSpec(this, _processSingleEdition);
19
+ _classPrivateMethodInitSpec(this, _parseEdition);
20
+ _classPrivateMethodInitSpec(this, _buildTagsString);
11
21
  this.editionOrder = editionOrder;
12
22
  }
13
23
  processTags(userArgs) {
@@ -15,36 +25,36 @@ class TagProcessor {
15
25
  const edition = userArgs['edition'] || null;
16
26
  if (!edition) return tagArgs;
17
27
  const editionsArray = edition.split(',');
18
- const editionTags = editionsArray.length === 1 ? _assertClassBrand(_TagProcessor_brand, this, _processSingleEdition).call(this, editionsArray[0], tagArgs) : _assertClassBrand(_TagProcessor_brand, this, _processMultipleEditions).call(this, editionsArray, tagArgs);
28
+ const editionTags = editionsArray.length === 1 ? _classPrivateMethodGet(this, _processSingleEdition, _processSingleEdition2).call(this, editionsArray[0], tagArgs) : _classPrivateMethodGet(this, _processMultipleEditions, _processMultipleEditions2).call(this, editionsArray, tagArgs);
19
29
  return editionTags;
20
30
  }
21
31
  }
22
- function _buildTagsString(tags, editionTags) {
32
+ function _buildTagsString2(tags, editionTags) {
23
33
  return tags && tags !== '' ? `${tags} and not (${editionTags})` : `not (${editionTags})`;
24
34
  }
25
- function _parseEdition(edition) {
35
+ function _parseEdition2(edition) {
26
36
  if (edition.startsWith('<=')) return ['<=', edition.slice(2)];
27
37
  if (edition.startsWith('>=')) return ['>=', edition.slice(2)];
28
38
  if (edition.startsWith('<')) return ['<', edition.slice(1)];
29
39
  if (edition.startsWith('>')) return ['>', edition.slice(1)];
30
40
  return [null, edition];
31
41
  }
32
- function _processSingleEdition(selectedEdition, tagArgs) {
33
- const editionArgs = _assertClassBrand(_TagProcessor_brand, this, _getEditionArgs).call(this, selectedEdition);
42
+ function _processSingleEdition2(selectedEdition, tagArgs) {
43
+ const editionArgs = _classPrivateMethodGet(this, _getEditionArgs, _getEditionArgs2).call(this, selectedEdition);
34
44
  if (editionArgs && editionArgs.length > 0) {
35
- const editionTags = _assertClassBrand(_TagProcessor_brand, this, _buildEditionTags).call(this, editionArgs, 'or');
36
- return _assertClassBrand(_TagProcessor_brand, this, _buildTagsString).call(this, tagArgs, editionTags);
45
+ const editionTags = _classPrivateMethodGet(this, _buildEditionTags, _buildEditionTags2).call(this, editionArgs, 'or');
46
+ return _classPrivateMethodGet(this, _buildTagsString, _buildTagsString2).call(this, tagArgs, editionTags);
37
47
  }
38
48
  _logger.Logger.log(_logger.Logger.INFO_TYPE, `No matching editions for ${selectedEdition} found. Running with default edition`);
39
49
  return tagArgs;
40
50
  }
41
- function _processMultipleEditions(editionsArray, tagArgs) {
51
+ function _processMultipleEditions2(editionsArray, tagArgs) {
42
52
  const filteredEditions = this.editionOrder.filter(edition => !editionsArray.includes(edition));
43
- const editionTags = _assertClassBrand(_TagProcessor_brand, this, _buildEditionTags).call(this, filteredEditions, 'or');
44
- return _assertClassBrand(_TagProcessor_brand, this, _buildTagsString).call(this, tagArgs, editionTags);
53
+ const editionTags = _classPrivateMethodGet(this, _buildEditionTags, _buildEditionTags2).call(this, filteredEditions, 'or');
54
+ return _classPrivateMethodGet(this, _buildTagsString, _buildTagsString2).call(this, tagArgs, editionTags);
45
55
  }
46
- function _getEditionArgs(selectedEdition) {
47
- const [operator, editionValue] = _assertClassBrand(_TagProcessor_brand, this, _parseEdition).call(this, selectedEdition.toLowerCase());
56
+ function _getEditionArgs2(selectedEdition) {
57
+ const [operator, editionValue] = _classPrivateMethodGet(this, _parseEdition, _parseEdition2).call(this, selectedEdition.toLowerCase());
48
58
  const index = this.editionOrder.findIndex(edition => edition.toLowerCase() === editionValue);
49
59
  if (index === -1) {
50
60
  _logger.Logger.log(_logger.Logger.INFO_TYPE, `No matching editions for ${selectedEdition} found. Running with default edition`);
@@ -63,7 +73,7 @@ function _getEditionArgs(selectedEdition) {
63
73
  return this.editionOrder.filter((_, i) => i !== index);
64
74
  }
65
75
  }
66
- function _buildEditionTags(editionArgs, operator = 'or') {
76
+ function _buildEditionTags2(editionArgs, operator = 'or') {
67
77
  return editionArgs.map(edition => `@edition_${edition}`).join(` ${operator} `);
68
78
  }
69
79
  module.exports = TagProcessor;
package/build/index.js CHANGED
@@ -70,6 +70,12 @@ Object.defineProperty(exports, "performLoginSteps", {
70
70
  return _index.performLoginSteps;
71
71
  }
72
72
  });
73
+ Object.defineProperty(exports, "setup", {
74
+ enumerable: true,
75
+ get: function () {
76
+ return _index.setup;
77
+ }
78
+ });
73
79
  Object.defineProperty(exports, "test", {
74
80
  enumerable: true,
75
81
  get: function () {
@@ -24,7 +24,7 @@ describe('getUATFileName', () => {
24
24
  });
25
25
  test('return the default config files for pipeline matched files not exists', () => {
26
26
  const mode = 'ci';
27
- const defaultPath = `${mockCwd}/uat.config.js`;
27
+ const defaultPath = `${mockCwd}/uat/conf/default/uat.config.js`;
28
28
  _fs.existsSync.mockReturnValue(false);
29
29
  _path.default.resolve.mockImplementation((...args) => args.join('/'));
30
30
  const result = (0, _configFileNameProvider.getUATFileName)(mode);
@@ -2,70 +2,95 @@
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
4
  var _fileMutex = _interopRequireDefault(require("../../../../../core/playwright/helpers/fileMutex"));
5
- var _properLockfile = _interopRequireDefault(require("proper-lockfile"));
6
5
  var _path = _interopRequireDefault(require("path"));
7
- var _fs = _interopRequireDefault(require("fs"));
8
- jest.mock('proper-lockfile');
6
+ var _fs = require("fs");
9
7
  jest.mock('fs');
10
8
  describe('FileMutex', () => {
11
9
  const directory = '/tmp/locks';
12
10
  const lockFileName = 'test-lock';
13
- const options = {
14
- stale: 10000,
15
- retries: {
16
- retries: 5,
17
- factor: 1,
18
- minTimeout: 5000,
19
- maxTimeout: 8000
20
- }
11
+ const email = 'test@example.com';
12
+ const authFile = '/tmp/authFile';
13
+ const fileDeletionTimeoutConfig = {
14
+ timeout: 1000
21
15
  };
22
16
  const lockFilePath = _path.default.resolve(directory, lockFileName + '.lock');
23
17
  let fileMutex;
24
18
  beforeEach(() => {
25
- fileMutex = new _fileMutex.default(directory, lockFileName, options);
26
19
  jest.clearAllMocks();
20
+ fileMutex = new _fileMutex.default(directory, lockFileName, email, authFile, fileDeletionTimeoutConfig);
27
21
  });
28
22
  describe('acquire', () => {
29
- it('should create the directory if it does not exist', async () => {
30
- _fs.default.existsSync.mockReturnValue(false);
31
- _fs.default.mkdirSync.mockImplementation(() => {});
32
- _properLockfile.default.lock.mockResolvedValue();
33
- await fileMutex.acquire();
34
- expect(_fs.default.existsSync).toHaveBeenCalledWith(directory);
35
- expect(_fs.default.mkdirSync).toHaveBeenCalledWith(directory, {
23
+ it('should create directory if it does not exist', async () => {
24
+ _fs.existsSync.mockReturnValue(false);
25
+ await fileMutex.createDirectoryIfNotExist();
26
+ expect(_fs.mkdirSync).toHaveBeenCalledWith(directory, {
36
27
  recursive: true
37
28
  });
38
29
  });
39
30
  it('should create the lock file if it does not exist', async () => {
40
- _fs.default.existsSync.mockImplementation(filePath => filePath !== lockFilePath);
41
- _fs.default.writeFileSync.mockImplementation(() => {});
42
- _properLockfile.default.lock.mockResolvedValue();
31
+ _fs.existsSync.mockImplementation(filePath => filePath === authFile ? false : false);
32
+ _fs.writeFileSync.mockImplementation(() => {});
33
+ await fileMutex.acquire();
34
+ expect(_fs.writeFileSync).toHaveBeenCalledWith(fileMutex.lockFilePath, 'locked');
35
+ });
36
+ it('should resolve immediately if auth file exists', async () => {
37
+ _fs.existsSync.mockImplementation(filePath => filePath === authFile);
43
38
  await fileMutex.acquire();
44
- expect(_fs.default.existsSync).toHaveBeenCalledWith(lockFilePath);
45
- expect(_fs.default.writeFileSync).toHaveBeenCalledWith(lockFilePath, 'locked');
39
+ expect(_fs.existsSync).toHaveBeenCalledWith(authFile);
46
40
  });
47
- it('should acquire the lock using proper-lockfile', async () => {
48
- _fs.default.existsSync.mockReturnValue(true);
49
- _properLockfile.default.lock.mockResolvedValue();
41
+ it('should wait for lock file deletion if it exists', async () => {
42
+ _fs.existsSync.mockImplementation(filePath => filePath === fileMutex.lockFilePath);
43
+ _fs.watch.mockImplementation((dir, callback) => {
44
+ setTimeout(() => {
45
+ _fs.existsSync.mockImplementation(() => false);
46
+ callback('rename', fileMutex.lockFileName);
47
+ }, fileDeletionTimeoutConfig);
48
+ return {
49
+ close: jest.fn()
50
+ };
51
+ });
50
52
  await fileMutex.acquire();
51
- expect(_properLockfile.default.lock).toHaveBeenCalledWith(lockFilePath, options);
53
+ expect(_fs.watch).toHaveBeenCalledWith(directory, expect.any(Function));
52
54
  });
53
- it('should throw an error if lock acquisition fails', async () => {
54
- const errorMessage = 'Lock acquisition failed';
55
- _properLockfile.default.lock.mockRejectedValue(new Error(errorMessage));
56
- await expect(fileMutex.acquire()).rejects.toThrow(`Failed to acquire lock after ${options.retries.retries} attempts: ${errorMessage}`);
55
+ it('should reject if watch timeout exceeds', async () => {
56
+ _fs.existsSync.mockImplementation(filePath => filePath === lockFilePath);
57
+ _fs.watch.mockImplementation(() => {
58
+ return {
59
+ close: jest.fn()
60
+ };
61
+ });
62
+ await expect(fileMutex.acquire()).rejects.toThrow('Watch timeout exceeded');
57
63
  });
58
64
  });
59
65
  describe('release', () => {
60
- it('should release the lock using proper-lockfile', async () => {
61
- _properLockfile.default.unlock.mockResolvedValue();
66
+ it('should delete the lock file if it exists', async () => {
67
+ _fs.existsSync.mockReturnValue(true);
68
+ _fs.unlinkSync.mockImplementation(() => {});
62
69
  await fileMutex.release();
63
- expect(_properLockfile.default.unlock).toHaveBeenCalledWith(lockFilePath);
70
+ expect(_fs.existsSync).toHaveBeenCalledWith(lockFilePath);
71
+ expect(_fs.unlinkSync).toHaveBeenCalledWith(lockFilePath);
64
72
  });
65
- it('should throw an error if lock release fails', async () => {
66
- const errorMessage = 'Lock release failed';
67
- _properLockfile.default.unlock.mockRejectedValue(new Error(errorMessage));
68
- await expect(fileMutex.release()).rejects.toThrow(`Failed to release lock: ${errorMessage}`);
73
+ it('should release lock by deleting lock file', async () => {
74
+ _fs.existsSync.mockReturnValue(true);
75
+ _fs.unlinkSync.mockImplementation(() => {});
76
+ await fileMutex.release();
77
+ expect(_fs.unlinkSync).toHaveBeenCalledWith(lockFilePath);
78
+ });
79
+ it('should not attempt to delete the lock file if it does not exist', async () => {
80
+ _fs.existsSync.mockReturnValue(false);
81
+ await fileMutex.release();
82
+ expect(_fs.existsSync).toHaveBeenCalledWith(lockFilePath);
83
+ expect(_fs.unlinkSync).not.toHaveBeenCalled();
84
+ });
85
+ it('should log an error if deleting the lock file fails', async () => {
86
+ const errorMessage = 'Error deleting lock file';
87
+ _fs.existsSync.mockReturnValue(true);
88
+ _fs.unlinkSync.mockImplementation(() => {
89
+ throw new Error(errorMessage);
90
+ });
91
+ console.error = jest.fn();
92
+ await fileMutex.release();
93
+ expect(console.error).toHaveBeenCalledWith(`Error deleting lock file: ${errorMessage}`);
69
94
  });
70
95
  });
71
96
  });