github.com/streamdal/segmentio-kafka-go@v0.4.47-streamdal/protocol/prototest/response.go (about) 1 package prototest 2 3 import ( 4 "bufio" 5 "bytes" 6 "encoding/hex" 7 "fmt" 8 "io" 9 "testing" 10 11 "github.com/segmentio/kafka-go/protocol" 12 ) 13 14 func TestResponse(t *testing.T, version int16, msg protocol.Message) { 15 reset := load(msg) 16 17 t.Run(fmt.Sprintf("v%d", version), func(t *testing.T) { 18 b := &bytes.Buffer{} 19 20 if err := protocol.WriteResponse(b, version, 1234, msg); err != nil { 21 t.Fatal(err) 22 } 23 24 reset() 25 26 t.Logf("\n%s", hex.Dump(b.Bytes())) 27 28 correlationID, res, err := protocol.ReadResponse(b, msg.ApiKey(), version) 29 if err != nil { 30 t.Fatal(err) 31 } 32 if correlationID != 1234 { 33 t.Errorf("correlation id mismatch: %d != %d", correlationID, 1234) 34 } 35 if !deepEqual(msg, res) { 36 t.Errorf("response message mismatch:") 37 t.Logf("expected: %+v", msg) 38 t.Logf("found: %+v", res) 39 } 40 closeMessage(res) 41 }) 42 } 43 44 func BenchmarkResponse(b *testing.B, version int16, msg protocol.Message) { 45 reset := load(msg) 46 47 b.Run(fmt.Sprintf("v%d", version), func(b *testing.B) { 48 apiKey := msg.ApiKey() 49 buffer := &bytes.Buffer{} 50 buffer.Grow(1024) 51 52 b.Run("read", func(b *testing.B) { 53 w := io.Writer(buffer) 54 55 if err := protocol.WriteResponse(w, version, 1234, msg); err != nil { 56 b.Fatal(err) 57 } 58 59 reset() 60 61 p := buffer.Bytes() 62 x := bytes.NewReader(p) 63 r := bufio.NewReader(x) 64 65 for i := 0; i < b.N; i++ { 66 _, res, err := protocol.ReadResponse(r, apiKey, version) 67 if err != nil { 68 b.Fatal(err) 69 } 70 closeMessage(res) 71 x.Reset(p) 72 r.Reset(x) 73 } 74 75 b.SetBytes(int64(len(p))) 76 buffer.Reset() 77 }) 78 79 b.Run("write", func(b *testing.B) { 80 w := io.Writer(buffer) 81 n := int64(0) 82 83 for i := 0; i < b.N; i++ { 84 if err := protocol.WriteResponse(w, version, 1234, msg); err != nil { 85 b.Fatal(err) 86 } 87 reset() 88 n = int64(buffer.Len()) 89 buffer.Reset() 90 } 91 92 b.SetBytes(n) 93 }) 94 }) 95 }