You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
97 lines
2.8 KiB
Go
97 lines
2.8 KiB
Go
package integration
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/noahlann/nnet/pkg/nnet"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// TestHandlerTimeout 测试处理器超时
|
|
func TestHandlerTimeout(t *testing.T) {
|
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
require.NoError(t, err)
|
|
port := listener.Addr().(*net.TCPAddr).Port
|
|
listener.Close()
|
|
|
|
cfg := &nnet.Config{
|
|
Addr: fmt.Sprintf("tcp://127.0.0.1:%d", port),
|
|
HandlerTimeout: 500 * time.Millisecond, // 设置较短的超时时间
|
|
}
|
|
|
|
ts := StartTestServerWithRoutes(t, cfg, func(srv nnet.Server) {
|
|
// 注册一个会阻塞的路由
|
|
srv.Router().RegisterString("slow", func(ctx nnet.Context) error {
|
|
// 阻塞超过超时时间
|
|
time.Sleep(1 * time.Second)
|
|
return ctx.Response().WriteBytes([]byte("ok\n"))
|
|
})
|
|
|
|
// 注册一个快速的路由
|
|
srv.Router().RegisterString("fast", func(ctx nnet.Context) error {
|
|
return ctx.Response().WriteBytes([]byte("ok\n"))
|
|
})
|
|
})
|
|
defer CleanupTestServer(t, ts)
|
|
|
|
client := NewTestClient(t, ts.Addr, nil)
|
|
defer CleanupTestClient(t, client)
|
|
|
|
ConnectTestClient(t, client)
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
// 快速路由应该正常响应
|
|
resp := RequestWithTimeout(t, client, []byte("fast"), 3*time.Second)
|
|
assert.Contains(t, string(resp), "ok", "Fast route should respond normally")
|
|
|
|
// 慢路由可能会超时(取决于实现)
|
|
// 注意:超时行为取决于服务器的实现
|
|
slowResp, slowErr := client.Request([]byte("slow"), 2*time.Second)
|
|
if slowErr != nil {
|
|
// 如果请求超时,这是预期的行为
|
|
t.Logf("Slow route timed out as expected: %v", slowErr)
|
|
assert.Error(t, slowErr, "Slow route should timeout")
|
|
} else {
|
|
// 如果收到响应,可能是错误响应
|
|
t.Logf("Slow route response: %q", string(slowResp))
|
|
}
|
|
}
|
|
|
|
// TestReadTimeout 测试读取超时
|
|
func TestReadTimeout(t *testing.T) {
|
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
require.NoError(t, err)
|
|
port := listener.Addr().(*net.TCPAddr).Port
|
|
listener.Close()
|
|
|
|
cfg := &nnet.Config{
|
|
Addr: fmt.Sprintf("tcp://127.0.0.1:%d", port),
|
|
ReadTimeout: 500 * time.Millisecond, // 设置较短的读取超时时间
|
|
}
|
|
|
|
ts := StartTestServerWithRoutes(t, cfg, func(srv nnet.Server) {
|
|
srv.Router().RegisterString("test", func(ctx nnet.Context) error {
|
|
return ctx.Response().WriteBytes([]byte("ok\n"))
|
|
})
|
|
})
|
|
defer CleanupTestServer(t, ts)
|
|
|
|
// 创建客户端,使用较短的超时时间
|
|
client := NewTestClient(t, ts.Addr, &nnet.ClientConfig{
|
|
ReadTimeout: 1 * time.Second,
|
|
})
|
|
defer CleanupTestClient(t, client)
|
|
|
|
ConnectTestClient(t, client)
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
// 正常请求应该能够成功
|
|
resp := RequestWithTimeout(t, client, []byte("test"), 3*time.Second)
|
|
assert.Contains(t, string(resp), "ok", "Request should succeed")
|
|
}
|
|
|