Skip to content

Commit a611b1a

Browse files
committed
change strategy for testing CloseConnection races
Only pay for a task context switch when the code is under test.
1 parent ea25026 commit a611b1a

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

tests/test_connection.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
open_websocket_url,
5959
serve_websocket,
6060
WebSocketServer,
61+
WebSocketRequest,
6162
wrap_client_stream,
6263
wrap_server_stream
6364
)
@@ -906,8 +907,9 @@ async def handler(request):
906907
async def test_close_race(nursery, autojump_clock):
907908
"""server attempts close just as client disconnects (issue #96)"""
908909

909-
async def handler(request):
910+
async def handler(request: WebSocketRequest):
910911
ws = await request.accept()
912+
ws._for_testing_peer_closed_connection = trio.Event()
911913
await ws.send_message('foo')
912914
await ws._for_testing_peer_closed_connection.wait()
913915
# with bug, this would raise ConnectionClosed from websocket internal task

trio_websocket/_impl.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import ssl
1010
import struct
1111
import urllib.parse
12-
from typing import List
12+
from typing import List, Optional
1313

1414
import trio
1515
import trio.abc
@@ -744,9 +744,10 @@ def __init__(self, stream, ws_connection, *, host=None, path=None,
744744
# Set once a WebSocket closed handshake takes place, i.e after a close
745745
# frame has been sent and a close frame has been received.
746746
self._close_handshake = trio.Event()
747-
# Set immediately upon receiving closed event from peer. Used to
748-
# test close race conditions between client and server.
749-
self._for_testing_peer_closed_connection = trio.Event()
747+
# When not None, set immediately upon receiving CloseConnection from peer,
748+
# followed by sleep(0) for a context switch. Used to test close race
749+
# conditions between client and server.
750+
self._for_testing_peer_closed_connection: Optional[trio.Event] = None
750751

751752
@property
752753
def closed(self):
@@ -1095,8 +1096,9 @@ async def _handle_close_connection_event(self, event):
10951096
10961097
:param wsproto.events.CloseConnection event:
10971098
'''
1098-
self._for_testing_peer_closed_connection.set()
1099-
await trio.sleep(0)
1099+
if self._for_testing_peer_closed_connection:
1100+
self._for_testing_peer_closed_connection.set()
1101+
await trio.sleep(0)
11001102
if self._wsproto.state == ConnectionState.REMOTE_CLOSING:
11011103
await self._send(event.response())
11021104
await self._close_web_socket(event.code, event.reason or None)

0 commit comments

Comments
 (0)