-
Notifications
You must be signed in to change notification settings - Fork 18
/
fs.go
82 lines (67 loc) · 1.73 KB
/
fs.go
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package testutil
import (
"github.com/otiai10/copy"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"testing"
)
func RestoreDirLater(t *testing.T) {
savedDir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.Chdir(savedDir); err != nil {
t.Fatal(err)
}
})
}
// tempDir supplements an alternative to TB.TempDir()[1], which is only available in 1.15.
// [1]: https://github.com/golang/go/issues/35998
func TempDir(t *testing.T) string {
tempDirRoot := "" // will use os.TempDir()
if runtime.GOOS == "darwin" {
// override the default since Docker for Mac
// doesn't mount /var/folder by default where os.TempDir() will be located
// See https://docs.docker.com/docker-for-mac/#file-sharing
tempDirRoot = "/tmp"
}
dir, err := ioutil.TempDir(tempDirRoot, filepath.Base(t.Name()))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.RemoveAll(dir); err != nil {
t.Fatal(err)
}
})
return dir
}
// TempChdir switches to a temporary per-test directory.
func TempChdir(t *testing.T) {
dir := TempDir(t)
RestoreDirLater(t)
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
}
// TempChdirPopulatedWith creates a temporary per-test directory
// filled with sourceDir contents and switches to it.
func TempDirPopulatedWith(t *testing.T, sourceDir string) string {
tempDir := TempDir(t)
if err := copy.Copy(sourceDir, tempDir); err != nil {
t.Fatal(err)
}
return tempDir
}
// TempChdirPopulatedWith creates a temporary per-test directory
// filled with sourceDir contents and switches to it.
func TempChdirPopulatedWith(t *testing.T, sourceDir string) {
dir := TempDirPopulatedWith(t, sourceDir)
RestoreDirLater(t)
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
}