Skip to content

Commit

Permalink
added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jewei1997 committed Jul 29, 2024
1 parent dfc009e commit 26414c1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
4 changes: 4 additions & 0 deletions libs/bytes/bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ func (bz HexBytes) Format(s fmt.State, verb rune) {
}
}

// Matches the hexbytes MarshalJSON of tendermint/tendermint. Overrides the
// default []byte Marshal implementation. This is basically the point of hex bytes.
func (bz HexBytes) MarshalJSON() ([]byte, error) {
s := strings.ToUpper(hex.EncodeToString(bz))
jbz := make([]byte, len(s)+2)
Expand All @@ -79,6 +81,8 @@ func (bz HexBytes) MarshalJSON() ([]byte, error) {
return jbz, nil
}

// Matches the hexbytes UnmarshalJSON of tendermint/tendermint. Overrides the
// default []byte Marshal implementation. This is basically the point of hex bytes.
func (bz *HexBytes) UnmarshalJSON(data []byte) error {
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
return fmt.Errorf("invalid hex string: %s", data)
Expand Down
38 changes: 38 additions & 0 deletions libs/bytes/bytes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,41 @@ func TestHexBytes_String(t *testing.T) {
t.Fatal(err)
}
}

// Define a struct to match the JSON structure
type ValidatorsHash struct {
NextValidatorsHash HexBytes `json:"next_validators_hash"`
}

func TestMarshalBasic(t *testing.T) {
var vh ValidatorsHash
vh.NextValidatorsHash = []byte("abc")
bz, err := json.Marshal(vh)
if err != nil {
t.Fatal(err)
}
assert.Equal(t, string(bz), "{\"next_validators_hash\":\"616263\"}")
}

func TestUnmarshalBasic(t *testing.T) {
jsonData := []byte(`{"next_validators_hash":"616263"}`)
var vh ValidatorsHash
err := json.Unmarshal(jsonData, &vh)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %v", err)
return
}
assert.Equal(t, string(vh.NextValidatorsHash), "abc")
}

func TestUnmarshalExample(t *testing.T) {
jsonData := []byte(`{"next_validators_hash":"20021C2FB4B2DDFF6E8C484A2ED5862910E3AD7074FC6AD1C972AD34891AE3A4"}`)
expectedLength := 32
var vh ValidatorsHash
err := json.Unmarshal(jsonData, &vh)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %v", err)
return
}
assert.Equal(t, expectedLength, len(vh.NextValidatorsHash))
}

0 comments on commit 26414c1

Please sign in to comment.