github.com/moqsien/xraycore@v1.8.5/common/protocol/server_picker_test.go (about)

     1  package protocol_test
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/moqsien/xraycore/common/net"
     8  	. "github.com/moqsien/xraycore/common/protocol"
     9  )
    10  
    11  func TestServerList(t *testing.T) {
    12  	list := NewServerList()
    13  	list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(1)), AlwaysValid()))
    14  	if list.Size() != 1 {
    15  		t.Error("list size: ", list.Size())
    16  	}
    17  	list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(2)), BeforeTime(time.Now().Add(time.Second))))
    18  	if list.Size() != 2 {
    19  		t.Error("list.size: ", list.Size())
    20  	}
    21  
    22  	server := list.GetServer(1)
    23  	if server.Destination().Port != 2 {
    24  		t.Error("server: ", server.Destination())
    25  	}
    26  	time.Sleep(2 * time.Second)
    27  	server = list.GetServer(1)
    28  	if server != nil {
    29  		t.Error("server: ", server)
    30  	}
    31  
    32  	server = list.GetServer(0)
    33  	if server.Destination().Port != 1 {
    34  		t.Error("server: ", server.Destination())
    35  	}
    36  }
    37  
    38  func TestServerPicker(t *testing.T) {
    39  	list := NewServerList()
    40  	list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(1)), AlwaysValid()))
    41  	list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(2)), BeforeTime(time.Now().Add(time.Second))))
    42  	list.AddServer(NewServerSpec(net.TCPDestination(net.LocalHostIP, net.Port(3)), BeforeTime(time.Now().Add(time.Second))))
    43  
    44  	picker := NewRoundRobinServerPicker(list)
    45  	server := picker.PickServer()
    46  	if server.Destination().Port != 1 {
    47  		t.Error("server: ", server.Destination())
    48  	}
    49  	server = picker.PickServer()
    50  	if server.Destination().Port != 2 {
    51  		t.Error("server: ", server.Destination())
    52  	}
    53  	server = picker.PickServer()
    54  	if server.Destination().Port != 3 {
    55  		t.Error("server: ", server.Destination())
    56  	}
    57  	server = picker.PickServer()
    58  	if server.Destination().Port != 1 {
    59  		t.Error("server: ", server.Destination())
    60  	}
    61  
    62  	time.Sleep(2 * time.Second)
    63  	server = picker.PickServer()
    64  	if server.Destination().Port != 1 {
    65  		t.Error("server: ", server.Destination())
    66  	}
    67  	server = picker.PickServer()
    68  	if server.Destination().Port != 1 {
    69  		t.Error("server: ", server.Destination())
    70  	}
    71  }