partitioner_test.go 1.8 KB

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