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
Stephan Aßmus f855658e06
Enhance piperutils.Files and mock.FilesMock (#1664)
* Flesh out piperutils.Files and mock.FilesMock functionality
* Avoid a lot of code-duplication via embedding
2020-06-15 09:47:33 +02:00

79 lines
2.0 KiB
Go

package piperutils
import (
"github.com/stretchr/testify/assert"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestFileExists(t *testing.T) {
t.Parallel()
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 TestCopy(t *testing.T) {
t.Parallel()
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)
}