github.com/badrootd/celestia-core@v0.0.0-20240305091328-aa4207a4b25d/mempool/cache_test.go (about)

     1  package mempool
     2  
     3  import (
     4  	"crypto/rand"
     5  	"testing"
     6  
     7  	"github.com/badrootd/celestia-core/types"
     8  	"github.com/stretchr/testify/require"
     9  )
    10  
    11  func populate(cache TxCache, numTxs int) ([][]byte, error) {
    12  
    13  	txs := make([][]byte, numTxs)
    14  	for i := 0; i < numTxs; i++ {
    15  		// probability of collision is 2**-256
    16  		txBytes := make([]byte, 32)
    17  		_, err := rand.Read(txBytes)
    18  
    19  		if err != nil {
    20  			return nil, err
    21  		}
    22  
    23  		txs[i] = txBytes
    24  		cache.Push(txBytes)
    25  	}
    26  
    27  	return txs, nil
    28  }
    29  
    30  func TestCacheRemove(t *testing.T) {
    31  	cache := NewLRUTxCache(100)
    32  	numTxs := 10
    33  
    34  	txs, err := populate(cache, numTxs)
    35  	require.NoError(t, err)
    36  	require.Equal(t, numTxs, len(cache.cacheMap))
    37  	require.Equal(t, numTxs, cache.list.Len())
    38  
    39  	for i := 0; i < numTxs; i++ {
    40  		cache.Remove(txs[i])
    41  		// make sure its removed from both the map and the linked list
    42  		require.Equal(t, numTxs-(i+1), len(cache.cacheMap))
    43  		require.Equal(t, numTxs-(i+1), cache.list.Len())
    44  	}
    45  }
    46  
    47  func TestCacheRemoveByKey(t *testing.T) {
    48  	cache := NewLRUTxCache(100)
    49  	numTxs := 10
    50  
    51  	txs, err := populate(cache, numTxs)
    52  	require.NoError(t, err)
    53  	require.Equal(t, numTxs, len(cache.cacheMap))
    54  	require.Equal(t, numTxs, cache.list.Len())
    55  
    56  	for i := 0; i < numTxs; i++ {
    57  		cache.RemoveTxByKey(types.Tx(txs[i]).Key())
    58  		// make sure its removed from both the map and the linked list
    59  		require.Equal(t, numTxs-(i+1), len(cache.cacheMap))
    60  		require.Equal(t, numTxs-(i+1), cache.list.Len())
    61  	}
    62  }