Skip to content

Commit

Permalink
tests(cdc): fix data race in TestMessageClientBasics (#4417)
Browse files Browse the repository at this point in the history
ref #3825
  • Loading branch information
liuzix authored Jan 20, 2022
1 parent c04f715 commit 962d115
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
3 changes: 1 addition & 2 deletions pkg/p2p/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,7 @@ func TestMessageClientBasics(t *testing.T) {
sender.AssertExpectations(t)

// Test point 7: Interrupt the connection
grpcStream.ExpectedCalls = nil
grpcStream.Calls = nil
grpcStream.ResetMock()

sender.ExpectedCalls = nil
sender.Calls = nil
Expand Down
26 changes: 22 additions & 4 deletions pkg/p2p/mock_grpc_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@ package p2p

import (
"context"
"sync"
"sync/atomic"

"github.com/pingcap/tiflow/proto/p2p"
"github.com/stretchr/testify/mock"
"google.golang.org/grpc"
)

//nolint:unused
type mockSendMessageClient struct {
mu sync.Mutex
mock.Mock
// embeds an empty interface
p2p.CDCPeerToPeer_SendMessageClient
Expand All @@ -41,13 +42,24 @@ func newMockSendMessageClient(ctx context.Context) *mockSendMessageClient {
}

func (s *mockSendMessageClient) Send(packet *p2p.MessagePacket) error {
s.mu.Lock()
defer s.mu.Unlock()

args := s.Called(packet)
atomic.AddInt32(&s.msgCount, 1)
return args.Error(0)
}

func (s *mockSendMessageClient) Recv() (*p2p.SendMessageResponse, error) {
args := s.Called()
var args mock.Arguments
func() {
// We use a deferred Unlock in case `s.Called()` panics.
s.mu.Lock()
defer s.mu.Unlock()

args = s.MethodCalled("Recv")
}()

if err := args.Error(1); err != nil {
return nil, err
}
Expand All @@ -66,12 +78,18 @@ func (s *mockSendMessageClient) Context() context.Context {
return s.ctx
}

//nolint:unused
func (s *mockSendMessageClient) ResetMock() {
s.mu.Lock()
defer s.mu.Unlock()

s.ExpectedCalls = nil
s.Calls = nil
}

type mockCDCPeerToPeerClient struct {
mock.Mock
}

//nolint:unused
func (c *mockCDCPeerToPeerClient) SendMessage(
ctx context.Context, opts ...grpc.CallOption,
) (p2p.CDCPeerToPeer_SendMessageClient, error) {
Expand Down

0 comments on commit 962d115

Please sign in to comment.