Skip to content

Commit

Permalink
fix(websocket): ASGI websocket must pass thru bytes as is (#2651)
Browse files Browse the repository at this point in the history
  • Loading branch information
SaidBySolo authored Feb 5, 2023
1 parent c7a71cd commit 5e7f699
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
4 changes: 2 additions & 2 deletions sanic/server/websockets/connection.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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)
data = await ws.receive()

assert data == msg["bytes"]

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

0 comments on commit 5e7f699

Please sign in to comment.