-
Notifications
You must be signed in to change notification settings - Fork 1
/
main_test.go
104 lines (91 loc) · 2.37 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
103
104
package main
import (
"bufio"
"bytes"
"fmt"
"net"
"os"
"regexp"
"testing"
)
var listenAddrPattern = regexp.MustCompile(`listening on (.+?:\d+)`)
func TestMain(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"emissary"}
_, stderrWriter, _ := os.Pipe()
oldStderr := os.Stderr
os.Stderr = stderrWriter
defer func() { os.Stderr = oldStderr }()
t.Log("Testing main without args...")
main()
t.Log("Testing main with single upstream...")
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Errorf("Failed to start listener: %s", err)
}
stderrReader, stderrWriter, _ := os.Pipe()
go func(f *os.File) {
oldStderr := os.Stderr
os.Stderr = f
defer func() { os.Stderr = oldStderr }()
os.Args = []string{
"emissary",
"-alsologtostderr",
"-bind",
"localhost:0",
"-upstream",
fmt.Sprintf("/^GET/:%s", listener.Addr().String()),
}
main()
}(stderrWriter)
reader := bufio.NewReader(stderrReader)
line, _, err := reader.ReadLine()
if err != nil {
t.Errorf("Failed to read output from cli: %s", err)
}
matchAddr := listenAddrPattern.FindStringSubmatch(string(line))
if len(matchAddr) != 2 {
t.Errorf("Unexpected output line from cli: %s", line)
}
server, err := net.Dial("tcp", matchAddr[1])
defer server.Close()
if err != nil {
t.Errorf("Failed to connect to emissary: %s", err)
}
server.Write([]byte("GET /\n"))
client, err := listener.Accept()
defer client.Close()
if err != nil {
t.Errorf("Failed to accept connection: %s", err)
}
// buf := make([]byte, 6)
// client.Read(buf)
response := []byte("HTTP/1.0 740 Computer says no")
client.Write(response)
buf := make([]byte, len(response))
server.Read(buf)
if bytes.Compare(buf, response) != 0 {
t.Error("Expected responses to match")
t.Errorf("`%s' != `%s'", response, buf)
}
}
func TestMainVersion(t *testing.T) {
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"emissary", "-version"}
stdoutReader, stdoutWriter, _ := os.Pipe()
oldStdout := os.Stdout
os.Stdout = stdoutWriter
defer func() { os.Stdout = oldStdout }()
t.Log("Testing main version flag...")
main()
buf := make([]byte, 46)
stdoutReader.Read(buf)
expectedOutput := []byte(`emissary version: unknown
build time: unknown
`)
if bytes.Compare(expectedOutput, buf) != 0 {
t.Errorf("Unexpected output from `emissary -version'")
}
}