| 1 | package websocket_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "os" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/coder/websocket" |
| 11 | "github.com/coder/websocket/internal/test/assert" |
| 12 | "github.com/coder/websocket/internal/test/wstest" |
| 13 | ) |
| 14 | |
| 15 | func TestWasm(t *testing.T) { |
| 16 | t.Parallel() |
| 17 | |
| 18 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 19 | defer cancel() |
| 20 | |
| 21 | c, resp, err := websocket.Dial(ctx, os.Getenv("WS_ECHO_SERVER_URL"), &websocket.DialOptions{ |
| 22 | Subprotocols: []string{"echo"}, |
| 23 | }) |
| 24 | assert.Success(t, err) |
| 25 | defer c.Close(websocket.StatusInternalError, "") |
| 26 | |
| 27 | assert.Equal(t, "subprotocol", "echo", c.Subprotocol()) |
| 28 | assert.Equal(t, "response code", http.StatusSwitchingProtocols, resp.StatusCode) |
| 29 | |
| 30 | c.SetReadLimit(65536) |
| 31 | for i := 0; i < 10; i++ { |
| 32 | err = wstest.Echo(ctx, c, 65536) |
| 33 | assert.Success(t, err) |
| 34 | } |
| 35 | |
| 36 | err = c.Close(websocket.StatusNormalClosure, "") |
| 37 | assert.Success(t, err) |
| 38 | } |
| 39 | |
| 40 | func TestWasmDialTimeout(t *testing.T) { |
| 41 | t.Parallel() |
| 42 | |
| 43 | ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) |
| 44 | defer cancel() |
| 45 | |
| 46 | beforeDial := time.Now() |
| 47 | _, _, err := websocket.Dial(ctx, "ws://example.com:9893", &websocket.DialOptions{ |
| 48 | Subprotocols: []string{"echo"}, |
| 49 | }) |
| 50 | assert.Error(t, err) |
| 51 | if time.Since(beforeDial) >= time.Second { |
| 52 | t.Fatal("wasm context dial timeout is not working", time.Since(beforeDial)) |
| 53 | } |
| 54 | } |