...

Source file src/github.com/aws/smithy-go/container/private/cache/lru/lru_test.go

Documentation: github.com/aws/smithy-go/container/private/cache/lru

     1  package lru
     2  
     3  import "testing"
     4  
     5  func TestCache(t *testing.T) {
     6  	cache := New(4).(*lru)
     7  
     8  	// fill cache
     9  	cache.Put(1, 2)
    10  	cache.Put(2, 3)
    11  	cache.Put(3, 4)
    12  	cache.Put(4, 5)
    13  	assertEntry(t, cache, 1, 2)
    14  	assertEntry(t, cache, 2, 3)
    15  	assertEntry(t, cache, 3, 4)
    16  	assertEntry(t, cache, 4, 5)
    17  
    18  	// touch the last entry
    19  	cache.Get(1)
    20  	cache.Put(5, 6)
    21  	assertNoEntry(t, cache, 2)
    22  	assertEntry(t, cache, 3, 4)
    23  	assertEntry(t, cache, 4, 5)
    24  	assertEntry(t, cache, 1, 2)
    25  	assertEntry(t, cache, 5, 6)
    26  
    27  	// put something new, 3 should now be the oldest
    28  	cache.Put(6, 7)
    29  	assertNoEntry(t, cache, 3)
    30  	assertEntry(t, cache, 4, 5)
    31  	assertEntry(t, cache, 1, 2)
    32  	assertEntry(t, cache, 5, 6)
    33  	assertEntry(t, cache, 6, 7)
    34  
    35  	// touch something in the middle
    36  	cache.Get(5)
    37  	assertEntry(t, cache, 4, 5)
    38  	assertEntry(t, cache, 1, 2)
    39  	assertEntry(t, cache, 5, 6)
    40  	assertEntry(t, cache, 6, 7)
    41  
    42  	// put 3 new things, 5 should remain after the touch
    43  	cache.Put(7, 8)
    44  	cache.Put(8, 9)
    45  	cache.Put(9, 0)
    46  	assertNoEntry(t, cache, 4)
    47  	assertNoEntry(t, cache, 1)
    48  	assertNoEntry(t, cache, 6)
    49  	assertEntry(t, cache, 5, 6)
    50  	assertEntry(t, cache, 7, 8)
    51  	assertEntry(t, cache, 8, 9)
    52  	assertEntry(t, cache, 9, 0)
    53  }
    54  
    55  func assertEntry(t *testing.T, c *lru, k interface{}, v interface{}) {
    56  	e, ok := c.entries[k]
    57  	if !ok {
    58  		t.Errorf("expected entry %v=%v, but no entry found", k, v)
    59  	}
    60  	if actual := e.Value.(*element).value; actual != v {
    61  		t.Errorf("expected entry %v=%v, but got entry value %v", k, v, actual)
    62  	}
    63  }
    64  
    65  func assertNoEntry(t *testing.T, c *lru, k interface{}) {
    66  	if _, ok := c.Get(k); ok {
    67  		t.Errorf("expected no entry for %v, but one was found", k)
    68  	}
    69  }
    70  

View as plain text