policies_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright (c) 2015 The gocql Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gocql
  5. import "testing"
  6. func TestRoundRobinHostPolicy(t *testing.T) {
  7. policy := NewRoundRobinHostPolicy()
  8. hosts := []HostInfo{
  9. HostInfo{HostId: "0"},
  10. HostInfo{HostId: "1"},
  11. }
  12. policy.SetHosts(hosts)
  13. // the first host selected is actually at [1], but this is ok for RR
  14. // interleaved iteration should always increment the host
  15. iterA := policy.Pick(nil)
  16. if actual := iterA(); actual != &hosts[1] {
  17. t.Errorf("Expected hosts[1] but was hosts[%s]", actual.HostId)
  18. }
  19. iterB := policy.Pick(nil)
  20. if actual := iterB(); actual != &hosts[0] {
  21. t.Errorf("Expected hosts[0] but was hosts[%s]", actual.HostId)
  22. }
  23. if actual := iterB(); actual != &hosts[1] {
  24. t.Errorf("Expected hosts[1] but was hosts[%s]", actual.HostId)
  25. }
  26. if actual := iterA(); actual != &hosts[0] {
  27. t.Errorf("Expected hosts[0] but was hosts[%s]", actual.HostId)
  28. }
  29. iterC := policy.Pick(nil)
  30. if actual := iterC(); actual != &hosts[1] {
  31. t.Errorf("Expected hosts[1] but was hosts[%s]", actual.HostId)
  32. }
  33. if actual := iterC(); actual != &hosts[0] {
  34. t.Errorf("Expected hosts[0] but was hosts[%s]", actual.HostId)
  35. }
  36. }
  37. func TestTokenAwareHostPolicy(t *testing.T) {
  38. policy := NewTokenAwareHostPolicy(NewRoundRobinHostPolicy())
  39. hosts := []HostInfo{
  40. HostInfo{HostId: "0", Peer: "0", Tokens: []string{"00"}},
  41. HostInfo{HostId: "1", Peer: "1", Tokens: []string{"25"}},
  42. HostInfo{HostId: "2", Peer: "2", Tokens: []string{"50"}},
  43. HostInfo{HostId: "3", Peer: "3", Tokens: []string{"75"}},
  44. }
  45. policy.SetHosts(hosts)
  46. policy.SetPartitioner("OrderedPartitioner")
  47. query := &Query{}
  48. query.RoutingKey([]byte("30"))
  49. if actual := policy.Pick(query)(); actual != &hosts[2] {
  50. t.Errorf("Expected hosts[2] but was hosts[%s]", actual.HostId)
  51. }
  52. }
  53. func TestRoundRobinConnPolicy(t *testing.T) {
  54. policy := NewRoundRobinConnPolicy()
  55. conn0 := &Conn{}
  56. conn1 := &Conn{}
  57. conn := []*Conn{
  58. conn0,
  59. conn1,
  60. }
  61. policy.SetConns(conn)
  62. // the first conn selected is actually at [1], but this is ok for RR
  63. if actual := policy.Pick(nil); actual != conn1 {
  64. t.Error("Expected conn1")
  65. }
  66. if actual := policy.Pick(nil); actual != conn0 {
  67. t.Error("Expected conn0")
  68. }
  69. if actual := policy.Pick(nil); actual != conn1 {
  70. t.Error("Expected conn1")
  71. }
  72. }