Skip to content

Commit

Permalink
fix: jsonschema integer validation
Browse files Browse the repository at this point in the history
  • Loading branch information
WeiAnAn committed Sep 20, 2024
1 parent 194a03e commit 7831bde
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
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

0 comments on commit 7831bde

Please sign in to comment.