partitioner_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. }
  63. func TestConstantPartitioner(t *testing.T) {
  64. partitioner := &ConstantPartitioner{Constant: 0}
  65. for i := 1; i < 50; i++ {
  66. choice := partitioner.Partition(nil, 50)
  67. if choice != 0 {
  68. t.Error("Returned partition", choice, "instead of 0.")
  69. }
  70. }
  71. }