forked from LunaNode/lobster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlobster_test.go
84 lines (75 loc) · 2.12 KB
/
lobster_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
package lobster
import "github.com/gorilla/websocket"
import "bufio"
import "encoding/base64"
import "fmt"
import "net"
import "net/http"
import "strings"
import "testing"
import "time"
func TestWebsockify(t *testing.T) {
TestReset()
// create fake listener
ln, _ := net.Listen("tcp", "127.0.0.1:0")
port := ln.Addr().(*net.TCPAddr).Port
okChannel := make(chan bool, 1)
go func() {
conn, err := ln.Accept()
if err != nil {
t.Error(err)
okChannel <- false
return
}
defer conn.Close()
if err := conn.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
t.Errorf("Server SetWriteDeadline: %v", err)
}
message, err := bufio.NewReader(conn).ReadString('\n')
message = strings.TrimSpace(message)
if err != nil {
t.Errorf("Server Read: %v", err)
okChannel <- false
return
} else if message != "ping" {
t.Errorf("Expected ping, got %s", message)
okChannel <- false
return
}
if _, err := conn.Write([]byte("pong\n")); err != nil {
t.Errorf("Server Write: %v", err)
}
okChannel <- true
}()
defer func() {
ln.Close()
lnOk := <-okChannel
if !lnOk {
t.Errorf("Listener not OK")
}
}()
// connect via websocket
// HandleWebsockify returns only the token with the testing Novnc.Url configuration
token := HandleWebsockify(fmt.Sprintf("127.0.0.1:%d", port), "foo")
ws, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:6080/websockify", http.Header{"Cookie": {"token=" + token}})
if err != nil {
t.Fatal(err)
}
if err := ws.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatalf("SetWriteDeadline: %v", err)
}
if err := ws.WriteMessage(websocket.TextMessage, []byte(base64.StdEncoding.EncodeToString([]byte("ping\n")))); err != nil {
t.Fatalf("WriteMessage: %v", err)
}
if err := ws.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
t.Fatalf("SetReadDeadline: %v", err)
}
_, messageBase64, err := ws.ReadMessage()
if err != nil {
t.Fatalf("ReadMessage: %v", err)
}
message, _ := base64.StdEncoding.DecodeString(string(messageBase64))
if strings.TrimSpace(string(message)) != "pong" {
t.Fatalf("Expected pong, got %s", message)
}
}