CalejoControl/tests/utils/port_utils.py

40 lines
1.0 KiB
Python

"""
Utility functions for managing ports in tests.
"""
import socket
from typing import List
def find_free_port(start_port: int = 8000, max_attempts: int = 100) -> int:
"""
Find a free port starting from the specified port.
Args:
start_port: Starting port to check
max_attempts: Maximum number of ports to check
Returns:
Free port number
"""
for port in range(start_port, start_port + max_attempts):
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', port))
return port
except OSError:
continue
raise RuntimeError(f"Could not find free port in range {start_port}-{start_port + max_attempts}")
def get_test_ports() -> dict:
"""
Get a set of unique ports for testing.
Returns:
Dictionary with port assignments
"""
return {
'opcua_port': find_free_port(4840),
'modbus_port': find_free_port(5020),
'rest_api_port': find_free_port(8000)
}