helpers: simplify path tests with T.TempDir

This commit is contained in:
Oleksandr Redko 2023-05-15 11:52:06 +03:00 committed by Bjørn Erik Pedersen
parent bda082c98c
commit 3d90871e9e

View file

@ -239,42 +239,35 @@ func TestIsDir(t *testing.T) {
} }
} }
func createZeroSizedFileInTempDir() (*os.File, error) { func createZeroSizedFileInTempDir(t *testing.T) *os.File {
t.Helper()
filePrefix := "_path_test_" filePrefix := "_path_test_"
f, e := os.CreateTemp("", filePrefix) // dir is os.TempDir() f, err := os.CreateTemp(t.TempDir(), filePrefix)
if e != nil { if err != nil {
// if there was an error no file was created. t.Error(err)
// => no requirement to delete the file
return nil, e
} }
return f, nil if err := f.Close(); err != nil {
t.Error(err)
}
return f
} }
func createNonZeroSizedFileInTempDir() (*os.File, error) { func createNonZeroSizedFileInTempDir(t *testing.T) *os.File {
f, err := createZeroSizedFileInTempDir() t.Helper()
if err != nil {
// no file ?? f := createZeroSizedFileInTempDir(t)
return nil, err
}
byteString := []byte("byteString") byteString := []byte("byteString")
err = os.WriteFile(f.Name(), byteString, 0644) err := os.WriteFile(f.Name(), byteString, 0644)
if err != nil { if err != nil {
// delete the file t.Error(err)
deleteFileInTempDir(f)
return nil, err
} }
return f, nil return f
}
func deleteFileInTempDir(f *os.File) {
_ = os.Remove(f.Name())
} }
func TestExists(t *testing.T) { func TestExists(t *testing.T) {
zeroSizedFile, _ := createZeroSizedFileInTempDir() zeroSizedFile := createZeroSizedFileInTempDir(t)
defer deleteFileInTempDir(zeroSizedFile) nonZeroSizedFile := createNonZeroSizedFileInTempDir(t)
nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
defer deleteFileInTempDir(nonZeroSizedFile)
emptyDirectory := t.TempDir() emptyDirectory := t.TempDir()
nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt" nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
nonExistentDir := os.TempDir() + "/this/directory/does/not/exist/" nonExistentDir := os.TempDir() + "/this/directory/does/not/exist/"
@ -420,8 +413,7 @@ func TestFindCWD(t *testing.T) {
} }
func TestSafeWriteToDisk(t *testing.T) { func TestSafeWriteToDisk(t *testing.T) {
emptyFile, _ := createZeroSizedFileInTempDir() emptyFile := createZeroSizedFileInTempDir(t)
defer deleteFileInTempDir(emptyFile)
tmpDir := t.TempDir() tmpDir := t.TempDir()
randomString := "This is a random string!" randomString := "This is a random string!"
@ -461,8 +453,7 @@ func TestSafeWriteToDisk(t *testing.T) {
} }
func TestWriteToDisk(t *testing.T) { func TestWriteToDisk(t *testing.T) {
emptyFile, _ := createZeroSizedFileInTempDir() emptyFile := createZeroSizedFileInTempDir(t)
defer deleteFileInTempDir(emptyFile)
tmpDir := t.TempDir() tmpDir := t.TempDir()
randomString := "This is a random string!" randomString := "This is a random string!"