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.

65 lines
1.3 KiB

  1. package common
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. // This is a trivial test for protobuf compatibility.
  9. func TestMarshal(t *testing.T) {
  10. bz := []byte("hello world")
  11. dataB := HexBytes(bz)
  12. bz2, err := dataB.Marshal()
  13. assert.Nil(t, err)
  14. assert.Equal(t, bz, bz2)
  15. var dataB2 HexBytes
  16. err = (&dataB2).Unmarshal(bz)
  17. assert.Nil(t, err)
  18. assert.Equal(t, dataB, dataB2)
  19. }
  20. // Test that the hex encoding works.
  21. func TestJSONMarshal(t *testing.T) {
  22. type TestStruct struct {
  23. B1 []byte
  24. B2 HexBytes
  25. }
  26. cases := []struct {
  27. input []byte
  28. expected string
  29. }{
  30. {[]byte(``), `{"B1":"","B2":""}`},
  31. {[]byte(``), `{"B1":"","B2":""}`},
  32. {[]byte(``), `{"B1":"","B2":""}`},
  33. }
  34. for i, tc := range cases {
  35. t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) {
  36. ts := TestStruct{B1: tc.input, B2: tc.input}
  37. // Test that it marshals correctly to JSON.
  38. jsonBytes, err := json.Marshal(ts)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. assert.Equal(t, string(jsonBytes), tc.expected)
  43. // TODO do fuzz testing to ensure that unmarshal fails
  44. // Test that unmarshaling works correctly.
  45. ts2 := TestStruct{}
  46. err = json.Unmarshal(jsonBytes, &ts2)
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. assert.Equal(t, ts2.B1, tc.input)
  51. assert.Equal(t, ts2.B2, HexBytes(tc.input))
  52. })
  53. }
  54. }