Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
18 changes: 13 additions & 5 deletions starlette/websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ def __init__(self, code: int = 1000, reason: str | None = None) -> None:
self.reason = reason or ""


class WebSocketDisconnected(RuntimeError):
"""
Raised when attempting to use a disconnected WebSocket.
"""

pass
Comment on lines +25 to +30
Copy link
Owner

Choose a reason for hiding this comment

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

That's not really what I meant... The exception already exists.

Copy link
Author

Choose a reason for hiding this comment

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

Well, reading the code, WebSocketDisconnect seems to be called when you want to disconnect a socket, in these cases the socket is already disconnected. In my opinion, it would make more sense to create a new exception (WebSocketDisconnected). Tell me if you still want to use WebSocketDisconnect and if so I will make such changes.



class WebSocket(HTTPConnection):
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
super().__init__(scope)
Expand Down Expand Up @@ -53,7 +61,7 @@ async def receive(self) -> Message:
self.client_state = WebSocketState.DISCONNECTED
return message
else:
raise RuntimeError('Cannot call "receive" once a disconnect message has been received.')
raise WebSocketDisconnected('Cannot call "receive" once a disconnect message has been received.')

async def send(self, message: Message) -> None:
"""
Expand Down Expand Up @@ -94,7 +102,7 @@ async def send(self, message: Message) -> None:
self.application_state = WebSocketState.DISCONNECTED
await self._send(message)
else:
raise RuntimeError('Cannot call "send" once a close message has been sent.')
raise WebSocketDisconnected('Cannot call "send" once a close message has been sent.')

async def accept(
self,
Expand All @@ -114,14 +122,14 @@ def _raise_on_disconnect(self, message: Message) -> None:

async def receive_text(self) -> str:
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError('WebSocket is not connected. Need to call "accept" first.')
raise WebSocketDisconnected('WebSocket is not connected. Need to call "accept" first.')
message = await self.receive()
self._raise_on_disconnect(message)
return typing.cast(str, message["text"])

async def receive_bytes(self) -> bytes:
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError('WebSocket is not connected. Need to call "accept" first.')
raise WebSocketDisconnected('WebSocket is not connected. Need to call "accept" first.')
message = await self.receive()
self._raise_on_disconnect(message)
return typing.cast(bytes, message["bytes"])
Expand All @@ -130,7 +138,7 @@ async def receive_json(self, mode: str = "text") -> typing.Any:
if mode not in {"text", "binary"}:
raise RuntimeError('The "mode" argument should be "text" or "binary".')
if self.application_state != WebSocketState.CONNECTED:
raise RuntimeError('WebSocket is not connected. Need to call "accept" first.')
raise WebSocketDisconnected('WebSocket is not connected. Need to call "accept" first.')
message = await self.receive()
self._raise_on_disconnect(message)

Expand Down
61 changes: 55 additions & 6 deletions tests/test_websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from starlette.responses import Response
from starlette.testclient import WebSocketDenialResponse
from starlette.types import Message, Receive, Scope, Send
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketDisconnected, WebSocketState
from tests.types import TestClientFactory


Expand Down Expand Up @@ -449,7 +449,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
await websocket.close()

client = test_client_factory(app)
with pytest.raises(RuntimeError):
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover

Expand All @@ -463,7 +463,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
message = await websocket.receive()

client = test_client_factory(app)
with pytest.raises(RuntimeError):
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/") as websocket:
websocket.close()

Expand Down Expand Up @@ -539,7 +539,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
await websocket.receive_text()

client = test_client_factory(app)
with pytest.raises(RuntimeError):
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover

Expand All @@ -550,7 +550,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
await websocket.receive_bytes()

client = test_client_factory(app)
with pytest.raises(RuntimeError):
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover

Expand All @@ -561,7 +561,7 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
await websocket.receive_json()

client = test_client_factory(app)
with pytest.raises(RuntimeError):
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover

Expand All @@ -577,6 +577,42 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
pass # pragma: no cover


def test_receive_text_after_close(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.close()
await websocket.receive_text()

client = test_client_factory(app)
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover


def test_receive_bytes_after_close(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.close()
await websocket.receive_bytes()

client = test_client_factory(app)
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover


def test_receive_json_after_close(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.close()
await websocket.receive_json()

client = test_client_factory(app)
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover


def test_send_wrong_message_type(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
Expand All @@ -602,6 +638,19 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket.send({"type": "websocket.send"})


def test_receive_after_close(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
await websocket.accept()
websocket.client_state = WebSocketState.DISCONNECTED
await websocket.receive()

client = test_client_factory(app)
with pytest.raises(WebSocketDisconnected):
with client.websocket_connect("/"):
pass # pragma: no cover


def test_receive_wrong_message_type(test_client_factory: TestClientFactory) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
websocket = WebSocket(scope, receive=receive, send=send)
Expand Down