github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/module/counters/monotonous_counter_test.go (about)

     1  package counters
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/require"
     7  
     8  	"github.com/onflow/flow-go/utils/unittest"
     9  )
    10  
    11  func TestSet(t *testing.T) {
    12  	counter := NewMonotonousCounter(3)
    13  	require.True(t, counter.Set(4))
    14  	require.Equal(t, uint64(4), counter.Value())
    15  	require.False(t, counter.Set(2))
    16  	require.Equal(t, uint64(4), counter.Value())
    17  }
    18  
    19  func TestIncrement(t *testing.T) {
    20  	counter := NewMonotonousCounter(1)
    21  	require.Equal(t, uint64(2), counter.Increment())
    22  	require.Equal(t, uint64(3), counter.Increment())
    23  }
    24  
    25  // TestIncrementConcurrently tests that the MonotonousCounter's Increment method
    26  // works correctly when called concurrently from multiple goroutines
    27  func TestIncrementConcurrently(t *testing.T) {
    28  	counter := NewMonotonousCounter(0)
    29  
    30  	unittest.Concurrently(100, func(i int) {
    31  		counter.Increment()
    32  	})
    33  
    34  	require.Equal(t, uint64(100), counter.Value())
    35  }
    36  
    37  func TestFuzzy(t *testing.T) {
    38  	counter := NewMonotonousCounter(3)
    39  	require.True(t, counter.Set(4))
    40  	require.False(t, counter.Set(2))
    41  	require.True(t, counter.Set(7))
    42  	require.True(t, counter.Set(9))
    43  	require.True(t, counter.Set(12))
    44  	require.False(t, counter.Set(10))
    45  	require.True(t, counter.Set(18))
    46  
    47  	for i := 20; i < 100; i++ {
    48  		require.True(t, counter.Set(uint64(i)))
    49  	}
    50  
    51  	for i := 20; i < 100; i++ {
    52  		require.False(t, counter.Set(uint64(i)))
    53  	}
    54  }
    55  
    56  func TestConcurrent(t *testing.T) {
    57  	counter := NewMonotonousCounter(3)
    58  
    59  	unittest.Concurrently(100, func(i int) {
    60  		counter.Set(uint64(i))
    61  	})
    62  
    63  	require.Equal(t, uint64(99), counter.Value())
    64  }