github.com/deanMdreon/kafka-go@v0.4.32/protocol/prototest/request.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/deanMdreon/kafka-go/protocol" 12 ) 13 14 func TestRequest(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.WriteRequest(b, version, 1234, "me", msg); err != nil { 21 t.Fatal(err) 22 } 23 24 reset() 25 26 t.Logf("\n%s\n", hex.Dump(b.Bytes())) 27 28 apiVersion, correlationID, clientID, req, err := protocol.ReadRequest(b) 29 if err != nil { 30 t.Fatal(err) 31 } 32 if apiVersion != version { 33 t.Errorf("api version mismatch: %d != %d", apiVersion, version) 34 } 35 if correlationID != 1234 { 36 t.Errorf("correlation id mismatch: %d != %d", correlationID, 1234) 37 } 38 if clientID != "me" { 39 t.Errorf("client id mismatch: %q != %q", clientID, "me") 40 } 41 if !deepEqual(msg, req) { 42 t.Errorf("request message mismatch:") 43 t.Logf("expected: %+v", msg) 44 t.Logf("found: %+v", req) 45 } 46 }) 47 } 48 49 func BenchmarkRequest(b *testing.B, version int16, msg protocol.Message) { 50 reset := load(msg) 51 52 b.Run(fmt.Sprintf("v%d", version), func(b *testing.B) { 53 buffer := &bytes.Buffer{} 54 buffer.Grow(1024) 55 56 b.Run("read", func(b *testing.B) { 57 w := io.Writer(buffer) 58 59 if err := protocol.WriteRequest(w, version, 1234, "client", msg); err != nil { 60 b.Fatal(err) 61 } 62 63 reset() 64 65 p := buffer.Bytes() 66 x := bytes.NewReader(p) 67 r := bufio.NewReader(x) 68 69 for i := 0; i < b.N; i++ { 70 _, _, _, req, err := protocol.ReadRequest(r) 71 if err != nil { 72 b.Fatal(err) 73 } 74 closeMessage(req) 75 x.Reset(p) 76 r.Reset(x) 77 } 78 79 b.SetBytes(int64(len(p))) 80 buffer.Reset() 81 }) 82 83 b.Run("write", func(b *testing.B) { 84 w := io.Writer(buffer) 85 n := int64(0) 86 87 for i := 0; i < b.N; i++ { 88 if err := protocol.WriteRequest(w, version, 1234, "client", msg); err != nil { 89 b.Fatal(err) 90 } 91 reset() 92 n = int64(buffer.Len()) 93 buffer.Reset() 94 } 95 96 b.SetBytes(n) 97 }) 98 }) 99 }