github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/p2p/client_connector_test.go (about) 1 // Copyright 2021 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package p2p 15 16 import ( 17 "context" 18 "fmt" 19 "net" 20 "sync" 21 "sync/atomic" 22 "testing" 23 "time" 24 25 "github.com/phayes/freeport" 26 "github.com/pingcap/tiflow/pkg/security" 27 "github.com/pingcap/tiflow/proto/p2p" 28 "github.com/stretchr/testify/require" 29 "google.golang.org/grpc" 30 ) 31 32 type mockService struct { 33 callCount int32 34 } 35 36 func (s *mockService) SendMessage(server p2p.CDCPeerToPeer_SendMessageServer) error { 37 atomic.AddInt32(&s.callCount, 1) 38 return nil 39 } 40 41 func TestClientConnector(t *testing.T) { 42 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) 43 defer cancel() 44 mockService := &mockService{} 45 grpcServer := grpc.NewServer() 46 47 port := freeport.GetPort() 48 addr := fmt.Sprintf("127.0.0.1:%d", port) 49 lis, err := net.Listen("tcp", addr) 50 require.NoError(t, err) 51 52 p2p.RegisterCDCPeerToPeerServer(grpcServer, mockService) 53 54 var wg sync.WaitGroup 55 wg.Add(1) 56 go func() { 57 defer wg.Done() 58 _ = grpcServer.Serve(lis) 59 }() 60 61 cc := newClientConnector() 62 63 client, release, err := cc.Connect(clientConnectOptions{ 64 network: "tcp", 65 addr: addr, 66 credential: &security.Credential{}, 67 }) 68 require.NoError(t, err) 69 defer release() 70 71 _, err = client.SendMessage(ctx) 72 require.NoError(t, err) 73 74 require.Eventually(t, func() bool { 75 return atomic.LoadInt32(&mockService.callCount) == 1 76 }, time.Second*5, time.Millisecond*100) 77 78 cancel() 79 grpcServer.Stop() 80 wg.Wait() 81 }