websocket-tests
БесплатноБез исполняемых скриптовНе проверенUse whenever the task is to test a WebSocket endpoint or real-time server: connect, send and receive messages, ping/pong, close codes, reconnect after the…
от testland★ 18 звёзд на GitHubОб этом скилле
websocket-tests
Per [RFC 6455], tests must cover the handshake, control frames, close codes, and subprotocol negotiation - not just message round-trips.
When to use
- Testing a real-time service: chat, notifications, collaborative editing, live dashboards.
- Validating reconnection logic after server-side restart or network partition.
- Pre-deployment gate: the close-code matrix is correct + ping/pong keepalive is wired.
Step 1 - Pick the client lib
| Stack | Library |
|---|---|
| Node | ws (npm install ws) |
| Browser e2e | Playwright page.on('websocket', …) for frame inspection |
| Python | websockets |
| Go | github.com/gorilla/websocket |
| Java | io.javalin/javalin-testtools or org.glassfish.tyrus/tyrus-client |
Step 2 - Handshake assertions
Per [RFC 6455], the opening handshake requires:
- HTTP GET, version 1.1+
Upgrade: websocketConnection: UpgradeSec-WebSocket-Key: base64 16-byte nonceSec-WebSocket-Version: 13
Test that an upgrade is performed (101) and that the accept header matches:
import { WebSocket } from 'ws';
import crypto from 'crypto';
test('handshake completes with correct accept header', async () => {
const ws = new WebSocket('ws://localhost:8080/');
await new Promise((res, rej) => {
ws.once('upgrade', (msg) => {
expect(msg.statusCode).toBe(101);
// server derives accept: base64(sha1(key + RFC 6455 GUID))
const expectedKey = crypto
.createHash('sha1')
.update(ws._req?.getHeader('Sec-WebSocket-Key') + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
.digest('base64');
expect(msg.headers['sec-websocket-accept']).toBe(expectedKey);
res(null);
});
ws.once('error', rej);
});
ws.close();
});
Step 3 - Subprotocol negotiation
The Sec-WebSocket-Protocol header negotiates a subprotocol; the
server selects one or none.
test('server picks v2 subprotocol when offered', async () => {
const ws = new WebSocket('ws://localhost:8080/', ['chat-v1', 'chat-v2']);
await new Promise((r) => ws.once('open', r));
expect(ws.protocol).toBe('chat-v2');
ws.close();
});
test('client gives up when the server picks none of its subprotocols', async () => {
const ws = new WebSocket('ws://localhost:8080/', ['unknown-v99']);
const err = new Promise((r) => ws.once('error', r));
const code = new Promise((r) => ws.once('close', (c) => r(c)));
expect((await err).message).toBe('Server sent no subprotocol');
expect(await code).toBe(1006);
});
No close frame is involved here: when a ws server's handleProtocols
returns false the upgrade succeeds without a Sec-WebSocket-Protocol
header, and the ws client aborts the handshake itself with the error
above, so the close code is the local 1006, not 1002 ([ws-src]).
Step 4 - Ping/pong keepalive
Control frames include ping (0x9), pong (0xA), close (0x8);
payloads <= 125 bytes.
test('client receives pong within 5s of ping', async () => {
const ws = new WebSocket('ws://localhost:8080/');
await new Promise((r) => ws.once('open', r));
const pongReceived = new Promise((resolve) => {
ws.on('pong', () => resolve(true));
});
ws.ping('keepalive');
const got = await Promise.race([
pongReceived,
new Promise((r) => setTimeout(() => r(false), 5000)),
]);
expect(got).toBe(true);
ws.close();
});
Deeper recipes
The close-frame status-code matrix (1000/1001/1002/1006/1011) and
the backpressure / large-message (maxPayload, 1009) recipes are in
references/websocket-test-recipes.md.
Step 5 - Reconnect: backoff, when to stop, browser close rules
Backoff is in the protocol itself. [RFC 6455] section 7.2.3: "clients SHOULD use some form of backoff when trying to reconnect after abnormal closures", "The first reconnect attempt SHOULD be delayed by a random amount of time", and later attempts "SHOULD be delayed by increasingly longer amounts of time". A fixed delay makes every client that lost the same server come back in the same second (a reconnect storm). Use a random first delay, then capped exponential delays with jitter, and reset the attempt counter once a connection has stayed up.
Not every close should be retried. Decide by close code:
| Close code | Meaning | Client action |
|---|---|---|
Own close(1000) (logout, unmount) |
Deliberate | Stop. Set a stopped flag before closing. |
| 1006 | Connection dropped without a close frame (reported locally) | Reconnect with backoff. |
| 1001, 1011, 1012-1014 | Server going away or failing | Reconnect with backoff. |
| 1008 | Policy violation | Stop; fix the cause or re-authenticate. |
| 1009 | Message too big | Don't resend the same message. |
| 4000-4999 chosen by the app for auth or session revoked | Application decision | Stop and re-authenticate; retrying loops forever. |
RFC 6455 section 7.4.2 reserves 3000-3999 "for use by libraries, frameworks, and app
Установить websocket-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл websocket-tests?
Use whenever the task is to test a WebSocket endpoint or real-time server: connect, send and receive messages, ping/pong, close codes, reconnect after the server drops, subprotocols and backpressure, with ws, Python websockets or Playwright.
Как установить скилл websocket-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл websocket-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic