Skip to content
This repository has been archived by the owner on Aug 21, 2024. It is now read-only.

Commit

Permalink
Add test coverage for webhook (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
mszostok committed Aug 14, 2019
1 parent 1514fc9 commit 7aef74c
Show file tree
Hide file tree
Showing 25 changed files with 1,729 additions and 578 deletions.
209 changes: 147 additions & 62 deletions Gopkg.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion cmd/webhook/server/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ import (
"fmt"
"net/http"

scTypes "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
csbmutation "github.com/kubernetes-incubator/service-catalog/pkg/webhook/servicecatalog/clusterservicebroker/mutation"
sbmutation "github.com/kubernetes-incubator/service-catalog/pkg/webhook/servicecatalog/servicebinding/mutation"
brmutation "github.com/kubernetes-incubator/service-catalog/pkg/webhook/servicecatalog/servicebroker/mutation"
simutation "github.com/kubernetes-incubator/service-catalog/pkg/webhook/servicecatalog/serviceinstance/mutation"
scTypes "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"

"github.com/pkg/errors"
"k8s.io/apiserver/pkg/server/healthz"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import (
"net/http"

sc "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
webhookutil "github.com/kubernetes-incubator/service-catalog/pkg/webhook/util"
"github.com/kubernetes-incubator/service-catalog/pkg/webhookutil"

admissionTypes "k8s.io/api/admission/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
Copyright 2019 The Kubernetes Authors.
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
http://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 mutation_test

import (
"context"
"net/http"
"testing"

"github.com/appscode/jsonpatch"
sc "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
"github.com/kubernetes-incubator/service-catalog/pkg/webhook/servicecatalog/clusterservicebroker/mutation"
"github.com/kubernetes-incubator/service-catalog/pkg/webhookutil/tester"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
admissionv1beta1 "k8s.io/api/admission/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

func TestCreateUpdateHandlerHandleCreateSuccess(t *testing.T) {
tests := map[string]struct {
givenRawObj []byte

expPatches []jsonpatch.Operation
}{
"Should set all default fields": {
givenRawObj: []byte(`{
"apiVersion": "servicecatalog.k8s.io/v1beta1",
"kind": "ClusterServiceBroker",
"metadata": {
"creationTimestamp": null,
"name": "test-broker"
},
"spec": {
"relistRequests": 1,
"url": "http://localhost:8081/"
}
}`),
expPatches: []jsonpatch.Operation{
{
Operation: "add",
Path: "/metadata/finalizers",
Value: []interface{}{
"kubernetes-incubator/service-catalog",
},
},
{
Operation: "add",
Path: "/spec/relistBehavior",
Value: "Duration",
},
},
},
"Should omit relistBehavior if it's already set": {
givenRawObj: []byte(`{
"apiVersion": "servicecatalog.k8s.io/v1beta1",
"kind": "ClusterServiceBroker",
"metadata": {
"creationTimestamp": null,
"name": "test-broker"
},
"spec": {
"relistRequests": 1,
"relistBehavior": "Manual",
"url": "http://localhost:8081/"
}
}`),
expPatches: []jsonpatch.Operation{
{
Operation: "add",
Path: "/metadata/finalizers",
Value: []interface{}{
"kubernetes-incubator/service-catalog",
},
},
},
},
}

for tn, tc := range tests {
t.Run(tn, func(t *testing.T) {
// given
sc.AddToScheme(scheme.Scheme)
decoder, err := admission.NewDecoder(scheme.Scheme)
require.NoError(t, err)

fixReq := admission.Request{
AdmissionRequest: admissionv1beta1.AdmissionRequest{
Operation: admissionv1beta1.Create,
Name: "test-broker",
Namespace: "system",
Kind: metav1.GroupVersionKind{
Kind: "ClusterServiceBroker",
Version: "v1beta1",
Group: "servicecatalog.k8s.io",
},
Object: runtime.RawExtension{Raw: tc.givenRawObj},
},
}

handler := mutation.CreateUpdateHandler{}
handler.InjectDecoder(decoder)

// when
resp := handler.Handle(context.Background(), fixReq)

// then
assert.True(t, resp.Allowed)
require.NotNil(t, resp.PatchType)
assert.Equal(t, admissionv1beta1.PatchTypeJSONPatch, *resp.PatchType)

// filtering out status cause k8s api-server will discard this too
patches := tester.FilterOutStatusPatch(resp.Patches)

require.Len(t, patches, len(tc.expPatches))
for _, expPatch := range tc.expPatches {
assert.Contains(t, patches, expPatch)
}
})
}
}

func TestCreateUpdateHandlerHandleReturnErrorIfGVKMismatch(t *testing.T) {
// given
sc.AddToScheme(scheme.Scheme)
decoder, err := admission.NewDecoder(scheme.Scheme)
require.NoError(t, err)

fixReq := admission.Request{
AdmissionRequest: admissionv1beta1.AdmissionRequest{
Operation: admissionv1beta1.Create,
Name: "test-broker",
Namespace: "system",
Kind: metav1.GroupVersionKind{
Kind: "ClusterServiceClass",
Version: "v1beta1",
Group: "servicecatalog.k8s.io",
},
},
}

expReqResult := &metav1.Status{
Code: http.StatusBadRequest,
Message: "type mismatch: want: servicecatalog.k8s.io/v1beta1, Kind=ClusterServiceBroker got: servicecatalog.k8s.io/v1beta1, Kind=ClusterServiceClass",
}

handler := mutation.CreateUpdateHandler{}
handler.InjectDecoder(decoder)

// when
resp := handler.Handle(context.Background(), fixReq)

// then
assert.False(t, resp.Allowed)
assert.Equal(t, expReqResult, resp.Result)
}

func TestCreateUpdateHandlerHandleReturnErrorIfReqObjIsMalformed(t *testing.T) {
// given
sc.AddToScheme(scheme.Scheme)
decoder, err := admission.NewDecoder(scheme.Scheme)
require.NoError(t, err)

fixReq := admission.Request{
AdmissionRequest: admissionv1beta1.AdmissionRequest{
Operation: admissionv1beta1.Create,
Name: "test-broker",
Namespace: "system",
Kind: metav1.GroupVersionKind{
Kind: "ClusterServiceBroker",
Version: "v1beta1",
Group: "servicecatalog.k8s.io",
},
Object: runtime.RawExtension{Raw: []byte("{malformed: JSON,,")},
},
}

expReqResult := &metav1.Status{
Code: http.StatusBadRequest,
Message: "couldn't get version/kind; json parse error: invalid character 'm' looking for beginning of object key string",
}

handler := mutation.CreateUpdateHandler{}
handler.InjectDecoder(decoder)

// when
resp := handler.Handle(context.Background(), fixReq)

// then
assert.False(t, resp.Allowed)
assert.Equal(t, expReqResult, resp.Result)
}
6 changes: 3 additions & 3 deletions pkg/webhook/servicecatalog/servicebinding/mutation/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,17 @@ import (

sc "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
scfeatures "github.com/kubernetes-incubator/service-catalog/pkg/features"
webhookutil "github.com/kubernetes-incubator/service-catalog/pkg/webhook/util"
"github.com/kubernetes-incubator/service-catalog/pkg/webhookutil"

admissionTypes "k8s.io/api/admission/v1beta1"
"k8s.io/apimachinery/pkg/util/uuid"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

// CreateUpdateHandler handles ServiceBinding
type CreateUpdateHandler struct {
decoder *admission.Decoder
UUID webhookutil.UUIDGenerator
}

var _ admission.Handler = &CreateUpdateHandler{}
Expand Down Expand Up @@ -87,7 +87,7 @@ func (h *CreateUpdateHandler) mutateOnCreate(ctx context.Context, req admission.
binding.Finalizers = []string{sc.FinalizerServiceCatalog}

if binding.Spec.ExternalID == "" {
binding.Spec.ExternalID = string(uuid.NewUUID())
binding.Spec.ExternalID = string(h.UUID.New())
}

if binding.Spec.SecretName == "" {
Expand Down
Loading

0 comments on commit 7aef74c

Please sign in to comment.