testhelper.go 1.54 KB
Newer Older
1 2
package testhelper

Bob Van Landuyt's avatar
Bob Van Landuyt committed
3 4 5 6 7 8 9 10 11 12 13 14 15
import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"runtime"

	"github.com/otiai10/copy"
)

var (
	TestRoot, _ = ioutil.TempDir("", "test-gitlab-shell")
)
16 17 18 19 20 21 22 23 24 25 26 27 28 29

func TempEnv(env map[string]string) func() {
	var original = make(map[string]string)
	for key, value := range env {
		original[key] = os.Getenv(key)
		os.Setenv(key, value)
	}

	return func() {
		for key, originalValue := range original {
			os.Setenv(key, originalValue)
		}
	}
}
Bob Van Landuyt's avatar
Bob Van Landuyt committed
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

func PrepareTestRootDir() (func(), error) {
	if err := os.MkdirAll(TestRoot, 0700); err != nil {
		return nil, err
	}

	var oldWd string
	cleanup := func() {
		if oldWd != "" {
			err := os.Chdir(oldWd)
			if err != nil {
				panic(err)
			}
		}

		if err := os.RemoveAll(TestRoot); err != nil {
			panic(err)
		}
	}

	if err := copyTestData(); err != nil {
		cleanup()
		return nil, err
	}

	oldWd, err := os.Getwd()
	if err != nil {
		cleanup()
		return nil, err
	}

	if err := os.Chdir(TestRoot); err != nil {
		cleanup()
		return nil, err
	}

	return cleanup, nil
}

func copyTestData() error {
	testDataDir, err := getTestDataDir()
	if err != nil {
		return err
	}

	testdata := path.Join(testDataDir, "testroot")

	return copy.Copy(testdata, TestRoot)
}

func getTestDataDir() (string, error) {
	_, currentFile, _, ok := runtime.Caller(0)
	if !ok {
		return "", fmt.Errorf("Could not get caller info")
	}

	return path.Join(path.Dir(currentFile), "testdata"), nil
}
Małgorzata Ksionek's avatar
Małgorzata Ksionek committed
88 89 90 91 92 93

func Setenv(key, value string) (func(), error) {
	oldValue := os.Getenv(key)
	err := os.Setenv(key, value)
	return func() { os.Setenv(key, oldValue) }, err
}