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
12 changes: 11 additions & 1 deletion Lib/asyncio/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,17 @@ def connection_made(self, transport):
self._over_ssl = transport.get_extra_info('sslcontext') is not None
if self._client_connected_cb is not None:
writer = StreamWriter(transport, self, reader, self._loop)
res = self._client_connected_cb(reader, writer)
try:
res = self._client_connected_cb(reader, writer)
except Exception as exc:
self._loop.call_exception_handler({
'message': 'Unhandled exception in client_connected_cb',
'exception': exc,
'transport': transport,
})
transport.close()
self._strong_reader = None
return
if coroutines.iscoroutine(res):
def callback(task):
if task.cancelled():
Expand Down
32 changes: 32 additions & 0 deletions Lib/test/test_asyncio/test_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -1267,6 +1267,38 @@ async def handle_echo(reader, writer):
messages = self._basetest_unhandled_exceptions(handle_echo)
self.assertEqual(messages, [])

def test_unhandled_exception_sync_callback(self):
# An exception raised by a plain-function client_connected_cb is
# reported like the coroutine case and the transport is closed.
port = socket_helper.find_unused_port()

messages = []
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))

async def client():
rd, wr = await asyncio.open_connection('localhost', port)
async with asyncio.timeout(60):
data = await rd.read()
self.assertEqual(data, b'') # the server closed the connection
wr.close()
await wr.wait_closed()

async def main():
def handle_echo(reader, writer):
raise Exception('test')

server = await asyncio.start_server(
handle_echo, 'localhost', port)
await server.start_serving()
await client()
server.close()
await server.wait_closed()

self.loop.run_until_complete(main())

self.assertEqual(messages[0]['message'],
'Unhandled exception in client_connected_cb')

def test_open_connection_happy_eyeball_refcycles(self):
port = socket_helper.find_unused_port()
async def main():
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix :func:`asyncio.start_server` when a plain-function *client_connected_cb*
raises: the error is now reported like the coroutine case and the transport
is closed, instead of leaving the connection open forever (which also made
:meth:`asyncio.Server.wait_closed` hang).
Loading