51 lines
2.1 KiB
JavaScript
51 lines
2.1 KiB
JavaScript
// Tests for the gate: in process, and over a real Cap'n Web session on a MessageChannel; no network.
|
|
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { newMessagePortRpcSession } from 'capnweb';
|
|
import { Gate } from './gate.js';
|
|
import { Speech } from './speech.js';
|
|
|
|
test('the right key opens the gate; a wrong one is refused', () => {
|
|
const cap = { it: 'the capability' };
|
|
const gate = new Gate('k3y', cap);
|
|
assert.equal(gate.open('k3y'), cap);
|
|
assert.throws(() => gate.open('guess'), /no such key/);
|
|
assert.throws(() => gate.open(''), /no such key/);
|
|
assert.throws(() => gate.open(undefined), /no such key/);
|
|
});
|
|
|
|
/** A client's stub for a gate served across a MessageChannel. */
|
|
const serve = (gate) => {
|
|
const { port1, port2 } = new MessageChannel();
|
|
newMessagePortRpcSession(port1, gate);
|
|
const stub = newMessagePortRpcSession(port2);
|
|
return { stub, close: () => { stub[Symbol.dispose](); port1.close(); port2.close(); } };
|
|
};
|
|
|
|
test('over a session: open and call in one round trip; a wrong key is refused', async () => {
|
|
const { stub, close } = serve(new Gate('k3y', new Speech(async (c) => `${c.length} bytes`)));
|
|
try {
|
|
assert.equal(await stub.open('k3y').transcribe(new Uint8Array(4)), '4 bytes');
|
|
await assert.rejects(async () => stub.open('guess').transcribe(new Uint8Array(4)), /no such key/);
|
|
} finally {
|
|
close();
|
|
}
|
|
});
|
|
|
|
test('over a session: only public methods reach across; private fields do not', async () => {
|
|
const transcribe = async () => 'secret';
|
|
const { stub, close } = serve(new Gate('k3y', new Speech(transcribe)));
|
|
try {
|
|
// #want and #cap aren't properties at all; neither are Speech's #transcribe or #inTurn.
|
|
for (const name of ['want', 'cap', '#want', '#cap', 'constructor']) {
|
|
await assert.rejects(async () => stub[name](), undefined, `gate.${name}`);
|
|
}
|
|
const speech = stub.open('k3y');
|
|
for (const name of ['transcribe_', '#transcribe', 'inTurn', '#inTurn', 'last']) {
|
|
await assert.rejects(async () => speech[name](), undefined, `speech.${name}`);
|
|
}
|
|
} finally {
|
|
close();
|
|
}
|
|
});
|