Skip to content

Commit 0004686

Browse files
kumaraditya303miss-islington
authored andcommitted
pythonGH-106684: raise ResourceWarning when asyncio.StreamWriter is not closed (pythonGH-107650)
(cherry picked from commit 41178e4) Co-authored-by: Kumar Aditya <kumaraditya@python.org>
1 parent 7e834c4 commit 0004686

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

Lib/asyncio/streams.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,11 @@ async def start_tls(self, sslcontext, *,
391391
self._transport = new_transport
392392
protocol._replace_writer(self)
393393

394+
def __del__(self, warnings=warnings):
395+
if not self._transport.is_closing():
396+
self.close()
397+
warnings.warn(f"unclosed {self!r}", ResourceWarning)
398+
394399

395400
class StreamReader:
396401

Lib/test/test_asyncio/test_streams.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,6 +1068,29 @@ def test_eof_feed_when_closing_writer(self):
10681068

10691069
self.assertEqual(messages, [])
10701070

1071+
def test_unclosed_resource_warnings(self):
1072+
async def inner(httpd):
1073+
rd, wr = await asyncio.open_connection(*httpd.address)
1074+
1075+
wr.write(b'GET / HTTP/1.0\r\n\r\n')
1076+
data = await rd.readline()
1077+
self.assertEqual(data, b'HTTP/1.0 200 OK\r\n')
1078+
data = await rd.read()
1079+
self.assertTrue(data.endswith(b'\r\n\r\nTest message'))
1080+
with self.assertWarns(ResourceWarning):
1081+
del wr
1082+
gc.collect()
1083+
1084+
1085+
messages = []
1086+
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
1087+
1088+
with test_utils.run_test_server() as httpd:
1089+
self.loop.run_until_complete(inner(httpd))
1090+
1091+
self.assertEqual(messages, [])
1092+
1093+
10711094

10721095
if __name__ == '__main__':
10731096
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Raise :exc:`ResourceWarning` when :class:`asyncio.StreamWriter` is not closed leading to memory leaks. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)