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.

66 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(`a`), `{"B1":"YQ==","B2":"61"}`},
  32. {[]byte(`abc`), `{"B1":"YWJj","B2":"616263"}`},
  33. }
  34. for i, tc := range cases {
  35. tc := tc
  36. t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) {
  37. ts := TestStruct{B1: tc.input, B2: tc.input}
  38. // Test that it marshals correctly to JSON.
  39. jsonBytes, err := json.Marshal(ts)
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. assert.Equal(t, string(jsonBytes), tc.expected)
  44. // TODO do fuzz testing to ensure that unmarshal fails
  45. // Test that unmarshaling works correctly.
  46. ts2 := TestStruct{}
  47. err = json.Unmarshal(jsonBytes, &ts2)
  48. if err != nil {
  49. t.Fatal(err)
  50. }
  51. assert.Equal(t, ts2.B1, tc.input)
  52. assert.Equal(t, ts2.B2, HexBytes(tc.input))
  53. })
  54. }
  55. }