/
fs_testutil.go
96 lines (80 loc) · 2.29 KB
/
fs_testutil.go
1
2
3
4
5
6
7
8
9
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package syslutil
import (
"os"
"path/filepath"
"regexp"
"runtime"
"sort"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const sep = string(os.PathSeparator)
// AssertFsHasExactly asserts that fs contains the given files and only
// those. All paths must start with '/'.
func AssertFsHasExactly(t *testing.T, fs afero.Fs, paths ...string) bool {
expected := make([]string, 0, len(paths))
for _, p := range paths {
expected = append(expected, MustAbsolute(t, p))
}
sort.Strings(expected)
actual := []string{}
root := MustAbsolute(t, sep)
// special case for MemFs in windows as walking from root results in infinite loop
_, isMemFs := fs.(*afero.MemMapFs)
isMemFsWindows := runtime.GOOS == windows && isMemFs
if isMemFsWindows {
root = sep
}
require.NoError(t, afero.Walk(fs, root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
actual = append(actual, path)
}
return nil
}))
sort.Strings(actual)
// add back the volume name as expected always have absolute path
if isMemFsWindows {
for i := 0; i < len(actual); i++ {
actual[i] = MustAbsolute(t, filepath.Join(sep, actual[i]))
}
}
return assert.Equal(t, expected, actual)
}
func WriteToMemOverlayFs(osRoot string) (memFs, fs afero.Fs) {
memFs = NewChrootFs(afero.NewMemMapFs(), "/")
fs = afero.NewCopyOnWriteFs(NewChrootFs(afero.NewOsFs(), osRoot), memFs)
return
}
func MustAbsolute(t *testing.T, path string) string {
fullPath, err := filepath.Abs(path)
require.NoError(t, err)
return fullPath
}
func MustRelative(t *testing.T, base, target string) string {
base = MustAbsolute(t, base)
target = MustAbsolute(t, target)
rel, err := filepath.Rel(base, target)
require.NoError(t, err)
return rel
}
func BuildFolderTest(t *testing.T, fs afero.Fs, folders, files []string) {
for _, folder := range folders {
require.NoError(t, fs.MkdirAll(trimVolumeName(MustAbsolute(t, folder)), os.ModeTemporary))
}
for _, file := range files {
_, err := fs.Create(trimVolumeName(MustAbsolute(t, file)))
require.NoError(t, err)
}
}
func HandleCRLF(text []byte) []byte {
if runtime.GOOS == windows {
re := regexp.MustCompile("(\r\n|\r)")
text = re.ReplaceAll(text, []byte("\n"))
}
return text
}