-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test(daemon): Add mutex unit tests (merge #2122)
Adds tests for `daemon/src/mutex.js`.
- Loading branch information
Showing
1 changed file
with
93 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = () => new Promise(resolve => setTimeout(resolve, 1)); | ||
|
||
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(); | ||
results.push(1); | ||
}), | ||
mutex.enqueue(async () => { | ||
await delay(); | ||
results.push(2); | ||
}), | ||
mutex.enqueue(async () => { | ||
await delay(); | ||
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(); | ||
results.push(2); | ||
}), | ||
(async () => { | ||
results.push(1); | ||
await mutex.enqueue(() => delay()); | ||
results.push(3); | ||
})(), | ||
mutex.enqueue(async () => { | ||
results.push(4); | ||
}), | ||
]); | ||
|
||
t.deepEqual(results, [1, 2, 3, 4]); | ||
}); |