]> git.ipfire.org Git - thirdparty/psycopg.git/commitdiff
test: fix resource leaking in tests
authorDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 13 Dec 2022 04:04:04 +0000 (04:04 +0000)
committerDaniele Varrazzo <daniele.varrazzo@gmail.com>
Tue, 13 Dec 2022 11:20:24 +0000 (11:20 +0000)
It results in spurious warnings on ``gc_collect()`` in some innocent test
downstream::

    ResourceWarning: unclosed <socket.socket fd=14,
    family=AddressFamily.AF_UNIX, type=SocketKind.SOCK_STREAM, proto=0>

tests/pool/test_pool_async_noasyncio.py

index 0f0813716b18a953074c6a8819d1a0c8900163e2..f6e34e472d9a15b957309ae59e9cef6d6ae25665 100644 (file)
@@ -5,6 +5,8 @@ import asyncio
 
 import pytest
 
+from ..utils import gc_collect
+
 try:
     import psycopg_pool as pool
 except ImportError:
@@ -13,7 +15,7 @@ except ImportError:
 
 
 @pytest.mark.slow
-def test_reconnect_after_max_lifetime(dsn):
+def test_reconnect_after_max_lifetime(dsn, asyncio_run):
     # See issue #219, pool created before the loop.
     p = pool.AsyncConnectionPool(dsn, min_size=1, max_lifetime=0.2, open=False)
 
@@ -30,11 +32,11 @@ def test_reconnect_after_max_lifetime(dsn):
         finally:
             await p.close()
 
-    asyncio.run(asyncio.wait_for(test(), timeout=2.0))
+    asyncio_run(asyncio.wait_for(test(), timeout=2.0))
 
 
 @pytest.mark.slow
-def test_working_created_before_loop(dsn):
+def test_working_created_before_loop(dsn, asyncio_run):
     p = pool.AsyncNullConnectionPool(dsn, open=False)
 
     async def test():
@@ -50,9 +52,27 @@ def test_working_created_before_loop(dsn):
         finally:
             await p.close()
 
-    asyncio.run(asyncio.wait_for(test(), timeout=2.0))
+    asyncio_run(asyncio.wait_for(test(), timeout=2.0))
 
 
 def test_cant_create_open_outside_loop(dsn):
     with pytest.raises(RuntimeError):
         pool.AsyncConnectionPool(dsn, open=True)
+
+
+@pytest.fixture
+def asyncio_run(recwarn):
+    """Fixture reuturning asyncio.run, but managing resources at exit.
+
+    In certain runs, fd objects are leaked and the error will only be caught
+    downstream, by some innocent test calling gc_collect().
+    """
+    recwarn.clear()
+    try:
+        yield asyncio.run
+    finally:
+        gc_collect()
+        if recwarn:
+            warn = recwarn.pop(ResourceWarning)
+            assert "unclosed event loop" in str(warn.message)
+            assert not recwarn