import { mainReference } from "https://esm.town/v/karfau/mainReference";
import { dlock as dlock2 } from "https://esm.town/v/karfau/dlock";
import { testRunner } from "https://esm.town/v/karfau/testRunner";
export const test_dlock = await testRunner(
{
val: ["karfau", "dlock"],
dlock: dlock2,
get deadline() {
return Math.floor(Date.now() / 1000 + 1);
},
id: mainReference(({ userHandle, valName }) =>
`val_town-${userHandle}-${valName}`
),
ttl: 1,
fetchStub:
(data = {}, { status = 200, ok = status < 400 } = {}) => async () =>
Promise.resolve({ ok, status, json: async () => data } as const),
throwingFetchStub: async () => {
throw new Error("sync from test_dlock::throwingFetchStub");
},
...await import("https://deno.land/std/assert/mod.ts"),
...await import("https://deno.land/std/testing/mock.ts"),
} as const,
async function should_reject_after_last_attempt(
{
dlock,
id,
ttl,
throwingFetchStub,
assertEquals,
assertRejects,
assertSpyCall,
assertSpyCalls,
spy,
},
) {
const fetchSpy = spy(throwingFetchStub);
const err = await assertRejects(() => dlock({ id, ttl }, fetchSpy));
assertEquals(err.message, "sync from test_dlock::throwingFetchStub");
assertSpyCalls(fetchSpy, 5);
assertSpyCall(fetchSpy, 4, {
args: [`https://dlock.univalent.net/lock/${id}/aquire?ttl=${ttl}`],
});
},
async function should_reject_ttl_of_0(
{ dlock, id, ttl, fetchStub, assertMatch, assertRejects },
) {
const err = await assertRejects(() => dlock({ id, ttl: 0 }, fetchStub()));
assertMatch(err.message, /ttl/);
},
async function should_return_lock_on_successful_request(
{ dlock, deadline, fetchStub, assertFalse, assertEquals },
) {
const lease = 375;
const lock = await dlock({}, fetchStub({ lease, deadline }));
assertEquals(lock.lease, lease, "lease");
assertEquals(lock.deadline, deadline, "deadline");
assertEquals(lock.id, "val_town-karfau-testRunner", "id");
assertFalse(lock.isExpired(), "isExpired");
},
async function skip_should_reject_when_id_is_locked(
{ dlock, id, ttl, deadline, fetchStub, assertRejects, assertEquals },
) {
const error = "lock is acquired by another client";
const err = await assertRejects(() =>
dlock({ id, ttl }, fetchStub({ error, deadline }, { status: 409 }))
);
assertEquals(err.message, error);
},
);