//nolint:testpackage // exercises the unexported deviceNumberFromStat package snapshot import ( "os" "path/filepath" "syscall" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // The device number a real backup reads is the same for a directory and // a file in it, and differs between the temp directory and /dev. // Without it no mount point is ever found. See // https://git.eeqj.de/sneak/vaultik/issues/395. func TestDeviceNumberFromStat(t *testing.T) { t.Parallel() dir := t.TempDir() file := filepath.Join(dir, "file.txt") require.NoError(t, os.WriteFile(file, nil, 0o600)) deviceOf := func(path string) uint64 { t.Helper() info, err := os.Stat(path) require.NoError(t, err) device, ok := deviceNumberFromStat(info) require.True(t, ok, "no device number read for %s", path) return device } assert.Equal(t, deviceOf(dir), deviceOf(file)) // /dev is a different filesystem from the temp dir on Linux, macOS and in Docker. assert.NotEqual(t, deviceOf(dir), deviceOf("/dev")) } // fileInfoWithStat is a file's info whose Sys returns stat. type fileInfoWithStat struct { os.FileInfo stat *syscall.Stat_t } func (i fileInfoWithStat) Sys() any { return i.stat } // The in-memory test filesystem has no device numbers. The pinned afero // gives no stat; its unreleased master gives a stat holding only uid, gid // and size. See https://git.eeqj.de/sneak/vaultik/issues/462. func TestDeviceNumberFromStatInMemory(t *testing.T) { t.Parallel() fs := afero.NewMemMapFs() require.NoError(t, afero.WriteFile(fs, "/file.txt", []byte("data"), 0o600)) info, err := fs.Stat("/file.txt") require.NoError(t, err) _, ok := deviceNumberFromStat(info) assert.False(t, ok, "device number read from a file info with no stat") zeroed := fileInfoWithStat{ FileInfo: info, stat: &syscall.Stat_t{Uid: 1000, Gid: 1000, Size: 4}, } _, ok = deviceNumberFromStat(zeroed) assert.False(t, ok, "device number read from a stat with no device or inode number") }