validators_test.gno
2.42 Kb ยท 101 lines
1package validators
2
3import (
4 "std"
5 "testing"
6
7 "gno.land/p/demo/avl"
8 "gno.land/p/demo/testutils"
9 "gno.land/p/demo/uassert"
10 "gno.land/p/demo/ufmt"
11 "gno.land/p/sys/validators"
12)
13
14// generateTestValidators generates a dummy validator set
15func generateTestValidators(count int) []validators.Validator {
16 vals := make([]validators.Validator, 0, count)
17
18 for i := 0; i < count; i++ {
19 val := validators.Validator{
20 Address: testutils.TestAddress(ufmt.Sprintf("%d", i)),
21 PubKey: "public-key",
22 VotingPower: 10,
23 }
24
25 vals = append(vals, val)
26 }
27
28 return vals
29}
30
31func TestValidators_AddRemove(t *testing.T) {
32 // Clear any changes
33 changes = avl.NewTree()
34
35 var (
36 vals = generateTestValidators(100)
37 initialHeight = int64(123)
38 )
39
40 // Add in the validators
41 for _, val := range vals {
42 addValidator(val)
43
44 // Make sure the validator is added
45 uassert.True(t, vp.IsValidator(val.Address))
46
47 testing.SkipHeights(1)
48 }
49
50 for i := initialHeight; i < initialHeight+int64(len(vals)); i++ {
51 // Make sure the changes are saved
52 chs := GetChanges(i)
53
54 // We use the funky index calculation to make sure
55 // changes are properly handled for each block span
56 uassert.Equal(t, initialHeight+int64(len(vals))-i, int64(len(chs)))
57
58 for index, val := range vals[i-initialHeight:] {
59 // Make sure the changes are equal to the additions
60 ch := chs[index]
61
62 uassert.Equal(t, val.Address, ch.Address)
63 uassert.Equal(t, val.PubKey, ch.PubKey)
64 uassert.Equal(t, val.VotingPower, ch.VotingPower)
65 }
66 }
67
68 // Save the beginning height for the removal
69 initialRemoveHeight := std.ChainHeight()
70
71 // Clear any changes
72 changes = avl.NewTree()
73
74 // Remove the validators
75 for _, val := range vals {
76 removeValidator(val.Address)
77
78 // Make sure the validator is removed
79 uassert.False(t, vp.IsValidator(val.Address))
80
81 testing.SkipHeights(1)
82 }
83
84 for i := initialRemoveHeight; i < initialRemoveHeight+int64(len(vals)); i++ {
85 // Make sure the changes are saved
86 chs := GetChanges(i)
87
88 // We use the funky index calculation to make sure
89 // changes are properly handled for each block span
90 uassert.Equal(t, initialRemoveHeight+int64(len(vals))-i, int64(len(chs)))
91
92 for index, val := range vals[i-initialRemoveHeight:] {
93 // Make sure the changes are equal to the additions
94 ch := chs[index]
95
96 uassert.Equal(t, val.Address, ch.Address)
97 uassert.Equal(t, val.PubKey, ch.PubKey)
98 uassert.Equal(t, uint64(0), ch.VotingPower)
99 }
100 }
101}