github.com/hoveychen/kafka-go@v0.4.42/heartbeat_test.go (about)

     1  package kafka
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"context"
     7  	"log"
     8  	"os"
     9  	"reflect"
    10  	"testing"
    11  	"time"
    12  )
    13  
    14  func TestClientHeartbeat(t *testing.T) {
    15  	client, topic, shutdown := newLocalClientAndTopic()
    16  	defer shutdown()
    17  
    18  	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
    19  	defer cancel()
    20  
    21  	groupID := makeGroupID()
    22  
    23  	group, err := NewConsumerGroup(ConsumerGroupConfig{
    24  		ID:                groupID,
    25  		Topics:            []string{topic},
    26  		Brokers:           []string{"localhost:9092"},
    27  		HeartbeatInterval: 2 * time.Second,
    28  		RebalanceTimeout:  2 * time.Second,
    29  		RetentionTime:     time.Hour,
    30  		Logger:            log.New(os.Stdout, "cg-test: ", 0),
    31  	})
    32  	if err != nil {
    33  		t.Fatal(err)
    34  	}
    35  	defer group.Close()
    36  
    37  	gen, err := group.Next(ctx)
    38  	if err != nil {
    39  		t.Fatal(err)
    40  	}
    41  
    42  	ctx, cancel = context.WithTimeout(context.Background(), time.Second*30)
    43  	defer cancel()
    44  
    45  	resp, err := client.Heartbeat(ctx, &HeartbeatRequest{
    46  		GroupID:      groupID,
    47  		GenerationID: gen.ID,
    48  		MemberID:     gen.MemberID,
    49  	})
    50  	if err != nil {
    51  		t.Fatal(err)
    52  	}
    53  
    54  	if resp.Error != nil {
    55  		t.Error(resp.Error)
    56  	}
    57  }
    58  
    59  func TestHeartbeatRequestV0(t *testing.T) {
    60  	item := heartbeatResponseV0{
    61  		ErrorCode: 2,
    62  	}
    63  
    64  	b := bytes.NewBuffer(nil)
    65  	w := &writeBuffer{w: b}
    66  	item.writeTo(w)
    67  
    68  	var found heartbeatResponseV0
    69  	remain, err := (&found).readFrom(bufio.NewReader(b), b.Len())
    70  	if err != nil {
    71  		t.Error(err)
    72  		t.FailNow()
    73  	}
    74  	if remain != 0 {
    75  		t.Errorf("expected 0 remain, got %v", remain)
    76  		t.FailNow()
    77  	}
    78  	if !reflect.DeepEqual(item, found) {
    79  		t.Error("expected item and found to be the same")
    80  		t.FailNow()
    81  	}
    82  }