Skip to content

Commit

Permalink
feat: add detail type mismatch info in number fields check (#3386) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lxy1992 authored Jul 11, 2023
1 parent 77da459 commit b9c0c0f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
6 changes: 5 additions & 1 deletion core/mapping/unmarshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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]
Expand Down
27 changes: 27 additions & 0 deletions core/mapping/unmarshaler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package mapping
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"strings"
"testing"
Expand Down Expand Up @@ -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{})
Expand Down

0 comments on commit b9c0c0f

Please sign in to comment.