github.com/rbisecke/kafka-go@v0.4.27/findcoordinator_test.go (about) 1 package kafka 2 3 import ( 4 "bufio" 5 "bytes" 6 "context" 7 "errors" 8 "fmt" 9 "reflect" 10 "strings" 11 "testing" 12 "time" 13 ) 14 15 func TestFindCoordinatorResponseV0(t *testing.T) { 16 item := findCoordinatorResponseV0{ 17 ErrorCode: 2, 18 Coordinator: findCoordinatorResponseCoordinatorV0{ 19 NodeID: 3, 20 Host: "b", 21 Port: 4, 22 }, 23 } 24 25 b := bytes.NewBuffer(nil) 26 w := &writeBuffer{w: b} 27 item.writeTo(w) 28 29 var found findCoordinatorResponseV0 30 remain, err := (&found).readFrom(bufio.NewReader(b), b.Len()) 31 if err != nil { 32 t.Error(err) 33 t.FailNow() 34 } 35 if remain != 0 { 36 t.Errorf("expected 0 remain, got %v", remain) 37 t.FailNow() 38 } 39 if !reflect.DeepEqual(item, found) { 40 t.Error("expected item and found to be the same") 41 t.FailNow() 42 } 43 } 44 45 func TestClientFindCoordinator(t *testing.T) { 46 client, shutdown := newLocalClient() 47 defer shutdown() 48 49 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) 50 defer cancel() 51 resp, err := waitForCoordinatorIndefinitely(ctx, client, &FindCoordinatorRequest{ 52 Addr: client.Addr, 53 Key: "TransactionalID-1", 54 KeyType: CoordinatorKeyTypeTransaction, 55 }) 56 57 if err != nil { 58 t.Fatal(err) 59 } 60 61 if resp.Coordinator.Host != "localhost" { 62 t.Fatal("Coordinator should be found @ localhost") 63 } 64 } 65 66 // WaitForCoordinatorIndefinitely is a blocking call till a coordinator is found 67 func waitForCoordinatorIndefinitely(ctx context.Context, c *Client, req *FindCoordinatorRequest) (*FindCoordinatorResponse, error) { 68 fmt.Println("Trying to find Coordinator.") 69 resp, err := c.FindCoordinator(ctx, req) 70 71 for shouldRetryfindingCoordinator(resp, err) && ctx.Err() == nil { 72 time.Sleep(1 * time.Second) 73 resp, err = c.FindCoordinator(ctx, req) 74 } 75 return resp, err 76 } 77 78 // Should retry looking for coordinator 79 // Returns true when the test Kafka broker is still setting up 80 func shouldRetryfindingCoordinator(resp *FindCoordinatorResponse, err error) bool { 81 brokerSetupIncomplete := err != nil && 82 strings.Contains( 83 strings.ToLower(err.Error()), 84 strings.ToLower("unexpected EOF")) 85 coordinatorNotFound := resp != nil && 86 resp.Error != nil && 87 errors.Is(resp.Error, GroupCoordinatorNotAvailable) 88 return brokerSetupIncomplete || coordinatorNotFound 89 }