rule_each_test.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package valid
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. "testing"
  7. )
  8. func TestEach(t *testing.T) {
  9. var a *int
  10. var f = func(v string) string { return v }
  11. var c0 chan int
  12. c1 := make(chan int)
  13. tests := []struct {
  14. tag string
  15. value interface{}
  16. err string
  17. }{
  18. {"t1", nil, "must be an iterable (map, slice or array)"},
  19. {"t2", map[string]string{}, ""},
  20. {"t3", map[string]string{"key1": "value1", "key2": "value2"}, ""},
  21. {"t4", map[string]string{"key1": "", "key2": "value2", "key3": ""}, "key1: cannot be blank; key3: cannot be blank."},
  22. {"t5", map[string]map[string]string{"key1": {"key1.1": "value1"}, "key2": {"key2.1": "value1"}}, ""},
  23. {"t6", map[string]map[string]string{"": nil}, ": cannot be blank."},
  24. {"t7", map[interface{}]interface{}{}, ""},
  25. {"t8", map[interface{}]interface{}{"key1": struct{ foo string }{"foo"}}, ""},
  26. {"t9", map[interface{}]interface{}{nil: "", "": "", "key1": nil}, ": cannot be blank; key1: cannot be blank."},
  27. {"t10", []string{"value1", "value2", "value3"}, ""},
  28. {"t11", []string{"", "value2", ""}, "0: cannot be blank; 2: cannot be blank."},
  29. {"t12", []interface{}{struct{ foo string }{"foo"}}, ""},
  30. {"t13", []interface{}{nil, a}, "0: cannot be blank; 1: cannot be blank."},
  31. {"t14", []interface{}{c0, c1, f}, "0: cannot be blank."},
  32. }
  33. for _, test := range tests {
  34. r := Each(Required)
  35. err := r.Validate(test.value)
  36. assertError(t, test.err, err, test.tag)
  37. }
  38. }
  39. func TestEachWithContext(t *testing.T) {
  40. rule := Each(WithContext(func(ctx context.Context, value interface{}) error {
  41. if !strings.Contains(value.(string), ctx.Value("contains").(string)) {
  42. return errors.New("unexpected value")
  43. }
  44. return nil
  45. }))
  46. ctx1 := context.WithValue(context.Background(), "contains", "abc")
  47. ctx2 := context.WithValue(context.Background(), "contains", "xyz")
  48. tests := []struct {
  49. tag string
  50. value interface{}
  51. ctx context.Context
  52. err string
  53. }{
  54. {"t1.1", map[string]string{"key": "abc"}, ctx1, ""},
  55. {"t1.2", map[string]string{"key": "abc"}, ctx2, "key: unexpected value."},
  56. {"t1.3", map[string]string{"key": "xyz"}, ctx1, "key: unexpected value."},
  57. {"t1.4", map[string]string{"key": "xyz"}, ctx2, ""},
  58. {"t1.5", []string{"abc"}, ctx1, ""},
  59. {"t1.6", []string{"abc"}, ctx2, "0: unexpected value."},
  60. {"t1.7", []string{"xyz"}, ctx1, "0: unexpected value."},
  61. {"t1.8", []string{"xyz"}, ctx2, ""},
  62. }
  63. for _, test := range tests {
  64. err := ValidateWithContext(test.ctx, test.value, rule)
  65. assertError(t, test.err, err, test.tag)
  66. }
  67. }