Skip to content

Commit

Permalink
Fix HexNumber MarshalJSON (#139)
Browse files Browse the repository at this point in the history
* Fix HexNumber MarshalJSON

* Add more test cases
  • Loading branch information
tw-daniel authored Sep 25, 2023
1 parent 8e1feec commit d2333c4
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
2 changes: 1 addition & 1 deletion types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
type HexNumber big.Int

func (i HexNumber) MarshalJSON() ([]byte, error) {
hexNumber := fmt.Sprintf("\"0x%x\"", (*big.Int)(&i).Uint64())
hexNumber := fmt.Sprintf("\"0x%x\"", (*big.Int)(&i))

return []byte(hexNumber), nil
}
Expand Down
66 changes: 66 additions & 0 deletions types/types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package types

import (
"encoding/json"
"math/big"
"testing"

"github.com/stretchr/testify/assert"
)

func TestHex_UnmarshalAndMarshalJSON(t *testing.T) {
tests := []struct {
name string
input []byte
result string
isError bool
}{
{
name: "value greater than 2^64 -1",
input: []byte(`{"value":"0x850a9af493d065b6c"}`),
result: "153386322112866048876",
isError: false,
},
{
name: "value less than 2^64 -1",
input: []byte(`{"value":"0x746a528800"}`),
result: "500000000000",
isError: false,
},
{
name: "error case: not hex (string)",
input: []byte(`{"value":"error_value"}`),
result: "",
isError: true,
},
{
name: "error case: not hex (octal)",
input: []byte(`{"value":"20502515364447501455554"}`),
result: "",
isError: true,
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
type req struct {
Value *HexNumber `json:"value"`
}

var v req

err := json.Unmarshal(tc.input, &v)
if tc.isError {
return
}
assert.NoError(t, err)

output := (*big.Int)(v.Value)
assert.Equal(t, tc.result, output.String())

bytes, err := json.Marshal(v)
assert.NoError(t, err)
assert.Equal(t, tc.input, bytes)
})
}
}

0 comments on commit d2333c4

Please sign in to comment.