github.com/cloudwego/hertz@v0.9.3/pkg/common/test/mock/reader_test.go (about) 1 /* 2 * Copyright 2022 CloudWeGo Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package mock 18 19 import ( 20 "bufio" 21 "io" 22 "testing" 23 "testing/iotest" 24 25 "github.com/cloudwego/hertz/pkg/common/test/assert" 26 ) 27 28 func TestZeroCopyReader(t *testing.T) { 29 // raw 30 r := "abcdef4343" 31 zr := NewZeroCopyReader(r) 32 rs := readBytes(zr.Reader) 33 assert.DeepEqual(t, rs, r) 34 35 // peek 36 zr = NewZeroCopyReader(r) 37 s, err := zr.Peek(1) 38 assert.DeepEqual(t, nil, err) 39 assert.DeepEqual(t, "a", string(s)) 40 41 s, err = zr.Peek(4) 42 assert.DeepEqual(t, nil, err) 43 assert.DeepEqual(t, "abcd", string(s)) 44 45 // https://github.com/golang/go/issues/50569 46 ezr := NewZeroCopyReader("") 47 s, err = ezr.Peek(32) 48 assert.DeepEqual(t, io.EOF, err) 49 assert.DeepEqual(t, "", string(s)) 50 51 // skip 52 err = zr.Skip(1) 53 assert.DeepEqual(t, nil, err) 54 55 s, err = zr.Peek(4) 56 assert.DeepEqual(t, nil, err) 57 assert.DeepEqual(t, "bcde", string(s)) 58 59 // len 60 assert.DeepEqual(t, len(r)-1, zr.Len()) 61 assert.DeepEqual(t, nil, ezr.Release()) 62 assert.Panic(t, func() { // not implement 63 zr.ReadBinary(10) 64 }) 65 } 66 67 func TestEOFReader(t *testing.T) { 68 r := &EOFReader{} 69 s, err := r.Peek(1) 70 assert.DeepEqual(t, io.EOF, err) 71 assert.DeepEqual(t, "", string(s)) 72 assert.DeepEqual(t, nil, r.Skip(1)) 73 assert.DeepEqual(t, 0, r.Len()) 74 75 _, err = r.ReadByte() 76 assert.DeepEqual(t, io.EOF, err) 77 _, err = r.ReadBinary(10) 78 assert.DeepEqual(t, io.EOF, err) 79 _, err = r.Read(s) 80 assert.DeepEqual(t, io.EOF, err) 81 assert.DeepEqual(t, nil, r.Release()) 82 } 83 84 func readBytes(buf *bufio.Reader) string { 85 var b [1000]byte 86 nb := 0 87 for { 88 c, err := buf.ReadByte() 89 if err == io.EOF { 90 break 91 } 92 if err == nil { 93 b[nb] = c 94 nb++ 95 } else if err != iotest.ErrTimeout { 96 panic("Data: " + err.Error()) 97 } 98 } 99 return string(b[0:nb]) 100 }