Skip to content

Instantly share code, notes, and snippets.

@fatih
Created December 4, 2022 11:05
Show Gist options
  • Select an option

  • Save fatih/04565624d9a9e2b9f09842f5f43d5c5c to your computer and use it in GitHub Desktop.

Select an option

Save fatih/04565624d9a9e2b9f09842f5f43d5c5c to your computer and use it in GitHub Desktop.

Revisions

  1. fatih created this gist Dec 4, 2022.
    94 changes: 94 additions & 0 deletions example.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,94 @@
    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,
    },
    },
    },
    },
    },
    }
    }