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

counter_test.gno

2.24 Kb · 81 lines
 1package counter
 2
 3import (
 4	"strings"
 5	"testing"
 6
 7	"gno.land/p/nt/testutils/v0"
 8	"gno.land/p/nt/uassert/v0"
 9)
10
11// TestIncDecReset drives the full mutation lifecycle across two callers and
12// checks value, total count, and history accounting.
13func TestIncDecReset(cur realm, t *testing.T) {
14	// reset package-level state for a clean run
15	value = 0
16	total = 0
17	history = nil
18
19	alice := testutils.TestAddress("alice")
20	bob := testutils.TestAddress("bob")
21
22	testing.SetRealm(testing.NewUserRealm(alice))
23	uassert.Equal(t, 1, Inc(cross(cur)))
24	uassert.Equal(t, 2, Inc(cross(cur)))
25
26	testing.SetRealm(testing.NewUserRealm(bob))
27	uassert.Equal(t, 1, Dec(cross(cur)))
28
29	uassert.Equal(t, 1, Value())
30	uassert.Equal(t, 3, Total())
31	uassert.Equal(t, 3, len(history))
32
33	// Reset should bring the value to zero with a delta of -1.
34	uassert.Equal(t, 0, Reset(cross(cur)))
35	uassert.Equal(t, 0, Value())
36	uassert.Equal(t, 4, Total())
37
38	last := history[len(history)-1]
39	uassert.Equal(t, -1, last.delta)
40	uassert.Equal(t, 0, last.value)
41	uassert.Equal(t, bob.String(), last.caller.String())
42}
43
44// TestHistoryCapAndRender checks the rolling 20-entry cap and that Render
45// reflects the current value and total.
46func TestHistoryCapAndRender(cur realm, t *testing.T) {
47	value = 0
48	total = 0
49	history = nil
50
51	caller := testutils.TestAddress("counter")
52	testing.SetRealm(testing.NewUserRealm(caller))
53
54	// Apply 25 increments; history must cap at maxHistory (20), total = 25.
55	for i := 0; i < 25; i++ {
56		Inc(cross(cur))
57	}
58
59	uassert.Equal(t, 25, Value())
60	uassert.Equal(t, 25, Total())
61	uassert.Equal(t, maxHistory, len(history))
62
63	// Oldest surviving entry should have value 6 (changes 1..5 dropped).
64	uassert.Equal(t, 6, history[0].value)
65
66	out := Render("")
67	uassert.True(t, strings.Contains(out, "# 25"), "render shows current value")
68	uassert.True(t, strings.Contains(out, "Total changes:"), "render shows total")
69	uassert.True(t, strings.Contains(out, "| +1 |"), "render shows a delta cell")
70}
71
72// TestRenderEmpty verifies the empty-state message before any mutations.
73func TestRenderEmpty(t *testing.T) {
74	value = 0
75	total = 0
76	history = nil
77
78	out := Render("")
79	uassert.True(t, strings.Contains(out, "No changes yet"), "shows empty state")
80	uassert.True(t, strings.Contains(out, "# 0"), "shows zero value")
81}