Debian Codegraph @

preallocate_darwin_test.go

raw
1 //go:build darwin
2
3 package desync
4
5 import (
6 "bytes"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "testing"
11
12 "github.com/stretchr/testify/require"
13 "golang.org/x/sys/unix"
14 )
15
16 // TestPreallocateTightDisk re-preallocates an existing file to its current
17 // size on a nearly-full volume. This must not require additional disk
18 // space: F_PREALLOCATE with F_PEOFPOSMODE allocates relative to the
19 // existing end of file, so requesting the full size instead of only the
20 // missing difference over-allocates and fails with ENOSPC.
21 func TestPreallocateTightDisk(t *testing.T) {
22 if _, err := exec.LookPath("hdiutil"); err != nil {
23 t.Skip("hdiutil not available")
24 }
25 dir := t.TempDir()
26 img := filepath.Join(dir, "small.dmg")
27 mount := filepath.Join(dir, "mnt")
28 require.NoError(t, os.Mkdir(mount, 0755))
29
30 out, err := exec.Command("hdiutil", "create", "-size", "32m", "-fs", "APFS", "-volname", "desync-test", img).CombinedOutput()
31 require.NoError(t, err, string(out))
32 out, err = exec.Command("hdiutil", "attach", img, "-mountpoint", mount, "-nobrowse").CombinedOutput()
33 require.NoError(t, err, string(out))
34 t.Cleanup(func() { _ = exec.Command("hdiutil", "detach", mount, "-force").Run() })
35
36 var st unix.Statfs_t
37 require.NoError(t, unix.Statfs(mount, &st))
38 free := int64(st.Bavail) * int64(st.Bsize)
39
40 // Fill most of the volume with an existing file, leaving less free
41 // space than the size of the file itself
42 size := free * 2 / 3
43 name := filepath.Join(mount, "existing")
44 require.NoError(t, os.WriteFile(name, bytes.Repeat([]byte{0xab}, int(size)), 0666))
45
46 // The file already has the right size, nothing should be allocated
47 require.NoError(t, preallocateFile(name, size))
48 }