diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 078e8785..7e537558 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -11,10 +11,26 @@ import pytest -def _get_free_port(): - sock = socket.socket() - sock.bind(("", 0)) - return sock.getsockname()[1] +def _get_free_port(upper_bound=50_000): + """Returns a random free port, with an upper bound. + + The upper bound is required as Docker does not have + permissions on high port numbers on some systems. + + """ + port = upper_bound + 1 + attempts = 0 + max_attempts = 10 + while port > upper_bound and attempts < max_attempts: + sock = socket.socket() + sock.bind(("", 0)) + port = sock.getsockname()[1] + attempts += 1 + + if attempts == max_attempts: + raise RuntimeError(f"Could not find a free port to use with the provided {upper_bound=}.") + + return port def _get_random_name(length=6):