select_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package help
  2. import (
  3. "strconv"
  4. "testing"
  5. )
  6. func TestSelect(t *testing.T) {
  7. tests := []struct {
  8. input interface{}
  9. selector func(interface{}) interface{}
  10. output []interface{}
  11. }{
  12. {[]int{1, 2, 3}, func(i interface{}) interface{} {
  13. return i.(int) * 2
  14. }, []interface{}{2, 4, 6}},
  15. {"str", func(i interface{}) interface{} {
  16. return string(i.(rune)) + "1"
  17. }, []interface{}{"s1", "t1", "r1"}},
  18. }
  19. for _, test := range tests {
  20. if q := From(test.input).Select(test.selector); !validateQuery(q, test.output) {
  21. t.Errorf("From(%v).Select()=%v expected %v", test.input, toSlice(q), test.output)
  22. }
  23. }
  24. }
  25. func TestSelectT_PanicWhenSelectorFnIsInvalid(t *testing.T) {
  26. mustPanicWithError(t, "SelectT: parameter [selectorFn] has a invalid function signature. Expected: 'func(T)T', actual: 'func(int,int)int'", func() {
  27. From([]int{1, 1, 1, 2, 1, 2, 3, 4, 2}).SelectT(func(item, idx int) int { return item + 2 })
  28. })
  29. }
  30. func TestSelectIndexed(t *testing.T) {
  31. tests := []struct {
  32. input interface{}
  33. selector func(int, interface{}) interface{}
  34. output []interface{}
  35. }{
  36. {[]int{1, 2, 3}, func(i int, x interface{}) interface{} {
  37. return x.(int) * i
  38. }, []interface{}{0, 2, 6}},
  39. {"str", func(i int, x interface{}) interface{} {
  40. return string(x.(rune)) + strconv.Itoa(i)
  41. }, []interface{}{"s0", "t1", "r2"}},
  42. }
  43. for _, test := range tests {
  44. if q := From(test.input).SelectIndexed(test.selector); !validateQuery(q, test.output) {
  45. t.Errorf("From(%v).SelectIndexed()=%v expected %v", test.input, toSlice(q), test.output)
  46. }
  47. }
  48. }
  49. func TestSelectIndexedT_PanicWhenSelectorFnIsInvalid(t *testing.T) {
  50. mustPanicWithError(t, "SelectIndexedT: parameter [selectorFn] has a invalid function signature. Expected: 'func(int,T)T', actual: 'func(string,int)int'", func() {
  51. From([]int{1, 1, 1, 2, 1, 2, 3, 4, 2}).SelectIndexedT(func(index string, item int) int { return item + 2 })
  52. })
  53. }