SPB Git

Repository Public MIT Selected

semaphore.test.mjs 1.8 KB 46 lines javascript

1/**2 * ─────────────────────────────────────────────3 *  SPB Git — Personal Git Platform4 * ─────────────────────────────────────────────5 *  Author  : Simon-Pierre Boucher6 *  Contact : contact@spboucher.ai7 *  File    : test/unit/semaphore.test.mjs8 *  Purpose : Unit tests — bounded concurrency semaphore9 *  License : MIT © Simon-Pierre Boucher10 * ─────────────────────────────────────────────11 */1213import { describe, it, expect } from 'vitest';14import { Semaphore } from '../../src/lib/semaphore.mjs';1516describe('Semaphore', () => {17  it('never exceeds its limit and releases in FIFO order', async () => {18    const sem = new Semaphore(3);19    let active = 0;20    let peak = 0;21    const order = [];22    const jobs = Array.from({ length: 10 }, (_, i) => sem.run(async () => {23      active += 1;24      peak = Math.max(peak, active);25      order.push(i);26      await new Promise((r) => setTimeout(r, 5));27      active -= 1;28      return i;29    }));30    const results = await Promise.all(jobs);31    expect(peak).toBe(3);32    expect(results).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);33    expect(order).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);34    expect(sem.stats()).toEqual({ active: 0, waiting: 0, limit: 3 });35  });3637  it('releases the slot when the job throws and ignores double release', async () => {38    const sem = new Semaphore(1);39    await expect(sem.run(async () => { throw new Error('boom'); })).rejects.toThrow('boom');40    const release = await sem.acquire();41    release();42    release();43    expect(sem.stats().active).toBe(0);44  });45});46
Files main
Menu

Theme