No Description

AsyncLock.test.ts 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { expect } from '@std/expect'
  2. import { randomInt } from 'node:crypto'
  3. import { describe, it } from 'node:test'
  4. import { AsyncLock, AsyncLockType } from '../../src/utils/AsyncLock.js'
  5. await describe('AsyncLock test suite', async () => {
  6. await it('Verify runExclusive() on sync fn', () => {
  7. const runs = 10
  8. const executed: number[] = []
  9. let count = 0
  10. const fn = () => {
  11. executed.push(++count)
  12. }
  13. for (let i = 0; i < runs; i++) {
  14. AsyncLock.runExclusive(AsyncLockType.configuration, fn)
  15. .then(() => {
  16. expect(executed).toStrictEqual(new Array(count).fill(0).map((_, i) => ++i))
  17. return undefined
  18. })
  19. .catch(console.error)
  20. }
  21. })
  22. await it('Verify runExclusive() on async fn', () => {
  23. const runs = 10
  24. const executed: number[] = []
  25. let count = 0
  26. const asyncFn = async () => {
  27. await new Promise(resolve => {
  28. setTimeout(resolve, randomInt(1, 100))
  29. })
  30. executed.push(++count)
  31. }
  32. for (let i = 0; i < runs; i++) {
  33. AsyncLock.runExclusive(AsyncLockType.configuration, asyncFn)
  34. .then(() => {
  35. expect(executed).toStrictEqual(new Array(count).fill(0).map((_, i) => ++i))
  36. return undefined
  37. })
  38. .catch(console.error)
  39. }
  40. })
  41. })