rule_required_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package valid
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestRequired(t *testing.T) {
  8. s1 := "123"
  9. s2 := ""
  10. var time1 time.Time
  11. tests := []struct {
  12. tag string
  13. value interface{}
  14. err string
  15. }{
  16. {"t1", 123, ""},
  17. {"t2", "", "cannot be blank"},
  18. {"t3", &s1, ""},
  19. {"t4", &s2, "cannot be blank"},
  20. {"t5", nil, "cannot be blank"},
  21. {"t6", time1, "cannot be blank"},
  22. }
  23. for _, test := range tests {
  24. r := Required
  25. err := r.Validate(test.value)
  26. assertError(t, test.err, err, test.tag)
  27. }
  28. }
  29. func TestRequiredRule_When(t *testing.T) {
  30. r := Required.When(false)
  31. err := Validate(nil, r)
  32. assert.Nil(t, err)
  33. r = Required.When(true)
  34. err = Validate(nil, r)
  35. assert.Equal(t, ErrRequired, err)
  36. }
  37. func TestNilOrNotEmpty(t *testing.T) {
  38. s1 := "123"
  39. s2 := ""
  40. tests := []struct {
  41. tag string
  42. value interface{}
  43. err string
  44. }{
  45. {"t1", 123, ""},
  46. {"t2", "", "cannot be blank"},
  47. {"t3", &s1, ""},
  48. {"t4", &s2, "cannot be blank"},
  49. {"t5", nil, ""},
  50. }
  51. for _, test := range tests {
  52. r := NilOrNotEmpty
  53. err := r.Validate(test.value)
  54. assertError(t, test.err, err, test.tag)
  55. }
  56. }
  57. func Test_requiredRule_Error(t *testing.T) {
  58. r := Required
  59. assert.Equal(t, "cannot be blank", r.Validate(nil).Error())
  60. assert.False(t, r.skipNil)
  61. r2 := r.Error("123")
  62. assert.Equal(t, "cannot be blank", r.Validate(nil).Error())
  63. assert.False(t, r.skipNil)
  64. assert.Equal(t, "123", r2.err.Message())
  65. assert.False(t, r2.skipNil)
  66. r = NilOrNotEmpty
  67. assert.Equal(t, "cannot be blank", r.Validate("").Error())
  68. assert.True(t, r.skipNil)
  69. r2 = r.Error("123")
  70. assert.Equal(t, "cannot be blank", r.Validate("").Error())
  71. assert.True(t, r.skipNil)
  72. assert.Equal(t, "123", r2.err.Message())
  73. assert.True(t, r2.skipNil)
  74. }
  75. func TestRequiredRule_Error(t *testing.T) {
  76. r := Required
  77. err := NewError("code", "abc")
  78. r = r.ErrorObject(err)
  79. assert.Equal(t, err, r.err)
  80. assert.Equal(t, err.Code(), r.err.Code())
  81. assert.Equal(t, err.Message(), r.err.Message())
  82. assert.NotEqual(t, err, Required.err)
  83. }