github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/utils/lru/lru_test.go (about)

     1  package lru
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/Asutorufa/yuhaiin/pkg/utils/assert"
     7  )
     8  
     9  func TestLru(t *testing.T) {
    10  	l := New(WithCapacity[string, string](4))
    11  
    12  	l.Add("a", "a")
    13  	l.Add("b", "b")
    14  	l.Add("c", "c")
    15  
    16  	c, ok := l.Load("b")
    17  	assert.Equal(t, true, ok)
    18  	assert.Equal(t, "b", c)
    19  
    20  	c, ok = l.Load("a")
    21  	assert.Equal(t, true, ok)
    22  	assert.Equal(t, "a", c)
    23  
    24  	c, ok = l.Load("c")
    25  	assert.Equal(t, true, ok)
    26  	assert.Equal(t, "c", c)
    27  
    28  	l.Add("d", "d")
    29  	l.Add("e", "e")
    30  
    31  	_, ok = l.Load("b")
    32  	assert.Equal(t, false, ok)
    33  	_, ok = l.Load("a")
    34  	assert.Equal(t, true, ok)
    35  
    36  	assert.Equal(t, true, l.ValueExist("a"))
    37  	assert.Equal(t, false, l.ValueExist("b"))
    38  	assert.Equal(t, true, l.ValueExist("c"))
    39  	assert.Equal(t, true, l.ValueExist("d"))
    40  	assert.Equal(t, true, l.ValueExist("e"))
    41  }
    42  
    43  func BenchmarkNewLru(b *testing.B) {
    44  	l := New[string, string]()
    45  
    46  	l.Add("a", "a")
    47  	l.Add("b", "b")
    48  	l.Add("c", "c")
    49  
    50  	b.RunParallel(func(p *testing.PB) {
    51  		for p.Next() {
    52  			l.Load("a")
    53  		}
    54  	})
    55  }