github.com/0xsequence/ethkit@v1.25.0/util/channel_test.go (about) 1 package util_test 2 3 import ( 4 "fmt" 5 "math/big" 6 "sync" 7 "testing" 8 "time" 9 10 "github.com/0xsequence/ethkit/ethmonitor" 11 "github.com/0xsequence/ethkit/go-ethereum/core/types" 12 "github.com/0xsequence/ethkit/util" 13 "github.com/goware/logger" 14 "github.com/stretchr/testify/assert" 15 ) 16 17 func TestSlowProducer(t *testing.T) { 18 testUnboundedBufferedChannel(t, 100*time.Millisecond, 0, 10) 19 } 20 21 func TestSlowConsumer(t *testing.T) { 22 testUnboundedBufferedChannel(t, 0, 100*time.Microsecond, 100) 23 } 24 25 func testUnboundedBufferedChannel(t *testing.T, producerDelay time.Duration, consumerDelay time.Duration, messages int) { 26 ch := make(chan ethmonitor.Blocks) 27 sendCh := util.MakeUnboundedChan(ch, logger.NewLogger(logger.LogLevel_INFO), 100) 28 29 var wg sync.WaitGroup 30 wg.Add(1) 31 32 go func() { 33 expected := 0 34 for blocks, ok := <-ch; ok; blocks, ok = <-ch { 35 fmt.Printf("received message %v\n", blocks[0].Number()) 36 time.Sleep(consumerDelay) 37 assert.Equal(t, expected, int(blocks[0].NumberU64())) 38 expected++ 39 } 40 41 assert.Equal(t, messages, expected) 42 wg.Done() 43 }() 44 45 for i := 0; i < messages; i++ { 46 fmt.Printf("sending message %v\n", i) 47 header := types.NewBlockWithHeader(&types.Header{Number: big.NewInt(int64(i))}) 48 sendCh <- ethmonitor.Blocks{ðmonitor.Block{Block: header}} 49 time.Sleep(producerDelay) 50 } 51 52 close(sendCh) 53 wg.Wait() 54 }