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
7 changes: 7 additions & 0 deletions starlette/websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
self.client_state = WebSocketState.CONNECTING
self.application_state = WebSocketState.CONNECTING

@property
def is_disconnected(self) -> bool:
return (
self.client_state == WebSocketState.DISCONNECTED
or self.application_state == WebSocketState.DISCONNECTED
)

async def receive(self) -> Message:
"""
Receive ASGI websocket messages, ensuring valid state transitions.
Expand Down
15 changes: 15 additions & 0 deletions tests/test_websockets.py
Original file line number Diff line number Diff line change
Expand Up @@ -651,3 +651,18 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None:
with pytest.raises(RuntimeError):
with client.websocket_connect("/") as websocket:
websocket.send({"type": "websocket.connect"})


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

client = test_client_factory(app)
with client.websocket_connect("/") as websocket:
websocket.send_json({"close": True})
Loading