OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / go-crypto / embed_test.go
1 package crypto_test
2
3 import (
4         "fmt"
5         "testing"
6
7         "github.com/stretchr/testify/assert"
8         "github.com/stretchr/testify/require"
9         data "github.com/tendermint/go-wire/data"
10 )
11
12 type PubName struct {
13         PubNameInner
14 }
15
16 type PubNameInner interface {
17         AssertIsPubNameInner()
18         String() string
19 }
20
21 func (p PubName) MarshalJSON() ([]byte, error) {
22         return pubNameMapper.ToJSON(p.PubNameInner)
23 }
24
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)
29         }
30         return err
31 }
32
33 var pubNameMapper = data.NewMapper(PubName{}).
34         RegisterImplementation(PubNameFoo{}, "foo", 1).
35         RegisterImplementation(PubNameBar{}, "bar", 2)
36
37 func (f PubNameFoo) AssertIsPubNameInner() {}
38 func (f PubNameBar) AssertIsPubNameInner() {}
39
40 //----------------------------------------
41
42 type PubNameFoo struct {
43         Name string
44 }
45
46 func (f PubNameFoo) String() string { return "Foo: " + f.Name }
47
48 type PubNameBar struct {
49         Age int
50 }
51
52 func (b PubNameBar) String() string { return fmt.Sprintf("Bar #%d", b.Age) }
53
54 //----------------------------------------
55
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)
59
60         cases := []struct {
61                 in, out  PubNameInner
62                 expected string
63         }{
64                 {PubName{PubNameFoo{"pub-foo"}}, &PubName{}, "Foo: pub-foo"},
65                 {PubName{PubNameBar{7}}, &PubName{}, "Bar #7"},
66         }
67
68         for i, tc := range cases {
69
70                 // Make sure it is proper to start
71                 require.Equal(tc.expected, tc.in.String())
72
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)
77                         if assert.Nil(err2) {
78                                 assert.Equal(tc.expected, tc.out.String())
79                         }
80                 }
81
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)
86                         if assert.Nil(err2) {
87                                 assert.Equal(tc.expected, tc.out.String())
88                         }
89                 }
90         }
91 }