瀏覽代碼

fix: unmarshal from number to string with incorrect error message (#3625)

Kevin Wan 1 年之前
父節點
當前提交
4f22034342
共有 3 個文件被更改,包括 15 次插入5 次删除
  1. 5 4
      core/mapping/unmarshaler.go
  2. 1 1
      core/mapping/unmarshaler_test.go
  3. 9 0
      core/mapping/yamlunmarshaler_test.go

+ 5 - 4
core/mapping/unmarshaler.go

@@ -19,9 +19,10 @@ import (
 )
 
 const (
-	defaultKeyName = "key"
-	delimiter      = '.'
-	ignoreKey      = "-"
+	defaultKeyName   = "key"
+	delimiter        = '.'
+	ignoreKey        = "-"
+	numberTypeString = "number"
 )
 
 var (
@@ -634,7 +635,7 @@ func (u *Unmarshaler) processFieldPrimitiveWithJSONNumber(fieldType reflect.Type
 
 		target.SetFloat(fValue)
 	default:
-		return newTypeMismatchErrorWithHint(fullName, typeKind.String(), value.Type().String())
+		return newTypeMismatchErrorWithHint(fullName, typeKind.String(), numberTypeString)
 	}
 
 	SetValue(fieldType, value, target)

+ 1 - 1
core/mapping/unmarshaler_test.go

@@ -5490,7 +5490,7 @@ func TestUnmarshalerProcessFieldPrimitiveWithJSONNumber(t *testing.T) {
 		err := m.processFieldPrimitiveWithJSONNumber(fieldType, value.Elem(), v,
 			&fieldOptionsWithContext{}, "field")
 		assert.Error(t, err)
-		assert.Equal(t, `type mismatch for field "field", expect "string", actual "int"`, err.Error())
+		assert.Equal(t, `type mismatch for field "field", expect "string", actual "number"`, err.Error())
 	})
 
 	t.Run("right type", func(t *testing.T) {

+ 9 - 0
core/mapping/yamlunmarshaler_test.go

@@ -1011,6 +1011,15 @@ func TestUnmarshalYamlMapRune(t *testing.T) {
 	assert.Equal(t, rune(3), v.Machine["node3"])
 }
 
+func TestUnmarshalYamlStringOfInt(t *testing.T) {
+	text := `password: 123456`
+	var v struct {
+		Password string `json:"password"`
+	}
+	reader := strings.NewReader(text)
+	assert.Error(t, UnmarshalYamlReader(reader, &v))
+}
+
 func TestUnmarshalYamlBadInput(t *testing.T) {
 	var v struct {
 		Any string