Files
zogo/nettest/nettest_test.go
T
4566704 8a038d4df3 feat(nettest): 自 go-hua 迁入网络连通性探测
- TCP 端口探测 + 原始 ICMP Ping, 持续统计成功率与延迟
- 附测试、examples/nettest 例程与包 README
2026-09-20 12:25:37 +08:00

103 lines
2.4 KiB
Go

package nettest
import (
"net"
"testing"
"time"
)
func TestCheckSum(t *testing.T) {
// 单字节直接累加:sum=0x01 → ^0x01 = 0xFFFE
if got := CheckSum([]byte{0x01}); got != 0xFFFE {
t.Errorf("CheckSum([0x01]) = %#04x, want 0xFFFE", got)
}
// 双字节:sum=0x0102 → ^0x0102 = 0xFEFD
if got := CheckSum([]byte{0x01, 0x02}); got != 0xFEFD {
t.Errorf("CheckSum([0x01,0x02]) = %#04x, want 0xFEFD", got)
}
// 往返性质:带正确校验和的报文再次计算应为 0
data := []byte{0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01}
cs := CheckSum(data)
full := append(data, byte(cs>>8), byte(cs&0xFF))
if got := CheckSum(full); got != 0 {
t.Errorf("正确校验和报文再计算 = %#04x, want 0", got)
}
}
func TestPortCheck(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
c.Close()
}
}()
port := l.Addr().(*net.TCPAddr).Port
p := NewPing("127.0.0.1", port, 1000)
if got := p.Test(); got < 0 {
t.Errorf("本地端口探测应成功, got %d", got)
}
// 探测不存在的端口应失败
if got := NewPing("127.0.0.1", 1, 500).Test(); got >= 0 {
t.Errorf("不可达端口应返回 -1, got %d", got)
}
}
func TestPingSet(t *testing.T) {
p := NewPing("127.0.0.1", 80, 1000)
p.Set("localhost", 443, 2000)
if p.addr != "localhost" || p.port != 443 || p.timeout != 2000 {
t.Errorf("Set 后字段错误: %+v", p)
}
}
func TestNetTestFlow(t *testing.T) {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer l.Close()
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
c.Close()
}
}()
port := l.Addr().(*net.TCPAddr).Port
// timeout 300ms 同时作为探测间隔
tt := NewNetTest(1, "test", "127.0.0.1", port, 300, false)
tt.Start()
time.Sleep(1100 * time.Millisecond)
tt.Stop()
r := tt.GetResult(false)
if r.TotalCount == 0 {
t.Fatal("应有探测记录")
}
if r.SuccessCount == 0 {
t.Errorf("本地端口应全部成功: %+v", r)
}
if r.SuccessCount+r.FailCount != r.TotalCount {
t.Errorf("成功+失败应等于总数: %+v", r)
}
// GetResult(false) 不清零
r2 := tt.GetResult(false)
if r2.TotalCount != r.TotalCount {
t.Errorf("isReset=false 时统计不应清零: %d != %d", r2.TotalCount, r.TotalCount)
}
}