forked from tendermint/go-crypto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embed_test.go
91 lines (71 loc) · 1.97 KB
/
embed_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
package crypto_test
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
data "github.com/tendermint/go-wire/data"
)
type PubName struct {
PubNameInner
}
type PubNameInner interface {
AssertIsPubNameInner()
String() string
}
func (p PubName) MarshalJSON() ([]byte, error) {
return pubNameMapper.ToJSON(p.PubNameInner)
}
func (p *PubName) UnmarshalJSON(data []byte) error {
parsed, err := pubNameMapper.FromJSON(data)
if err == nil && parsed != nil {
p.PubNameInner = parsed.(PubNameInner)
}
return err
}
var pubNameMapper = data.NewMapper(PubName{}).
RegisterImplementation(PubNameFoo{}, "foo", 1).
RegisterImplementation(PubNameBar{}, "bar", 2)
func (f PubNameFoo) AssertIsPubNameInner() {}
func (f PubNameBar) AssertIsPubNameInner() {}
//----------------------------------------
type PubNameFoo struct {
Name string
}
func (f PubNameFoo) String() string { return "Foo: " + f.Name }
type PubNameBar struct {
Age int
}
func (b PubNameBar) String() string { return fmt.Sprintf("Bar #%d", b.Age) }
//----------------------------------------
// TestEncodeDemo tries the various strategies to encode the objects
func TestEncodeDemo(t *testing.T) {
assert, require := assert.New(t), require.New(t)
cases := []struct {
in, out PubNameInner
expected string
}{
{PubName{PubNameFoo{"pub-foo"}}, &PubName{}, "Foo: pub-foo"},
{PubName{PubNameBar{7}}, &PubName{}, "Bar #7"},
}
for i, tc := range cases {
// Make sure it is proper to start
require.Equal(tc.expected, tc.in.String())
// Try to encode as binary
b, err := data.ToWire(tc.in)
if assert.Nil(err, "%d: %#v", i, tc.in) {
err2 := data.FromWire(b, tc.out)
if assert.Nil(err2) {
assert.Equal(tc.expected, tc.out.String())
}
}
// Try to encode it as json
j, err := data.ToJSON(tc.in)
if assert.Nil(err, "%d: %#v", i, tc.in) {
err2 := data.FromJSON(j, tc.out)
if assert.Nil(err2) {
assert.Equal(tc.expected, tc.out.String())
}
}
}
}