File: testhelper.go

package info (click to toggle)
gitlab-shell 14.35.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,652 kB
  • sloc: ruby: 1,129; makefile: 583; sql: 391; sh: 384
file content (62 lines) | stat: -rw-r--r-- 1,270 bytes parent folder | download
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
// Package testhelper consists of various helper functions to setup the test environment.
package testhelper

import (
	"fmt"
	"os"
	"path"
	"runtime"
	"testing"

	"github.com/otiai10/copy"
	"github.com/stretchr/testify/require"
)

// TempEnv sets environment variables for the test
func TempEnv(t *testing.T, env map[string]string) {
	for key, value := range env {
		t.Setenv(key, value)
	}
}

// PrepareTestRootDir prepares the test root directory with the test data
func PrepareTestRootDir(t *testing.T) string {
	t.Helper()

	testRoot := t.TempDir()
	t.Cleanup(func() { require.NoError(t, os.RemoveAll(testRoot)) })

	require.NoError(t, copyTestData(testRoot))

	oldWd, err := os.Getwd()
	require.NoError(t, err)

	t.Cleanup(func() {
		err = os.Chdir(oldWd)
		require.NoError(t, err)
	})

	require.NoError(t, os.Chdir(testRoot))

	return testRoot
}

func copyTestData(testRoot string) 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
}