golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/lru/cache_test.go (about)

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package lru
     6  
     7  import (
     8  	"reflect"
     9  	"testing"
    10  )
    11  
    12  func TestLRU(t *testing.T) {
    13  	c := New(2)
    14  
    15  	expectMiss := func(k string) {
    16  		v, ok := c.Get(k)
    17  		if ok {
    18  			t.Fatalf("expected cache miss on key %q but hit value %v", k, v)
    19  		}
    20  	}
    21  
    22  	expectHit := func(k string, ev interface{}) {
    23  		v, ok := c.Get(k)
    24  		if !ok {
    25  			t.Fatalf("expected cache(%q)=%v; but missed", k, ev)
    26  		}
    27  		if !reflect.DeepEqual(v, ev) {
    28  			t.Fatalf("expected cache(%q)=%v; but got %v", k, ev, v)
    29  		}
    30  	}
    31  
    32  	expectMiss("1")
    33  	c.Add("1", "one")
    34  	expectHit("1", "one")
    35  
    36  	c.Add("2", "two")
    37  	expectHit("1", "one")
    38  	expectHit("2", "two")
    39  
    40  	c.Add("3", "three")
    41  	expectHit("3", "three")
    42  	expectHit("2", "two")
    43  	expectMiss("1")
    44  }
    45  
    46  func TestRemoveOldest(t *testing.T) {
    47  	c := New(2)
    48  	c.Add("1", "one")
    49  	c.Add("2", "two")
    50  	if k, v := c.RemoveOldest(); k != "1" || v != "one" {
    51  		t.Fatalf("oldest = %q, %q; want 1, one", k, v)
    52  	}
    53  	if k, v := c.RemoveOldest(); k != "2" || v != "two" {
    54  		t.Fatalf("oldest = %q, %q; want 2, two", k, v)
    55  	}
    56  	if k, v := c.RemoveOldest(); k != nil || v != nil {
    57  		t.Fatalf("oldest = %v, %v; want \"\", nil", k, v)
    58  	}
    59  }