github.com/unionj-cloud/go-doudou/v2@v2.3.5/toolkit/memberlist/transport_test.go (about) 1 package memberlist_test 2 3 import ( 4 "github.com/golang/mock/gomock" 5 . "github.com/smartystreets/goconvey/convey" 6 "github.com/unionj-cloud/go-doudou/v2/toolkit/memberlist" 7 memmock "github.com/unionj-cloud/go-doudou/v2/toolkit/memberlist/mock" 8 "io" 9 "net" 10 "strings" 11 "sync/atomic" 12 "testing" 13 "time" 14 15 "github.com/stretchr/testify/require" 16 ) 17 18 type testCountingWriter struct { 19 t *testing.T 20 numCalls *int32 21 } 22 23 func (tw testCountingWriter) Write(p []byte) (n int, err error) { 24 atomic.AddInt32(tw.numCalls, 1) 25 if !strings.Contains(string(p), "memberlist: Error accepting TCP connection") { 26 tw.t.Error("did not receive expected log message") 27 } 28 tw.t.Log("countingWriter:", string(p)) 29 return len(p), nil 30 } 31 32 func TestAddress_String(t *testing.T) { 33 addr := &memberlist.Address{ 34 Addr: "localhost:7946", 35 Name: "testNode", 36 } 37 require.Equal(t, "testNode (localhost:7946)", addr.String()) 38 39 addr = &memberlist.Address{ 40 Addr: "localhost:7946", 41 } 42 require.Equal(t, "localhost:7946", addr.String()) 43 } 44 45 func Test_shimNodeAwareTransport_WriteToAddress(t *testing.T) { 46 Convey("", t, func() { 47 ctrl := gomock.NewController(t) 48 defer ctrl.Finish() 49 nat := memmock.NewMockTransport(ctrl) 50 addr := memberlist.Address{ 51 Addr: "localhost:7946", 52 Name: "testNode", 53 } 54 now := time.Now() 55 msg := []byte("test message") 56 nat. 57 EXPECT(). 58 WriteTo(msg, addr.Addr). 59 AnyTimes(). 60 Return(now, nil) 61 62 s := memberlist.NewshimNodeAwareTransport(nat) 63 sendAt, err := s.WriteToAddress(msg, addr) 64 So(err, ShouldBeNil) 65 So(sendAt, ShouldResemble, now) 66 }) 67 } 68 69 type emptyReadNetConn struct { 70 net.Conn 71 } 72 73 func (c *emptyReadNetConn) Read(b []byte) (n int, err error) { 74 return 0, io.EOF 75 } 76 77 func (c *emptyReadNetConn) Close() error { 78 return nil 79 } 80 81 func Test_shimNodeAwareTransport_DialAddressTimeout(t1 *testing.T) { 82 Convey("", t1, func() { 83 ctrl := gomock.NewController(t1) 84 defer ctrl.Finish() 85 nat := memmock.NewMockTransport(ctrl) 86 addr := memberlist.Address{ 87 Addr: "localhost:7946", 88 Name: "testNode", 89 } 90 nat. 91 EXPECT(). 92 DialTimeout(addr.Addr, 10*time.Second). 93 AnyTimes(). 94 Return(&emptyReadNetConn{}, nil) 95 96 s := memberlist.NewshimNodeAwareTransport(nat) 97 _, err := s.DialAddressTimeout(addr, 10*time.Second) 98 So(err, ShouldBeNil) 99 }) 100 }