为什么我在假 K8s 客户端中收到错误的结果?

问题描述 投票:0回答:1

下面我有一个非常简单的测试和一个最小的工作示例。

在测试中,我将 4 个作业插入到我的假客户端中。然后,我删除与标签和命名空间匹配的所有作业。我用

// match
标记了应该删除的作业。其他 2 个工作应该保留。

当我运行这个时,我得到

Error:          "map[App1:%!s(bool=true) App2:%!s(bool=true) OtherApp:%!s(bool=true)]" should have 2 item(s), but has 3

为什么

App1
App2
OtherApp
没有被删除?这是假k8s客户端中的错误吗?

package somepackage

import (
    "context"
    "testing"

    "github.com/stretchr/testify/require"
    batchv1 "k8s.io/api/batch/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/apimachinery/pkg/labels"
    "k8s.io/apimachinery/pkg/runtime"

    fake2 "k8s.io/client-go/kubernetes/fake"
)

func TestFunc(t *testing.T) {
    myNamespace := "namespace"
    myLabels := map[string]string{"key": "value"}

    allJobs := []runtime.Object{
        &batchv1.Job{ // match
            ObjectMeta: metav1.ObjectMeta{
                Name:      "App1",
                Namespace: myNamespace,
                Labels:    myLabels,
            },
        }, &batchv1.Job{ // match
            ObjectMeta: metav1.ObjectMeta{
                Name:      "App2",
                Namespace: myNamespace,
                Labels:    myLabels,
            },
        }, &batchv1.Job{ // other namespace
            ObjectMeta: metav1.ObjectMeta{
                Name:      "App3",
                Namespace: "otherNamespace",
                Labels:    myLabels,
            },
        }, &batchv1.Job{ // other labels
            ObjectMeta: metav1.ObjectMeta{
                Name:      "OtherApp",
                Namespace: myNamespace,
                Labels:    map[string]string{"other": "label"},
            },
        },
    }

    cliSet := fake2.NewSimpleClientset(allJobs...)

    err := cliSet.BatchV1().Jobs(myNamespace).DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{
        LabelSelector: labels.FormatLabels(myLabels),
    })

    jobs, err := cliSet.BatchV1().Jobs(myNamespace).List(context.Background(), metav1.ListOptions{}) 

    require.NoError(t, err)

    jobNameSet := map[string]bool{}
    for _, job := range jobs.Items {
        jobNameSet[job.Name] = true
    }
    require.Len(t, jobNameSet, 2, "Expected 2 jobs after deletion")
    require.NotContains(t, jobNameSet, "App1")
    require.NotContains(t, jobNameSet, "App2")
    require.Contains(t, jobNameSet, "App3", "Should exist, because other namespace")
    require.Contains(t, jobNameSet, "OtherApp", "Should exist, because other labels")

}
unit-testing go kubernetes mocking
1个回答
0
投票

您可以使用

Delete

    err = cliSet.BatchV1().Jobs(myNamespace).Delete(context.TODO(), "App2", metav1.DeleteOptions{})

Clientset
由一个非常简单的对象跟踪器支持,但不支持
DeleteCollection

© www.soinside.com 2019 - 2024. All rights reserved.