rule_in_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package valid
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestIn(t *testing.T) {
  7. var v = 1
  8. var v2 *int
  9. tests := []struct {
  10. tag string
  11. values []interface{}
  12. value interface{}
  13. err string
  14. }{
  15. {"t0", []interface{}{1, 2}, 0, ""},
  16. {"t1", []interface{}{1, 2}, 1, ""},
  17. {"t2", []interface{}{1, 2}, 2, ""},
  18. {"t3", []interface{}{1, 2}, 3, "must be a valid value"},
  19. {"t4", []interface{}{}, 3, "must be a valid value"},
  20. {"t5", []interface{}{1, 2}, "1", "must be a valid value"},
  21. {"t6", []interface{}{1, 2}, &v, ""},
  22. {"t7", []interface{}{1, 2}, v2, ""},
  23. {"t8", []interface{}{[]byte{1}, 1, 2}, []byte{1}, ""},
  24. }
  25. for _, test := range tests {
  26. r := In(test.values...)
  27. err := r.Validate(test.value)
  28. assertError(t, test.err, err, test.tag)
  29. }
  30. }
  31. func Test_InRule_Error(t *testing.T) {
  32. r := In(1, 2, 3)
  33. val := 4
  34. assert.Equal(t, "must be a valid value", r.Validate(&val).Error())
  35. r = r.Error("123")
  36. assert.Equal(t, "123", r.err.Message())
  37. }
  38. func TestInRule_ErrorObject(t *testing.T) {
  39. r := In(1, 2, 3)
  40. err := NewError("code", "abc")
  41. r = r.ErrorObject(err)
  42. assert.Equal(t, err, r.err)
  43. assert.Equal(t, err.Code(), r.err.Code())
  44. assert.Equal(t, err.Message(), r.err.Message())
  45. }