github.com/verrazzano/verrazzano@v1.7.1/cluster-operator/apis/clusters/v1alpha1/ocneoci_webhook_test.go (about) 1 // Copyright (c) 2023, Oracle and/or its affiliates. 2 // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. 3 4 package v1alpha1 5 6 import ( 7 _ "embed" 8 "github.com/oracle/oci-go-sdk/v53/core" 9 "github.com/stretchr/testify/assert" 10 ocifake "github.com/verrazzano/verrazzano/cluster-operator/controllers/quickcreate/controller/oci/fake" 11 "k8s.io/client-go/kubernetes/scheme" 12 "sigs.k8s.io/controller-runtime/pkg/client/fake" 13 "sigs.k8s.io/yaml" 14 "testing" 15 ) 16 17 var ( 18 //go:embed testdata/ociocnequickcreate_valid.yaml 19 testValidOCIOCNECR []byte 20 //go:embed testdata/ociocnequickcreate_invalid.yaml 21 testInvalidOCIOCNECR []byte 22 testID = "test" 23 ) 24 25 func TestValidateCreateOCNEOCI(t *testing.T) { 26 cm, err := testOCNEConfigMap() 27 assert.NoError(t, err) 28 cli := fake.NewClientBuilder().WithScheme(scheme.Scheme).WithObjects(cm).Build() 29 ociClient := &ocifake.ClientImpl{ 30 VCN: &core.Vcn{ 31 Id: &testID, 32 }, 33 } 34 35 var tests = []struct { 36 name string 37 crBytes []byte 38 hasError bool 39 }{ 40 { 41 "no error for valid CR", 42 testValidOCIOCNECR, 43 false, 44 }, 45 { 46 "error for invalid CR", 47 testInvalidOCIOCNECR, 48 true, 49 }, 50 } 51 for _, tt := range tests { 52 t.Run(tt.name, func(t *testing.T) { 53 defer func() { NewValidationContext = newValidationContext }() 54 NewValidationContext = func() (*validationContext, error) { 55 return testValidationContextWithOCIClient(cli, ociClient), nil 56 } 57 o := &OCNEOCIQuickCreate{} 58 err := yaml.Unmarshal(tt.crBytes, o) 59 assert.NoError(t, err) 60 err = o.ValidateCreate() 61 if tt.hasError { 62 assert.Error(t, err) 63 } else { 64 assert.NoError(t, err) 65 } 66 }) 67 } 68 } 69 70 func TestValidateUpdateOCNEOCI(t *testing.T) { 71 o := &OCNEOCIQuickCreate{} 72 err := yaml.Unmarshal(testValidOCIOCNECR, o) 73 assert.NoError(t, err) 74 var tests = []struct { 75 name string 76 modifier func(o *OCNEOCIQuickCreate) 77 hasError bool 78 }{ 79 { 80 "no error when no update", 81 func(o *OCNEOCIQuickCreate) {}, 82 false, 83 }, 84 { 85 "error when spec update", 86 func(o *OCNEOCIQuickCreate) { 87 o.Spec.IdentityRef.Name = "foo" 88 }, 89 true, 90 }, 91 } 92 93 for _, tt := range tests { 94 t.Run(tt.name, func(t *testing.T) { 95 o1 := o.DeepCopy() 96 o2 := o.DeepCopy() 97 tt.modifier(o2) 98 err := o1.ValidateUpdate(o2) 99 if tt.hasError { 100 assert.Error(t, err) 101 } else { 102 assert.NoError(t, err) 103 } 104 }) 105 } 106 }