Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom UnmarshalJSON for bytesize type #4289

Merged
merged 3 commits into from
Sep 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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" }`,
dannykopping marked this conversation as resolved.
Show resolved Hide resolved
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