render_test.gno
2.27 Kb · 83 lines
1package lru
2
3import (
4 "strconv"
5 "strings"
6 "testing"
7
8 "gno.land/p/nt/uassert/v0"
9)
10
11// clear empties the cache without needing a realm argument, so examples (which
12// take no `cur`) can start from a known state. Examples run after all tests.
13func clear() {
14 c = &cache{index: make(map[string]*node)}
15}
16
17// ExampleRender pins the empty-cache view.
18func ExampleRender() {
19 clear()
20 print(Render(""))
21 // Output:
22 // # LRU Cache
23 //
24 // A fixed-capacity least-recently-used cache.
25 //
26 // ## Stats
27 //
28 // - Capacity: 8
29 // - Size: 0
30 // - Hits: 0
31 // - Misses: 0
32 // - Hit rate: n/a
33 //
34 // ## Entries (MRU → LRU)
35 //
36 // _empty_
37}
38
39// TestRenderListsEntriesMRUFirst checks the table is ordered most-recently-used
40// first and renumbered from 1.
41func TestRenderListsEntriesMRUFirst(cur realm, t *testing.T) {
42 reset(cur)
43 Put(cross(cur), "a", "1")
44 Put(cross(cur), "b", "2")
45 Put(cross(cur), "c", "3")
46 Get(cross(cur), "a") // a becomes MRU
47
48 out := Render("")
49 uassert.True(t, strings.Contains(out, "| 1 | a | 1 |\n| 2 | c | 3 |\n| 3 | b | 2 |\n"),
50 "entries should be listed MRU->LRU: a, c, b")
51 uassert.True(t, strings.Contains(out, "- Size: 3\n"), "size should be 3")
52}
53
54// TestRenderHitRate covers the integer-percent branch and the n/a branch.
55func TestRenderHitRate(cur realm, t *testing.T) {
56 reset(cur)
57 uassert.True(t, strings.Contains(Render(""), "- Hit rate: n/a\n"),
58 "no lookups yet should render n/a")
59
60 Put(cross(cur), "a", "1")
61 Get(cross(cur), "a") // hit
62 Get(cross(cur), "nope") // miss
63
64 out := Render("")
65 uassert.True(t, strings.Contains(out, "- Hits: 1\n"), "one hit")
66 uassert.True(t, strings.Contains(out, "- Misses: 1\n"), "one miss")
67 uassert.True(t, strings.Contains(out, "- Hit rate: 50%\n"), "1/2 should be 50%")
68}
69
70// TestRenderCapacityMatchesConst guards the header against a capacity change
71// that the pinned example would otherwise silently disagree with.
72func TestRenderCapacityMatchesConst(cur realm, t *testing.T) {
73 reset(cur)
74 uassert.True(t, strings.Contains(Render(""), "- Capacity: "+strconv.Itoa(capacity)+"\n"),
75 "rendered capacity should match the constant")
76}
77
78// TestRenderIgnoresPath documents that Render has no sub-routes.
79func TestRenderIgnoresPath(cur realm, t *testing.T) {
80 reset(cur)
81 Put(cross(cur), "k", "v")
82 uassert.Equal(t, Render(""), Render("/whatever"))
83}