You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.0 KiB

8 years ago
  1. package crypto_test
  2. import (
  3. "fmt"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/stretchr/testify/require"
  7. data "github.com/tendermint/go-wire/data"
  8. )
  9. type PubName struct {
  10. PubNameInner
  11. }
  12. type PubNameInner interface {
  13. AssertIsPubNameInner()
  14. String() string
  15. }
  16. func (p PubName) MarshalJSON() ([]byte, error) {
  17. return pubNameMapper.ToJSON(p.PubNameInner)
  18. }
  19. func (p *PubName) UnmarshalJSON(data []byte) error {
  20. parsed, err := pubNameMapper.FromJSON(data)
  21. if err == nil && parsed != nil {
  22. p.PubNameInner = parsed.(PubNameInner)
  23. }
  24. return err
  25. }
  26. var pubNameMapper = data.NewMapper(PubName{}).
  27. RegisterImplementation(PubNameFoo{}, "foo", 1).
  28. RegisterImplementation(PubNameBar{}, "bar", 2)
  29. func (f PubNameFoo) AssertIsPubNameInner() {}
  30. func (f PubNameBar) AssertIsPubNameInner() {}
  31. //----------------------------------------
  32. type PubNameFoo struct {
  33. Name string
  34. }
  35. func (f PubNameFoo) String() string { return "Foo: " + f.Name }
  36. type PubNameBar struct {
  37. Age int
  38. }
  39. func (b PubNameBar) String() string { return fmt.Sprintf("Bar #%d", b.Age) }
  40. //----------------------------------------
  41. // TestEncodeDemo tries the various strategies to encode the objects
  42. func TestEncodeDemo(t *testing.T) {
  43. assert, require := assert.New(t), require.New(t)
  44. cases := []struct {
  45. in, out PubNameInner
  46. expected string
  47. }{
  48. {PubName{PubNameFoo{"pub-foo"}}, &PubName{}, "Foo: pub-foo"},
  49. {PubName{PubNameBar{7}}, &PubName{}, "Bar #7"},
  50. }
  51. for i, tc := range cases {
  52. // Make sure it is proper to start
  53. require.Equal(tc.expected, tc.in.String())
  54. // Try to encode as binary
  55. b, err := data.ToWire(tc.in)
  56. if assert.Nil(err, "%d: %#v", i, tc.in) {
  57. err2 := data.FromWire(b, tc.out)
  58. if assert.Nil(err2) {
  59. assert.Equal(tc.expected, tc.out.String())
  60. }
  61. }
  62. // Try to encode it as json
  63. j, err := data.ToJSON(tc.in)
  64. if assert.Nil(err, "%d: %#v", i, tc.in) {
  65. err2 := data.FromJSON(j, tc.out)
  66. if assert.Nil(err2) {
  67. assert.Equal(tc.expected, tc.out.String())
  68. }
  69. }
  70. }
  71. }