kingofdice_test.gno
2.09 Kb · 85 lines
1package kingofdice
2
3import (
4 "strings"
5 "testing"
6
7 "gno.land/p/nt/avl/v0"
8 "gno.land/p/nt/testutils/v0"
9)
10
11// resetState clears package globals between tests.
12func resetState() {
13 players = avl.Tree{}
14 var zero address
15 king = zero
16 kingRoll = 0
17 reignSince = 0
18 nonce = 0
19 totalRolls = 0
20}
21
22func TestPseudoRollDeterministicAndRanged(t *testing.T) {
23 alice := testutils.TestAddress("alice")
24
25 r1 := pseudoRoll(alice, 1, 100)
26 r2 := pseudoRoll(alice, 1, 100)
27 if r1 != r2 {
28 t.Fatalf("same inputs must give same roll: %d != %d", r1, r2)
29 }
30 if r1 < 1 || r1 > 100 {
31 t.Fatalf("roll must be in [1, 100], got %d", r1)
32 }
33
34 r3 := pseudoRoll(alice, 2, 100)
35 if r1 == r3 {
36 t.Fatal("different nonce should (almost always) change the roll")
37 }
38}
39
40// Crossing test: takes `cur realm` so it can call crossing functions via
41// cross(cur). SetRealm is called directly in this frame.
42func TestRollCrownsFirstCallerThenSwapsOnHigherRoll(cur realm, t *testing.T) {
43 resetState()
44
45 alice := testutils.TestAddress("alice")
46 bob := testutils.TestAddress("bob")
47
48 testing.SetRealm(testing.NewUserRealm(alice))
49 Roll(cross(cur))
50 if !king.IsValid() {
51 t.Fatal("someone should be king after first roll")
52 }
53 firstKing := king
54
55 // Keep rolling as bob until bob out-rolls alice, or give up after a
56 // generous number of attempts (rolls are deterministic per nonce/height,
57 // so this always terminates locally).
58 testing.SetRealm(testing.NewUserRealm(bob))
59 for i := 0; i < 200 && king == firstKing; i++ {
60 Roll(cross(cur))
61 }
62
63 if get(alice).reigns != 1 {
64 t.Fatalf("alice should have exactly one recorded reign, got %d", get(alice).reigns)
65 }
66}
67
68func TestRenderShowsNoKingThenKing(cur realm, t *testing.T) {
69 resetState()
70 if !strings.Contains(Render(""), "No king yet") {
71 t.Fatal("expected empty-board placeholder")
72 }
73
74 alice := testutils.TestAddress("alice")
75 testing.SetRealm(testing.NewUserRealm(alice))
76 Roll(cross(cur))
77
78 out := Render("")
79 if !strings.Contains(out, "Current king") {
80 t.Fatal("expected current king section once someone rolled")
81 }
82 if !strings.Contains(out, "Blocks reigned") {
83 t.Fatal("expected leaderboard header")
84 }
85}