github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/storage/cache/lfu/lfu_test.go (about)

     1  package lfu
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  func TestLFU(t *testing.T) {
     8  	c := New()
     9  	c.Set("a", "a")
    10  	if v := c.Get("a"); v != "a" {
    11  		t.Errorf("Value was not saved: %v != 'a'", v)
    12  	}
    13  	if l := c.Len(); l != 1 {
    14  		t.Errorf("Length was not updated: %v != 1", l)
    15  	}
    16  
    17  	c.Set("b", "b")
    18  	if v := c.Get("b"); v != "b" {
    19  		t.Errorf("Value was not saved: %v != 'b'", v)
    20  	}
    21  	if l := c.Len(); l != 2 {
    22  		t.Errorf("Length was not updated: %v != 2", l)
    23  	}
    24  
    25  	c.Get("a")
    26  	evicted := c.Evict(1)
    27  	if v := c.Get("a"); v != "a" {
    28  		t.Errorf("Value was improperly evicted: %v != 'a'", v)
    29  	}
    30  	if v := c.Get("b"); v != nil {
    31  		t.Errorf("Value was not evicted: %v", v)
    32  	}
    33  	if l := c.Len(); l != 1 {
    34  		t.Errorf("Length was not updated: %v != 1", l)
    35  	}
    36  	if evicted != 1 {
    37  		t.Errorf("Number of evicted items is wrong: %v != 1", evicted)
    38  	}
    39  }
    40  
    41  func TestEviction(t *testing.T) {
    42  	ch := make(chan Eviction, 1)
    43  
    44  	c := New()
    45  	c.EvictionChannel = ch
    46  	c.Set("a", "b")
    47  	c.Evict(1)
    48  
    49  	ev := <-ch
    50  
    51  	if ev.Key != "a" || ev.Value.(string) != "b" {
    52  		t.Error("Incorrect item")
    53  	}
    54  }
    55  
    56  func TestEvictionOrder(t *testing.T) {
    57  	c := New()
    58  	c.Set("a1", 1)
    59  	c.Set("a2", 2)
    60  	c.Set("a3", 3)
    61  	c.Get("a1")
    62  	c.Evict(2)
    63  
    64  	if e := c.Get("a1"); e == nil {
    65  		t.Error("Incorrect eviction order")
    66  	}
    67  }