github.com/coocood/badger@v1.5.1-0.20200528065104-c02ac3616d04/fileutil/writer_test.go (about)

     1  package fileutil
     2  
     3  import (
     4  	"io"
     5  	"os"
     6  	"testing"
     7  
     8  	"github.com/ncw/directio"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestAlignedSize(t *testing.T) {
    13  	tests := []struct {
    14  		size          int64
    15  		alignedBlocks int64
    16  	}{
    17  		{0, 0},
    18  		{1, 1},
    19  		{4095, 1},
    20  		{4096, 1},
    21  		{4097, 2},
    22  		{8191, 2},
    23  		{8192, 2},
    24  		{8193, 3},
    25  	}
    26  	for _, tt := range tests {
    27  		if alignedSize(tt.size) != tt.alignedBlocks*directio.BlockSize {
    28  			t.FailNow()
    29  		}
    30  	}
    31  }
    32  
    33  func TestDirectWriter(t *testing.T) {
    34  	fileName := "direct_test"
    35  	fd, err := directio.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
    36  	directFile := NewDirectWriter(fd, directio.BlockSize, nil)
    37  	defer os.Remove(fileName)
    38  	require.Nil(t, err)
    39  	val := make([]byte, 1000)
    40  	for i := 0; i < 100; i++ {
    41  		setVal(val, byte(i))
    42  		err := directFile.Append(val)
    43  		require.Nil(t, err)
    44  	}
    45  	err = directFile.Finish()
    46  	require.Nil(t, err)
    47  	fd.Close()
    48  	file, err := os.Open(fileName)
    49  	require.Nil(t, err)
    50  	info, err := file.Stat()
    51  	require.Nil(t, err)
    52  	require.Equal(t, info.Size(), int64(100*1000))
    53  	for i := 0; i < 100; i++ {
    54  		_, err = io.ReadFull(file, val)
    55  		require.Nil(t, err)
    56  		for _, v := range val {
    57  			require.Equal(t, v, byte(i))
    58  		}
    59  	}
    60  	file.Close()
    61  }
    62  
    63  func setVal(buf []byte, v byte) {
    64  	for i := range buf {
    65  		buf[i] = v
    66  	}
    67  }