code.gitea.io/gitea@v1.22.3/modules/util/io_test.go (about)

     1  // Copyright 2023 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package util
     5  
     6  import (
     7  	"bytes"
     8  	"errors"
     9  	"testing"
    10  
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  type readerWithError struct {
    15  	buf *bytes.Buffer
    16  }
    17  
    18  func (r *readerWithError) Read(p []byte) (n int, err error) {
    19  	if r.buf.Len() < 2 {
    20  		return 0, errors.New("test error")
    21  	}
    22  	return r.buf.Read(p)
    23  }
    24  
    25  func TestReadWithLimit(t *testing.T) {
    26  	bs := []byte("0123456789abcdef")
    27  
    28  	// normal test
    29  	buf, err := readWithLimit(bytes.NewBuffer(bs), 5, 2)
    30  	assert.NoError(t, err)
    31  	assert.Equal(t, []byte("01"), buf)
    32  
    33  	buf, err = readWithLimit(bytes.NewBuffer(bs), 5, 5)
    34  	assert.NoError(t, err)
    35  	assert.Equal(t, []byte("01234"), buf)
    36  
    37  	buf, err = readWithLimit(bytes.NewBuffer(bs), 5, 6)
    38  	assert.NoError(t, err)
    39  	assert.Equal(t, []byte("012345"), buf)
    40  
    41  	buf, err = readWithLimit(bytes.NewBuffer(bs), 5, len(bs))
    42  	assert.NoError(t, err)
    43  	assert.Equal(t, []byte("0123456789abcdef"), buf)
    44  
    45  	buf, err = readWithLimit(bytes.NewBuffer(bs), 5, 100)
    46  	assert.NoError(t, err)
    47  	assert.Equal(t, []byte("0123456789abcdef"), buf)
    48  
    49  	// test with error
    50  	buf, err = readWithLimit(&readerWithError{bytes.NewBuffer(bs)}, 5, 10)
    51  	assert.NoError(t, err)
    52  	assert.Equal(t, []byte("0123456789"), buf)
    53  
    54  	buf, err = readWithLimit(&readerWithError{bytes.NewBuffer(bs)}, 5, 100)
    55  	assert.ErrorContains(t, err, "test error")
    56  	assert.Empty(t, buf)
    57  
    58  	// test public function
    59  	buf, err = ReadWithLimit(bytes.NewBuffer(bs), 2)
    60  	assert.NoError(t, err)
    61  	assert.Equal(t, []byte("01"), buf)
    62  
    63  	buf, err = ReadWithLimit(bytes.NewBuffer(bs), 9999999)
    64  	assert.NoError(t, err)
    65  	assert.Equal(t, []byte("0123456789abcdef"), buf)
    66  }