Created
December 4, 2022 11:05
-
-
Save fatih/04565624d9a9e2b9f09842f5f43d5c5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
corev1 "k8s.io/api/core/v1" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
) | |
func TestValidate(t *testing.T) { | |
tests := []struct { | |
name string | |
pod func(pod *corev1.Pod) | |
err string | |
}{ | |
{ | |
name: "valid pod", | |
}, | |
{ | |
name: "invalid pod, image is not set", | |
pod: func(pod *corev1.Pod) { | |
pod.Spec.Containers[0].Image = "" | |
}, | |
err: "container.Image is empty", | |
}, | |
{ | |
name: "invalid pod, ports is not set", | |
pod: func(pod *corev1.Pod) { | |
pod.Spec.Containers[0].Ports = nil | |
}, | |
err: "container.Ports is not set", | |
}, | |
} | |
for _, tt := range tests { | |
tt := tt | |
t.Run(tt.name, func(t *testing.T) { | |
pod := testPod() | |
if tt.pod != nil { | |
tt.pod(pod) | |
} | |
err := validate(pod) | |
// should it error? | |
if tt.err != "" { | |
if err == nil { | |
t.Fatal("validate should error, but got non-nil error") | |
return | |
} | |
if err.Error() != tt.err { | |
t.Errorf("err msg\nwant: %q\n got: %q", tt.err, err.Error()) | |
} | |
return | |
} | |
if err != nil { | |
t.Fatalf("validate error: %s", err) | |
} | |
}) | |
} | |
} | |
func testPod() *corev1.Pod { | |
return &corev1.Pod{ | |
ObjectMeta: metav1.ObjectMeta{ | |
Namespace: "default", | |
Name: "pod-123", | |
Annotations: map[string]string{ | |
"ready": "ensure that this annotation is set", | |
}, | |
}, | |
Spec: corev1.PodSpec{ | |
Containers: []corev1.Container{ | |
{ | |
Name: "some-container", | |
Image: "fatih/foo:test", | |
Command: []string{ | |
"./foo", | |
"--port=8800", | |
}, | |
Ports: []corev1.ContainerPort{ | |
{ | |
Name: "http", | |
ContainerPort: 8800, | |
Protocol: corev1.ProtocolTCP, | |
}, | |
}, | |
}, | |
}, | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment