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

fix(websocket): ASGI websocket must pass thru bytes as is #2651

Merged
merged 4 commits into from Feb 5, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 2 additions & 2 deletions sanic/server/websockets/connection.py
Expand Up @@ -45,15 +45,15 @@ async def send(self, data: Union[str, bytes], *args, **kwargs) -> None:

await self._send(message)

async def recv(self, *args, **kwargs) -> Optional[str]:
async def recv(self, *args, **kwargs) -> Optional[Union[str, bytes]]:
message = await self._receive()

if message["type"] == "websocket.receive":
try:
return message["text"]
except KeyError:
try:
return message["bytes"].decode()
return message["bytes"]
except KeyError:
raise InvalidUsage("Bad ASGI message received")
elif message["type"] == "websocket.disconnect":
Expand Down
11 changes: 10 additions & 1 deletion tests/test_asgi.py
Expand Up @@ -342,7 +342,7 @@ async def test_websocket_send(send, receive, message_stack):


@pytest.mark.asyncio
async def test_websocket_receive(send, receive, message_stack):
async def test_websocket_text_receive(send, receive, message_stack):
msg = {"text": "hello", "type": "websocket.receive"}
message_stack.append(msg)

Expand All @@ -351,6 +351,15 @@ async def test_websocket_receive(send, receive, message_stack):

assert text == msg["text"]

@pytest.mark.asyncio
async def test_websocket_bytes_receive(send, receive, message_stack):
msg = {"bytes": b"hello", "type": "websocket.receive"}
message_stack.append(msg)

ws = WebSocketConnection(send, receive)
bytes = await ws.receive()
Tronic marked this conversation as resolved.
Show resolved Hide resolved

assert bytes == msg["bytes"]

@pytest.mark.asyncio
async def test_websocket_accept_with_no_subprotocols(
Expand Down