-
Notifications
You must be signed in to change notification settings - Fork 10
/
main_test.go
102 lines (79 loc) · 2.36 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
95
96
97
98
99
100
101
102
package main
import (
"os"
"os/exec"
"strconv"
"strings"
"testing"
"time"
"gotest.tools/assert"
)
func runCrashingTest(t *testing.T, testCode func()) (outStr, errStr string) {
crashEnvVarName := "RUN_CRASHING_CODE"
crashEnvVarValue := "1"
if os.Getenv(crashEnvVarName) == crashEnvVarValue {
testCode()
// Cancel the second-level test so that we don't run
// the code after the call to this method more than once
t.SkipNow()
return
}
cmd := exec.Command(os.Args[0], "-test.run="+t.Name())
cmd.Env = append(os.Environ(), crashEnvVarName+"="+crashEnvVarValue)
var timedout bool
timer := time.AfterFunc(500*time.Millisecond, func() {
timedout = true
cmd.Process.Kill()
})
defer timer.Stop()
bytes, err := cmd.Output()
if timedout {
t.Fatal("Timeout")
return
}
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
return string(bytes), string(e.Stderr)
}
t.Fatal("process ran without an error, while we expected an error code")
return
}
func TestFlagsEmpty(t *testing.T) {
out, _ := runCrashingTest(t, func() {
os.Args = []string{"."}
main()
})
assert.Assert(t, strings.Contains(out, "must specify at least one configuration file"), "Output: "+out)
}
func TestFlagsPortOnly(t *testing.T) {
out, _ := runCrashingTest(t, func() {
os.Args = []string{".", "-p", "12345"}
main()
})
assert.Assert(t, strings.Contains(out, "must specify at least one configuration file"), "Output: "+out)
}
func TestFlagsInvalidPort(t *testing.T) {
invalidPort := "abcde"
_, err := runCrashingTest(t, func() {
os.Args = []string{".", "-p", invalidPort}
main()
})
assert.Assert(t, strings.Contains(err, "invalid value \""+invalidPort+"\" for flag -p"), "Error: "+err)
}
func TestFlagsValid(t *testing.T) {
validPortStr := "12345"
configFile := "example-configurations/test-exporter.yaml"
validPort, _ := strconv.Atoi(validPortStr)
os.Args = []string{".", "-p", validPortStr, "-f", configFile}
port, configFiles := parseFlags()
assert.Equal(t, port, validPort)
assert.Equal(t, len(configFiles), 1)
assert.Equal(t, configFiles[0], configFile)
}
func TestFlagsDefaultPort(t *testing.T) {
configFile := "example-configurations/test-exporter.yaml"
os.Args = []string{".", "-f", configFile}
port, configFiles := parseFlags()
assert.Equal(t, port, defaultMainPort)
assert.Equal(t, len(configFiles), 1)
assert.Equal(t, configFiles[0], configFile)
}