github.com/koko1123/flow-go-1@v0.29.6/engine/consensus/approvals/approvals_lru_cache_test.go (about)

     1  package approvals
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/require"
     8  
     9  	"github.com/koko1123/flow-go-1/model/flow"
    10  	"github.com/koko1123/flow-go-1/utils/unittest"
    11  )
    12  
    13  // TestApprovalsCache_Get_Put_All tests common use cases for approvals cache.
    14  func TestApprovalsLRUCacheSecondaryIndexPurge(t *testing.T) {
    15  	numElements := uint(10)
    16  	cache := NewApprovalsLRUCache(numElements)
    17  	approvals := make([]*flow.ResultApproval, 2*numElements)
    18  	for i := range approvals {
    19  		approval := unittest.ResultApprovalFixture()
    20  		approvals[i] = approval
    21  		cache.Put(approval)
    22  		require.Equal(t, approval, cache.Get(approval.Body.PartialID()))
    23  	}
    24  
    25  	// LRU kept the last 10 approvals
    26  	for i := 10; i < 20; i++ {
    27  		approval := approvals[i]
    28  		require.Equal(t, approval, cache.Get(approval.Body.PartialID()))
    29  	}
    30  	require.Len(t, cache.byResultID, int(numElements))
    31  }
    32  
    33  func TestApprovalsLRUCacheSecondaryIndexPurgeConcurrently(t *testing.T) {
    34  	numElements := 100
    35  	cache := NewApprovalsLRUCache(uint(numElements))
    36  
    37  	var wg sync.WaitGroup
    38  
    39  	for i := 0; i < 2*numElements; i++ {
    40  		wg.Add(1)
    41  		go func() {
    42  			defer wg.Done()
    43  			approval := unittest.ResultApprovalFixture()
    44  			cache.Put(approval)
    45  		}()
    46  	}
    47  	wg.Wait()
    48  	require.Len(t, cache.byResultID, int(numElements))
    49  }