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 97 98 99 100
|
// Copyright 2022 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0
package localizertest
import (
"io/fs"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"sigs.k8s.io/kustomize/kyaml/filesys"
)
// PrepareFs returns an in-memory and the actual file system, both with the test
// directory with the file content mapping in files.
// dirs are the directory paths that need to be created to write the files.
func PrepareFs(t *testing.T, dirs []string, files map[string]string) (
memory, actual filesys.FileSystem, test filesys.ConfirmedDir) {
t.Helper()
memory = filesys.MakeFsInMemory()
actual = filesys.MakeFsOnDisk()
testDir, err := filesys.NewTmpConfirmedDir()
require.NoError(t, err)
SetupDir(t, memory, testDir.String(), files)
for _, dirPath := range dirs {
require.NoError(t, actual.MkdirAll(testDir.Join(dirPath)))
}
SetupDir(t, actual, testDir.String(), files)
t.Cleanup(func() {
_ = actual.RemoveAll(testDir.String())
})
return memory, actual, testDir
}
// SetupDir creates each file, specified by the file name to content mapping in
// files, under dir on fSys
func SetupDir(t *testing.T, fSys filesys.FileSystem, dir string,
files map[string]string) {
t.Helper()
for file, content := range files {
require.NoError(t, fSys.WriteFile(filepath.Join(dir, file), []byte(content)))
}
}
// SetWorkingDir sets the working directory to workingDir and restores the
// original working directory after test completion.
func SetWorkingDir(t *testing.T, workingDir string) {
t.Helper()
wd, err := os.Getwd()
require.NoError(t, err)
t.Cleanup(func() {
require.NoError(t, os.Chdir(wd))
})
err = os.Chdir(workingDir)
require.NoError(t, err)
}
// CheckFs checks actual, the real file system, against expected, a file
// system in memory, for contents in directory dir.
// CheckFs does not allow symlinks.
func CheckFs(t *testing.T, dir string, expected, actual filesys.FileSystem) {
t.Helper()
err := actual.Walk(dir, func(path string, info fs.FileInfo, err error) error {
require.NoError(t, err)
require.NotEqual(t, os.ModeSymlink, info.Mode()&os.ModeSymlink)
require.True(t, expected.Exists(path), "unexpected file %q", path)
return nil
})
require.NoError(t, err)
err = expected.Walk(dir, func(path string, info fs.FileInfo, err error) error {
require.NoError(t, err)
if info.IsDir() {
require.DirExists(t, path)
} else {
require.FileExists(t, path)
expectedContent, err := expected.ReadFile(path)
require.NoError(t, err)
actualContent, err := actual.ReadFile(path)
require.NoError(t, err)
require.Equal(t, string(expectedContent), string(actualContent))
}
return nil
})
require.NoError(t, err)
}
|