-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathhttp_test.go
More file actions
386 lines (332 loc) · 10.3 KB
/
http_test.go
File metadata and controls
386 lines (332 loc) · 10.3 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package graphqlws_test
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gorilla/websocket"
graphqlws "github.com/graph-gophers/graphql-transport-ws"
)
type contextKey string
type subscribeCall struct {
ctx context.Context
document string
operationName string
variables map[string]any
}
type fakeGraphQLService struct {
mu sync.Mutex
calls []subscribeCall
subscribeFn func(ctx context.Context, document string, operationName string, variableValues map[string]any) (<-chan any, error)
}
func (s *fakeGraphQLService) Subscribe(ctx context.Context, document string, operationName string, variableValues map[string]any) (<-chan any, error) {
s.mu.Lock()
s.calls = append(s.calls, subscribeCall{ctx: ctx, document: document, operationName: operationName, variables: variableValues})
s.mu.Unlock()
if s.subscribeFn == nil {
c := make(chan any)
close(c)
return c, nil
}
return s.subscribeFn(ctx, document, operationName, variableValues)
}
func (s *fakeGraphQLService) getCalls() []subscribeCall {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]subscribeCall, len(s.calls))
copy(out, s.calls)
return out
}
type fakeHTTPHandler struct {
calls chan *http.Request
}
func (h *fakeHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.calls != nil {
select {
case h.calls <- r:
default:
}
}
w.WriteHeader(http.StatusOK)
}
type testMocker struct {
handler http.Handler
mockHTTP *fakeHTTPHandler
}
func TestNewHandlerFunc(t *testing.T) {
type Args struct {
isWebSocketTest bool
subprotocols []string
}
type Want struct {
assertion func(t *testing.T, conn *websocket.Conn)
checkHTTP func(t *testing.T, resp *http.Response)
checkError func(t *testing.T, err error)
expectedSubprotocol string
}
testTable := map[string]struct {
args Args
setup func() testMocker
want Want
}{
"graphql-transport-ws protocol ok ": {
args: Args{
isWebSocketTest: true,
subprotocols: []string{graphqlws.ProtocolGraphQLTransportWS},
},
setup: func() testMocker {
mockSvc := &fakeGraphQLService{}
return testMocker{handler: graphqlws.NewHandlerFunc(mockSvc, nil)}
},
want: Want{
expectedSubprotocol: graphqlws.ProtocolGraphQLTransportWS,
assertion: func(t *testing.T, conn *websocket.Conn) {
requireConnectionAck(t, conn)
},
},
},
"unsupported protocol error": {
args: Args{
isWebSocketTest: true,
subprotocols: []string{"unsupported-protocol"},
},
setup: func() testMocker {
return testMocker{handler: graphqlws.NewHandlerFunc(nil, nil)}
},
want: Want{
assertion: func(t *testing.T, conn *websocket.Conn) {
if conn.Subprotocol() != "" {
t.Fatalf("expected no subprotocol to be selected, got %q", conn.Subprotocol())
}
var closeError *websocket.CloseError
_, _, err := conn.ReadMessage()
if !errors.As(err, &closeError) {
t.Fatalf("expected server to close connection for unsupported protocol, got err=%v", err)
}
},
},
},
"HTTP fallback ok": {
setup: func() testMocker {
calls := make(chan *http.Request, 1)
mockHTTP := &fakeHTTPHandler{calls: calls}
return testMocker{
handler: graphqlws.NewHandlerFunc(nil, mockHTTP),
mockHTTP: mockHTTP,
}
},
want: Want{
checkHTTP: func(t *testing.T, resp *http.Response) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("expected status %d, got %d", http.StatusOK, resp.StatusCode)
}
},
},
},
"HTTP fallback nil handler returns 404": {
setup: func() testMocker {
return testMocker{handler: graphqlws.NewHandlerFunc(nil, nil)}
},
want: Want{
checkHTTP: func(t *testing.T, resp *http.Response) {
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("expected status %d, got %d", http.StatusNotFound, resp.StatusCode)
}
},
},
},
"missing websocket subprotocol closes connection": {
args: Args{
isWebSocketTest: true,
},
setup: func() testMocker {
mockSvc := &fakeGraphQLService{}
return testMocker{handler: graphqlws.NewHandlerFunc(mockSvc, nil)}
},
want: Want{
assertion: func(t *testing.T, conn *websocket.Conn) {
if conn.Subprotocol() != "" {
t.Fatalf("expected no subprotocol to be selected, got %q", conn.Subprotocol())
}
var closeError *websocket.CloseError
_, _, err := conn.ReadMessage()
if !errors.As(err, &closeError) {
t.Fatalf("expected server to close connection without protocol, got err=%v", err)
}
},
},
},
}
for name, tt := range testTable {
t.Run(name, func(t *testing.T) {
t.Parallel()
mocker := tt.setup()
server := httptest.NewServer(mocker.handler)
defer server.Close()
if !tt.args.isWebSocketTest {
resp, err := http.Get(server.URL)
if err != nil {
t.Fatalf("HTTP fallback request failed: %v", err)
}
defer resp.Body.Close()
if tt.want.checkHTTP != nil {
tt.want.checkHTTP(t, resp)
}
if mocker.mockHTTP != nil && mocker.mockHTTP.calls != nil {
select {
case req := <-mocker.mockHTTP.calls:
if req.Method != http.MethodGet {
t.Fatalf("expected HTTP method GET, got %s", req.Method)
}
case <-time.After(1 * time.Second):
t.Fatal("timed out waiting for ServeHTTP to be called")
}
}
return
}
wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
dialer := websocket.Dialer{Subprotocols: tt.args.subprotocols}
conn, _, err := dialer.Dial(wsURL, nil)
if tt.want.checkError != nil {
tt.want.checkError(t, err)
return
}
if err != nil {
t.Fatalf("websocket dial failed: %v", err)
}
defer conn.Close()
if conn.Subprotocol() != tt.want.expectedSubprotocol {
t.Fatalf("expected subprotocol %q, got %q", tt.want.expectedSubprotocol, conn.Subprotocol())
}
if tt.want.assertion != nil {
tt.want.assertion(t, conn)
}
})
}
}
func TestContextGenerators(t *testing.T) {
t.Run("context value is visible to subscriber", func(t *testing.T) {
t.Parallel()
key := contextKey("testKey")
mockSvc := &fakeGraphQLService{}
handler := graphqlws.NewHandlerFunc(
mockSvc,
nil,
graphqlws.WithContextGenerator(graphqlws.ContextGeneratorFunc(func(ctx context.Context, r *http.Request) (context.Context, error) {
return context.WithValue(ctx, key, "test value"), nil
})),
)
server := httptest.NewServer(handler)
defer server.Close()
wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
dialer := websocket.Dialer{Subprotocols: []string{graphqlws.ProtocolGraphQLTransportWS}}
conn, _, err := dialer.Dial(wsURL, nil)
if err != nil {
t.Fatalf("websocket dial failed: %v", err)
}
defer conn.Close()
if err := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"connection_init"}`)); err != nil {
t.Fatalf("failed to write connection_init: %v", err)
}
if err := conn.WriteMessage(websocket.TextMessage, []byte(`{"id":"1","type":"subscribe","payload":{"query":"subscription{}"}}`)); err != nil {
t.Fatalf("failed to write subscribe: %v", err)
}
deadline := time.Now().Add(1 * time.Second)
for {
calls := mockSvc.getCalls()
if len(calls) > 0 {
if got := calls[0].ctx.Value(key); got != "test value" {
t.Fatalf("expected context value %q, got %#v", "test value", got)
}
return
}
if time.Now().After(deadline) {
t.Fatal("timed out waiting for Subscribe call")
}
time.Sleep(10 * time.Millisecond)
}
})
t.Run("context generator error rejects upgrade", func(t *testing.T) {
t.Parallel()
handler := graphqlws.NewHandlerFunc(
&fakeGraphQLService{},
nil,
graphqlws.WithContextGenerator(graphqlws.ContextGeneratorFunc(func(ctx context.Context, r *http.Request) (context.Context, error) {
return nil, errors.New("unexpected error generating context")
})),
)
server := httptest.NewServer(handler)
defer server.Close()
wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
dialer := websocket.Dialer{Subprotocols: []string{graphqlws.ProtocolGraphQLTransportWS}}
_, resp, err := dialer.Dial(wsURL, nil)
if err == nil {
t.Fatal("expected websocket dial to fail")
}
if resp == nil {
t.Fatal("expected HTTP response on failed websocket upgrade")
}
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, resp.StatusCode)
}
})
}
func TestWithCheckOrigin(t *testing.T) {
handler := graphqlws.NewHandlerFunc(
&fakeGraphQLService{},
nil,
graphqlws.WithCheckOrigin(func(r *http.Request) bool {
return r.Header.Get("Origin") == "https://trusted.example"
}),
)
server := httptest.NewServer(handler)
defer server.Close()
wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
t.Run("rejects untrusted origin", func(t *testing.T) {
dialer := websocket.Dialer{Subprotocols: []string{graphqlws.ProtocolGraphQLTransportWS}}
_, resp, err := dialer.Dial(wsURL, http.Header{"Origin": []string{"https://evil.example"}})
if err == nil {
t.Fatal("expected websocket dial to fail for untrusted origin")
}
if resp == nil {
t.Fatal("expected HTTP response on failed websocket upgrade")
}
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected status %d, got %d", http.StatusForbidden, resp.StatusCode)
}
})
t.Run("accepts trusted origin", func(t *testing.T) {
dialer := websocket.Dialer{Subprotocols: []string{graphqlws.ProtocolGraphQLTransportWS}}
conn, _, err := dialer.Dial(wsURL, http.Header{"Origin": []string{"https://trusted.example"}})
if err != nil {
t.Fatalf("websocket dial failed for trusted origin: %v", err)
}
defer conn.Close()
requireConnectionAck(t, conn)
})
}
func requireConnectionAck(t *testing.T, conn *websocket.Conn) {
t.Helper()
err := conn.WriteMessage(websocket.TextMessage, []byte(`{"type":"connection_init"}`))
if err != nil {
t.Fatalf("failed to send connection_init: %v", err)
}
_, p, err := conn.ReadMessage()
if err != nil {
t.Fatalf("failed to read message from server: %v", err)
}
var msg struct {
Type string `json:"type"`
}
if err := json.Unmarshal(p, &msg); err != nil {
t.Fatalf("failed to unmarshal server message: %v", err)
}
if msg.Type != "connection_ack" {
t.Fatalf("expected connection_ack message, got %q", msg.Type)
}
}