sing-box/test/box_test.go

61 lines
1.9 KiB
Go
Raw Normal View History

2022-07-08 16:01:23 +00:00
package main
import (
"context"
"net"
"testing"
2022-07-10 11:17:44 +00:00
"time"
2022-07-08 16:01:23 +00:00
"github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/option"
2022-07-10 06:22:28 +00:00
"github.com/sagernet/sing/common/control"
2022-07-15 03:18:14 +00:00
F "github.com/sagernet/sing/common/format"
2022-07-08 16:01:23 +00:00
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/protocol/socks"
"github.com/stretchr/testify/require"
)
func mkPort(t *testing.T) uint16 {
2022-07-10 06:22:28 +00:00
var lc net.ListenConfig
lc.Control = control.ReuseAddr()
2022-07-08 16:01:23 +00:00
for {
2022-07-15 03:18:14 +00:00
tcpListener, err := lc.Listen(context.Background(), "tcp", ":0")
2022-07-08 16:01:23 +00:00
require.NoError(t, err)
listenPort := M.SocksaddrFromNet(tcpListener.Addr()).Port
tcpListener.Close()
2022-07-15 03:18:14 +00:00
udpListener, err := lc.Listen(context.Background(), "tcp", F.ToString(":", listenPort))
2022-07-08 16:01:23 +00:00
if err != nil {
continue
}
udpListener.Close()
return listenPort
}
}
func startInstance(t *testing.T, options option.Options) {
instance, err := box.New(context.Background(), options)
require.NoError(t, err)
require.NoError(t, instance.Start())
t.Cleanup(func() {
instance.Close()
})
2022-07-10 06:22:28 +00:00
time.Sleep(time.Second)
2022-07-08 16:01:23 +00:00
}
func testSuit(t *testing.T, clientPort uint16, testPort uint16) {
dialer := socks.NewClient(N.SystemDialer, M.ParseSocksaddrHostPort("127.0.0.1", clientPort), socks.Version5, "", "")
dialTCP := func() (net.Conn, error) {
return dialer.DialContext(context.Background(), "tcp", M.ParseSocksaddrHostPort("127.0.0.1", testPort))
}
dialUDP := func() (net.PacketConn, error) {
return dialer.ListenPacket(context.Background(), M.ParseSocksaddrHostPort("127.0.0.1", testPort))
}
require.NoError(t, testPingPongWithConn(t, testPort, dialTCP))
require.NoError(t, testLargeDataWithConn(t, testPort, dialTCP))
require.NoError(t, testPingPongWithPacketConn(t, testPort, dialUDP))
require.NoError(t, testLargeDataWithPacketConn(t, testPort, dialUDP))
require.NoError(t, testPacketConnTimeout(t, dialUDP))
}