Files
lingniu-vehicle-ingest/go/vehicle-gateway/internal/loadsim/runner_test.go
2026-07-03 18:01:40 +08:00

110 lines
3.1 KiB
Go

package loadsim
import (
"context"
"net"
"sync/atomic"
"testing"
"time"
)
func TestRunnerDialsTargetConnectionsAndWritesFrames(t *testing.T) {
var writes atomic.Int64
var closed atomic.Int64
runner := Runner{
Dial: func(ctx context.Context, network, addr string) (net.Conn, error) {
return &recordingConn{
write: func(p []byte) (int, error) {
writes.Add(1)
return len(p), nil
},
close: func() error {
closed.Add(1)
return nil
},
}, nil
},
}
stats, err := runner.Run(context.Background(), Config{
Protocol: ProtocolJT808,
Addr: "127.0.0.1:808",
Connections: 3,
ConnectRatePerSecond: 1000,
SendInterval: time.Millisecond,
Duration: 5 * time.Millisecond,
Template: "0200",
SendFrames: true,
})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if stats.ConnectionsOpened != 3 {
t.Fatalf("ConnectionsOpened = %d, want 3", stats.ConnectionsOpened)
}
if stats.FramesWritten == 0 {
t.Fatalf("FramesWritten = 0, want at least one")
}
if writes.Load() != int64(stats.FramesWritten) {
t.Fatalf("recorded writes = %d, stats = %d", writes.Load(), stats.FramesWritten)
}
if closed.Load() != 3 {
t.Fatalf("closed = %d, want 3", closed.Load())
}
}
func TestRunnerCanHoldConnectionsWithoutWritingFrames(t *testing.T) {
var writes atomic.Int64
runner := Runner{
Dial: func(ctx context.Context, network, addr string) (net.Conn, error) {
return &recordingConn{
write: func(p []byte) (int, error) {
writes.Add(1)
return len(p), nil
},
close: func() error { return nil },
}, nil
},
}
stats, err := runner.Run(context.Background(), Config{
Protocol: ProtocolJT808,
Addr: "127.0.0.1:808",
Connections: 2,
ConnectRatePerSecond: 1000,
SendInterval: time.Millisecond,
Duration: 5 * time.Millisecond,
Template: "0200",
SendFrames: false,
})
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if stats.ConnectionsOpened != 2 {
t.Fatalf("ConnectionsOpened = %d, want 2", stats.ConnectionsOpened)
}
if stats.FramesWritten != 0 || writes.Load() != 0 {
t.Fatalf("frames written stats=%d writes=%d, want 0", stats.FramesWritten, writes.Load())
}
}
type recordingConn struct {
write func([]byte) (int, error)
close func() error
}
func (c *recordingConn) Read(p []byte) (int, error) { return 0, context.Canceled }
func (c *recordingConn) Write(p []byte) (int, error) { return c.write(p) }
func (c *recordingConn) Close() error { return c.close() }
func (c *recordingConn) LocalAddr() net.Addr { return testAddr("local") }
func (c *recordingConn) RemoteAddr() net.Addr { return testAddr("remote") }
func (c *recordingConn) SetDeadline(t time.Time) error { return nil }
func (c *recordingConn) SetReadDeadline(t time.Time) error { return nil }
func (c *recordingConn) SetWriteDeadline(t time.Time) error { return nil }
type testAddr string
func (a testAddr) Network() string { return "tcp" }
func (a testAddr) String() string { return string(a) }