-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket_test.go
93 lines (72 loc) · 2 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package tinytcp
import (
"bytes"
"github.com/stretchr/testify/assert"
"io"
"testing"
)
func TestSocketInput(t *testing.T) {
// given
payload := []byte("Hello world!")
payloadSize := len(payload)
in := bytes.NewBuffer(payload)
socket := MockSocket(in, io.Discard)
// when
buffer := make([]byte, payloadSize)
n, err := socket.Read(buffer)
// then
assert.Nil(t, err, "err should be nil")
assert.Equal(t, payloadSize, n, "n should equal to bytes read")
assert.Equal(t, payload, buffer, "payloads should match")
}
func TestSocketInputEOF(t *testing.T) {
// given
socket := MockSocket(&eofReader{}, io.Discard)
var closeHandlerCalled bool
socket.OnClose(func(reason CloseReason) {
closeHandlerCalled = true
assert.Equal(t, CloseReasonClient, reason, "close reason should be correct")
})
// when
_, err := socket.Read(nil)
// then
assert.Error(t, io.EOF, err, "err should be equal to io.EOF")
assert.Truef(t, closeHandlerCalled, "close handler should be called")
}
func TestSocketOutput(t *testing.T) {
// given
payload := []byte("Hello world")
payloadSize := len(payload)
var out bytes.Buffer
socket := MockSocket(nil, &out)
// when
n, err := socket.Write(payload)
// then
assert.Nil(t, err, "err should be nil")
assert.Equal(t, payloadSize, n, "n should equal to bytes read")
assert.Equal(t, payload, out.Bytes(), "payloads should match")
}
func TestSocketOutputEOF(t *testing.T) {
// given
socket := MockSocket(nil, &eofWriter{})
var closeHandlerCalled bool
socket.OnClose(func(reason CloseReason) {
closeHandlerCalled = true
assert.Equal(t, CloseReasonClient, reason, "close reason should be correct")
})
// when
_, err := socket.Write(nil)
// then
assert.Error(t, io.EOF, err, "err should be equal to io.EOF")
assert.Truef(t, closeHandlerCalled, "close handler should be called")
}
type eofReader struct {
}
func (er *eofReader) Read(_ []byte) (int, error) {
return 0, io.EOF
}
type eofWriter struct {
}
func (ew *eofWriter) Write(_ []byte) (int, error) {
return 0, io.EOF
}