Files

51 lines
2.9 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {runInNewContext} from 'node:vm';
import ts from 'typescript';
test('wire frame logging stays muted and preserves transmitted frames',()=>{
for(const debugIO of [false,true]){
const logs:unknown[][]=[],sent:string[]=[],received:string[]=[];
let socket:any;
class WebSocket {
constructor(readonly url:string){socket=this;}
send(frame:string){sent.push(frame);}
}
const exports:any={};
const source=readFileSync(new URL('../../YouleNexus/assets/framework/net/cocos-transport.ts',import.meta.url),'utf8');
runInNewContext(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText,
{exports,WebSocket,console:{log:(...args:unknown[])=>logs.push(args)},require:()=>({STARTUP_CONFIG:{debugIO}})});
const transport=new exports.CocosWebSocketTransport();transport.onMessage((s:string)=>received.push(s));transport.connect('ws://test');
const frame='{"route":"agent","rpc":"player_login","data":{"state":0}}';
transport.send(frame);socket.onmessage({data:frame});socket.onmessage({data:'{"com":"@serverheartbeat"}'});
assert.deepEqual(sent,[frame]);assert.equal(received[0],frame);
const frames=logs.filter(args=>String(args[0]).includes('包 '));
assert.equal(frames.length,0);
assert.equal(received[1],'{"com":"@serverheartbeat"}');
if(!debugIO)assert.equal(logs.length,0);
}
});
test('connection debug logs preserve close evidence and are disabled by debugIO',()=>{
for(const debugIO of [false,true]){
const logs:any[][]=[];let socket:any,opened=0,closed=0;
class WebSocket {
readyState=0;
constructor(readonly url:string){socket=this;}
close(){this.readyState=3;this.onclose({code:1006,reason:'test disconnect',wasClean:false});}
onclose:any;
}
const exports:any={};
const source=readFileSync(new URL('../../YouleNexus/assets/framework/net/cocos-transport.ts',import.meta.url),'utf8');
runInNewContext(ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2020}}).outputText,
{exports,WebSocket,console:{log:(...args:any[])=>logs.push(args)},require:()=>({STARTUP_CONFIG:{debugIO}})});
const transport=new exports.CocosWebSocketTransport();
transport.onOpen(()=>opened++);transport.onClose(()=>closed++);transport.connect('ws://test');
socket.readyState=1;socket.onopen();socket.onerror({type:'error'});
assert.equal(opened,1);assert.equal(closed,1);
assert.deepEqual(logs.map(x=>x[0]),debugIO?['[WebSocket] 连接中','[WebSocket] 已连接','[WebSocket] 连接错误','[WebSocket] 已断开']:[]);
if(debugIO){assert.equal(logs[3][1].code,1006);assert.equal(logs[3][1].reason,'test disconnect');assert.equal(logs[3][1].readyState,3);}
}
});