rule_match_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package valid
  2. import (
  3. "regexp"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestMatch(t *testing.T) {
  8. var v2 *string
  9. tests := []struct {
  10. tag string
  11. re string
  12. value interface{}
  13. err string
  14. }{
  15. {"t1", "[a-z]+", "abc", ""},
  16. {"t2", "[a-z]+", "", ""},
  17. {"t3", "[a-z]+", v2, ""},
  18. {"t4", "[a-z]+", "123", "must be in a valid format"},
  19. {"t5", "[a-z]+", []byte("abc"), ""},
  20. {"t6", "[a-z]+", []byte("123"), "must be in a valid format"},
  21. {"t7", "[a-z]+", []byte(""), ""},
  22. {"t8", "[a-z]+", nil, ""},
  23. }
  24. for _, test := range tests {
  25. r := Match(regexp.MustCompile(test.re))
  26. err := r.Validate(test.value)
  27. assertError(t, test.err, err, test.tag)
  28. }
  29. }
  30. func Test_MatchRule_Error(t *testing.T) {
  31. r := Match(regexp.MustCompile("[a-z]+"))
  32. assert.Equal(t, "must be in a valid format", r.Validate("13").Error())
  33. r = r.Error("123")
  34. assert.Equal(t, "123", r.err.Message())
  35. }
  36. func TestMatchRule_ErrorObject(t *testing.T) {
  37. r := Match(regexp.MustCompile("[a-z]+"))
  38. err := NewError("code", "abc")
  39. r = r.ErrorObject(err)
  40. assert.Equal(t, err, r.err)
  41. assert.Equal(t, err.Code(), r.err.Code())
  42. assert.Equal(t, err.Message(), r.err.Message())
  43. }