wrr_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package wrr
  2. import (
  3. "context"
  4. "fmt"
  5. "testing"
  6. nmd "go-common/library/net/metadata"
  7. wmeta "go-common/library/net/rpc/warden/metadata"
  8. "google.golang.org/grpc/balancer"
  9. "google.golang.org/grpc/resolver"
  10. )
  11. type testSubConn struct {
  12. addr resolver.Address
  13. }
  14. func (s *testSubConn) UpdateAddresses([]resolver.Address) {
  15. }
  16. // Connect starts the connecting for this SubConn.
  17. func (s *testSubConn) Connect() {
  18. fmt.Println(s.addr.Addr)
  19. }
  20. func TestBalancerPick(t *testing.T) {
  21. scs := map[resolver.Address]balancer.SubConn{}
  22. sc1 := &testSubConn{
  23. addr: resolver.Address{
  24. Addr: "test1",
  25. Metadata: wmeta.MD{
  26. Weight: 8,
  27. },
  28. },
  29. }
  30. sc2 := &testSubConn{
  31. addr: resolver.Address{
  32. Addr: "test2",
  33. Metadata: wmeta.MD{
  34. Weight: 4,
  35. Color: "red",
  36. },
  37. },
  38. }
  39. sc3 := &testSubConn{
  40. addr: resolver.Address{
  41. Addr: "test3",
  42. Metadata: wmeta.MD{
  43. Weight: 2,
  44. Color: "red",
  45. },
  46. },
  47. }
  48. scs[sc1.addr] = sc1
  49. scs[sc2.addr] = sc2
  50. scs[sc3.addr] = sc3
  51. b := &wrrPickerBuilder{}
  52. picker := b.Build(scs)
  53. res := []string{"test1", "test1", "test1", "test1"}
  54. for i := 0; i < 3; i++ {
  55. conn, _, err := picker.Pick(context.Background(), balancer.PickOptions{})
  56. if err != nil {
  57. t.Fatalf("picker.Pick failed!idx:=%d", i)
  58. }
  59. sc := conn.(*testSubConn)
  60. if sc.addr.Addr != res[i] {
  61. t.Fatalf("the subconn picked(%s),but expected(%s)", sc.addr.Addr, res[i])
  62. }
  63. }
  64. res2 := []string{"test2", "test3", "test2", "test2", "test3", "test2"}
  65. ctx := nmd.NewContext(context.Background(), nmd.New(map[string]interface{}{"color": "red"}))
  66. for i := 0; i < 6; i++ {
  67. conn, _, err := picker.Pick(ctx, balancer.PickOptions{})
  68. if err != nil {
  69. t.Fatalf("picker.Pick failed!idx:=%d", i)
  70. }
  71. sc := conn.(*testSubConn)
  72. if sc.addr.Addr != res2[i] {
  73. t.Fatalf("the (%d) subconn picked(%s),but expected(%s)", i, sc.addr.Addr, res2[i])
  74. }
  75. }
  76. ctx = nmd.NewContext(context.Background(), nmd.New(map[string]interface{}{"color": "black"}))
  77. for i := 0; i < 4; i++ {
  78. conn, _, err := picker.Pick(ctx, balancer.PickOptions{})
  79. if err != nil {
  80. t.Fatalf("picker.Pick failed!idx:=%d", i)
  81. }
  82. sc := conn.(*testSubConn)
  83. if sc.addr.Addr != res[i] {
  84. t.Fatalf("the (%d) subconn picked(%s),but expected(%s)", i, sc.addr.Addr, res[i])
  85. }
  86. }
  87. }