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.

73 lines
1.5 KiB

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