From b562695aca85d4f9108b5d67267355d4074ee945 Mon Sep 17 00:00:00 2001 From: Saif Modan Date: Tue, 17 Nov 2026 13:54:20 +0530 Subject: [PATCH 1/2] Deprecate unused_tcp_port, unused_tcp_port_factory, unused_udp_port and unused_udp_port_factory fixtures The fixtures bind a temporary socket to port 0 and close it before returning the port number, so another process can claim the port before the test server starts. Emit a PytestDeprecationWarning on use and document the migration: bind port 0 and read the assigned port from the server socket or transport. Fixes #1614 --- changelog.d/1614.deprecated.rst | 1 + docs/reference/fixtures/index.rst | 23 +++++++++++ pytest_asyncio/plugin.py | 37 ++++++++++++++++++ tests/test_port_factories.py | 65 +++++++++++++++++++++++++++++-- 4 files changed, 123 insertions(+), 3 deletions(-) create mode 100644 changelog.d/1614.deprecated.rst diff --git a/changelog.d/1614.deprecated.rst b/changelog.d/1614.deprecated.rst new file mode 100644 index 00000000..ca6d49ca --- /dev/null +++ b/changelog.d/1614.deprecated.rst @@ -0,0 +1 @@ +Deprecated the ``unused_tcp_port``, ``unused_tcp_port_factory``, ``unused_udp_port`` and ``unused_udp_port_factory`` fixtures. The returned port is released before the test runs, so another process can claim it before the test server starts. Bind port 0 instead and read the assigned port from the server socket or transport. diff --git a/docs/reference/fixtures/index.rst b/docs/reference/fixtures/index.rst index ade01d18..b748a8b4 100644 --- a/docs/reference/fixtures/index.rst +++ b/docs/reference/fixtures/index.rst @@ -7,6 +7,13 @@ unused_tcp_port Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers. +.. note:: + Deprecated. The returned port is released before the test runs, so another + process can claim it before the test server starts. Bind port 0 instead + and read the assigned port from the server socket, for example pass + ``port=0`` to ``asyncio.start_server()`` and read + ``server.sockets[0].getsockname()``. + unused_tcp_port_factory ======================= A callable which returns a different unused TCP port each invocation. Useful @@ -17,6 +24,22 @@ when several unused TCP ports are required in a test. def a_test(unused_tcp_port_factory): _port1, _port2 = unused_tcp_port_factory(), unused_tcp_port_factory() +.. note:: + Deprecated. The returned ports are released before the test runs, so + another process can claim them before the test server starts. Bind port 0 + instead and read the assigned port from the server socket, for example + pass ``port=0`` to ``asyncio.start_server()`` and read + ``server.sockets[0].getsockname()``. + unused_udp_port and unused_udp_port_factory =========================================== Works just like their TCP counterparts but returns unused UDP ports. + +.. note:: + Deprecated. The returned ports are released before the test runs, so + another process can claim them before the test server starts. Bind port 0 + instead and read the assigned port from the transport, for example pass + ``local_addr=("127.0.0.1", 0)`` to ``loop.create_datagram_endpoint()`` and + read ``transport.get_extra_info("sockname")``. A subprocess can inherit an + already-bound socket, or bind port 0 itself and report its address when + ready. diff --git a/pytest_asyncio/plugin.py b/pytest_asyncio/plugin.py index 32b1a834..35ec08e8 100644 --- a/pytest_asyncio/plugin.py +++ b/pytest_asyncio/plugin.py @@ -1067,19 +1067,49 @@ def _unused_port(socket_type: int) -> int: return sock.getsockname()[1] +def _warn_unused_port_fixture_deprecated(fixture_name: str, alternative: str) -> None: + warnings.warn( + PytestDeprecationWarning( + f"The {fixture_name} fixture is deprecated: the returned port is " + "released before the test runs, so another process can claim it " + "before the test server starts. " + f"{alternative}" + ) + ) + + @pytest.fixture def unused_tcp_port() -> int: + _warn_unused_port_fixture_deprecated( + "unused_tcp_port", + "Bind port 0 instead and read the assigned port from the server " + "socket, for example pass port=0 to asyncio.start_server() and read " + "server.sockets[0].getsockname().", + ) return _unused_port(socket.SOCK_STREAM) @pytest.fixture def unused_udp_port() -> int: + _warn_unused_port_fixture_deprecated( + "unused_udp_port", + "Bind port 0 instead and read the assigned port from the transport, " + "for example pass local_addr=('127.0.0.1', 0) to " + "loop.create_datagram_endpoint() and read " + "transport.get_extra_info('sockname').", + ) return _unused_port(socket.SOCK_DGRAM) @pytest.fixture(scope="session") def unused_tcp_port_factory() -> Callable[[], int]: """A factory function, producing different unused TCP ports.""" + _warn_unused_port_fixture_deprecated( + "unused_tcp_port_factory", + "Bind port 0 instead and read the assigned port from the server " + "socket, for example pass port=0 to asyncio.start_server() and read " + "server.sockets[0].getsockname().", + ) produced = set() def factory(): @@ -1099,6 +1129,13 @@ def factory(): @pytest.fixture(scope="session") def unused_udp_port_factory() -> Callable[[], int]: """A factory function, producing different unused UDP ports.""" + _warn_unused_port_fixture_deprecated( + "unused_udp_port_factory", + "Bind port 0 instead and read the assigned port from the transport, " + "for example pass local_addr=('127.0.0.1', 0) to " + "loop.create_datagram_endpoint() and read " + "transport.get_extra_info('sockname').", + ) produced = set() def factory(): diff --git a/tests/test_port_factories.py b/tests/test_port_factories.py index 0acdea34..1258d113 100644 --- a/tests/test_port_factories.py +++ b/tests/test_port_factories.py @@ -2,7 +2,8 @@ from textwrap import dedent -from pytest import Pytester +import pytest +from pytest import PytestDeprecationWarning, Pytester import pytest_asyncio.plugin @@ -145,7 +146,7 @@ def connection_lost(self, *arg, **kwd): """)) -def test_unused_port_factory_duplicate(unused_tcp_port_factory, monkeypatch): +def test_unused_port_factory_duplicate(request, monkeypatch): """Test correct avoidance of duplicate ports.""" counter = 0 @@ -160,11 +161,16 @@ def mock_unused_tcp_port(_ignored): monkeypatch.setattr(pytest_asyncio.plugin, "_unused_port", mock_unused_tcp_port) + with pytest.warns( + PytestDeprecationWarning, match="unused_tcp_port_factory fixture is deprecated" + ): + unused_tcp_port_factory = request.getfixturevalue("unused_tcp_port_factory") + assert unused_tcp_port_factory() == 10000 assert unused_tcp_port_factory() > 10000 -def test_unused_udp_port_factory_duplicate(unused_udp_port_factory, monkeypatch): +def test_unused_udp_port_factory_duplicate(request, monkeypatch): """Test correct avoidance of duplicate UDP ports.""" counter = 0 @@ -179,5 +185,58 @@ def mock_unused_udp_port(_ignored): monkeypatch.setattr(pytest_asyncio.plugin, "_unused_port", mock_unused_udp_port) + with pytest.warns( + PytestDeprecationWarning, match="unused_udp_port_factory fixture is deprecated" + ): + unused_udp_port_factory = request.getfixturevalue("unused_udp_port_factory") + assert unused_udp_port_factory() == 10000 assert unused_udp_port_factory() > 10000 + + +@pytest.mark.parametrize( + "fixture_name", + [ + "unused_tcp_port", + "unused_udp_port", + ], +) +def test_unused_port_fixtures_are_deprecated(request, fixture_name): + """Requesting an unused port fixture emits a deprecation warning.""" + with pytest.warns( + PytestDeprecationWarning, match=f"{fixture_name} fixture is deprecated" + ): + fixture = request.getfixturevalue(fixture_name) + # The fixture still works while it is deprecated. + assert isinstance(fixture, int) + + +def test_unused_port_fixtures_warn_on_use(pytester: Pytester): + """Requesting any unused port fixture emits a deprecation warning.""" + pytester.makepyfile(dedent("""\ + import pytest + + + @pytest.mark.parametrize( + "fixture_name", + [ + "unused_tcp_port", + "unused_udp_port", + "unused_tcp_port_factory", + "unused_udp_port_factory", + ], + ) + def test_fixture_emits_deprecation_warning(request, fixture_name): + with pytest.warns( + pytest.PytestDeprecationWarning, + match=f"{fixture_name} fixture is deprecated", + ): + fixture = request.getfixturevalue(fixture_name) + # The fixture still works while it is deprecated. + if callable(fixture): + assert isinstance(fixture(), int) + else: + assert isinstance(fixture, int) + """)) + result = pytester.runpytest() + result.assert_outcomes(passed=4) From d3a91d452193339754f6e2cb8a06d48459920e93 Mon Sep 17 00:00:00 2001 From: Saif Modan Date: Tue, 17 Nov 2026 21:54:15 +0530 Subject: [PATCH 2/2] Configure asyncio default fixture loop scope in testsConfigure pytester warning defaults Add configuration for asyncio default fixture loop scope --- tests/test_port_factories.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_port_factories.py b/tests/test_port_factories.py index 1258d113..9e948fdf 100644 --- a/tests/test_port_factories.py +++ b/tests/test_port_factories.py @@ -213,6 +213,10 @@ def test_unused_port_fixtures_are_deprecated(request, fixture_name): def test_unused_port_fixtures_warn_on_use(pytester: Pytester): """Requesting any unused port fixture emits a deprecation warning.""" + pytester.makeini(""" + [pytest] + asyncio_default_fixture_loop_scope = function + """) pytester.makepyfile(dedent("""\ import pytest