-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetutil_test.go
109 lines (91 loc) · 1.93 KB
/
netutil_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
package netutil_test
import (
"bufio"
"net"
"os"
"testing"
"time"
"github.com/knzm/go-netutil"
)
// Notes:
// * An empty IP address may not be appropriate in some environments,
// such as a docker container. The 127.0.0.1 is selected just as
// a simple default.
// * The :0 means that one of the available ports is automatically
// chosen by the system.
var ListenAddr = "127.0.0.1:0"
func init() {
if a := os.Getenv("NETUTIL_TEST_LISTEN_ADDR"); a != "" {
ListenAddr = a
}
}
func TestBrokenPipeErrorIsNotFatal(t *testing.T) {
if testing.Short() {
t.Skip("skip a slow test using real network connections")
}
// an ill-mannered client
client := func(conn net.Conn) {
// send a request
_, err := conn.Write([]byte("ping\n"))
if err != nil {
t.Fatal(err)
}
// then disconnect without reading any response
err = conn.Close()
if err != nil {
t.Fatal(err)
}
}
// open a server side connection
listener, err := net.Listen("tcp", ListenAddr)
if err != nil {
t.Fatal(err)
}
addr := listener.Addr()
t.Logf("address: %s", addr)
go func() {
// open a client side connection
conn, err := net.Dial("tcp", addr.String())
if err != nil {
t.Fatal(err)
}
client(conn)
}()
conn, err := listener.Accept()
if err != nil {
t.Fatal(err)
}
// read from the socket
r := bufio.NewReader(conn)
_, err = r.ReadString('\n')
if err != nil {
t.Fatal(err)
}
// write to the socket that is already closed for a second repeatedly
err = func(conn net.Conn) error {
timer := time.After(1 * time.Second)
for {
select {
case <-timer:
return nil
default:
}
b := make([]byte, 1)
_, err = conn.Write(b)
if err != nil {
return err
}
}
}(conn)
if err == nil {
t.Fatal("An error should be occured.")
}
if netutil.IsNetworkErrorFatal(err) {
t.Fatalf("Fatal error: %s", err)
}
t.Logf("Non fatal error: %v", err)
err = conn.Close()
if err != nil {
t.Fatal(err)
}
}