-
Notifications
You must be signed in to change notification settings - Fork 5
/
websocket_test.go
72 lines (60 loc) · 1.38 KB
/
websocket_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
package ogmigo
import (
"context"
"errors"
"fmt"
"log"
"net"
"net/http"
"strings"
"testing"
"time"
"github.com/gorilla/websocket"
)
func timeout(delay time.Duration) http.HandlerFunc {
var upgrader = websocket.Upgrader{} // use default options
return func(w http.ResponseWriter, req *http.Request) {
c, err := upgrader.Upgrade(w, req, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
select {
case <-req.Context().Done():
case <-time.After(delay):
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}
}
}
func TestClient_query(t *testing.T) {
listener, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatalf("got %v; want nil", err)
}
defer listener.Close()
go func() {
_ = http.Serve(listener, timeout(time.Minute))
}()
parts := strings.Split(listener.Addr().String(), ":")
port := parts[len(parts)-1]
client := New(WithEndpoint(fmt.Sprintf("ws://127.0.0.1:%v", port)))
ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
defer cancel()
err = client.SubmitTx(ctx, []byte(`{}`))
if ok := errors.Is(err, context.DeadlineExceeded); !ok {
t.Fatalf("expected context.Canceled; got %v", err)
}
}