1
0
mirror of https://github.com/SAP/jenkins-library.git synced 2024-12-14 11:03:09 +02:00
sap-jenkins-library/pkg/piperutils/fileUtils_test.go
2020-07-20 14:23:33 +02:00

99 lines
2.6 KiB
Go

package piperutils
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestFileExists(t *testing.T) {
runInTempDir(t, "testing dir returns false", "dir", func(t *testing.T) {
err := os.Mkdir("test", 0777)
if err != nil {
t.Fatal("failed to create test dir in temporary dir")
}
result, err := FileExists("test")
assert.NoError(t, err)
assert.False(t, result)
})
runInTempDir(t, "testing file returns true", "dir", func(t *testing.T) {
file, err := ioutil.TempFile("", "testFile")
assert.NoError(t, err)
result, err := FileExists(file.Name())
assert.NoError(t, err)
assert.True(t, result)
})
}
func TestDirExists(t *testing.T) {
runInTempDir(t, "testing dir exists", "dir-exists", func(t *testing.T) {
err := os.Mkdir("test", 0777)
if err != nil {
t.Fatal("failed to create test dir in temporary dir")
}
files := Files{}
result, err := files.DirExists("test")
assert.NoError(t, err)
assert.True(t, result, "created folder should exist")
result, err = files.DirExists(".")
assert.NoError(t, err)
assert.True(t, result, "current directory should exist")
result, err = files.DirExists(string(os.PathSeparator))
assert.NoError(t, err)
assert.True(t, result, "root directory should exist")
})
}
func TestCopy(t *testing.T) {
runInTempDir(t, "copying file succeeds", "dir2", func(t *testing.T) {
file := "testFile"
err := ioutil.WriteFile(file, []byte{byte(1), byte(2), byte(3)}, 0700)
if err != nil {
t.Fatal("Failed to create temporary workspace directory")
}
result, err := Copy(file, "testFile2")
assert.NoError(t, err, "Didn't expert error but got one")
assert.Equal(t, int64(3), result, "Expected true but got false")
})
runInTempDir(t, "copying directory fails", "dir3", func(t *testing.T) {
src := filepath.Join("some", "file")
dst := filepath.Join("another", "file")
err := os.MkdirAll(src, 0777)
if err != nil {
t.Fatal("Failed to create test directory")
}
files := Files{}
exists, err := files.DirExists(src)
assert.NoError(t, err)
assert.True(t, exists)
length, err := files.Copy(src, dst)
assert.EqualError(t, err, "Source file '"+src+"' does not exist")
assert.Equal(t, length, int64(0))
})
}
func runInTempDir(t *testing.T, nameOfRun, tempDirPattern string, run func(t *testing.T)) {
dir, err := ioutil.TempDir("", tempDirPattern)
if err != nil {
t.Fatal("Failed to create temporary directory")
}
oldCWD, _ := os.Getwd()
_ = os.Chdir(dir)
// clean up tmp dir
defer func() {
_ = os.Chdir(oldCWD)
_ = os.RemoveAll(dir)
}()
t.Run(nameOfRun, run)
}