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.

74 lines
1.6 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.NoError(t, err)
  15. assert.Equal(t, bz, bz2)
  16. var dataB2 HexBytes
  17. err = (&dataB2).Unmarshal(bz)
  18. assert.NoError(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. {[]byte("\x1a\x2b\x3c"), `{"B1":"Gis8","B2":"1A2B3C"}`},
  35. }
  36. for i, tc := range cases {
  37. tc := tc
  38. t.Run(fmt.Sprintf("Case %d", i), func(t *testing.T) {
  39. ts := TestStruct{B1: tc.input, B2: tc.input}
  40. // Test that it marshals correctly to JSON.
  41. jsonBytes, err := json.Marshal(ts)
  42. if err != nil {
  43. t.Fatal(err)
  44. }
  45. assert.Equal(t, string(jsonBytes), tc.expected)
  46. // TODO do fuzz testing to ensure that unmarshal fails
  47. // Test that unmarshaling works correctly.
  48. ts2 := TestStruct{}
  49. err = json.Unmarshal(jsonBytes, &ts2)
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. assert.Equal(t, ts2.B1, tc.input)
  54. assert.Equal(t, ts2.B2, HexBytes(tc.input))
  55. })
  56. }
  57. }
  58. func TestHexBytes_String(t *testing.T) {
  59. hs := HexBytes([]byte("test me"))
  60. if _, err := strconv.ParseInt(hs.String(), 16, 64); err != nil {
  61. t.Fatal(err)
  62. }
  63. }