github.com/grailbio/base@v0.0.11/compress/zstd/zstd_test.go (about)

     1  package zstd_test
     2  
     3  import (
     4  	"flag"
     5  	"io/ioutil"
     6  	"os"
     7  	"testing"
     8  
     9  	"bytes"
    10  	"io"
    11  
    12  	"github.com/grailbio/base/compress/zstd"
    13  	"github.com/grailbio/testutil/assert"
    14  )
    15  
    16  func TestCompress(t *testing.T) {
    17  	z, err := zstd.CompressLevel(nil, []byte("hello"), -1)
    18  	assert.NoError(t, err)
    19  	assert.GT(t, len(z), 0)
    20  	d, err := zstd.Decompress(nil, z)
    21  	assert.NoError(t, err)
    22  	assert.EQ(t, d, []byte("hello"))
    23  }
    24  
    25  func TestCompressScratch(t *testing.T) {
    26  	z, err := zstd.CompressLevel(make([]byte, 3), []byte("hello"), -1)
    27  	assert.NoError(t, err)
    28  	assert.GT(t, len(z), 0)
    29  	d, err := zstd.Decompress(make([]byte, 3), z)
    30  	assert.NoError(t, err)
    31  	assert.EQ(t, d, []byte("hello"))
    32  }
    33  
    34  func TestReadWrite(t *testing.T) {
    35  	buf := bytes.Buffer{}
    36  	w, err := zstd.NewWriter(&buf)
    37  	assert.NoError(t, err)
    38  	_, err = io.WriteString(w, "hello2")
    39  	assert.NoError(t, err)
    40  	assert.NoError(t, w.Close())
    41  
    42  	r, err := zstd.NewReader(&buf)
    43  	assert.NoError(t, err)
    44  	d, err := ioutil.ReadAll(r)
    45  	assert.NoError(t, err)
    46  	assert.EQ(t, d, []byte("hello2"))
    47  }
    48  
    49  var plaintextFlag = flag.String("plaintext", "", "plaintext file used in compression test")
    50  
    51  func BenchmarkCompress(b *testing.B) {
    52  	if *plaintextFlag == "" {
    53  		b.Skip("--plaintext not set")
    54  	}
    55  
    56  	for i := 0; i < b.N; i++ {
    57  		buf := bytes.Buffer{}
    58  		w, err := zstd.NewWriter(&buf)
    59  		assert.NoError(b, err)
    60  		r, err := os.Open(*plaintextFlag)
    61  		assert.NoError(b, err)
    62  		_, err = io.Copy(w, r)
    63  		assert.NoError(b, err)
    64  		assert.NoError(b, w.Close())
    65  		assert.NoError(b, r.Close())
    66  	}
    67  }
    68  
    69  func BenchmarkUncompress(b *testing.B) {
    70  	if *plaintextFlag == "" {
    71  		b.Skip("--plaintext not set")
    72  	}
    73  
    74  	b.StopTimer()
    75  	buf := bytes.Buffer{}
    76  	w, err := zstd.NewWriter(&buf)
    77  	assert.NoError(b, err)
    78  	r, err := os.Open(*plaintextFlag)
    79  	assert.NoError(b, err)
    80  	_, err = io.Copy(w, r)
    81  	assert.NoError(b, err)
    82  	assert.NoError(b, w.Close())
    83  	assert.NoError(b, r.Close())
    84  	b.StartTimer()
    85  
    86  	for i := 0; i < b.N; i++ {
    87  		zr, err := zstd.NewReader(bytes.NewReader(buf.Bytes()))
    88  		assert.NoError(b, err)
    89  
    90  		w := bytes.Buffer{}
    91  		_, err = io.Copy(&w, zr)
    92  		assert.NoError(b, err)
    93  		assert.NoError(b, zr.Close())
    94  	}
    95  }