Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions changelog.d/1614.deprecated.rst
Original file line number Diff line number Diff line change
@@ -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.
23 changes: 23 additions & 0 deletions docs/reference/fixtures/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
37 changes: 37 additions & 0 deletions pytest_asyncio/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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():
Expand Down
69 changes: 66 additions & 3 deletions tests/test_port_factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

from textwrap import dedent

from pytest import Pytester
import pytest
from pytest import PytestDeprecationWarning, Pytester

import pytest_asyncio.plugin

Expand Down Expand Up @@ -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

Expand All @@ -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

Expand All @@ -179,5 +185,62 @@ 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.makeini("""
[pytest]
asyncio_default_fixture_loop_scope = function
""")
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)
Loading