forked from stripe/veneur
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_test.go
73 lines (61 loc) · 1.94 KB
/
socket_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
package veneur
import (
"fmt"
"net"
"testing"
"github.com/stretchr/testify/assert"
)
func writeReadUDP(t *testing.T, sock net.PacketConn, addr string) {
client, err := net.Dial("udp", addr)
assert.NoError(t, err, "should have connected to socket")
_, err = client.Write([]byte("hello world"))
assert.NoError(t, err, "should have written to socket")
b := make([]byte, 15)
n, laddr, err := sock.ReadFrom(b)
assert.NoError(t, err, "should have read from socket")
assert.Equal(t, n, 11, "should have read 11 bytes from socket")
assert.Equal(t, "hello world", string(b[:n]), "should have gotten message from socket")
assert.Equal(t, client.LocalAddr().String(), laddr.String(), "should have gotten message from client's address")
err = client.Close()
assert.NoError(t, err, "client.Close should not fail")
}
func TestSocket(t *testing.T) {
HTTPAddrPort++
portString := fmt.Sprintf("%d", HTTPAddrPort)
v4Localhost := "127.0.0.1:" + portString
v6Localhost := "[::1]:" + portString
// see if the system supports ipv6 by listening to a port
systemSupportsV6 := true
conn, err := net.ListenPacket("udp", "[::1]:0")
if err != nil {
systemSupportsV6 = false
} else {
conn.Close()
}
tests := []struct {
addr string
supportsIPv4 bool
supportsIPv6 bool
}{
{v4Localhost, true, false},
{v6Localhost, false, true},
{":" + portString, true, true},
}
for _, test := range tests {
if test.addr == v6Localhost && !systemSupportsV6 {
continue
}
addr, err := net.ResolveUDPAddr("udp", test.addr)
assert.NoError(t, err, "should have resolved udp address %s correctly", test.addr)
sock, err := NewSocket(addr, 2*1024*1024, false)
assert.NoError(t, err, "should have constructed socket correctly")
if test.supportsIPv4 {
writeReadUDP(t, sock, v4Localhost)
}
if test.supportsIPv6 && systemSupportsV6 {
writeReadUDP(t, sock, v6Localhost)
}
err = sock.Close()
assert.NoError(t, err, "close should not fail")
}
}