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

fix: jsonschema integer validation #852

Merged
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
4 changes: 4 additions & 0 deletions jsonschema/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ func Validate(schema Definition, data any) bool {
_, ok := data.(bool)
return ok
case Integer:
// Golang unmarshals all numbers as float64, so we need to check if the float64 is an integer
if num, ok := data.(float64); ok {
return num == float64(int64(num))
}
_, ok := data.(int)
return ok
case Null:
Expand Down
48 changes: 38 additions & 10 deletions jsonschema/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,6 @@ func TestUnmarshal(t *testing.T) {
content []byte
v any
}
var result1 struct {
String string `json:"string"`
Number float64 `json:"number"`
}
var result2 struct {
String string `json:"string"`
Number float64 `json:"number"`
}
tests := []struct {
name string
args args
Expand All @@ -108,7 +100,10 @@ func TestUnmarshal(t *testing.T) {
},
},
content: []byte(`{"string":"abc","number":123.4}`),
v: &result1,
v: &struct {
String string `json:"string"`
Number float64 `json:"number"`
}{},
}, false},
{"", args{
schema: jsonschema.Definition{
Expand All @@ -120,7 +115,40 @@ func TestUnmarshal(t *testing.T) {
Required: []string{"string", "number"},
},
content: []byte(`{"string":"abc"}`),
v: result2,
v: struct {
String string `json:"string"`
Number float64 `json:"number"`
}{},
}, true},
{"validate integer", args{
schema: jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"string": {Type: jsonschema.String},
"integer": {Type: jsonschema.Integer},
},
Required: []string{"string", "integer"},
},
content: []byte(`{"string":"abc","integer":123}`),
v: &struct {
String string `json:"string"`
Integer int `json:"integer"`
}{},
}, false},
{"validate integer failed", args{
schema: jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
"string": {Type: jsonschema.String},
"integer": {Type: jsonschema.Integer},
},
Required: []string{"string", "integer"},
},
content: []byte(`{"string":"abc","integer":123.4}`),
v: &struct {
String string `json:"string"`
Integer int `json:"integer"`
}{},
}, true},
}
for _, tt := range tests {
Expand Down
Loading