-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys_test.go
107 lines (90 loc) · 2.61 KB
/
keys_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package collections
import (
"bytes"
"sort"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
)
func TestUint64(t *testing.T) {
t.Run("bijectivity", func(t *testing.T) {
assertBijective(t, Uint64KeyEncoder, uint64(0x0123456789ABCDEF))
})
t.Run("empty", func(t *testing.T) {
var k uint64
require.Equal(t, []byte{0, 0, 0, 0, 0, 0, 0, 0}, Uint64KeyEncoder.Encode(k))
})
}
func TestStringKey(t *testing.T) {
t.Run("bijective", func(t *testing.T) {
assertBijective[string](t, StringKeyEncoder, "test")
})
t.Run("panics", func(t *testing.T) {
// invalid string key
require.Panics(t, func() {
invalid := []byte{0x1, 0x0, 0x3}
StringKeyEncoder.Encode(string(invalid))
})
// invalid bytes do not end with 0x0
require.Panics(t, func() {
StringKeyEncoder.Decode([]byte{0x1, 0x2})
})
// invalid size
require.Panics(t, func() {
StringKeyEncoder.Decode([]byte{0x1})
})
})
t.Run("empty string", func(t *testing.T) {
b := StringKeyEncoder.Encode("")
i, r := StringKeyEncoder.Decode(b)
require.Equal(t, 1, i)
require.Equal(t, "", r)
})
t.Run("proper ordering", func(t *testing.T) {
stringKeys := []string{
"a", "aa", "b", "c", "dd",
"1", "2", "3", "55", string([]byte{1}),
}
strings := make([]string, len(stringKeys))
bytesStringKeys := make([][]byte, len(stringKeys))
for i, sk := range stringKeys {
strings[i] = sk
bytesStringKeys[i] = StringKeyEncoder.Encode(sk)
}
sort.Strings(strings)
sort.Slice(bytesStringKeys, func(i, j int) bool {
return bytes.Compare(bytesStringKeys[i], bytesStringKeys[j]) < 0
})
for i, b := range bytesStringKeys {
expected := strings[i]
got := string(b[:len(b)-1]) // removes null termination
require.Equal(t, expected, got)
}
})
}
func TestAccAddressKey(t *testing.T) {
t.Run("bijective", func(t *testing.T) {
assertBijective[sdk.AccAddress](t, AccAddressKeyEncoder, sdk.AccAddress(secp256k1.GenPrivKey().PubKey().Address()))
})
}
func TestTimeKey(t *testing.T) {
t.Run("bijective", func(t *testing.T) {
key := time.Now()
assertBijective[time.Time](t, TimeKeyEncoder, key.Round(0).UTC())
})
}
func TestValAddressKey(t *testing.T) {
t.Run("bijective", func(t *testing.T) {
assertBijective(t, ValAddressKeyEncoder, sdk.ValAddress(secp256k1.GenPrivKey().PubKey().Address()))
})
}
func TestSdkDecKey(t *testing.T) {
t.Run("bijective", func(t *testing.T) {
assertBijective(t, SdkDecKeyEncoder, sdk.NewDec(123456789))
})
t.Run("zero dec", func(t *testing.T) {
assertBijective(t, SdkDecKeyEncoder, sdk.ZeroDec())
})
}