github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/segment/writer/metrics/compress/compressor_test.go (about)

     1  /*
     2  Copyright 2023.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package compress
    18  
    19  import (
    20  	"bytes"
    21  	"math/rand"
    22  	"testing"
    23  	"time"
    24  
    25  	fuzz "github.com/google/gofuzz"
    26  	"github.com/stretchr/testify/assert"
    27  	"github.com/stretchr/testify/require"
    28  )
    29  
    30  func Test_Compress_Decompress(t *testing.T) {
    31  	type data struct {
    32  		t uint32
    33  		v float64
    34  	}
    35  	header := uint32(time.Now().Unix())
    36  
    37  	const dataLen = 50000
    38  	expected := make([]data, dataLen)
    39  	valueFuzz := fuzz.New().NilChance(0)
    40  	ts := header
    41  	for i := 0; i < dataLen; i++ {
    42  		if 0 < i && i%10 == 0 {
    43  			ts -= uint32(rand.Intn(100))
    44  		} else {
    45  			ts += uint32(rand.Int31n(100))
    46  		}
    47  		var v float64
    48  		valueFuzz.Fuzz(&v)
    49  		expected[i] = data{ts, v}
    50  	}
    51  
    52  	buf := new(bytes.Buffer)
    53  
    54  	// Compression
    55  	c, finish, err := NewCompressor(buf, header)
    56  	require.Nil(t, err)
    57  	for _, data := range expected {
    58  		b, err := c.Compress(data.t, data.v)
    59  		require.Nil(t, err)
    60  		require.Greater(t, b, uint64(0))
    61  	}
    62  	require.Nil(t, finish())
    63  
    64  	// Decompression
    65  	var actual []data
    66  	iter, err := NewDecompressIterator(buf)
    67  	require.Nil(t, err)
    68  	for iter.Next() {
    69  		t, v := iter.At()
    70  		actual = append(actual, data{t, v})
    71  	}
    72  	require.Nil(t, iter.Err())
    73  	assert.Equal(t, expected, actual)
    74  }