github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/lru/lru_test.go (about)

     1  package lru
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/keybase/client/go/libkb"
     6  	"github.com/stretchr/testify/require"
     7  	"golang.org/x/net/context"
     8  	"testing"
     9  )
    10  
    11  type obj struct {
    12  	I int
    13  	S string
    14  }
    15  
    16  func (o obj) DbKey() libkb.DbKey {
    17  	return libkb.DbKey{Typ: 20, Key: o.S}
    18  }
    19  
    20  func (o obj) MemKey() string {
    21  	return o.S
    22  }
    23  
    24  func TestLRU(t *testing.T) {
    25  	tc := libkb.SetupTest(t, "TestLookup", 1)
    26  	defer tc.Cleanup()
    27  
    28  	var objs []obj
    29  
    30  	N := 10
    31  	for i := 0; i < N; i++ {
    32  		objs = append(objs, obj{i, fmt.Sprintf("%d", i)})
    33  	}
    34  
    35  	lru := NewLRU(tc.G, 2, 1, obj{})
    36  	ctx := context.TODO()
    37  
    38  	testPut := func(i int) {
    39  		err := lru.Put(ctx, tc.G, objs[i], &objs[i])
    40  		require.NoError(t, err)
    41  	}
    42  
    43  	testPut(0)
    44  	testPut(1)
    45  
    46  	var stats stats
    47  
    48  	testGet := func(i int, memHit bool) {
    49  		ret, err := lru.Get(ctx, tc.G, objs[i])
    50  		require.NoError(t, err)
    51  		require.Equal(t, ret, &objs[i])
    52  		if memHit {
    53  			stats.memHit++
    54  		} else {
    55  			stats.diskHit++
    56  		}
    57  	}
    58  
    59  	testMiss := func(i int, isStale bool) {
    60  		ret, err := lru.Get(ctx, tc.G, objs[i])
    61  		require.NoError(t, err)
    62  		require.Nil(t, ret)
    63  		if isStale {
    64  			stats.diskStale++
    65  		} else {
    66  			stats.miss++
    67  		}
    68  	}
    69  
    70  	testStats := func() {
    71  		require.Equal(t, stats, lru.stats)
    72  	}
    73  
    74  	testGet(0, true)
    75  	testGet(1, true)
    76  	testMiss(2, false)
    77  	testStats()
    78  	lru.ClearMemory()
    79  	testGet(0, false)
    80  	testGet(1, false)
    81  	testStats()
    82  
    83  	// All of the following should be disk hits
    84  	for i := 0; i < N; i++ {
    85  		testPut(i)
    86  	}
    87  	for i := 0; i < N; i++ {
    88  		testGet(i, false)
    89  	}
    90  	testStats()
    91  
    92  	// test that a put of the old version fails to get when we
    93  	// want the new version
    94  	testPut(0)
    95  	lru.ClearMemory()
    96  	lru.version = 2
    97  	testMiss(0, true)
    98  	testStats()
    99  }