hashring_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package loadbalancer
  2. import (
  3. "testing"
  4. )
  5. const (
  6. node1 = "192.168.1.1"
  7. node2 = "192.168.1.2"
  8. node3 = "192.168.1.3"
  9. )
  10. func getNodesCount(nodes nodesArray) (int, int, int) {
  11. node1Count := 0
  12. node2Count := 0
  13. node3Count := 0
  14. for _, node := range nodes {
  15. if node.nodeKey == node1 {
  16. node1Count += 1
  17. }
  18. if node.nodeKey == node2 {
  19. node2Count += 1
  20. }
  21. if node.nodeKey == node3 {
  22. node3Count += 1
  23. }
  24. }
  25. return node1Count, node2Count, node3Count
  26. }
  27. func TestHash1(t *testing.T) {
  28. nodeWeight := make(map[string]int)
  29. nodeWeight[node1] = 2
  30. nodeWeight[node2] = 2
  31. nodeWeight[node3] = 3
  32. hash := NewHashRing()
  33. hash.AddNodes(nodeWeight)
  34. if hash.GetNode("1") != node1 {
  35. t.Fatalf("expetcd %v got %v", node3, hash.GetNode("1"))
  36. }
  37. if hash.GetNode("2") != node3 {
  38. t.Fatalf("expetcd %v got %v", node3, hash.GetNode("2"))
  39. }
  40. if hash.GetNode("3") != node2 {
  41. t.Fatalf("expetcd %v got %v", node2, hash.GetNode("3"))
  42. }
  43. c1, c2, c3 := getNodesCount(hash.nodes)
  44. t.Logf("len of nodes is %v after AddNodes node1:%v, node2:%v, node3:%v", len(hash.nodes), c1, c2, c3)
  45. hash.RemoveNode(node3)
  46. if hash.GetNode("1") != node1 {
  47. t.Fatalf("expetcd %v got %v", node1, hash.GetNode("1"))
  48. }
  49. if hash.GetNode("2") != node2 {
  50. t.Fatalf("expetcd %v got %v", node1, hash.GetNode("2"))
  51. }
  52. if hash.GetNode("3") != node2 {
  53. t.Fatalf("expetcd %v got %v", node2, hash.GetNode("3"))
  54. }
  55. c1, c2, c3 = getNodesCount(hash.nodes)
  56. t.Logf("len of nodes is %v after RemoveNode node1:%v, node2:%v, node3:%v", len(hash.nodes), c1, c2, c3)
  57. hash.AddNode(node3, 3)
  58. if hash.GetNode("1") != node1 {
  59. t.Fatalf("expetcd %v got %v", node3, hash.GetNode("1"))
  60. }
  61. if hash.GetNode("2") != node3 {
  62. t.Fatalf("expetcd %v got %v", node3, hash.GetNode("2"))
  63. }
  64. if hash.GetNode("3") != node2 {
  65. t.Fatalf("expetcd %v got %v", node2, hash.GetNode("3"))
  66. }
  67. c1, c2, c3 = getNodesCount(hash.nodes)
  68. t.Logf("len of nodes is %v after AddNode node1:%v, node2:%v, node3:%v", len(hash.nodes), c1, c2, c3)
  69. }