forked from varshard/merkletree
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode_test.go
103 lines (81 loc) · 1.91 KB
/
node_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
package merkletree
import (
"crypto/sha256"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewNode(t *testing.T) {
data := []byte("hello, world")
expectation := sha256.Sum256(data)
node := NewNode(data)
assert.Equal(t, expectation[:], node.Hash)
}
func TestNewParentNode(t *testing.T) {
left := Node{
Hash: []byte("1"),
}
right := Node{
Hash: []byte("2"),
}
n := NewParentNode(&left, &right)
assert.Equal(t, n.Left.Hash, left.Hash)
assert.Equal(t, n.Right.Hash, right.Hash)
concatedHash := sha256.Sum256(append(left.Hash, right.Hash...))
assert.Equal(t, n.Hash, concatedHash[:])
}
func TestNewParentWithOddNode(t *testing.T) {
left := Node{
Hash: []byte("1"),
}
n := NewParentNode(&left, nil)
assert.NotNil(t, n.Left)
assert.Nil(t, n.Right)
assert.Equal(t, n.Hash, left.Hash)
}
func TestMarshalNode(t *testing.T) {
n := Node{
Hash: []byte("1"),
}
marshaled, err := json.Marshal(n)
assert.NoError(t, err)
unmarshaledNode := Node{}
unmarshaledNode.FromJSON(marshaled)
assert.Equal(t, n, unmarshaledNode)
}
func TestMarshalNestedNode(t *testing.T) {
left := Node{
Hash: []byte("1"),
}
right := Node{
Hash: []byte("2"),
}
n := NewParentNode(&left, &right)
marshaled, err := json.Marshal(n)
assert.NoError(t, err)
unmarshaledNode := Node{}
assert.NoError(t, unmarshaledNode.FromJSON(marshaled))
assert.Equal(t, n, &unmarshaledNode)
}
func TestMarshal2LevelNode(t *testing.T) {
left1 := Node{
Hash: []byte("1"),
}
right1 := Node{
Hash: []byte("2"),
}
parentLeft := NewParentNode(&left1, &right1)
left2 := Node{
Hash: []byte("3"),
}
right2 := Node{
Hash: []byte("4"),
}
parentRight := NewParentNode(&left2, &right2)
n := NewParentNode(parentLeft, parentRight)
marshaled, err := json.Marshal(n)
assert.NoError(t, err)
unmarshaledNode := Node{}
assert.NoError(t, unmarshaledNode.FromJSON(marshaled))
assert.Equal(t, n, &unmarshaledNode)
}