-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtesting_utils_test.go
83 lines (71 loc) · 1.61 KB
/
testing_utils_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
package main
import (
"bytes"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/sirupsen/logrus"
)
// Not a real test file just file with utils code for other test files
type LogCapture struct {
buf bytes.Buffer
}
func NewLogCapture() (*LogCapture, func()) {
c := LogCapture{}
current := logrus.StandardLogger().Out
log.SetOutput(&c.buf)
return &c, func() { log.SetOutput(current) }
}
func (c *LogCapture) RequireInLog(t *testing.T, phrase string) {
if strings.Contains(c.buf.String(), phrase) {
return
}
t.Fatalf("Logs do not contain [%s], in\n%s", phrase, c.buf.String())
}
type TempDir struct {
*testing.T
path string
}
func NewTempDir(t *testing.T, prefix string) *TempDir {
tmpDir, err := os.MkdirTemp("", prefix)
if err != nil {
t.Fatalf("Error creating tmp dir %v", err)
}
td := TempDir{
T: t,
path: tmpDir,
}
return &td
}
func (td *TempDir) Path() string {
return td.path
}
func (td *TempDir) Cleanup() {
err := os.RemoveAll(td.path)
if err != nil {
td.Errorf("Error deleting temp dir %v", err)
}
}
func (td *TempDir) Write(fname, content string) string {
filePath := path.Join(td.path, fname)
err := os.WriteFile(filePath, bytes.NewBufferString(content).Bytes(), 0755)
if err != nil {
td.Fatalf("Error creating done file %v", err)
}
return filePath
}
func (td *TempDir) ReadFile(fname string) string {
file, err := os.Open(filepath.Join(td.path, fname))
if err != nil {
td.Fatalf("Error opening memory file %v", err)
return ""
}
b := make([]byte, 0)
_, err = file.Read(b)
if err != nil {
td.Fatalf("Error reading memory file %v", err)
}
return string(b)
}