github.com/grailbio/base@v0.0.11/file/fsnodefuse/trailingbuf/trailbuf_test.go (about)

     1  package trailingbuf
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"strings"
     7  	"testing"
     8  
     9  	"github.com/grailbio/base/ioctx"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestBasic(t *testing.T) {
    14  	const src = "0123456789"
    15  	r := New(ioctx.FromStdReader(strings.NewReader(src)), 0, 2)
    16  	ctx := context.Background()
    17  
    18  	// Initial read, larger than trail buf.
    19  	b := make([]byte, 3)
    20  	n, err := r.ReadAt(ctx, b, 0)
    21  	require.NoError(t, err)
    22  	require.Equal(t, len(b), n)
    23  	require.Equal(t, "012", string(b))
    24  
    25  	// Backwards by a little.
    26  	b = make([]byte, 2)
    27  	n, err = r.ReadAt(ctx, b, 1)
    28  	require.NoError(t, err)
    29  	require.Equal(t, len(b), n)
    30  	require.Equal(t, "12", string(b))
    31  
    32  	// Backwards by too much.
    33  	b = make([]byte, 1)
    34  	_, err = r.ReadAt(ctx, b, 0)
    35  	require.Error(t, err)
    36  	require.ErrorIs(t, err, ErrTooFarBehind)
    37  
    38  	// Jump forward. Discards (not visible; exercising internal paths) because we skip off=3.
    39  	b = make([]byte, 2)
    40  	n, err = r.ReadAt(ctx, b, 4)
    41  	require.NoError(t, err)
    42  	require.Equal(t, len(b), n)
    43  	require.Equal(t, "45", string(b))
    44  
    45  	// Forwards, overlapping.
    46  	b = make([]byte, 4)
    47  	n, err = r.ReadAt(ctx, b, 4)
    48  	require.NoError(t, err)
    49  	require.Equal(t, len(b), n)
    50  	require.Equal(t, "4567", string(b))
    51  
    52  	// Jump again.
    53  	b = make([]byte, 5)
    54  	n, err = r.ReadAt(ctx, b, 9)
    55  	if err != io.EOF {
    56  		require.NoError(t, err)
    57  	}
    58  	require.Equal(t, 1, n)
    59  	require.Equal(t, "9", string(b[:1]))
    60  
    61  	// Make sure we can still read backwards after EOF.
    62  	b = make([]byte, 1)
    63  	n, err = r.ReadAt(ctx, b, 8)
    64  	if err != io.EOF {
    65  		require.NoError(t, err)
    66  	}
    67  	require.Equal(t, len(b), n)
    68  	require.Equal(t, "8", string(b))
    69  }
    70  
    71  // TODO: Randomized, concurrent tests.