From: Daniele Varrazzo Date: Tue, 13 Dec 2022 04:04:04 +0000 (+0000) Subject: test: fix resource leaking in tests X-Git-Tag: 3.1.5~3 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=880baa0e48f540a907c52bdc526a7222dcebb876;p=thirdparty%2Fpsycopg.git test: fix resource leaking in tests It results in spurious warnings on ``gc_collect()`` in some innocent test downstream:: ResourceWarning: unclosed --- diff --git a/tests/pool/test_pool_async_noasyncio.py b/tests/pool/test_pool_async_noasyncio.py index 0f0813716..f6e34e472 100644 --- a/tests/pool/test_pool_async_noasyncio.py +++ b/tests/pool/test_pool_async_noasyncio.py @@ -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