Skip to content

Commit

Permalink
Made WebsocketCommunicator assertions more informative. (#2098)
Browse files Browse the repository at this point in the history
  • Loading branch information
hovi committed May 13, 2024
1 parent 8087d47 commit 42deaca
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
14 changes: 10 additions & 4 deletions channels/testing/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,27 +78,33 @@ async def receive_from(self, timeout=1):
"""
response = await self.receive_output(timeout)
# Make sure this is a send message
assert response["type"] == "websocket.send"
assert (
response["type"] == "websocket.send"
), f"Expected type 'websocket.send', but was '{response['type']}'"
# Make sure there's exactly one key in the response
assert ("text" in response) != (
"bytes" in response
), "The response needs exactly one of 'text' or 'bytes'"
# Pull out the right key and typecheck it for our users
if "text" in response:
assert isinstance(response["text"], str), "Text frame payload is not str"
assert isinstance(
response["text"], str
), f"Text frame payload is not str, it is {type(response['text'])}"
return response["text"]
else:
assert isinstance(
response["bytes"], bytes
), "Binary frame payload is not bytes"
), f"Binary frame payload is not bytes, it is {type(response['bytes'])}"
return response["bytes"]

async def receive_json_from(self, timeout=1):
"""
Receives a JSON text frame payload and decodes it
"""
payload = await self.receive_from(timeout)
assert isinstance(payload, str), "JSON data is not a text frame"
assert isinstance(
payload, str
), f"JSON data is not a text frame, it is {type(payload)}"
return json.loads(payload)

async def disconnect(self, code=1000, timeout=1):
Expand Down
26 changes: 26 additions & 0 deletions tests/test_testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ def receive(self, text_data=None, bytes_data=None):
self.send(text_data=text_data, bytes_data=bytes_data)


class AcceptCloseWebsocketApp(WebsocketConsumer):
def connect(self):
assert self.scope["path"] == "/testws/"
self.accept()
self.close()


class ErrorWebsocketApp(WebsocketConsumer):
"""
Barebones WebSocket ASGI app for error testing.
Expand Down Expand Up @@ -93,6 +100,25 @@ async def test_websocket_communicator():
await communicator.disconnect()


@pytest.mark.django_db
@pytest.mark.asyncio
async def test_websocket_incorrect_read_json():
"""
When using an invalid communicator method, an assertion error will be raised with
informative message.
In this test, the server accepts and then immediately closes the connection so
the server is not in a valid state to handle "receive_from".
"""
communicator = WebsocketCommunicator(AcceptCloseWebsocketApp(), "/testws/")
await communicator.connect()
with pytest.raises(AssertionError) as exception_info:
await communicator.receive_from()
assert (
str(exception_info.value)
== "Expected type 'websocket.send', but was 'websocket.close'"
)


@pytest.mark.django_db
@pytest.mark.asyncio
async def test_websocket_application():
Expand Down

0 comments on commit 42deaca

Please sign in to comment.