github.com/lingyao2333/mo-zero@v1.4.1/core/iox/read_test.go (about) 1 package iox 2 3 import ( 4 "bytes" 5 "io" 6 "os" 7 "testing" 8 "time" 9 10 "github.com/lingyao2333/mo-zero/core/fs" 11 "github.com/lingyao2333/mo-zero/core/stringx" 12 "github.com/stretchr/testify/assert" 13 ) 14 15 func TestReadText(t *testing.T) { 16 tests := []struct { 17 input string 18 expect string 19 }{ 20 { 21 input: `a`, 22 expect: `a`, 23 }, { 24 input: `a 25 `, 26 expect: `a`, 27 }, { 28 input: `a 29 b`, 30 expect: `a 31 b`, 32 }, { 33 input: `a 34 b 35 `, 36 expect: `a 37 b`, 38 }, 39 } 40 41 for _, test := range tests { 42 t.Run(test.input, func(t *testing.T) { 43 tmpfile, err := fs.TempFilenameWithText(test.input) 44 assert.Nil(t, err) 45 defer os.Remove(tmpfile) 46 47 content, err := ReadText(tmpfile) 48 assert.Nil(t, err) 49 assert.Equal(t, test.expect, content) 50 }) 51 } 52 } 53 54 func TestReadTextLines(t *testing.T) { 55 text := `1 56 57 2 58 59 #a 60 3` 61 62 tmpfile, err := fs.TempFilenameWithText(text) 63 assert.Nil(t, err) 64 defer os.Remove(tmpfile) 65 66 tests := []struct { 67 options []TextReadOption 68 expectLines int 69 }{ 70 { 71 nil, 72 6, 73 }, { 74 []TextReadOption{KeepSpace(), OmitWithPrefix("#")}, 75 6, 76 }, { 77 []TextReadOption{WithoutBlank()}, 78 4, 79 }, { 80 []TextReadOption{OmitWithPrefix("#")}, 81 5, 82 }, { 83 []TextReadOption{WithoutBlank(), OmitWithPrefix("#")}, 84 3, 85 }, 86 } 87 88 for _, test := range tests { 89 t.Run(stringx.Rand(), func(t *testing.T) { 90 lines, err := ReadTextLines(tmpfile, test.options...) 91 assert.Nil(t, err) 92 assert.Equal(t, test.expectLines, len(lines)) 93 }) 94 } 95 } 96 97 func TestDupReadCloser(t *testing.T) { 98 input := "hello" 99 reader := io.NopCloser(bytes.NewBufferString(input)) 100 r1, r2 := DupReadCloser(reader) 101 verify := func(r io.Reader) { 102 output, err := io.ReadAll(r) 103 assert.Nil(t, err) 104 assert.Equal(t, input, string(output)) 105 } 106 107 verify(r1) 108 verify(r2) 109 } 110 111 func TestReadBytes(t *testing.T) { 112 reader := io.NopCloser(bytes.NewBufferString("helloworld")) 113 buf := make([]byte, 5) 114 err := ReadBytes(reader, buf) 115 assert.Nil(t, err) 116 assert.Equal(t, "hello", string(buf)) 117 } 118 119 func TestReadBytesNotEnough(t *testing.T) { 120 reader := io.NopCloser(bytes.NewBufferString("hell")) 121 buf := make([]byte, 5) 122 err := ReadBytes(reader, buf) 123 assert.Equal(t, io.EOF, err) 124 } 125 126 func TestReadBytesChunks(t *testing.T) { 127 buf := make([]byte, 5) 128 reader, writer := io.Pipe() 129 130 go func() { 131 for i := 0; i < 10; i++ { 132 writer.Write([]byte{'a'}) 133 time.Sleep(10 * time.Millisecond) 134 } 135 }() 136 137 err := ReadBytes(reader, buf) 138 assert.Nil(t, err) 139 assert.Equal(t, "aaaaa", string(buf)) 140 }