ringlog_test.gno
2.46 Kb · 126 lines
1package ringlog
2
3import (
4 "strconv"
5 "strings"
6 "testing"
7)
8
9func resetState() {
10 buf = [Cap]Entry{}
11 head = 0
12 count = 0
13}
14
15func TestPostAndRetrieve(t *testing.T) {
16 resetState()
17
18 Post("hello world")
19
20 if count != 1 {
21 t.Errorf("want count=1, got %d", count)
22 }
23 entries := Entries()
24 if len(entries) != 1 {
25 t.Fatalf("want 1 entry, got %d", len(entries))
26 }
27 if entries[0].Message != "hello world" {
28 t.Errorf("want 'hello world', got %q", entries[0].Message)
29 }
30}
31
32func TestLen(t *testing.T) {
33 resetState()
34
35 if Len() != 0 {
36 t.Errorf("want Len()=0, got %d", Len())
37 }
38 Post("a")
39 Post("b")
40 Post("c")
41 if Len() != 3 {
42 t.Errorf("want Len()=3, got %d", Len())
43 }
44}
45
46func TestRingWrap(t *testing.T) {
47 resetState()
48
49 // Write Cap+3 messages — the first 3 should be evicted.
50 for i := 0; i < Cap+3; i++ {
51 Post("msg" + strconv.Itoa(i))
52 }
53
54 if count != Cap {
55 t.Errorf("want count=%d after overflow, got %d", Cap, count)
56 }
57
58 entries := Entries()
59 if len(entries) != Cap {
60 t.Fatalf("want %d entries, got %d", Cap, len(entries))
61 }
62
63 // Oldest surviving message should be msg3 (msg0..msg2 were overwritten).
64 if entries[0].Message != "msg3" {
65 t.Errorf("oldest entry should be 'msg3', got %q", entries[0].Message)
66 }
67 // Newest message should be msg(Cap+2).
68 want := "msg" + strconv.Itoa(Cap+2)
69 if entries[Cap-1].Message != want {
70 t.Errorf("newest entry should be %q, got %q", want, entries[Cap-1].Message)
71 }
72}
73
74func TestChronologicalOrder(t *testing.T) {
75 resetState()
76
77 msgs := []string{"first", "second", "third"}
78 for _, m := range msgs {
79 Post(m)
80 }
81
82 entries := Entries()
83 for i, m := range msgs {
84 if entries[i].Message != m {
85 t.Errorf("entry[%d]: want %q, got %q", i, m, entries[i].Message)
86 }
87 }
88}
89
90func TestEmptyPanicsOnEmpty(t *testing.T) {
91 resetState()
92 defer func() {
93 if r := recover(); r == nil {
94 t.Error("expected panic on empty message, got none")
95 }
96 }()
97 Post(" ")
98}
99
100func TestTooLongPanics(t *testing.T) {
101 resetState()
102 defer func() {
103 if r := recover(); r == nil {
104 t.Error("expected panic on too-long message, got none")
105 }
106 }()
107 Post(strings.Repeat("x", 281))
108}
109
110func TestRender(t *testing.T) {
111 resetState()
112
113 r := Render("")
114 if !strings.Contains(r, "No messages yet") {
115 t.Error("empty ring should show 'No messages yet'")
116 }
117
118 Post("first message")
119 r = Render("")
120 if !strings.Contains(r, "first message") {
121 t.Error("render should include 'first message'")
122 }
123 if !strings.Contains(r, "RingLog") {
124 t.Error("render should include title 'RingLog'")
125 }
126}