Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added unit tests for mutatingwebhook.go #114

Merged
merged 5 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
cloud.google.com/go/storage v1.34.1
github.com/container-storage-interface/spec v1.9.0
github.com/go-logr/logr v1.3.0
github.com/google/go-cmp v0.6.0
github.com/google/uuid v1.4.0
github.com/kubernetes-csi/csi-lib-utils v0.15.0
github.com/kubernetes-csi/csi-test/v5 v5.1.0
Expand Down Expand Up @@ -62,7 +63,6 @@ require (
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/cel-go v0.16.1 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.1-0.20210504230335-f78f29fc09ea // indirect
github.com/google/pprof v0.0.0-20231101202521-4ca4178f5c7a // indirect
github.com/google/s2a-go v0.1.7 // indirect
Expand Down
195 changes: 195 additions & 0 deletions pkg/webhook/mutatingwebhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
/*
Copyright 2018 The Kubernetes Authors.
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package webhook

import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
v1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

func TestValidateMutatingWebhookResponse(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
inputPod *corev1.Pod
operation v1.Operation
wantResponse admission.Response
}{
{
name: "Empty request test.",
inputPod: nil,
wantResponse: admission.Errored(http.StatusBadRequest, fmt.Errorf("there is no content to decode")),
},
{
name: "Different operation test.",
operation: v1.Update,
inputPod: &corev1.Pod{
Spec: corev1.PodSpec{
Containers: []corev1.Container{GetSidecarContainerSpec(FakeConfig())},
Volumes: GetSidecarContainerVolumeSpec(),
},
},
wantResponse: admission.Allowed(fmt.Sprintf("No injection required for operation %v.", v1.Update)),
},
{
name: "Annotation key not found test",
operation: v1.Create,
inputPod: &corev1.Pod{
Spec: corev1.PodSpec{
Containers: []corev1.Container{GetSidecarContainerSpec(FakeConfig())},
Volumes: GetSidecarContainerVolumeSpec(),
},
},
wantResponse: admission.Allowed(fmt.Sprintf("The annotation key %q is not found, no injection required.", AnnotationGcsfuseVolumeEnableKey)),
},
{
name: "Sidecar already injected test.",
operation: v1.Create,
inputPod: &corev1.Pod{
Spec: corev1.PodSpec{
Containers: []corev1.Container{GetSidecarContainerSpec(FakeConfig())},
Volumes: GetSidecarContainerVolumeSpec(),
},
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"gke-gcsfuse/volumes": "true",
},
},
},
wantResponse: admission.Allowed("The sidecar container was injected, no injection required."),
},
{
name: "Injection successful test.",
operation: v1.Create,
inputPod: validInputPod(),
wantResponse: wantResponse(t),
},
}

for n, tc := range testCases {
t.Logf("test case %v: %s", n+1, tc.name)
si := SidecarInjector{
Client: nil,
Config: FakeConfig(),
Decoder: admission.NewDecoder(runtime.NewScheme()),
}
request := &admission.Request{
AdmissionRequest: v1.AdmissionRequest{
Operation: tc.operation,
},
}
if tc.inputPod != nil {
request.Object = runtime.RawExtension{
Raw: serialize(t, tc.inputPod),
}
}

gotResponse := si.Handle(context.Background(), *request)

if err := compareResponses(tc.wantResponse, gotResponse); err != nil {
t.Errorf("\nGot injection result: %v, but want: %v.", gotResponse, tc.wantResponse)
t.Error("Details: ", err)
}
}
}

func serialize(t *testing.T, obj any) []byte {
t.Helper()
b, err := json.Marshal(obj)
if err != nil {
t.Errorf("Error serializing object %o.", obj)

return nil
}

return b
}

func compareResponses(wantResponse, gotResponse admission.Response) error {
if diff := cmp.Diff(gotResponse.String(), wantResponse.String()); diff != "" {
return fmt.Errorf("request args differ (-got, +want)\n%s", diff)
}
if len(wantResponse.Patches) != len(gotResponse.Patches) {
return fmt.Errorf("expecting %d patches, got %d patches", len(wantResponse.Patches), len(gotResponse.Patches))
}
var wantPaths, gotPaths []string
for i := 0; i < len(wantResponse.Patches); i++ {
wantPaths = append(wantPaths, wantResponse.Patches[i].Path)
gotPaths = append(gotPaths, gotResponse.Patches[i].Path)
}

if len(wantPaths) > 0 && len(gotPaths) > 0 {
less := func(a, b string) bool { return a > b }
if diff := cmp.Diff(wantPaths, gotPaths, cmpopts.SortSlices(less)); diff != "" {
return fmt.Errorf("unexpected pod args (-got, +want)\n%s", diff)
}
}

return nil
}

func validInputPod() *corev1.Pod {
return &corev1.Pod{
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "FakeContainer1",
},
{
Name: "FakeContainer2",
},
},
Volumes: []corev1.Volume{
{
Name: "FakeVolume1",
},
{
Name: "FakeVolume2",
},
},
TerminationGracePeriodSeconds: ptr.To[int64](60),
},
ObjectMeta: metav1.ObjectMeta{
Annotations: map[string]string{
"gke-gcsfuse/volumes": "true",
},
},
}
}

func wantResponse(t *testing.T) admission.Response {
t.Helper()
newPod := validInputPod()
newPod.Spec.Containers = append([]corev1.Container{GetSidecarContainerSpec(FakeConfig())}, newPod.Spec.Containers...)
newPod.Spec.Volumes = append(GetSidecarContainerVolumeSpec(), newPod.Spec.Volumes...)

return admission.PatchResponseFromRaw(serialize(t, validInputPod()), serialize(t, newPod))
}
185 changes: 185 additions & 0 deletions vendor/github.com/google/go-cmp/cmp/cmpopts/equate.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading