rule_absent_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package valid
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestNil(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, "must be blank"},
  17. {"t2", "", "must be blank"},
  18. {"t3", &s1, "must be blank"},
  19. {"t4", &s2, "must be blank"},
  20. {"t5", nil, ""},
  21. {"t6", time1, "must be blank"},
  22. }
  23. for _, test := range tests {
  24. r := Nil
  25. err := r.Validate(test.value)
  26. assertError(t, test.err, err, test.tag)
  27. }
  28. }
  29. func TestEmpty(t *testing.T) {
  30. s1 := "123"
  31. s2 := ""
  32. time1 := time.Now()
  33. var time2 time.Time
  34. tests := []struct {
  35. tag string
  36. value interface{}
  37. err string
  38. }{
  39. {"t1", 123, "must be blank"},
  40. {"t2", "", ""},
  41. {"t3", &s1, "must be blank"},
  42. {"t4", &s2, ""},
  43. {"t5", nil, ""},
  44. {"t6", time1, "must be blank"},
  45. {"t7", time2, ""},
  46. }
  47. for _, test := range tests {
  48. r := Empty
  49. err := r.Validate(test.value)
  50. assertError(t, test.err, err, test.tag)
  51. }
  52. }
  53. func TestAbsentRule_When(t *testing.T) {
  54. r := Nil.When(false)
  55. err := Validate(42, r)
  56. assert.Nil(t, err)
  57. r = Nil.When(true)
  58. err = Validate(42, r)
  59. assert.Equal(t, ErrNil, err)
  60. }
  61. func Test_absentRule_Error(t *testing.T) {
  62. r := Nil
  63. assert.Equal(t, "must be blank", r.Validate("42").Error())
  64. assert.False(t, r.skipNil)
  65. r2 := r.Error("123")
  66. assert.Equal(t, "must be blank", r.Validate("42").Error())
  67. assert.False(t, r.skipNil)
  68. assert.Equal(t, "123", r2.err.Message())
  69. assert.False(t, r2.skipNil)
  70. r = Empty
  71. assert.Equal(t, "must be blank", r.Validate("42").Error())
  72. assert.True(t, r.skipNil)
  73. r2 = r.Error("123")
  74. assert.Equal(t, "must be blank", r.Validate("42").Error())
  75. assert.True(t, r.skipNil)
  76. assert.Equal(t, "123", r2.err.Message())
  77. assert.True(t, r2.skipNil)
  78. }
  79. func TestAbsentRule_Error(t *testing.T) {
  80. r := Nil
  81. err := NewError("code", "abc")
  82. r = r.ErrorObject(err)
  83. assert.Equal(t, err, r.err)
  84. assert.Equal(t, err.Code(), r.err.Code())
  85. assert.Equal(t, err.Message(), r.err.Message())
  86. assert.NotEqual(t, err, Nil.err)
  87. }