forked from umbracle/ethgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
structs_encoding_test.go
103 lines (91 loc) · 2.02 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
package web3
import (
"bytes"
"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: `{
"number": "0x1",
"hash": "{{.Hash1}}",
"parentHash": "{{.Hash2}}",
"sha3Uncles": "{{.Hash3}}",
"transactionsRoot": "{{.Hash1}}",
"stateRoot": "{{.Hash3}}",
"receiptsRoot": "{{.Hash2}}",
"miner": "{{.Addr1}}",
"gasLimit": "0x2",
"gasUsed": "0x3",
"timestamp": "0x4",
"difficulty": "0x5",
"extraData": "0x01",
"uncles": [
"{{.Hash1}}",
"{{.Hash2}}"
]
}`,
build: block,
},
{
Input: `{
"hash": "{{.Hash1}}",
"from": "{{.Addr1}}",
"input": "0x00",
"value": "0x0",
"gasPrice": "0x0",
"gas": "0x0",
"nonce": "0x10",
"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()
}
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()
}