distinct_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package help
  2. import "testing"
  3. func TestDistinct(t *testing.T) {
  4. tests := []struct {
  5. input interface{}
  6. output []interface{}
  7. }{
  8. {[]int{1, 2, 2, 3, 1}, []interface{}{1, 2, 3}},
  9. {[9]int{1, 1, 1, 2, 1, 2, 3, 4, 2}, []interface{}{1, 2, 3, 4}},
  10. {"sstr", []interface{}{'s', 't', 'r'}},
  11. }
  12. for _, test := range tests {
  13. if q := From(test.input).Distinct(); !validateQuery(q, test.output) {
  14. t.Errorf("From(%v).Distinct()=%v expected %v", test.input, toSlice(q), test.output)
  15. }
  16. }
  17. }
  18. func TestDistinctForOrderedQuery(t *testing.T) {
  19. tests := []struct {
  20. input interface{}
  21. output []interface{}
  22. }{
  23. {[]int{1, 2, 2, 3, 1}, []interface{}{1, 2, 3}},
  24. {[9]int{1, 1, 1, 2, 1, 2, 3, 4, 2}, []interface{}{1, 2, 3, 4}},
  25. {"sstr", []interface{}{'r', 's', 't'}},
  26. }
  27. for _, test := range tests {
  28. if q := From(test.input).OrderBy(func(i interface{}) interface{} {
  29. return i
  30. }).Distinct(); !validateQuery(q.Query, test.output) {
  31. t.Errorf("From(%v).Distinct()=%v expected %v", test.input, toSlice(q.Query), test.output)
  32. }
  33. }
  34. }
  35. func TestDistinctBy(t *testing.T) {
  36. type user struct {
  37. id int
  38. name string
  39. }
  40. users := []user{{1, "Foo"}, {2, "Bar"}, {3, "Foo"}}
  41. want := []interface{}{user{1, "Foo"}, user{2, "Bar"}}
  42. if q := From(users).DistinctBy(func(u interface{}) interface{} {
  43. return u.(user).name
  44. }); !validateQuery(q, want) {
  45. t.Errorf("From(%v).DistinctBy()=%v expected %v", users, toSlice(q), want)
  46. }
  47. }
  48. func TestDistinctByT_PanicWhenSelectorFnIsInvalid(t *testing.T) {
  49. mustPanicWithError(t, "DistinctByT: parameter [selectorFn] has a invalid function signature. Expected: 'func(T)T', actual: 'func(string,string)bool'", func() {
  50. From([]int{1, 1, 1, 2, 1, 2, 3, 4, 2}).DistinctByT(func(indice, item string) bool { return item == "2" })
  51. })
  52. }