| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"os" |
| 7 |
"path/filepath" |
| 8 |
"testing" |
| 9 |
"time" |
| 10 |
|
| 11 |
"github.com/stretchr/testify/assert" |
| 12 |
"github.com/stretchr/testify/require" |
| 13 |
) |
| 14 |
|
| 15 |
// tarDir archives a directory tree into a catar in memory. |
| 16 |
func tarDir(t *testing.T, dir string) *bytes.Buffer { |
| 17 |
t.Helper() |
| 18 |
b := new(bytes.Buffer) |
| 19 |
require.NoError(t, Tar(context.Background(), b, NewLocalFS(dir, LocalFSOptions{}))) |
| 20 |
return b |
| 21 |
} |
| 22 |
|
| 23 |
// TestUnTarDirMTime confirms that directory timestamps survive the writing of |
| 24 |
// their contents, which would otherwise update them. Runs on all platforms |
| 25 |
// since the deferral this relies on has to work with either path separator. |
| 26 |
func TestUnTarDirMTime(t *testing.T) { |
| 27 |
src := t.TempDir() |
| 28 |
|
| 29 |
// Deep enough for the decoder to walk back up more than one level |
| 30 |
require.NoError(t, os.MkdirAll(filepath.Join(src, "dir/sub/deep"), 0755)) |
| 31 |
require.NoError(t, os.WriteFile(filepath.Join(src, "dir/sub/file"), []byte("content"), 0644)) |
| 32 |
require.NoError(t, os.WriteFile(filepath.Join(src, "dir/file"), []byte("content"), 0644)) |
| 33 |
|
| 34 |
mtime := time.Unix(1577872800, 0) // 2020-01-01 |
| 35 |
names := []string{"dir/sub/deep", "dir/sub/file", "dir/sub", "dir/file", "dir", "."} |
| 36 |
for _, name := range names { |
| 37 |
require.NoError(t, os.Chtimes(filepath.Join(src, name), mtime, mtime)) |
| 38 |
} |
| 39 |
|
| 40 |
b := tarDir(t, src) |
| 41 |
|
| 42 |
dst := filepath.Join(t.TempDir(), "out") |
| 43 |
fs := NewLocalFS(dst, LocalFSOptions{NoSameOwner: true}) |
| 44 |
defer fs.Close() |
| 45 |
require.NoError(t, UnTar(context.Background(), b, fs)) |
| 46 |
|
| 47 |
for _, name := range names { |
| 48 |
info, err := os.Stat(filepath.Join(dst, name)) |
| 49 |
require.NoError(t, err) |
| 50 |
assert.Equal(t, mtime.Unix(), info.ModTime().Unix(), "mtime of %s", name) |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
func TestContains(t *testing.T) { |
| 55 |
tests := []struct { |
| 56 |
dir, name string |
| 57 |
want bool |
| 58 |
}{ |
| 59 |
{".", "dir", true}, |
| 60 |
{".", "dir/sub", true}, |
| 61 |
{"dir", "dir/sub", true}, |
| 62 |
{"dir", "dir/sub/file", true}, |
| 63 |
{"dir", "dir", false}, |
| 64 |
{"dir", "dirx/file", false}, |
| 65 |
{"dir/sub", "dir/file", false}, |
| 66 |
{"dir/sub", "other", false}, |
| 67 |
} |
| 68 |
for _, test := range tests { |
| 69 |
assert.Equal(t, test.want, contains(test.dir, test.name), "contains(%q, %q)", test.dir, test.name) |
| 70 |
} |
| 71 |
} |