blob: bf3926bf0c650092ad04dab65931ad9f0ff6bd42 [file] [log] [blame]
Dmitri Shuralyov7bf60f02023-02-28 19:12:21 -05001// Copyright 2011 The Go Authors. All rights reserved.
Brad Fitzpatrick1b1e0862015-06-04 18:25:50 -07002// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package lru
6
7import (
8 "reflect"
9 "testing"
10)
11
12func 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
46func 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}