gitea源码

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