7 "github.com/stretchr/testify/assert"
8 "github.com/stretchr/testify/require"
9 data "github.com/tendermint/go-wire/data"
16 type PubNameInner interface {
17 AssertIsPubNameInner()
21 func (p PubName) MarshalJSON() ([]byte, error) {
22 return pubNameMapper.ToJSON(p.PubNameInner)
25 func (p *PubName) UnmarshalJSON(data []byte) error {
26 parsed, err := pubNameMapper.FromJSON(data)
27 if err == nil && parsed != nil {
28 p.PubNameInner = parsed.(PubNameInner)
33 var pubNameMapper = data.NewMapper(PubName{}).
34 RegisterImplementation(PubNameFoo{}, "foo", 1).
35 RegisterImplementation(PubNameBar{}, "bar", 2)
37 func (f PubNameFoo) AssertIsPubNameInner() {}
38 func (f PubNameBar) AssertIsPubNameInner() {}
40 //----------------------------------------
42 type PubNameFoo struct {
46 func (f PubNameFoo) String() string { return "Foo: " + f.Name }
48 type PubNameBar struct {
52 func (b PubNameBar) String() string { return fmt.Sprintf("Bar #%d", b.Age) }
54 //----------------------------------------
56 // TestEncodeDemo tries the various strategies to encode the objects
57 func TestEncodeDemo(t *testing.T) {
58 assert, require := assert.New(t), require.New(t)
64 {PubName{PubNameFoo{"pub-foo"}}, &PubName{}, "Foo: pub-foo"},
65 {PubName{PubNameBar{7}}, &PubName{}, "Bar #7"},
68 for i, tc := range cases {
70 // Make sure it is proper to start
71 require.Equal(tc.expected, tc.in.String())
73 // Try to encode as binary
74 b, err := data.ToWire(tc.in)
75 if assert.Nil(err, "%d: %#v", i, tc.in) {
76 err2 := data.FromWire(b, tc.out)
78 assert.Equal(tc.expected, tc.out.String())
82 // Try to encode it as json
83 j, err := data.ToJSON(tc.in)
84 if assert.Nil(err, "%d: %#v", i, tc.in) {
85 err2 := data.FromJSON(j, tc.out)
87 assert.Equal(tc.expected, tc.out.String())