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

More informative assert errors for WebsocketCommunicator. #2098

Merged
merged 3 commits into from
May 13, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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']}'"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the useful and important one, the rest I added only for sake of completion.

# 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
25 changes: 25 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,24 @@ 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, as assertion error will be raised with informative message.
In this test, server accepts and then immediately closes the connection so the server is not in 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
Loading