github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/vdutil/regexp_test.go (about) 1 package vdutil 2 3 import ( 4 "context" 5 "errors" 6 "regexp" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 12 "github.com/jxskiss/gopkg/v2/perf/lru" 13 ) 14 15 func TestMatchRegexp(t *testing.T) { 16 ctx := context.Background() 17 vdErr := &ValidationError{} 18 19 t.Run("string pattern", func(t *testing.T) { 20 pattern := `\w+\s+\d+` 21 22 got1, err := MatchRegexp("testVar", pattern, "abc 123").Validate(ctx, nil) 23 require.Nil(t, err) 24 assert.Equal(t, "abc 123", got1) 25 26 _, err = MatchRegexp("testVar", pattern, "abc123").Validate(ctx, nil) 27 require.NotNil(t, err) 28 assert.True(t, errors.As(err, &vdErr)) 29 assert.Equal(t, `testVar: value "abc123" not match regexp`, err.Error()) 30 }) 31 32 t.Run("invalid pattern", func(t *testing.T) { 33 pattern := `(\w+\s+\d+` 34 _, err := MatchRegexp("testVar", pattern, "abc 123").Validate(ctx, nil) 35 require.NotNil(t, err) 36 assert.False(t, errors.As(err, &vdErr)) 37 }) 38 39 t.Run("regexp pattern", func(t *testing.T) { 40 pattern := regexp.MustCompile(`\w+\s+\d+`) 41 42 got1, err := MatchRegexp("testVar", pattern, "abc 123").Validate(ctx, nil) 43 require.Nil(t, err) 44 assert.Equal(t, "abc 123", got1) 45 46 _, err = MatchRegexp("testVar", pattern, "abc123").Validate(ctx, nil) 47 require.NotNil(t, err) 48 assert.True(t, errors.As(err, &vdErr)) 49 assert.Equal(t, `testVar: value "abc123" not match regexp`, err.Error()) 50 }) 51 52 t.Run("cache enabled", func(t *testing.T) { 53 cache := lru.NewCache[string, *regexp.Regexp](100) 54 EnableRegexpCache(cache) 55 56 pattern := `\w+\s+\d+` 57 58 got1, err := MatchRegexp("testVar", pattern, "abc 123").Validate(ctx, nil) 59 require.Nil(t, err) 60 assert.Equal(t, "abc 123", got1) 61 62 _, err = MatchRegexp("testVar", pattern, "abc123").Validate(ctx, nil) 63 require.NotNil(t, err) 64 assert.True(t, errors.As(err, &vdErr)) 65 }) 66 }