import WebSocket from 'ws'; import { generateSigningKey, sign } from '../dist/sys/crypto.js'; import { uts, wait } from '../dist/sys/tools.js'; import * as ws from "./ws/ws.js" function conn(url) { const ws = new WebSocket(url); ws.on('close', function open() { wsOpen = false; }); let wsOpen = true; var list = []; var c = 0; ws.on('message', function message(data) { data = data.toString(); if (data == "error") return void console.log("Server error"); var json = JSON.parse(data); for (let i = 0; i < list.length; i++) { const e = list[i]; if (e[0] == json.id) { e[2]({ state: json.state, data: json.data }); list.splice(i, 1); return; } } }); this.close = function () { ws.close(); } setInterval(() => { for (let i = 0; i < list.length; i++) { const e = list[i]; if (e[1] + 5 < uts()) { e[2]("timeout"); list.splice(i, 1); } } }, 1000); function req(act, data) { return new Promise((res, rej) => { if (!wsOpen) { console.error("WebSocket is closed"); rej("WebSocket is closed"); return; } var id = ++c; list.push([id, uts(), res, rej]); ws.send(JSON.stringify({ id, act, data })); }) } this.req = req; }; function shallowEqual(object1, object2) { const keys1 = Object.keys(object1); const keys2 = Object.keys(object2); if (keys1.length < keys2.length) { return false; } for (let key of keys1) { if (object1[key] != object2[key]) { return false; } } return true; } export async function wsTester(url, kill) { async function test(conn, act, data, expState, expData) { console.log("Testing Act:", act, "with Data:", data); let resp = await conn.req(act, data); if (resp.state != expState) { console.error(`Expected state: '${expState}', but got: '${resp.state}'`); kill(); process.exit(1); } if (typeof expData == "object" && expData != null) { if (!shallowEqual(expData, resp.data)) { console.error(`Expected data: '${expData}', but got: '${resp.data}'`); kill(); process.exit(1); } } else { if (expData != resp.data) { console.error(`Expected data: '${expData}', but got: '${resp.data}'`); kill(); process.exit(1); } } return resp.data; } for (const k in ws) { console.log(`Testing '${k}':`); const handler = [new conn(url)]; await wait(100); const currTest = ws[k]; let resp = true; try { resp = await currTest(handler[0], test, async ()=>{ let h = new conn(url); await wait(100); handler.push(h); return h; }); } catch (error) { console.error("Test Error: ", error); kill(); process.exit(1); } handler.forEach(h=>h.close()); if (resp === false) { console.log("Test respond with error indication!"); kill(); process.exit(1); } } }