Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.12] GH-106684: Close asyncio.StreamWriter when asyncio.StreamWriter is not closed by application (GH-107650) #107656

Merged
merged 3 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions Lib/asyncio/streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import collections
import socket
import sys
import warnings
import weakref

if hasattr(socket, 'AF_UNIX'):
Expand Down Expand Up @@ -392,6 +393,11 @@ async def start_tls(self, sslcontext, *,
self._transport = new_transport
protocol._replace_writer(self)

def __del__(self, warnings=warnings):
if not self._transport.is_closing():
self.close()
warnings.warn(f"unclosed {self!r}", ResourceWarning)


class StreamReader:

Expand Down
23 changes: 23 additions & 0 deletions Lib/test/test_asyncio/test_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,29 @@ def test_eof_feed_when_closing_writer(self):

self.assertEqual(messages, [])

def test_unclosed_resource_warnings(self):
async def inner(httpd):
rd, wr = await asyncio.open_connection(*httpd.address)

wr.write(b'GET / HTTP/1.0\r\n\r\n')
data = await rd.readline()
self.assertEqual(data, b'HTTP/1.0 200 OK\r\n')
data = await rd.read()
self.assertTrue(data.endswith(b'\r\n\r\nTest message'))
with self.assertWarns(ResourceWarning):
del wr
gc.collect()


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

with test_utils.run_test_server() as httpd:
self.loop.run_until_complete(inner(httpd))

self.assertEqual(messages, [])



if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Raise :exc:`ResourceWarning` when :class:`asyncio.StreamWriter` is not closed leading to memory leaks. Patch by Kumar Aditya.
Loading