leaderboard_test.gno
2.66 Kb · 89 lines
1package leaderboard
2
3import (
4 "strings"
5 "testing"
6
7 "gno.land/p/nt/uassert/v0"
8)
9
10// resetState clears package globals between tests. Global-state reset belongs
11// in a helper; realm setup (SetRealm) must NOT — it only affects its own frame.
12func resetState() {
13 keys := []string{}
14 players.Iterate("", "", func(key string, _ any) bool {
15 keys = append(keys, key)
16 return false
17 })
18 for _, k := range keys {
19 players.Remove(k)
20 }
21}
22
23const (
24 alice = "g1alice00000000000000000000000000000000"
25 bob = "g1bob0000000000000000000000000000000000"
26 carol = "g1carol00000000000000000000000000000000"
27)
28
29// Crossing test: takes `cur realm` so it can call crossing functions via
30// cross(cur). SetRealm is called directly in this frame (never via a helper).
31func TestAddPointsAccumulatesAndRanks(cur realm, t *testing.T) {
32 resetState()
33
34 testing.SetRealm(testing.NewUserRealm(address(alice)))
35 AddPoints(cross(cur), 10)
36 AddPoints(cross(cur), 5) // accumulates -> 15
37
38 testing.SetRealm(testing.NewUserRealm(address(bob)))
39 AddPoints(cross(cur), 20)
40
41 uassert.Equal(t, 15, get(address(alice)).points, "alice points")
42 uassert.Equal(t, 20, get(address(bob)).points, "bob points")
43
44 // Ranking: bob (20) outranks alice (15).
45 ranked := snapshot()
46 uassert.Equal(t, 2, len(ranked), "player count")
47 uassert.Equal(t, bob, ranked[0].addr.String(), "rank 1 is bob")
48 uassert.Equal(t, alice, ranked[1].addr.String(), "rank 2 is alice")
49}
50
51func TestRenderTableWithMedalsAndName(cur realm, t *testing.T) {
52 resetState()
53
54 // Empty board.
55 uassert.True(t, strings.Contains(Render(""), "No players yet"), "empty placeholder")
56
57 testing.SetRealm(testing.NewUserRealm(address(alice)))
58 AddPoints(cross(cur), 30)
59 SetName(cross(cur), "Alice")
60
61 testing.SetRealm(testing.NewUserRealm(address(bob)))
62 AddPoints(cross(cur), 20)
63
64 testing.SetRealm(testing.NewUserRealm(address(carol)))
65 AddPoints(cross(cur), 10)
66
67 out := Render("")
68
69 uassert.True(t, strings.Contains(out, "| 🥇 | Alice | 30 |"), "Alice gold row")
70 uassert.True(t, strings.Contains(out, "🥈"), "silver medal present")
71 uassert.True(t, strings.Contains(out, "🥉"), "bronze medal present")
72 uassert.True(t, strings.Contains(out, "Total players: **3**"), "total players count")
73}
74
75func TestSetNameTooLongPanics(cur realm, t *testing.T) {
76 resetState()
77 testing.SetRealm(testing.NewUserRealm(address(alice)))
78 uassert.AbortsWithMessage(t, cur, "name too long (max 32)", func() {
79 SetName(cross(cur), strings.Repeat("x", 33))
80 })
81}
82
83func TestAddPointsRejectsNonPositive(cur realm, t *testing.T) {
84 resetState()
85 testing.SetRealm(testing.NewUserRealm(address(alice)))
86 uassert.AbortsWithMessage(t, cur, "points must be positive", func() {
87 AddPoints(cross(cur), 0)
88 })
89}