I am trying to write unit test for my code, This is what i have defined as i need the annotation map from the admission review object which i get from http request.
package constants
type ObjectMeta struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
}
This is how i use this in my code to:
var objectMeta = constants.ObjectMeta{}
if err := json.Unmarshal(admissionReviewParsed.Request.Object.Raw, &objectMeta); err != nil {
logger.Error("Error in request Unmarshal: %s", err)
return nil, fmt.Sprint(err)
}
annotations := objectMeta.ObjectMeta.Annotations
This is my func to create a dummy admission review for unit testing :
func GetAdmissionReview() *v1beta1.AdmissionReview {
annotationMap := make(map[string]string)
annotationMap["k1"] = "v1"
uid := types.UID("test")
ObjectMeta := &metav1.ObjectMeta{
Name: "crd",
Annotations: annotationMap,
}
raw, err := json.Marshal(ObjectMeta)
if err != nil {
fmt.Println("error in marshaling", err)
}
testAdmissionRequest := &admissionv1.AdmissionRequest{
UID: uid,
Kind: metav1.GroupVersionKind{Group: "test", Version: "v1", Kind: "Crd"},
UserInfo: authv1.UserInfo{Username: "testuser"},
Object: runtime.RawExtension{
Raw: raw,
Object: runtime.Object(nil),
},
}
return &admissionv1.AdmissionReview{
TypeMeta: metav1.TypeMeta{
Kind: "AdmissionReview",
APIVersion: "admission.k8s.io/v1",
},
Request: testAdmissionRequest,
Response: &admissionv1.AdmissionResponse{
UID: uid,
Allowed: true,
Result: &metav1.Status{
Message: "testing",
},
},
}
}
but this gives me empty map when I unmarshall it during unit test.
I fixed the unit test if I redefine my struct as :
type ObjectMeta struct {
metav1.TypeMeta `json:"inline"`
Name string `json:"name"`
Annotations map[string]string `json:"annotations"`
}
But when i try to run the actual code with this in test cluster i get empty map for annotation in the code.
I think there is a type miss match but I dont know how to solve this. go lang doc : https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#ObjectMeta
how to fix this issue