Skip to content Search Apps Documentation Source Content File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

lru_test.gno

1.81 Kb · 76 lines
 1package lru
 2
 3import (
 4	"strconv"
 5	"testing"
 6
 7	"gno.land/p/nt/testutils/v0"
 8	"gno.land/p/nt/uassert/v0"
 9)
10
11func reset(cur realm) {
12	Reset(cross(cur))
13}
14
15func TestPutGetAndRecency(cur realm, t *testing.T) {
16	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("alice")))
17	reset(cur)
18
19	Put(cross(cur), "a", "1")
20	Put(cross(cur), "b", "2")
21
22	v, ok := Get(cross(cur), "a")
23	uassert.True(t, ok, "a should be present")
24	uassert.Equal(t, "1", v)
25
26	// miss
27	_, ok = Get(cross(cur), "zzz")
28	uassert.False(t, ok, "zzz should be absent")
29
30	// after Get("a"), a is MRU -> head
31	uassert.Equal(t, "a", c.head.key)
32	uassert.Equal(t, "b", c.tail.key)
33
34	// stats: 1 hit, 1 miss
35	uassert.Equal(t, 1, c.hits)
36	uassert.Equal(t, 1, c.miss)
37
38	// update existing key
39	Put(cross(cur), "b", "22")
40	v, _ = peek("b")
41	uassert.Equal(t, "22", v)
42	uassert.Equal(t, "b", c.head.key) // update marks MRU
43	uassert.Equal(t, 2, c.size)
44}
45
46func TestEviction(cur realm, t *testing.T) {
47	testing.SetRealm(testing.NewUserRealm(testutils.TestAddress("bob")))
48	reset(cur)
49
50	// fill beyond capacity (8): insert k0..k9
51	for i := 0; i < 10; i++ {
52		Put(cross(cur), "k"+strconv.Itoa(i), strconv.Itoa(i))
53	}
54
55	uassert.Equal(t, capacity, c.size)
56
57	// k0 and k1 should have been evicted (oldest inserts, never touched)
58	_, ok := peek("k0")
59	uassert.False(t, ok, "k0 should be evicted")
60	_, ok = peek("k1")
61	uassert.False(t, ok, "k1 should be evicted")
62
63	// newest is MRU head, k2 is now the LRU tail
64	uassert.Equal(t, "k9", c.head.key)
65	uassert.Equal(t, "k2", c.tail.key)
66
67	// touching k2 protects it; next insert evicts k3 instead
68	_, ok = Get(cross(cur), "k2")
69	uassert.True(t, ok, "k2 present")
70	Put(cross(cur), "k10", "10")
71	_, ok = peek("k2")
72	uassert.True(t, ok, "k2 protected after Get")
73	_, ok = peek("k3")
74	uassert.False(t, ok, "k3 evicted instead")
75	uassert.Equal(t, capacity, c.size)
76}