Skip to content

Commit f12ba7c

Browse files
asvetlovvstinner
authored andcommitted
bpo-36916: asyncio: Swallow unhandled write() exception (GH-13313)
1 parent c96be81 commit f12ba7c

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

Lib/asyncio/streams.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,13 @@ def __del__(self):
329329
closed.exception()
330330

331331

332+
def _swallow_unhandled_exception(task):
333+
# Do a trick to suppress unhandled exception
334+
# if stream.write() was used without await and
335+
# stream.drain() was paused and resumed with an exception
336+
task.exception()
337+
338+
332339
class StreamWriter:
333340
"""Wraps a Transport.
334341
@@ -393,7 +400,9 @@ def _fast_drain(self):
393400
# fast path, the stream is not paused
394401
# no need to wait for resume signal
395402
return self._complete_fut
396-
return self._loop.create_task(self.drain())
403+
ret = self._loop.create_task(self.drain())
404+
ret.add_done_callback(_swallow_unhandled_exception)
405+
return ret
397406

398407
def write_eof(self):
399408
return self._transport.write_eof()

Lib/test/test_asyncio/test_streams.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,8 @@ def test_drain_raises(self):
851851
# where it never gives up the event loop but the socket is
852852
# closed on the server side.
853853

854+
messages = []
855+
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
854856
q = queue.Queue()
855857

856858
def server():
@@ -883,6 +885,7 @@ async def client(host, port):
883885
# Clean up the thread. (Only on success; on failure, it may
884886
# be stuck in accept().)
885887
thread.join()
888+
self.assertEqual([], messages)
886889

887890
def test___repr__(self):
888891
stream = asyncio.StreamReader(loop=self.loop,
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Remove a message about an unhandled exception in a task when writer.write()
2+
is used without await and writer.drain() fails with an exception.

0 commit comments

Comments
 (0)