-
Notifications
You must be signed in to change notification settings - Fork 16
/
hash_test.go
74 lines (57 loc) · 1.23 KB
/
hash_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
package header
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"testing"
"github.com/stretchr/testify/require"
)
func TestHash(t *testing.T) {
h := randHash()
buf, err := h.MarshalJSON()
require.NoError(t, err)
var h2 Hash
err = h2.UnmarshalJSON(buf)
require.NoError(t, err)
require.Equal(t, h.String(), h2.String())
}
func BenchmarkHashMarshaling(b *testing.B) {
h := randHash()
golden, err := h.MarshalJSON()
require.NoError(b, err)
b.ResetTimer()
b.Run("String", func(b *testing.B) {
wantSize := hex.EncodedLen(len(h))
for i := 0; i < b.N; i++ {
ln := len(h.String())
require.Equal(b, ln, wantSize)
}
})
b.Run("Marshal", func(b *testing.B) {
for i := 0; i < b.N; i++ {
buf, err := h.MarshalJSON()
require.NoError(b, err)
require.NotZero(b, buf)
}
})
b.Run("Unmarshal", func(b *testing.B) {
var h2 Hash
for i := 0; i < b.N; i++ {
err := h2.UnmarshalJSON(golden)
require.NoError(b, err)
}
})
}
func Fuzz_hexToUpper(f *testing.F) {
f.Add([]byte("48656c6c6f20476f7068657221"))
f.Fuzz(func(t *testing.T, buf []byte) {
hexToUpper(buf)
})
}
func randHash() Hash {
var buf [sha256.Size]byte
if _, err := rand.Read(buf[:]); err != nil {
panic(err)
}
return Hash(buf[:])
}