-
Notifications
You must be signed in to change notification settings - Fork 170
/
dial_test.go
126 lines (110 loc) · 2.22 KB
/
dial_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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package transport
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"testing"
)
func helperCommand(name string, arg ...string) (cmd *exec.Cmd) {
cs := []string{"-test.run=TestHelperProcess", "--"}
cs = append(cs, name)
cs = append(cs, arg...)
cmd = exec.Command(os.Args[0], cs...)
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
return cmd
}
func TestHelperProcess(*testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
defer os.Exit(0)
args := os.Args
for len(args) > 0 {
if args[0] == "--" {
args = args[1:]
break
}
args = args[1:]
}
iargs := []any{}
for _, s := range args {
iargs = append(iargs, s)
}
fmt.Println(iargs...)
conn := GetStdioConn()
buf := make([]byte, 512)
for {
i, err := conn.Read(buf)
if err != nil {
break
}
read := buf[:i]
if string(read) == "error" {
os.Exit(1)
}
_, _ = conn.Write(read)
}
}
func TestDial(t *testing.T) {
execCommand = helperCommand
defer func() { execCommand = exec.Command }()
conn, err := Dial("executable", "arg1", "arg2")
if err != nil {
t.Error(err)
}
reader := bufio.NewReader(conn)
line, _, err := reader.ReadLine()
if err != nil {
t.Error(err)
}
str := string(line)
if str != "executable arg1 arg2" {
t.Errorf("unexpected string %s", str)
}
_, _ = conn.Write([]byte("hi there\n"))
line, _, err = reader.ReadLine()
if err != nil {
t.Error(err)
}
str = string(line)
if str != "hi there" {
t.Errorf("unexpected string %s", str)
}
err = conn.Close()
if err != nil {
t.Error(err)
}
}
func TestDial_Error(t *testing.T) {
execCommand = helperCommand
defer func() { execCommand = exec.Command }()
conn, err := Dial("executable", "arg1", "arg2")
if err != nil {
t.Error(err)
}
reader := bufio.NewReader(conn)
_, _, err = reader.ReadLine()
if err != nil {
t.Error(err)
}
_, _ = conn.Write([]byte("error"))
_, _, err = reader.ReadLine()
if err == nil {
t.Error("expected error")
}
if err != io.EOF {
t.Errorf("unexpected error %s", err)
}
}
func TestGetStdioConn(t *testing.T) {
conn := GetStdioConn()
if conn.RemoteAddr().String() != "remote" {
t.Errorf("unexpected remote address %s", conn.RemoteAddr().String())
}
err := conn.Close()
if err != nil {
t.Error(err)
}
}