code.gitea.io/gitea@v1.19.3/modules/validation/regex_pattern_test.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package validation 5 6 import ( 7 "regexp" 8 "testing" 9 10 "gitea.com/go-chi/binding" 11 ) 12 13 func getRegexPatternErrorString(pattern string) string { 14 if _, err := regexp.Compile(pattern); err != nil { 15 return err.Error() 16 } 17 return "" 18 } 19 20 var regexValidationTestCases = []validationTestCase{ 21 { 22 description: "Empty regex pattern", 23 data: TestForm{ 24 RegexPattern: "", 25 }, 26 expectedErrors: binding.Errors{}, 27 }, 28 { 29 description: "Valid regex", 30 data: TestForm{ 31 RegexPattern: `(\d{1,3})+`, 32 }, 33 expectedErrors: binding.Errors{}, 34 }, 35 36 { 37 description: "Invalid regex", 38 data: TestForm{ 39 RegexPattern: "[a-", 40 }, 41 expectedErrors: binding.Errors{ 42 binding.Error{ 43 FieldNames: []string{"RegexPattern"}, 44 Classification: ErrRegexPattern, 45 Message: getRegexPatternErrorString("[a-"), 46 }, 47 }, 48 }, 49 } 50 51 func Test_RegexPatternValidation(t *testing.T) { 52 AddBindingRules() 53 54 for _, testCase := range regexValidationTestCases { 55 t.Run(testCase.description, func(t *testing.T) { 56 performValidationTest(t, testCase) 57 }) 58 } 59 }