Skip to content

Commit

Permalink
Adds tests for ws custom headers
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Nov 13, 2023
1 parent 5b678b0 commit 645bd95
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions pkg/ws/ws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ws

import (
"net/http/httptest"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -80,4 +81,53 @@ func TestNewWSDisconnect(t *testing.T) {
case <-time.After(time.Millisecond * 10):
t.Errorf("Expected channel to be closed")
}

// Close again to make sure it doesn't panic
ws.Close()
}

func TestNewWSWithHeaders(t *testing.T) {
server := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
headerValue := ws.Request().Header.Get("X-Test")

if headerValue != "Test" {
t.Errorf("Expected header value to be 'Test', but got %v", headerValue)
}

var msg string
_ = websocket.Message.Receive(ws, &msg) // wait for request
_, _ = ws.Write([]byte(msg))
time.Sleep(time.Second) // to keep the connection open
}))
defer server.Close()

url := "ws://" + server.Listener.Addr().String()
ws, err := NewWS(url, Options{Headers: []string{"X-Test: Test"}})

if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

ws.Close()
}

func TestNewWSWithInvalidHeaders(t *testing.T) {
server := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
var msg string
_ = websocket.Message.Receive(ws, &msg) // wait for request
_, _ = ws.Write([]byte(msg))
time.Sleep(time.Second) // to keep the connection open
}))
defer server.Close()

url := "ws://" + server.Listener.Addr().String()
_, err := NewWS(url, Options{Headers: []string{"X-Test"}})

if err == nil {
t.Fatalf("Expected error, but got nil")
}

if !strings.Contains(err.Error(), "invalid header") {
t.Errorf("Expected error to contain 'invalid header', but got %v", err)
}
}

0 comments on commit 645bd95

Please sign in to comment.