首页 > 解决方案 > 模拟运行时对象模拟 K8S

问题描述

我使用以下有效的功能。现在我需要在下面的函数中添加一个单元测试,但我没有找到一种简单的方法来模拟 k8s 的运行时对象。

这是功能

import(
"k8s.io/apimachinery/pkg/runtime"

)


func GetModified(obj runtime.Object, annotate bool, codec runtime.Encoder) ([]byte, error) {
    var modified []byte
    annotates, err := metadataAccessor.Annotations(obj)
    if err != nil {
        return nil, err
    }

    if annotates == nil {
        annotates = map[string]string{}
    }

    original := annotates[corev1.LastAppliedConfigAnnotation]
    delete(annotates, corev1.LastAppliedConfigAnnotation)
    if err := metadataAccessor.SetAnnotations(obj, annotates); err != nil {
        return nil, err
    }

    modified, err = runtime.Encode(codec, obj)
    if err != nil {
        return nil, err
    }

    if annotate {
        annotates[corev1.LastAppliedConfigAnnotation] = string(modified)
        if err := metadataAccessor.SetAnnotations(obj, annotates); err != nil {
            return nil, err
        }

        modified, err = runtime.Encode(codec, obj)
        if err != nil {
            return nil, err
        }
    }
    annotates[corev1.LastAppliedConfigAnnotation] = original
    if err := metadataAccessor.SetAnnotations(obj, annotates); err != nil {
        return nil, err
    }
    return modified, nil
}

我想为其创建一个单元测试,但不确定如何模拟运行时

obj runtime.Object codec runtime.Encoder

知道如何模拟这两个值进行单元测试吗?

这是单元测试

func TestGetModified(t *testing.T) {
    
    
    
    type args struct {
        obj      runtime.Object
        annotate bool
        codec    runtime.Encoder
    }
    // HERE I NEED TO PROVIDE THE RUNTIME OBJECT
    args{
        obj:      nil,
        annotate: false,
        codec:    nil,
    }

    tests := []struct {
        name    string
        args    args
        want    []byte
        wantErr bool
    }{{
        name: "test",
        args: ,
        want:    nil,
        wantErr: false,
    },

    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := GetModified(tt.args.obj, tt.args.annotate, tt.args.codec)
            if (err != nil) != tt.wantErr {
                t.Errorf("GetModified() error = %v, wantErr %v", err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("GetModified() got = %v, want %v", got, tt.want)
            }
        })
    }
}

标签: gokubernetes

解决方案


推荐阅读