in_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package validate
  2. import (
  3. "fmt"
  4. "strings"
  5. "testing"
  6. )
  7. func TestIn(t *testing.T) {
  8. type TestCase[T comparable] struct {
  9. S []T
  10. Input T
  11. Err bool
  12. }
  13. strIn := []string{"abcd", "ef", "1234"}
  14. strTestCases := []TestCase[string]{
  15. {S: strIn, Input: "abcd"},
  16. {S: strIn, Input: "ef"},
  17. {S: strIn, Input: "1234"},
  18. {S: strIn, Input: "5678", Err: true},
  19. }
  20. for _, tc := range strTestCases {
  21. t.Logf("%q in %s", tc.Input, strings.Join(tc.S, ", "))
  22. f := In(tc.S...)
  23. err := f(tc.Input)
  24. if tc.Err {
  25. if err == nil {
  26. t.Error("Expected error; got nil")
  27. }
  28. } else {
  29. if err != nil {
  30. t.Errorf("Expected nil; got %s", err)
  31. }
  32. }
  33. }
  34. intIn := []int{1, 23, 456}
  35. intTestCases := []TestCase[int]{
  36. {S: intIn, Input: 1},
  37. {S: intIn, Input: 23},
  38. {S: intIn, Input: 456},
  39. {S: intIn, Input: 789, Err: true},
  40. }
  41. for _, tc := range intTestCases {
  42. intf := []string{}
  43. for _, v := range tc.S {
  44. intf = append(intf, fmt.Sprint(v))
  45. }
  46. t.Logf("%d in %s", tc.Input, strings.Join(intf, ", "))
  47. f := In(tc.S...)
  48. err := f(tc.Input)
  49. if tc.Err {
  50. if err == nil {
  51. t.Error("Expected error; got nil")
  52. }
  53. } else {
  54. if err != nil {
  55. t.Errorf("Expected nil; got %s", err)
  56. }
  57. }
  58. }
  59. }