github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/internal/pkg/gateway/commit/blocknotifier_test.go (about) 1 /* 2 Copyright hechain. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package commit 8 9 import ( 10 "sync" 11 "testing" 12 13 "github.com/hechain20/hechain/core/ledger" 14 "github.com/hechain20/hechain/internal/pkg/gateway/commit/mocks" 15 "github.com/stretchr/testify/require" 16 ) 17 18 //go:generate counterfeiter -o mocks/blocklistener.go --fake-name BlockListener . blockListener 19 20 func TestBlockNotifier(t *testing.T) { 21 t.Run("delivers events to listeners", func(t *testing.T) { 22 commitSend := make(chan *ledger.CommitNotification, 1) 23 listener := &mocks.BlockListener{} 24 var wait sync.WaitGroup 25 wait.Add(1) 26 listener.ReceiveBlockCalls(func(event *ledger.CommitNotification) { 27 wait.Done() 28 }) 29 notifier := newBlockNotifier(nil, commitSend, listener) 30 defer notifier.close() 31 32 commitSend <- &ledger.CommitNotification{ 33 BlockNumber: 1, 34 } 35 36 wait.Wait() 37 38 require.Equal(t, listener.ReceiveBlockArgsForCall(0).BlockNumber, uint64(1)) 39 }) 40 41 t.Run("closes listeners on failure to read event", func(t *testing.T) { 42 commitSend := make(chan *ledger.CommitNotification) 43 close(commitSend) 44 listener := &mocks.BlockListener{} 45 var wait sync.WaitGroup 46 wait.Add(1) 47 listener.CloseCalls(func() { 48 wait.Done() 49 }) 50 newBlockNotifier(nil, commitSend, listener) 51 52 wait.Wait() 53 54 require.Equal(t, listener.CloseCallCount(), 1) 55 }) 56 57 t.Run("close is idempotent", func(t *testing.T) { 58 listener := &mocks.BlockListener{} 59 notifier := newBlockNotifier(nil, nil, listener) 60 61 notifier.close() 62 notifier.close() 63 64 require.Equal(t, listener.CloseCallCount(), 1) 65 }) 66 }