-
Notifications
You must be signed in to change notification settings - Fork 183
/
utils.go
75 lines (66 loc) · 1.51 KB
/
utils.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
package neotest
import (
"encoding/json"
"io/ioutil"
"os"
"os/exec"
"testing"
)
// LoadJSON unmarshals JSON for a test
func LoadJSON(t *testing.T, path string, dst interface{}) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
t.Fatalf("failed to read %s", path)
}
if err := json.Unmarshal(bytes, dst); err != nil {
t.Fatalf("failed to unmarshal %s", path)
}
}
// CloneTestData clones the test data into a temporary directory and changes the
// working directory to the temporary directory. The function returned should be
// run as a deferred to restore the working directory and remove the files.
func CloneTestData(t *testing.T) (string, func()) {
dir, err := ioutil.TempDir("", "testdata")
if err != nil {
t.Fatal(err)
}
// Makes me sad.
cmd := exec.Command("cp", "-r", ".", dir)
cmd.Dir = "testdata"
if cmd.Run(); err != nil {
t.Fatal(err)
}
curdir, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
return dir, func() {
if os.Chdir(curdir); err != nil {
t.Fatal(err)
}
if err := os.RemoveAll(dir); err != nil {
t.Errorf("error removing temp dir: %s", err)
}
}
}
// Must calls fatal in the given test if err is non-nil
func Must(t *testing.T, err error) {
if err != nil {
t.Fatal(err)
}
}
// Dump i to stdout using JSON
func Dump(t *testing.T, i interface{}) {
if data, err := json.MarshalIndent(i, "", " "); err != nil {
if t != nil {
t.Fatal(err)
} else {
panic(err)
}
} else {
println(string(data))
}
}