Skip to content

Commit

Permalink
Add custom UnmarshalJSON for bytesize type (#4289)
Browse files Browse the repository at this point in the history
* Add custom UnmarshalJSON for bytesize type

* Add more test case

* Fix limits test
  • Loading branch information
kavirajk authored Sep 8, 2021
1 parent 1c90b9c commit a4b8974
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
12 changes: 12 additions & 0 deletions pkg/util/flagext/bytesize.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package flagext

import (
"encoding/json"
"strings"

"github.com/c2h5oh/datasize"
Expand Down Expand Up @@ -44,3 +45,14 @@ func (bs *ByteSize) UnmarshalYAML(unmarshal func(interface{}) error) error {

return bs.Set(str)
}

// UnmarshalJSON implements json.Unmarsal interface to work with JSON.
func (bs *ByteSize) UnmarshalJSON(val []byte) error {
var str string

if err := json.Unmarshal(val, &str); err != nil {
return err
}

return bs.Set(str)
}
37 changes: 37 additions & 0 deletions pkg/util/flagext/bytesize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package flagext
import (
"testing"

"encoding/json"

"github.com/stretchr/testify/require"
"gopkg.in/yaml.v2"
)
Expand Down Expand Up @@ -102,3 +104,38 @@ func Test_ByteSizeYAML(t *testing.T) {
})
}
}

func Test_ByteSizeJSON(t *testing.T) {
for _, tc := range []struct {
in string
err bool
out ByteSize
}{
{
in: `{ "bytes": "256GB" }`,
out: ByteSize(256 << 30),
},
{
// JSON shouldn't allow to set integer as value for ByteSize field.
in: `{ "bytes": 2.62144e+07 }`,
err: true,
},
{
in: `{ "bytes": "abc" }`,
err: true,
},
} {
t.Run(tc.in, func(t *testing.T) {
var out struct {
Bytes ByteSize `json:"bytes"`
}
err := json.Unmarshal([]byte(tc.in), &out)
if tc.err {
require.NotNil(t, err)
} else {
require.Nil(t, err)
require.Equal(t, tc.out, out.Bytes)
}
})
}
}
2 changes: 1 addition & 1 deletion pkg/validation/limits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ per_tenant_override_period: 230s
"reject_old_samples_max_age": "40s",
"creation_grace_period": "50s",
"enforce_metric_name": true,
"max_line_size": 60,
"max_line_size": "60",
"max_line_size_truncate": true,
"max_streams_per_user": 70,
"max_global_streams_per_user": 80,
Expand Down

0 comments on commit a4b8974

Please sign in to comment.