github.com/hack0072008/kafka-go@v1.0.1/protocol/buffer_test.go (about) 1 package protocol 2 3 import ( 4 "bytes" 5 "io" 6 "io/ioutil" 7 "testing" 8 ) 9 10 func TestPageBufferWriteReadSeek(t *testing.T) { 11 buffer := newPageBuffer() 12 defer buffer.unref() 13 14 io.WriteString(buffer, "Hello World!") 15 16 if n := buffer.Size(); n != 12 { 17 t.Fatal("invalid size:", n) 18 } 19 20 for i := 0; i < 3; i++ { 21 if n := buffer.Len(); n != 12 { 22 t.Fatal("invalid length before read:", n) 23 } 24 25 b, err := ioutil.ReadAll(buffer) 26 if err != nil { 27 t.Fatal(err) 28 } 29 30 if n := buffer.Len(); n != 0 { 31 t.Fatal("invalid length after read:", n) 32 } 33 34 if string(b) != "Hello World!" { 35 t.Fatalf("invalid content after read #%d: %q", i, b) 36 } 37 38 offset, err := buffer.Seek(0, io.SeekStart) 39 if err != nil { 40 t.Fatal(err) 41 } 42 if offset != 0 { 43 t.Fatalf("invalid offset after seek #%d: %d", i, offset) 44 } 45 } 46 } 47 48 func TestPageRefWriteReadSeek(t *testing.T) { 49 buffer := newPageBuffer() 50 defer buffer.unref() 51 52 io.WriteString(buffer, "Hello World!") 53 54 ref := buffer.ref(1, 11) 55 defer ref.unref() 56 57 if n := ref.Size(); n != 10 { 58 t.Fatal("invalid size:", n) 59 } 60 61 for i := 0; i < 3; i++ { 62 if n := ref.Len(); n != 10 { 63 t.Fatal("invalid length before read:", n) 64 } 65 66 b, err := ioutil.ReadAll(ref) 67 if err != nil { 68 t.Fatal(err) 69 } 70 71 if n := ref.Len(); n != 0 { 72 t.Fatal("invalid length after read:", n) 73 } 74 75 if string(b) != "ello World" { 76 t.Fatalf("invalid content after read #%d: %q", i, b) 77 } 78 79 offset, err := ref.Seek(0, io.SeekStart) 80 if err != nil { 81 t.Fatal(err) 82 } 83 if offset != 0 { 84 t.Fatalf("invalid offset after seek #%d: %d", i, offset) 85 } 86 } 87 } 88 89 func TestPageRefReadByte(t *testing.T) { 90 buffer := newPageBuffer() 91 defer buffer.unref() 92 93 content := bytes.Repeat([]byte("1234567890"), 10e3) 94 buffer.Write(content) 95 96 ref := buffer.ref(0, buffer.Size()) 97 defer ref.unref() 98 99 for i, c := range content { 100 b, err := ref.ReadByte() 101 if err != nil { 102 t.Fatal(err) 103 } 104 if b != c { 105 t.Fatalf("byte at offset %d mismatch, expected '%c' but got '%c'", i, c, b) 106 } 107 } 108 }