github.com/outcaste-io/ristretto@v0.2.3/ring_test.go (about)

     1  package ristretto
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  type testConsumer struct {
    11  	push func([]uint64)
    12  	save bool
    13  }
    14  
    15  func (c *testConsumer) Push(items []uint64) bool {
    16  	if c.save {
    17  		c.push(items)
    18  		return true
    19  	}
    20  	return false
    21  }
    22  
    23  func TestRingDrain(t *testing.T) {
    24  	drains := 0
    25  	r := newRingBuffer(&testConsumer{
    26  		push: func(items []uint64) {
    27  			drains++
    28  		},
    29  		save: true,
    30  	}, 1)
    31  	for i := 0; i < 100; i++ {
    32  		r.Push(uint64(i))
    33  	}
    34  	require.Equal(t, 100, drains, "buffers shouldn't be dropped with BufferItems == 1")
    35  }
    36  
    37  func TestRingReset(t *testing.T) {
    38  	drains := 0
    39  	r := newRingBuffer(&testConsumer{
    40  		push: func(items []uint64) {
    41  			drains++
    42  		},
    43  		save: false,
    44  	}, 4)
    45  	for i := 0; i < 100; i++ {
    46  		r.Push(uint64(i))
    47  	}
    48  	require.Equal(t, 0, drains, "testConsumer shouldn't be draining")
    49  }
    50  
    51  func TestRingConsumer(t *testing.T) {
    52  	mu := &sync.Mutex{}
    53  	drainItems := make(map[uint64]struct{})
    54  	r := newRingBuffer(&testConsumer{
    55  		push: func(items []uint64) {
    56  			mu.Lock()
    57  			defer mu.Unlock()
    58  			for i := range items {
    59  				drainItems[items[i]] = struct{}{}
    60  			}
    61  		},
    62  		save: true,
    63  	}, 4)
    64  	for i := 0; i < 100; i++ {
    65  		r.Push(uint64(i))
    66  	}
    67  	l := len(drainItems)
    68  	require.NotEqual(t, 0, l)
    69  	require.True(t, l <= 100)
    70  }