package ws import ( "testing" ) // TestConnSendAfterClose 验证:连接关闭后 sendRaw/sendEnvelope 不 panic(回归 send-on-closed-channel)。 func TestConnSendAfterClose(t *testing.T) { c := &Conn{ID: "1", send: make(chan []byte, 1), Kind: "agent"} c.close() // 已关闭,发送应返回 false 而非 panic if c.sendRaw([]byte("x"), true) { t.Fatal("send to closed conn should return false") } if c.sendRaw([]byte("x"), false) { t.Fatal("send to closed conn (drop) should return false") } } // TestConnDoubleClose 双重 close 不应 panic(closeOnce 保护) func TestConnDoubleClose(t *testing.T) { c := &Conn{ID: "1", send: make(chan []byte, 1)} c.close() c.close() // 第二次应无效果 } // TestRegisterReplaceOld 同设备重连替换旧连接:旧连接被 close,映射指向新连接,且不 panic func TestRegisterReplace(t *testing.T) { h := NewHub() old := &Conn{ID: "7", send: make(chan []byte, 64)} newc := &Conn{ID: "7", send: make(chan []byte, 64)} h.RegisterAgent(old) h.RegisterAgent(newc) if !h.AgentOnline(7) { t.Fatal("device 7 should be online via new conn") } h.UnregisterAgent(old) // 注销旧连接不应影响新连接 if !h.AgentOnline(7) { t.Fatal("device 7 should still be online after old conn unregister") } if old.sendRaw([]byte("x"), false) { t.Fatal("old conn should be closed") } }