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

     1  package counters_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/dgraph-io/badger/v2"
     7  	"github.com/stretchr/testify/require"
     8  
     9  	"github.com/onflow/flow-go/module"
    10  	"github.com/onflow/flow-go/module/counters"
    11  	bstorage "github.com/onflow/flow-go/storage/badger"
    12  	"github.com/onflow/flow-go/utils/unittest"
    13  )
    14  
    15  func TestMonotonicConsumer(t *testing.T) {
    16  	unittest.RunWithBadgerDB(t, func(db *badger.DB) {
    17  		var height1 = uint64(1234)
    18  		persistentStrictMonotonicCounter, err := counters.NewPersistentStrictMonotonicCounter(
    19  			bstorage.NewConsumerProgress(db, module.ConsumeProgressLastFullBlockHeight),
    20  			height1,
    21  		)
    22  		require.NoError(t, err)
    23  
    24  		// check value can be retrieved
    25  		actual := persistentStrictMonotonicCounter.Value()
    26  		require.Equal(t, height1, actual)
    27  
    28  		// try to update value with less than current
    29  		var lessHeight = uint64(1233)
    30  		err = persistentStrictMonotonicCounter.Set(lessHeight)
    31  		require.Error(t, err)
    32  		require.ErrorIs(t, err, counters.ErrIncorrectValue)
    33  
    34  		// update the value with bigger height
    35  		var height2 = uint64(1235)
    36  		err = persistentStrictMonotonicCounter.Set(height2)
    37  		require.NoError(t, err)
    38  
    39  		// check that the new value can be retrieved
    40  		actual = persistentStrictMonotonicCounter.Value()
    41  		require.Equal(t, height2, actual)
    42  
    43  		// check that new persistent strict monotonic counter has the same value
    44  		persistentStrictMonotonicCounter2, err := counters.NewPersistentStrictMonotonicCounter(
    45  			bstorage.NewConsumerProgress(db, module.ConsumeProgressLastFullBlockHeight),
    46  			height1,
    47  		)
    48  		require.NoError(t, err)
    49  
    50  		// check that the value still the same
    51  		actual = persistentStrictMonotonicCounter2.Value()
    52  		require.Equal(t, height2, actual)
    53  	})
    54  }