partitioner_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package sarama
  2. import "testing"
  3. func assertPartitioningConsistent(t *testing.T, partitioner Partitioner, key Encoder, numPartitions int) {
  4. choice := partitioner.Partition(key, numPartitions)
  5. if choice < 0 || choice >= numPartitions {
  6. t.Error(partitioner, "returned partition", choice, "outside of range for", key)
  7. }
  8. for i := 1; i < 50; i++ {
  9. newChoice := partitioner.Partition(key, numPartitions)
  10. if newChoice != choice {
  11. t.Error(partitioner, "returned partition", newChoice, "inconsistent with", choice, ".")
  12. }
  13. }
  14. }
  15. func TestRandomPartitioner(t *testing.T) {
  16. partitioner := NewRandomPartitioner()
  17. choice := partitioner.Partition(nil, 1)
  18. if choice != 0 {
  19. t.Error("Returned non-zero partition when only one available.")
  20. }
  21. for i := 1; i < 50; i++ {
  22. choice := partitioner.Partition(nil, 50)
  23. if choice < 0 || choice >= 50 {
  24. t.Error("Returned partition", choice, "outside of range.")
  25. }
  26. }
  27. }
  28. func TestRoundRobinPartitioner(t *testing.T) {
  29. partitioner := RoundRobinPartitioner{}
  30. choice := partitioner.Partition(nil, 1)
  31. if choice != 0 {
  32. t.Error("Returned non-zero partition when only one available.")
  33. }
  34. for i := 1; i < 50; i++ {
  35. choice := partitioner.Partition(nil, 7)
  36. if choice != i%7 {
  37. t.Error("Returned partition", choice, "expecting", i%7)
  38. }
  39. }
  40. }
  41. func TestHashPartitioner(t *testing.T) {
  42. partitioner := NewHashPartitioner()
  43. choice := partitioner.Partition(nil, 1)
  44. if choice != 0 {
  45. t.Error("Returned non-zero partition when only one available.")
  46. }
  47. for i := 1; i < 50; i++ {
  48. choice := partitioner.Partition(nil, 50)
  49. if choice < 0 || choice >= 50 {
  50. t.Error("Returned partition", choice, "outside of range for nil key.")
  51. }
  52. }
  53. assertPartitioningConsistent(t, partitioner, StringEncoder("ABC"), 50)
  54. assertPartitioningConsistent(t, partitioner, StringEncoder("ABCDEF"), 37)
  55. assertPartitioningConsistent(t, partitioner, StringEncoder("some random thing"), 3)
  56. }