-
Notifications
You must be signed in to change notification settings - Fork 44
/
helper_test.go
118 lines (77 loc) · 1.75 KB
/
helper_test.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package envplate
import (
"bytes"
"fmt"
"io"
"log"
"os"
"testing"
)
func _delete(t *testing.T, name string) {
if err := os.Remove(name); err != nil {
t.Fatal(fmt.Errorf("error while deleting '%s': %v", name, err))
}
}
func _exists(name string) bool {
_, err := os.Stat(name)
return err == nil
}
func _read(t *testing.T, name string) string {
content, err := os.ReadFile(name)
if err != nil {
t.Fatal(fmt.Errorf("error while reading '%s': %v", name, err))
}
return string(content)
}
func _redirect_logs(f func(func() string, func() string)) {
var (
logBuf bytes.Buffer
rawBuf bytes.Buffer
)
defer func(w io.Writer) {
Logger.Out = w
}(Logger.Out)
defer func(w io.Writer) {
log.SetOutput(w)
}(os.Stderr)
log.SetOutput(&logBuf)
Logger.Out = &rawBuf
logs := func(buf *bytes.Buffer) func() string {
return func() string {
logs := buf.String()
buf.Reset()
return logs
}
}
f(logs(&logBuf), logs(&rawBuf))
}
func _restore(file string) {
backup := fmt.Sprintf("%s.bak", file)
os.Remove(file)
os.Link(backup, file)
os.Remove(backup)
}
func _tmpdir(t *testing.T, f func(string)) {
dir, err := os.MkdirTemp("", "")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(dir)
f(dir)
}
func _write(t *testing.T, name, content string, mode os.FileMode) string {
file, err := os.CreateTemp("", name)
if err != nil {
t.Fatalf("Error while opening '%s': %v", name, err)
}
if _, err := file.WriteString(content); err != nil {
t.Fatalf("Error while writing to '%s': %v", name, err)
}
if err := file.Close(); err != nil {
t.Fatalf("Error while closing '%s': %v", name, err)
}
if err := os.Chmod(file.Name(), mode); err != nil {
t.Fatalf("Error while chmod '%s': %v", name, err)
}
return file.Name()
}