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 17, 2024
1 parent 194a03e commit f1be751
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 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
28 changes: 28 additions & 0 deletions jsonschema/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ func TestUnmarshal(t *testing.T) {
String string `json:"string"`
Number float64 `json:"number"`
}
var result3 struct {
String string `json:"string"`
Integer int `json:"integer"`
}
tests := []struct {
name string
args args
Expand Down Expand Up @@ -122,6 +126,30 @@ func TestUnmarshal(t *testing.T) {
content: []byte(`{"string":"abc"}`),
v: result2,
}, 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: &result3,
}, 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: &result3,
}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit f1be751

Please sign in to comment.