-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtestutils.go
91 lines (77 loc) · 1.77 KB
/
testutils.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
package rrh
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
)
func copyfile(fromfile string) string {
var content, err = ioutil.ReadFile(fromfile)
if err != nil {
panic(err.Error())
}
var file, err2 = ioutil.TempFile(".", "tmp")
if err2 != nil {
panic(err.Error())
}
file.Write(content)
defer file.Close()
return file.Name()
}
/*
Rollback rollbacks database after executing function f.
*/
func Rollback(dbFile, configFile string, f func(config *Config, db *Database)) string {
var newDBFile = copyfile(dbFile)
var newConfigFile = copyfile(configFile)
defer os.Remove(newConfigFile)
os.Setenv(ConfigPath, newConfigFile)
os.Setenv(DatabasePath, newDBFile)
var config = OpenConfig()
var db, err = Open(config)
if err != nil {
fmt.Println(err.Error())
}
f(config, db)
os.Setenv(ConfigPath, configFile) // replace the path of config file.
os.Setenv(DatabasePath, dbFile)
return newDBFile
}
/*
ReplaceNewline trims spaces and converts the return codes in `originalString` to `replaceTo` string.
*/
func ReplaceNewline(originalString, replaceTo string) string {
return strings.NewReplacer(
"\r\n", replaceTo,
"\r", replaceTo,
"\n", replaceTo,
).Replace(strings.TrimSpace(originalString))
}
/*
GivesStringAsStdin treats given inputFromStdin string as a byte stream from stdin.
*/
func GivesStringAsStdin(inputFromStdin string, f func()) {
var r, w, _ = os.Pipe()
var stdin = os.Stdin
os.Stdin = r
w.Write([]byte(inputFromStdin))
w.Close()
f()
os.Stdin = stdin
}
/*
CaptureStdout is referred from https://qiita.com/kami_zh/items/ff636f15da87dabebe6c.
*/
func CaptureStdout(f func()) string {
r, w, _ := os.Pipe()
var stdout = os.Stdout
os.Stdout = w
f()
os.Stdout = stdout
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
return buf.String()
}