groupby_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package help
  2. import (
  3. "reflect"
  4. "testing"
  5. )
  6. func TestGroupBy(t *testing.T) {
  7. input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
  8. wantEven := []interface{}{2, 4, 6, 8}
  9. wantOdd := []interface{}{1, 3, 5, 7, 9}
  10. q := From(input).GroupBy(
  11. func(i interface{}) interface{} { return i.(int) % 2 },
  12. func(i interface{}) interface{} { return i.(int) },
  13. )
  14. next := q.Iterate()
  15. eq := true
  16. for item, ok := next(); ok; item, ok = next() {
  17. group := item.(Group)
  18. switch group.Key.(int) {
  19. case 0:
  20. if !reflect.DeepEqual(group.Group, wantEven) {
  21. eq = false
  22. }
  23. case 1:
  24. if !reflect.DeepEqual(group.Group, wantOdd) {
  25. eq = false
  26. }
  27. default:
  28. eq = false
  29. }
  30. }
  31. t.Logf("From(%v).GroupBy()=%v", input, toSlice(q))
  32. if !eq {
  33. t.Errorf("From(%v).GroupBy()=%v", input, toSlice(q))
  34. }
  35. }
  36. func TestGroupByT_PanicWhenKeySelectorFnIsInvalid(t *testing.T) {
  37. mustPanicWithError(t, "GroupByT: parameter [keySelectorFn] has a invalid function signature. Expected: 'func(T)T', actual: 'func(int,int)bool'", func() {
  38. var r []int
  39. From([]int{1, 1, 1, 2, 1, 2, 3, 4, 2}).GroupByT(
  40. func(i, j int) bool { return true },
  41. func(i int) int { return i },
  42. ).ToSlice(&r)
  43. })
  44. }
  45. func TestGroupByT_PanicWhenElementSelectorFnIsInvalid(t *testing.T) {
  46. mustPanicWithError(t, "GroupByT: parameter [elementSelectorFn] has a invalid function signature. Expected: 'func(T)T', actual: 'func(int,int)int'", func() {
  47. var r []int
  48. From([]int{1, 1, 1, 2, 1, 2, 3, 4, 2}).GroupByT(
  49. func(i int) bool { return true },
  50. func(i, j int) int { return i },
  51. ).ToSlice(&r)
  52. })
  53. }