websocketPair sets up an httptest server with a websocket endpoint and returns the server-side conn. The server handler stays alive until ctx is done.
(ctx context.Context, t *testing.T)
| 20 | // returns the server-side conn. The server handler stays alive until ctx |
| 21 | // is done. |
| 22 | func websocketPair(ctx context.Context, t *testing.T) *websocket.Conn { |
| 23 | t.Helper() |
| 24 | serverConnCh := make(chan *websocket.Conn, 1) |
| 25 | |
| 26 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 27 | conn, err := websocket.Accept(w, r, nil) |
| 28 | if err != nil { |
| 29 | return |
| 30 | } |
| 31 | serverConnCh <- conn |
| 32 | // Keep the handler alive so the HTTP server doesn't close |
| 33 | // the connection from under us. |
| 34 | <-ctx.Done() |
| 35 | })) |
| 36 | t.Cleanup(srv.Close) |
| 37 | |
| 38 | //nolint:bodyclose |
| 39 | clientConn, _, err := websocket.Dial(ctx, srv.URL, nil) |
| 40 | require.NoError(t, err) |
| 41 | _ = clientConn.CloseRead(ctx) // Needed to handle pings/pongs. |
| 42 | t.Cleanup(func() { |
| 43 | _ = clientConn.Close(websocket.StatusNormalClosure, "test cleanup") |
| 44 | }) |
| 45 | |
| 46 | select { |
| 47 | case sc := <-serverConnCh: |
| 48 | _ = sc.CloseRead(ctx) // Needed to handle pings/pongs. |
| 49 | return sc |
| 50 | case <-ctx.Done(): |
| 51 | t.Fatal("timed out waiting for server websocket accept") |
| 52 | return nil |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | func TestHeartbeatClose(t *testing.T) { |
| 57 | t.Parallel() |