feat: add detail type mismatch info in number fields check (#3386) (#3387)

master
Xinyan Lu 1 year ago committed by GitHub
parent 77da459165
commit b9c0c0f8b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -618,7 +618,7 @@ func (u *Unmarshaler) processFieldPrimitiveWithJSONNumber(fieldType reflect.Type
target.SetFloat(fValue)
default:
return newTypeMismatchError(fullName)
return newTypeMismatchErrorWithHint(fullName, value.Type().String(), typeKind.String())
}
SetValue(fieldType, value, target)
@ -1054,6 +1054,10 @@ func newTypeMismatchError(name string) error {
return fmt.Errorf("type mismatch for field %q", name)
}
func newTypeMismatchErrorWithHint(name, errorType, rightType string) error {
return fmt.Errorf("type mismatch for field %q, expected %q, got %q", name, rightType, errorType)
}
func readKeys(key string) []string {
cacheKeysLock.Lock()
keys, ok := cacheKeys[key]

@ -3,6 +3,7 @@ package mapping
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
@ -4981,6 +4982,32 @@ func TestUnmarshaler_Unmarshal(t *testing.T) {
})
}
// TestUnmarshalerProcessFieldPrimitiveWithJSONNumber test the number type check.
func TestUnmarshalerProcessFieldPrimitiveWithJSONNumber(t *testing.T) {
t.Run("wrong type", func(t *testing.T) {
expectValue := "1"
realValue := 1
fieldType := reflect.TypeOf(expectValue)
value := reflect.ValueOf(&realValue) // pass a pointer to the value
v := json.Number(expectValue)
m := NewUnmarshaler("field")
err := m.processFieldPrimitiveWithJSONNumber(fieldType, value.Elem(), v, &fieldOptionsWithContext{}, "field")
assert.Error(t, err)
assert.Equal(t, "type mismatch for field \"field\", expected \"string\", got \"int\"", err.Error())
})
t.Run("right type", func(t *testing.T) {
expectValue := int64(1)
realValue := int64(1)
fieldType := reflect.TypeOf(expectValue)
value := reflect.ValueOf(&realValue) // pass a pointer to the value
v := json.Number(strconv.FormatInt(expectValue, 10))
m := NewUnmarshaler("field")
err := m.processFieldPrimitiveWithJSONNumber(fieldType, value.Elem(), v, &fieldOptionsWithContext{}, "field")
assert.NoError(t, err)
})
}
func TestGetValueWithChainedKeys(t *testing.T) {
t.Run("no key", func(t *testing.T) {
_, ok := getValueWithChainedKeys(nil, []string{})

Loading…
Cancel
Save