sigs.k8s.io/gateway-api@v1.0.0/apis/v1alpha2/validation/tcproute_test.go (about) 1 /* 2 Copyright 2022 The Kubernetes 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 validation 18 19 import ( 20 "testing" 21 22 "k8s.io/apimachinery/pkg/util/validation/field" 23 24 gatewayv1a2 "sigs.k8s.io/gateway-api/apis/v1alpha2" 25 ) 26 27 func TestValidateTCPRoute(t *testing.T) { 28 t.Parallel() 29 30 portNumber := gatewayv1a2.PortNumber(9080) 31 32 tests := []struct { 33 name string 34 rules []gatewayv1a2.TCPRouteRule 35 errs field.ErrorList 36 }{ 37 { 38 name: "valid TCPRoute with 1 backendRef", 39 rules: []gatewayv1a2.TCPRouteRule{ 40 { 41 BackendRefs: []gatewayv1a2.BackendRef{ 42 { 43 BackendObjectReference: gatewayv1a2.BackendObjectReference{ 44 Port: &portNumber, 45 }, 46 }, 47 }, 48 }, 49 }, 50 }, 51 { 52 name: "invalid TCPRoute with 1 backendRef (missing port)", 53 rules: []gatewayv1a2.TCPRouteRule{ 54 { 55 BackendRefs: []gatewayv1a2.BackendRef{ 56 { 57 BackendObjectReference: gatewayv1a2.BackendObjectReference{ 58 Port: nil, 59 }, 60 }, 61 }, 62 }, 63 }, 64 errs: field.ErrorList{ 65 { 66 Type: field.ErrorTypeRequired, 67 Field: "spec.rules[0].backendRefs[0].port", 68 Detail: "missing port for Service reference", 69 }, 70 }, 71 }, 72 } 73 74 for _, tc := range tests { 75 tc := tc 76 t.Run(tc.name, func(t *testing.T) { 77 t.Parallel() 78 79 route := gatewayv1a2.TCPRoute{Spec: gatewayv1a2.TCPRouteSpec{Rules: tc.rules}} 80 errs := ValidateTCPRoute(&route) 81 if len(errs) != len(tc.errs) { 82 t.Errorf("got %d errors, want %d errors: %s", len(errs), len(tc.errs), errs) 83 t.FailNow() 84 } 85 for i := 0; i < len(errs); i++ { 86 realErr := errs[i].Error() 87 expectedErr := tc.errs[i].Error() 88 if realErr != expectedErr { 89 t.Errorf("expect error message: %s, but got: %s", expectedErr, realErr) 90 t.FailNow() 91 } 92 } 93 }) 94 } 95 }