Add tests to ensure type coercion handles errors correctly
@@ -116,15 +116,17 @@ func TestAllowedGrouplessVersion(t *testing.T) {
func TestAllowedTypeCoercion(t *testing.T) {
ten := int64(10)
+ twenty := int32(10)
testcases := []struct {
name string
input []byte
into runtime.Object
expected runtime.Object
+ expectedErr string
}{
{
- name: "string to number",
+ name: "string to int64",
input: []byte(`{
"kind":"Pod",
"apiVersion":"v1",
@@ -135,6 +137,36 @@ func TestAllowedTypeCoercion(t *testing.T) {
Spec: v1.PodSpec{ActiveDeadlineSeconds: &ten},
},
},
+ {
+ name: "string to int64 malformed",
+ input: []byte(`{
+ "kind":"Pod",
+ "apiVersion":"v1",
+ "spec":{"activeDeadlineSeconds":"1.1"}
+ }`),
+ expectedErr: "read int64: unexpected character: \"",
+ },
+ {
+ name: "string to int32",
+ input: []byte(`{
+ "kind":"Pod",
+ "apiVersion":"v1",
+ "spec":{"priority":"10"}
+ }`),
+ expected: &v1.Pod{
+ TypeMeta: metav1.TypeMeta{Kind: "Pod", APIVersion: "v1"},
+ Spec: v1.PodSpec{Priority: &twenty},
+ },
+ },
+ {
+ name: "string to int32 malformed",
+ input: []byte(`{
+ "kind":"Pod",
+ "apiVersion":"v1",
+ "spec":{"priority":"1.1"}
+ }`),
+ expectedErr: "read int32: unexpected character: \"",
+ },
{
name: "empty object to array",
input: []byte(`{
@@ -144,8 +176,17 @@ func TestAllowedTypeCoercion(t *testing.T) {
}`),
expected: &v1.Pod{
TypeMeta: metav1.TypeMeta{Kind: "Pod", APIVersion: "v1"},
- Spec: v1.PodSpec{Containers: []v1.Container{}},
+ Spec: v1.PodSpec{Containers: nil},
+ },
},
+ {
+ name: "non-empty object to array fails",
+ input: []byte(`{
+ "kind":"Pod",
+ "apiVersion":"v1",
+ "spec":{"containers":{"name":"somevalue"}}
+ }`),
+ expectedErr: "v1.PodSpec.Containers: decode slice: expect [ or n, but found {",
},
}
@@ -155,8 +196,14 @@ func TestAllowedTypeCoercion(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
s := jsonserializer.NewSerializer(jsonserializer.DefaultMetaFactory, legacyscheme.Scheme, legacyscheme.Scheme, false)
obj, _, err := s.Decode(tc.input, nil, tc.into)
- if err != nil {
+ if err != nil || len(tc.expectedErr) > 0 {
+ if len(tc.expectedErr) == 0 {
t.Error(err)
+ } else if err == nil {
+ t.Errorf("expected error %q, got none", tc.expectedErr)
+ } else if !strings.Contains(err.Error(), tc.expectedErr) {
+ t.Errorf("expected error %q, got %q", tc.expectedErr, err.Error())
+ }
return
}
if !reflect.DeepEqual(obj, tc.expected) {
