github.com/avicd/go-utilx@v0.1.0/bufx/lru_test.go (about)

     1  package bufx
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/stretchr/testify/assert"
     6  	"sync"
     7  	"testing"
     8  )
     9  
    10  func TestLruCache_Put(t *testing.T) {
    11  	size := 1000
    12  	cache := &LruCache[int, string]{Size: size}
    13  	count := 0
    14  	var keys []int
    15  	cond := sync.NewCond(&sync.Mutex{})
    16  	mutex := sync.Mutex{}
    17  	testTotal := 5000
    18  	for i := 0; i < 100; i++ {
    19  		go func(id int) {
    20  			for j := 0; j < testTotal/100; j++ {
    21  				key := id*100 + j
    22  				cache.Put(key, fmt.Sprintf("key:%d", key))
    23  				mutex.Lock()
    24  				count++
    25  				if count > testTotal-size {
    26  					keys = append(keys, key)
    27  				}
    28  				mutex.Unlock()
    29  				if count == testTotal {
    30  					cond.Signal()
    31  				}
    32  			}
    33  		}(i)
    34  	}
    35  	cond.L.Lock()
    36  	cond.Wait()
    37  	assert.Equal(t, len(keys), cache.Len())
    38  	for _, id := range keys {
    39  		go func(key int) {
    40  			val, ok := cache.Get(key)
    41  			assert.Equal(t, true, ok)
    42  			assert.Equal(t, fmt.Sprintf("key:%d", key), val)
    43  		}(id)
    44  	}
    45  }
    46  
    47  func TestLruCache_Get(t *testing.T) {
    48  	cache := &LruCache[int, int]{Size: 3}
    49  	cache.Put(0, 1)
    50  	cache.Put(1, 1)
    51  	cache.Put(2, 1)
    52  	cache.Get(0)
    53  	cache.Put(3, 1)
    54  	val, ok := cache.Get(1)
    55  	assert.Equal(t, 3, cache.Len())
    56  	assert.Equal(t, false, ok)
    57  	assert.Equal(t, 0, val)
    58  }