detect_test.go 1.71 KB
Newer Older
1 2 3 4 5 6 7 8
package serialize

import (
	"io"
	"path/filepath"
	"testing"

	"github.com/ethereum-optimism/optimism/op-service/ioutil"
9
	"github.com/ethereum-optimism/optimism/op-service/jsonutil"
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
	"github.com/stretchr/testify/require"
)

func TestRoundtrip(t *testing.T) {
	tests := []struct {
		filename   string
		expectJSON bool
		expectGzip bool
	}{
		{filename: "test.json", expectJSON: true, expectGzip: false},
		{filename: "test.json.gz", expectJSON: true, expectGzip: true},
		{filename: "test.foo", expectJSON: true, expectGzip: false},
		{filename: "test.foo.gz", expectJSON: true, expectGzip: true},
		{filename: "test.bin", expectJSON: false, expectGzip: false},
		{filename: "test.bin.gz", expectJSON: false, expectGzip: true},
	}

	for _, test := range tests {
		test := test
		t.Run(test.filename, func(t *testing.T) {
			path := filepath.Join(t.TempDir(), test.filename)

			data := &serializableTestData{A: []byte{0xde, 0xad}, B: 3}
			err := Write[*serializableTestData](path, data, 0644)
			require.NoError(t, err)

			hasGzip, err := hasGzipHeader(path)
			require.NoError(t, err)
			require.Equal(t, test.expectGzip, hasGzip)

			decompressed, err := ioutil.OpenDecompressed(path)
			require.NoError(t, err)
			defer decompressed.Close()
			start := make([]byte, 1)
			_, err = io.ReadFull(decompressed, start)
			require.NoError(t, err)
46
			var load func(path string) (*serializableTestData, error)
47
			if test.expectJSON {
48
				load = jsonutil.LoadJSON[serializableTestData]
49 50
				require.Equal(t, "{", string(start))
			} else {
51
				load = LoadSerializedBinary[serializableTestData]
52 53 54
				require.NotEqual(t, "{", string(start))
			}

55
			result, err := load(path)
56 57 58 59 60
			require.NoError(t, err)
			require.EqualValues(t, data, result)
		})
	}
}