Skip to content

Commit

Permalink
fix assert_port_is_free
Browse files Browse the repository at this point in the history
  • Loading branch information
Ableytner committed Mar 13, 2024
1 parent b3e636d commit 2fa13c2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
17 changes: 11 additions & 6 deletions mcserverwrapper/test/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,28 +42,33 @@ def reset_workspace():
else:
shutil.rmtree(os.path.join("testdir", entry))

def assert_port_is_free(port: int = 25565) -> bool:
def assert_port_is_free(port: int = 25565, strict=True) -> bool:
"""Skips the current test if the given port is not free"""

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(("127.0.0.1", port))
return True
# windows error
except PermissionError:
pytest.skip(reason=f"Port {port} is in use")
if strict:
pytest.skip(reason=f"Port {port} is in use")
else:
return False
# linux error?
except socket.error as e:
if e.errno == errno.EADDRINUSE:
pytest.skip(reason=f"Port {port} is in use")
if strict:
pytest.skip(reason=f"Port {port} is in use")
else:
return False
else:
# something else raised the socket.error exception
raise e

def run_vanilla_test_url(url, offline_mode=False, version_name=None):
"""Run all tests for a single vanilla minecraft server url"""

assert_port_is_free()

setup_workspace()

jarfile = download_file(url)
Expand All @@ -74,7 +79,7 @@ def run_vanilla_test(jarfile, offline_mode=False, version_name=None):
"""Run all tests for a single vanilla minecraft server jar"""

port = 25565
while not assert_port_is_free(port):
while not assert_port_is_free(port, False):
port = randint(25500, 25600)

if not offline_mode:
Expand Down
10 changes: 9 additions & 1 deletion mcserverwrapper/test/test_wrapper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Module containing tests for the mcserverwrapper"""

import os
from random import randint
from time import sleep
from datetime import datetime, timedelta

Expand Down Expand Up @@ -72,12 +73,19 @@ def test_single_vanilla_offline(newest_server_jar):
def test_mineflayer(newest_server_jar):
"""Test the mineflayer bot"""

assert_port_is_free()
port = 25565
while not assert_port_is_free(port, False):
port = randint(25500, 25600)

start_cmd = f"java -Xmx2G -jar {newest_server_jar} nogui"

server_params = {
"port": port
}

wrapper = Wrapper(os.path.join(os.getcwd(), "testdir", newest_server_jar),
server_start_command=start_cmd,
server_property_args=server_params,
print_output=False)
wrapper.startup()
assert wrapper.server_running()
Expand Down

0 comments on commit 2fa13c2

Please sign in to comment.