From b3520030f57b050914a14f4363e3dccff3e51163 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Wed, 21 Dec 2022 16:07:21 +0100 Subject: [PATCH] tests: improve search of a free TCP port (#72645) --- hobo/test_utils.py | 12 ++++++++++++ tests/test_emails.py | 9 ++------- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/hobo/test_utils.py b/hobo/test_utils.py index 47bd38d..2aa8947 100644 --- a/hobo/test_utils.py +++ b/hobo/test_utils.py @@ -16,6 +16,9 @@ import hashlib import os +import socket +import struct +from contextlib import closing def get_safe_db_name(max_length=53): @@ -47,3 +50,12 @@ def get_safe_db_name(max_length=53): truncated_db_name = full_db_name[:prefix_length] + '_' + hashcode + '_' + full_db_name[-suffix_length:] assert len(truncated_db_name) == max_length return truncated_db_name + + +def find_free_port(): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: + s.bind(('', 0)) + # SO_LINGER (man 7 socket) l_onoff=1 l_linger=0, immediately release + # the port on closing of the socket + s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + return s.getsockname()[1] diff --git a/tests/test_emails.py b/tests/test_emails.py index 47f601e..779641b 100644 --- a/tests/test_emails.py +++ b/tests/test_emails.py @@ -16,17 +16,12 @@ from test_manager import login from hobo.emails.validators import validate_email_address from hobo.environment.models import Variable +from hobo.test_utils import find_free_port @pytest.fixture def port_available(): - errno = 0 - while not errno: - port = random.randint(49152, 65534) - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - errno = sock.connect_ex(('127.0.0.1', port)) - sock.close() - return port + return find_free_port() @pytest.fixture