Skip to content

Commit

Permalink
test(daemon): Add mutex unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
rekmarks committed Mar 8, 2024
1 parent d007e19 commit 93b3477
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions packages/daemon/test/test-mutex.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/* global setTimeout */
import '@endo/init/debug.js';

import rawTest from 'ava';
import { wrapTest } from '@endo/ses-ava';

import { makeMutex } from '../src/mutex.js';

const test = wrapTest(rawTest);

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

test('releases lock in expected order (sync functions)', async t => {
const mutex = makeMutex();
const results = [];

await Promise.all([
mutex.enqueue(() => {
results.push(1);
}),
mutex.enqueue(() => {
results.push(2);
}),
mutex.enqueue(() => {
results.push(3);
}),
]);

t.deepEqual(results, [1, 2, 3]);
});

test('releases lock in expected order (async functions)', async t => {
const mutex = makeMutex();
const results = [];

await Promise.all([
mutex.enqueue(async () => {
results.push(1);
}),
mutex.enqueue(async () => {
results.push(2);
}),
mutex.enqueue(async () => {
results.push(3);
}),
]);

t.deepEqual(results, [1, 2, 3]);
});

test('releases lock in expected order (async functions with await)', async t => {
const mutex = makeMutex();
const results = [];

await Promise.all([
mutex.enqueue(async () => {
await delay(1);
results.push(1);
}),
mutex.enqueue(async () => {
await delay(1);
results.push(2);
}),
mutex.enqueue(async () => {
await delay(1);
results.push(3);
}),
]);

t.deepEqual(results, [1, 2, 3]);
});

test('immediately releases the lock to the awaiter', async t => {
const mutex = makeMutex();
const results = [];

await Promise.all([
mutex.enqueue(async () => {
await delay(10);
results.push(2);
}),
(async () => {
results.push(1);
await mutex.enqueue(() => delay(1));
results.push(3);
})(),
mutex.enqueue(async () => {
results.push(4);
}),
]);

t.deepEqual(results, [1, 2, 3, 4]);
});

0 comments on commit 93b3477

Please sign in to comment.