-
Notifications
You must be signed in to change notification settings - Fork 9
/
structs_encoding_test.go
129 lines (117 loc) · 2.59 KB
/
structs_encoding_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package web3
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"testing"
"text/template"
"github.com/stretchr/testify/assert"
)
type jsonEncoder interface {
json.Marshaler
json.Unmarshaler
}
func TestJSONEncoding(t *testing.T) {
var (
block = func() jsonEncoder { return new(Block) }
txn = func() jsonEncoder { return new(Transaction) }
)
cases := []struct {
Input string
build func() jsonEncoder
}{
{
Input: `{
"parentHash": "{{.Hash2}}",
"sha3Uncles": "{{.Hash3}}",
"miner": "{{.Addr1}}",
"stateRoot": "{{.Hash3}}",
"transactionsRoot": "{{.Hash1}}",
"receiptsRoot": "{{.Hash2}}",
"logsBloom": "{{.Bloom}}",
"difficulty": "0x5",
"number": "0x1",
"gasLimit": "0x2",
"gasUsed": "0x3",
"timestamp": "0x4",
"extraData": "0x01",
"mixHash": "{{.Hash2}}",
"nonce": "{{.Nonce}}",
"hash": "{{.Hash1}}",
"uncles": [
"{{.Hash1}}",
"{{.Hash2}}"
]
}`,
build: block,
},
{
Input: `{
"hash": "{{.Hash1}}",
"from": "{{.Addr1}}",
"input": "0x00",
"value": "0x0",
"gasPrice": "0x0",
"gas": "0x0",
"nonce": "0x10",
"to": null,
"v":"0x25",
"r":"{{.Hash1}}",
"s":"{{.Hash1}}",
"blockHash": "{{.Hash0}}",
"blockNumber": "0x0",
"transactionIndex": "0x0"
}`,
build: txn,
},
{
Input: `{
"hash": "{{.Hash1}}",
"from": "{{.Addr1}}",
"input": "0x00",
"value": "0x0",
"gasPrice": "0x0",
"gas": "0x0",
"nonce": "0x10",
"to": "{{.Addr1}}",
"v":"0x25",
"r":"{{.Hash1}}",
"s":"{{.Hash1}}",
"blockHash": "{{.Hash0}}",
"blockNumber": "0x0",
"transactionIndex": "0x0"
}`,
build: txn,
},
}
for _, c := range cases {
tmpl, err := template.New("test").Parse(c.Input)
assert.NoError(t, err)
config := map[string]string{}
for i := 0; i <= 3; i++ {
config[fmt.Sprintf("Hash%d", i)] = (Hash{byte(i)}).String()
config[fmt.Sprintf("Addr%d", i)] = (Address{byte(i)}).String()
}
config["Bloom"] = "0x" + hex.EncodeToString(make([]byte, 256))
config["Nonce"] = "0x" + hex.EncodeToString(make([]byte, 8))
buffer := new(bytes.Buffer)
assert.NoError(t, tmpl.Execute(buffer, config))
input := compactJSON(buffer.String())
obj := c.build()
// unmarshal
err = obj.UnmarshalJSON([]byte(input))
assert.NoError(t, err)
// now marshal
res2, err := obj.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, string(res2), input)
}
}
func compactJSON(s string) string {
buffer := new(bytes.Buffer)
if err := json.Compact(buffer, []byte(s)); err != nil {
panic(err)
}
return buffer.String()
}