-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
94 lines (81 loc) · 1.5 KB
/
main_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
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
)
func TestRun(t *testing.T) {
var tests = []struct {
name string
args []string
err string
}{
{
name: "Fail app setup",
args: []string{
"app",
"-db_path", "",
},
err: "app database setup, ",
},
{
name: "Fail app setup",
args: []string{
"app",
"-db_path", "app.db",
"-addr", "127", // invalid server addr
},
err: "app run, ",
},
}
for ti, tt := range tests {
ti, tt := ti, tt
t.Run(fmt.Sprintf("%d. %s", ti, tt.name), func(t *testing.T) {
os.Args = tt.args
err := errStr(run())
if !strings.HasPrefix(err, tt.err) {
t.Errorf("%d. %s, exp err prefix: '%s' got: '%s'", ti, tt.name, tt.err, err)
}
if err != "" && tt.err == "" {
t.Errorf("%d. %s, exp no err got: '%s'", ti, tt.name, err)
}
})
}
}
func TestMainLogsError(t *testing.T) {
os.Args = []string{
"app",
"-db_path", "",
}
backup := os.Stdout
f, err := ioutil.TempFile("", "stdout")
logErr(t, err)
defer func() {
logErr(t, os.Remove(f.Name()))
}()
os.Stdout = f
main()
f.Close()
os.Stdout = backup
b, err := ioutil.ReadFile(f.Name())
logErr(t, err)
exp := "Error on "
got := string(b)
if !strings.Contains(got, exp) {
t.Errorf("Exp err prefix: '%s' got: '%s'", exp, got)
}
}
func errStr(err error) string {
if err != nil {
return err.Error()
}
return ""
}
func logErr(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("Unexpected error, %v", err)
}
}