github.com/kubevela/workflow@v0.6.0/pkg/webhook/v1alpha1/workflowrun/mutating_handler_test.go (about)

     1  /*
     2  Copyright 2022 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package workflowrun
    18  
    19  import (
    20  	. "github.com/onsi/ginkgo"
    21  	. "github.com/onsi/gomega"
    22  	"gomodules.xyz/jsonpatch/v2"
    23  	admissionv1 "k8s.io/api/admission/v1"
    24  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    25  	"k8s.io/apimachinery/pkg/runtime"
    26  	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
    27  )
    28  
    29  var _ = Describe("Test WorkflowRun Mutator", func() {
    30  
    31  	var mutatingHandler *MutatingHandler
    32  
    33  	BeforeEach(func() {
    34  		mutatingHandler = &MutatingHandler{}
    35  		Expect(mutatingHandler.InjectDecoder(decoder)).Should(BeNil())
    36  	})
    37  
    38  	It("Test WorkflowRun Mutator [bad request]", func() {
    39  		req := admission.Request{
    40  			AdmissionRequest: admissionv1.AdmissionRequest{
    41  				Operation: admissionv1.Create,
    42  				Resource:  metav1.GroupVersionResource{Group: "core.oam.dev", Version: "v1alpha1", Resource: "workflowruns"},
    43  				Object:    runtime.RawExtension{Raw: []byte("bad request")},
    44  			},
    45  		}
    46  		resp := mutatingHandler.Handle(ctx, req)
    47  		Expect(resp.Allowed).Should(BeFalse())
    48  	})
    49  
    50  	It("Test WorkflowRun Mutator [with patch]", func() {
    51  		req := admission.Request{
    52  			AdmissionRequest: admissionv1.AdmissionRequest{
    53  				Operation: admissionv1.Create,
    54  				Resource:  metav1.GroupVersionResource{Group: "core.oam.dev", Version: "v1alpha1", Resource: "workflowruns"},
    55  				Object: runtime.RawExtension{
    56  					Raw: []byte(
    57  						`{"apiVersion":"core.oam.dev/v1alpha1","kind":"WorkflowRun","metadata":{"name":"wr-sample"},"spec":{"workflowSpec":{"steps":[{"properties":{"duration":"3s"},"type":"suspend"}]}}}`),
    58  				},
    59  			},
    60  		}
    61  		resp := mutatingHandler.Handle(ctx, req)
    62  		Expect(resp.Allowed).Should(BeTrue())
    63  		Expect(resp.Patches).Should(ContainElement(jsonpatch.JsonPatchOperation{
    64  			Operation: "add",
    65  			Path:      "/spec/workflowSpec/steps/0/name",
    66  			Value:     "step-0",
    67  		}))
    68  	})
    69  })