k8s.io/kube-openapi@v0.0.0-20240228011516-70dd3763d340/pkg/validation/validate/rexp_test.go (about) 1 // Copyright 2015 go-swagger maintainers 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations untader the License. 14 15 package validate 16 17 import ( 18 re "regexp" 19 "testing" 20 21 "github.com/stretchr/testify/assert" 22 ) 23 24 // Save repeated regexp compilation 25 func Test_compileRegexp(t *testing.T) { 26 vrex := new(re.Regexp) 27 28 rex, err := compileRegexp(".*TestRegexp.*") 29 assert.NoError(t, err) 30 assert.NotNil(t, rex) 31 assert.IsType(t, vrex, rex) 32 33 rex, err = compileRegexp(".*TestRegexp.*") 34 assert.NoError(t, err) 35 assert.NotNil(t, rex) 36 37 irex, ierr := compileRegexp(".[*InvalidTestRegexp.*") 38 assert.Error(t, ierr) 39 assert.Nil(t, irex) 40 assert.IsType(t, vrex, irex) 41 } 42 43 // Save repeated regexp compilation, with panic on error 44 func testPanic() { 45 mustCompileRegexp(".[*InvalidTestRegexp.*") 46 } 47 48 func Test_mustCompileRegexp(t *testing.T) { 49 vrex := new(re.Regexp) 50 51 rex := mustCompileRegexp(".*TestRegexp2.*") 52 assert.NotNil(t, rex) 53 assert.IsType(t, vrex, rex) 54 55 rex = mustCompileRegexp(".*TestRegexp2.*") 56 assert.NotNil(t, rex) 57 58 assert.Panics(t, testPanic) 59 } 60 61 func TestRace_compileRegexp(t *testing.T) { 62 vrex := new(re.Regexp) 63 64 patterns := []string{ 65 ".*TestRegexp1.*", 66 ".*TestRegexp2.*", 67 ".*TestRegexp3.*", 68 } 69 70 comp := func(pattern string) { 71 rex, err := compileRegexp(pattern) 72 assert.NoError(t, err) 73 assert.NotNil(t, rex) 74 assert.IsType(t, vrex, rex) 75 } 76 77 for i := 0; i < 20; i++ { 78 t.Run(patterns[i%3], func(t *testing.T) { 79 t.Parallel() 80 comp(patterns[i%3]) 81 }) 82 } 83 } 84 85 func TestRace_mustCompileRegexp(t *testing.T) { 86 vrex := new(re.Regexp) 87 88 patterns := []string{ 89 ".*TestRegexp1.*", 90 ".*TestRegexp2.*", 91 ".*TestRegexp3.*", 92 } 93 94 comp := func(pattern string) { 95 rex := mustCompileRegexp(pattern) 96 assert.NotNil(t, rex) 97 assert.IsType(t, vrex, rex) 98 } 99 100 for i := 0; i < 20; i++ { 101 t.Run(patterns[i%3], func(t *testing.T) { 102 t.Parallel() 103 comp(patterns[i%3]) 104 }) 105 } 106 }