github.com/celestiaorg/celestia-node@v0.15.0-beta.1/share/p2p/peers/timedqueue_test.go (about) 1 package peers 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/benbjohnson/clock" 8 "github.com/libp2p/go-libp2p/core/peer" 9 "github.com/stretchr/testify/require" 10 ) 11 12 func TestTimedQueue(t *testing.T) { 13 t.Run("push item", func(t *testing.T) { 14 peers := []peer.ID{"peer1", "peer2"} 15 ttl := time.Second 16 17 popCh := make(chan struct{}, 1) 18 queue := newTimedQueue(ttl, func(id peer.ID) { 19 go func() { 20 require.Contains(t, peers, id) 21 popCh <- struct{}{} 22 }() 23 }) 24 mock := clock.NewMock() 25 queue.clock = mock 26 27 // push first item | global time : 0 28 queue.push(peers[0]) 29 require.Equal(t, queue.len(), 1) 30 31 // push second item with ttl/2 gap | global time : ttl/2 32 mock.Add(ttl / 2) 33 queue.push(peers[1]) 34 require.Equal(t, queue.len(), 2) 35 36 // advance clock 1 nano sec before first item should expire | global time : ttl - 1 37 mock.Add(ttl/2 - 1) 38 // check that releaseExpired doesn't remove items 39 queue.releaseExpired() 40 require.Equal(t, queue.len(), 2) 41 // first item should be released after its own timeout | global time : ttl 42 mock.Add(1) 43 44 select { 45 case <-popCh: 46 case <-time.After(ttl): 47 t.Fatal("first item is not released") 48 49 } 50 require.Equal(t, queue.len(), 1) 51 52 // first item should be released after ttl/2 gap timeout | global time : 3/2*ttl 53 mock.Add(ttl / 2) 54 select { 55 case <-popCh: 56 case <-time.After(ttl): 57 t.Fatal("second item is not released") 58 } 59 require.Equal(t, queue.len(), 0) 60 }) 61 }