Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support random availble port selection in DeviceEmulator #643

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions socs/testing/device_emulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import serial


def create_device_emulator(responses, relay_type, port=9001, encoding='utf-8',
def create_device_emulator(responses, relay_type, port=0, encoding='utf-8',
reconnect=False):
"""Create a device emulator fixture.

Expand All @@ -24,7 +24,8 @@ def create_device_emulator(responses, relay_type, port=9001, encoding='utf-8',
values. See :class:`.DeviceEmulator` for details.
relay_type (str): Communication relay type. Either 'serial' or 'tcp'.
port (int): Port for the TCP relay to listen for connections on.
Defaults to 9001. Only used if relay_type is 'tcp'.
Defaults to 0, which will select a random available port. Only used
if relay_type is 'tcp'.
encoding (str): Encoding for the messages and responses. See
:func:`socs.testing.device_emulator.DeviceEmulator` for more
details.
Expand Down Expand Up @@ -81,6 +82,8 @@ class DeviceEmulator:
Defaults to None.
encoding (str): Encoding for the messages and responses, set by the
encoding argument.
port (int): Port that the DeviceEmulator is listening on if using the
'tcp' relay.
_type (str): Relay type, either 'serial' or 'tcp'.
_read (bool): Used to stop the background reading of data recieved on
the relay.
Expand All @@ -96,6 +99,7 @@ def __init__(self, responses, encoding='utf-8', reconnect=False):
self._type = None
self._read = True
self._conn = None
self.port = None

self.logger = logging.getLogger(self.__class__.__name__)
self.logger.setLevel(logging.DEBUG)
Expand Down Expand Up @@ -249,6 +253,7 @@ def _read_socket(self, port):
try:
self._sock.bind(('127.0.0.1', port))
self._sock_bound = True
self.port = self._sock.getsockname()[1]
except OSError:
self.logger.error(f"Failed to bind to port {port}, trying again...")
time.sleep(1)
Expand Down Expand Up @@ -310,7 +315,9 @@ def create_tcp_relay(self, port):
DeviceEmulator object within a given test.

Args:
port (int): Port for the TCP relay to listen for connections on.
port (int): Port for the TCP relay to listen for connections on. A
port of 0 will select a random available port. The port number
will then be available at ``self.port``.

Notes:
This will not return until the socket is properly bound to the
Expand Down
14 changes: 7 additions & 7 deletions tests/common/test_moxa_serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
from socs.testing.device_emulator import create_device_emulator

tcp_emulator = create_device_emulator({'ping': 'pong\r'},
'tcp', 19001)
'tcp')


# Tried this as a fixture, but connections weren't cleaning up properly.
def create_tcpserver():
def create_tcpserver(port):
# Connection might not work on first attempt
for i in range(5):
try:
ser = moxa_serial.Serial_TCPServer(('127.0.0.1', 19001), 0.1)
ser = moxa_serial.Serial_TCPServer(('127.0.0.1', port), 0.1)
break
except ConnectionRefusedError:
print("Could not connect, waiting and trying again.")
Expand All @@ -24,24 +24,24 @@ def create_tcpserver():

@pytest.mark.integtest
def test_moxa_serial_create_serial_tcpserver(tcp_emulator):
create_tcpserver()
create_tcpserver(tcp_emulator.port)


@pytest.mark.integtest
def test_moxa_serial_write(tcp_emulator):
ser = create_tcpserver()
ser = create_tcpserver(tcp_emulator.port)
ser.write('ping')


@pytest.mark.integtest
def test_moxa_serial_writeread(tcp_emulator):
ser = create_tcpserver()
ser = create_tcpserver(tcp_emulator.port)
response = ser.writeread('ping')
assert response == 'pong'


@pytest.mark.integtest
def test_moxa_serial_write_readline(tcp_emulator):
ser = create_tcpserver()
ser = create_tcpserver(tcp_emulator.port)
ser.write('ping')
assert ser.readline() == 'pong\r'
2 changes: 1 addition & 1 deletion tests/integration/test_pfeiffer_tc400_agent_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def format_reply(data):
run_agent = create_agent_runner_fixture(
'../socs/agents/pfeiffer_tc400/agent.py', 'tc400_agent')
client = create_client_fixture('pfeifferturboA')
emulator = create_device_emulator({}, relay_type='tcp')
emulator = create_device_emulator({}, relay_type='tcp', port=9001)


@pytest.mark.integtest
Expand Down
5 changes: 3 additions & 2 deletions tests/test_device_emulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from socs.testing import device_emulator

tcp_emulator = device_emulator.create_device_emulator({'ping': 'pong'},
'tcp', 9001)
'tcp')


def test_create_device_emulator_invalid_type():
Expand All @@ -15,11 +15,12 @@ def test_create_device_emulator_invalid_type():


def test_create_device_emulator_tcp_relay(tcp_emulator):
port = tcp_emulator.port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# Connection might not work on first attempt
for i in range(5):
try:
s.connect(('127.0.0.1', 9001))
s.connect(('127.0.0.1', port))
break
except ConnectionRefusedError:
print("Could not connect, waiting and trying again.")
Expand Down