a73x

internal/agent/imagecache/format_test.go

Ref:   Size: 1.9 KiB   History

package imagecache

import (
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// TestSniffClassifiesByMagicNotSuffix pins the whole point of sniffing: the
// bytes decide, and anything without a magic number we recognize is raw.
func TestSniffClassifiesByMagicNotSuffix(t *testing.T) {
	tests := []struct {
		name string
		head []byte
		want imageFormat
	}{
		{"gzip", []byte{0x1f, 0x8b, 0x08, 0x00}, formatGzip},
		{"qcow2", []byte{'Q', 'F', 'I', 0xfb}, formatQcow2},
		{"raw with an MBR boot sector", []byte{0xeb, 0x63, 0x90, 0x10}, formatRaw},
		{"raw of zeros", []byte{0x00, 0x00, 0x00, 0x00}, formatRaw},
		{"empty", nil, formatRaw},
		{"shorter than any magic", []byte{0x1f}, formatRaw},
		{"gzip magic byte alone is not gzip", []byte{0x1f, 0x00}, formatRaw},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			assert.Equal(t, tc.want, sniff(tc.head))
		})
	}
}

// TestSniffFileReadsOnlyTheHead pins that classification works off a file on
// disk (what Ensure has after a download) and does not need to read it all.
func TestSniffFileReadsOnlyTheHead(t *testing.T) {
	dir := t.TempDir()
	tests := []struct {
		name string
		body []byte
		want imageFormat
	}{
		{"qcow2", append([]byte{'Q', 'F', 'I', 0xfb}, make([]byte, 4096)...), formatQcow2},
		{"gzip", append([]byte{0x1f, 0x8b}, make([]byte, 4096)...), formatGzip},
		{"raw", make([]byte, 4096), formatRaw},
		{"one byte", []byte{0x1f}, formatRaw},
		{"empty file", nil, formatRaw},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			p := filepath.Join(dir, tc.name)
			require.NoError(t, os.WriteFile(p, tc.body, 0o644))
			got, err := sniffFile(p)
			require.NoError(t, err)
			assert.Equal(t, tc.want, got)
		})
	}
}

func TestSniffFileMissingFileErrors(t *testing.T) {
	_, err := sniffFile(filepath.Join(t.TempDir(), "nope"))
	assert.Error(t, err)
}