-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetconn_test.go
99 lines (84 loc) · 2 KB
/
netconn_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
package gwebsocket
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gorilla/websocket"
)
func TestNewConn(t *testing.T) {
wsConn := websocket.Conn{}
nc := NewNetConn(&wsConn, websocket.TextMessage)
if nc == nil {
t.Error("netConn is nil")
}
}
func TestConn(t *testing.T) {
upgrader := websocket.Upgrader{}
ping := []byte("ping")
pong := []byte("pong")
done := make(chan error)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
c, err := upgrader.Upgrade(w, req, nil)
if err != nil {
done <- fmt.Errorf("upgrade req: %w", err)
return
}
defer c.Close()
nc := NewNetConn(c, websocket.TextMessage)
b := make([]byte, len(ping))
n, err := nc.Read(b)
if err != nil {
done <- fmt.Errorf("server read message: %w", err)
return
}
if n != len(ping) {
t.Errorf("reading ping message len unexpected, got '%v'", n)
}
msg := string(b)
if msg != "ping" {
done <- fmt.Errorf("incoming message is not expected value, got: '%v'", msg)
return
}
n, err = nc.Write(pong)
if err != nil {
done <- fmt.Errorf("write pong: %w", err)
return
}
if n != len(pong) {
done <- fmt.Errorf("pong message len unexpected, got: '%v'", n)
return
}
done <- nil
}))
defer server.Close()
c, _, err := websocket.DefaultDialer.Dial(strings.Replace(server.URL, "http", "ws", -1), nil)
if err != nil {
t.Errorf("dial: %w", err)
}
defer c.Close()
nc := NewNetConn(c, websocket.TextMessage)
n, err := nc.Write(ping)
if err != nil {
t.Errorf("write message: %w", err)
}
if n != len(ping) {
t.Errorf("ping message len unexpected, got: '%v'", n)
}
b := make([]byte, len(pong))
n, err = nc.Read(b)
if err != nil {
t.Errorf("read message: %w", err)
}
if n != len(pong) {
t.Errorf("reading pong message len unexpected, got '%v'", n)
}
msg := string(b)
if msg != "pong" {
t.Errorf("client incoming message unexpectd, got: '%v'", msg)
}
if err := <-done; err != nil {
t.Error(err)
}
}