Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional WebSocket send tests to cover all payload size categories #2149

Merged
merged 5 commits into from
Jun 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
64 changes: 63 additions & 1 deletion test/websocket/send.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ const { WebSocketServer } = require('ws')
const { Blob } = require('buffer')
const { WebSocket } = require('../..')

test('Sending > 2^16 bytes', (t) => {
// the following three tests exercise different code paths because of the three
// different ways a payload length may be specified in a WebSocket frame
// (https://datatracker.ietf.org/doc/html/rfc6455#section-5.2)

test('Sending >= 2^16 bytes', (t) => {
t.plan(3)

const server = new WebSocketServer({ port: 0 })
Expand Down Expand Up @@ -34,6 +38,64 @@ test('Sending > 2^16 bytes', (t) => {
})
})

test('Sending >= 126, < 2^16 bytes', (t) => {
t.plan(3)

const server = new WebSocketServer({ port: 0 })

server.on('connection', (ws) => {
ws.on('message', (m, isBinary) => {
ws.send(m, { binary: isBinary })
})
})

const payload = Buffer.allocUnsafe(126).fill('Hello')

const ws = new WebSocket(`ws://localhost:${server.address().port}`)

ws.addEventListener('open', () => {
ws.send(payload)
})

ws.addEventListener('message', async ({ data }) => {
t.type(data, Blob)
t.equal(data.size, payload.length)
t.same(Buffer.from(await data.arrayBuffer()), payload)

ws.close()
server.close()
})
})

test('Sending < 126 bytes', (t) => {
t.plan(3)

const server = new WebSocketServer({ port: 0 })

server.on('connection', (ws) => {
ws.on('message', (m, isBinary) => {
ws.send(m, { binary: isBinary })
})
})

const payload = Buffer.allocUnsafe(125).fill('Hello')

const ws = new WebSocket(`ws://localhost:${server.address().port}`)

ws.addEventListener('open', () => {
ws.send(payload)
})

ws.addEventListener('message', async ({ data }) => {
t.type(data, Blob)
t.equal(data.size, payload.length)
t.same(Buffer.from(await data.arrayBuffer()), payload)

ws.close()
server.close()
})
})

test('Sending data after close', (t) => {
t.plan(2)

Expand Down