socketcomputer/shared/test/Protocol.test.ts

78 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-04-02 07:43:54 -04:00
import { MessageDecoder, MessageEncoder } from '../src/Protocol.js';
function buf2hex(buffer) {
// buffer is an ArrayBuffer
return [...new Uint8Array(buffer)].map((x) => x.toString(16).padStart(2, '0')).join(' ');
}
async function decodeMessage(buf, isClient) {
// Let's try decoding this message
console.log('Got message:', await MessageDecoder.ReadMessage(buf, isClient));
}
function encodeMessage(f: (encoder: MessageEncoder) => void) {
var encoder = new MessageEncoder();
encoder.Init(4096);
f(encoder);
var buf = encoder.Finish();
console.log('the buffer of this message:', buf2hex(buf));
return buf;
}
(async () => {
console.log('[CLIENT TESTS]');
await decodeMessage(
encodeMessage((encoder) => {
2024-04-02 10:16:34 -04:00
encoder.SetKeyMessage(100, true);
2024-04-02 07:43:54 -04:00
}),
false
);
await decodeMessage(
encodeMessage((encoder) => {
encoder.SetTurnMessage();
}),
false
);
console.log('[END CLIENT TESTS]');
console.log('[SERVER TESTS]');
// server->client tests
await decodeMessage(
encodeMessage((encoder) => {
2024-04-02 10:16:34 -04:00
encoder.SetDisplaySizeMessage(1024, 1024);
2024-04-02 07:43:54 -04:00
}),
true
);
await decodeMessage(
encodeMessage((encoder) => {
encoder.SetTurnSrvMessage(1000, ['tester19200', 'tester59340', 'tester10000', 'tester1337']);
}),
true
);
console.log('[END SERVER TESTS]');
console.log('[BEGIN THINGS THAT SHOULD INTENTIONALLY NOT WORK]');
try {
let r = await decodeMessage(
encodeMessage((encoder) => {
encoder.SetDisplaySizeMessage(1000, 1000);
}),
false // the client wouldn't usually send a display size message..
);
console.log(`wait uhh.. how'd that work?`, r);
} catch (err) {
console.log(`ok cool, that returns this error: ${err}`);
}
console.log('[END THINGS THAT SHOULD INTENTIONALLY NOT WORK]');
})();