From 0ac982aafad55c246dd65a2eaafc3cb2a1f00027 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Thu, 6 Jul 2023 01:03:30 +0200 Subject: test: try mitigating port clashes Also, I don't think calling random.seed is necessary. --- test/py/conftest.py | 13 ++++--------- test/py/lib/net.py | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 9 deletions(-) create mode 100644 test/py/lib/net.py (limited to 'test') diff --git a/test/py/conftest.py b/test/py/conftest.py index 355bd83..9551210 100644 --- a/test/py/conftest.py +++ b/test/py/conftest.py @@ -5,10 +5,10 @@ import logging import os -import random from pytest import fixture +from lib.net import random_unused_port from lib.process import CmdLine from lib.test_repo import TestRepo @@ -75,11 +75,6 @@ def pytest_generate_tests(metafunc): metafunc.parametrize(opt.codename, metafunc.config.getoption(opt.codename)) -@fixture(scope='session') -def rng(): - random.seed() - - class Paths: def __init__(self, pytestconfig): for opt in BINARY_PARAMS: @@ -113,9 +108,9 @@ def version(pytestconfig): return pytestconfig.getoption(PARAM_VERSION.codename) -@fixture -def server_port(rng): - return str(random.randint(2000, 50000)) +@fixture(scope='session') +def server_port(): + return str(random_unused_port()) @fixture diff --git a/test/py/lib/net.py b/test/py/lib/net.py new file mode 100644 index 0000000..816dd99 --- /dev/null +++ b/test/py/lib/net.py @@ -0,0 +1,21 @@ +# Copyright (c) 2023 Egor Tensin +# This file is part of the "cimple" project. +# For details, see https://github.com/egor-tensin/cimple. +# Distributed under the MIT License. + +from contextlib import closing +import random +import socket + + +def port_is_open(host, port): + with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: + return sock.connect_ex((host, port)) == 0 + + +def random_unused_port(): + while True: + port = random.randint(20000, 40000) + if port_is_open('127.0.0.1', port): + continue + return port -- cgit v1.2.3