Skip to content

Commit

Permalink
Add tests to ensure type coercion handles errors correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
liggitt authored and deads2k committed Jul 2, 2018
1 parent a04b2e9 commit 95a270e
Showing 1 changed file with 55 additions and 8 deletions.
63 changes: 55 additions & 8 deletions pkg/api/compatibility_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
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",
Expand All @@ -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(`{
Expand All @@ -144,9 +176,18 @@ 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 {",
},
}

for i := range testcases {
Expand All @@ -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 {
t.Error(err)
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) {
Expand Down

0 comments on commit 95a270e

Please sign in to comment.