]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-106684: raise `ResourceWarning` when `asyncio.StreamWriter` is not closed (#107650)
authorKumar Aditya <kumaraditya@python.org>
Sat, 5 Aug 2023 12:18:15 +0000 (17:48 +0530)
committerGitHub <noreply@github.com>
Sat, 5 Aug 2023 12:18:15 +0000 (17:48 +0530)
Lib/asyncio/streams.py
Lib/test/test_asyncio/test_streams.py
Misc/NEWS.d/next/Library/2023-08-05-05-10-41.gh-issue-106684.P9zRXb.rst [new file with mode: 0644]

index bf15f517e50dcea50078e4b67d0abd5628b10396..b7ad365709b19e5939d093664622bae88a67456b 100644 (file)
@@ -5,6 +5,7 @@ __all__ = (
 import collections
 import socket
 import sys
+import warnings
 import weakref
 
 if hasattr(socket, 'AF_UNIX'):
@@ -392,6 +393,11 @@ class StreamWriter:
         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:
 
index 7f9dc6218083581aa5f08e746ef4e2c35fdcd54a..9c92e75886c593beb0119115de4f8c9728f2f2fb 100644 (file)
@@ -1074,6 +1074,29 @@ os.close(fd)
 
         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()
diff --git a/Misc/NEWS.d/next/Library/2023-08-05-05-10-41.gh-issue-106684.P9zRXb.rst b/Misc/NEWS.d/next/Library/2023-08-05-05-10-41.gh-issue-106684.P9zRXb.rst
new file mode 100644 (file)
index 0000000..02c52d7
--- /dev/null
@@ -0,0 +1 @@
+Raise :exc:`ResourceWarning` when :class:`asyncio.StreamWriter` is not closed leading to memory leaks. Patch by Kumar Aditya.