Skip to content

Commit

Permalink
Improve test performance regarding changed role of line endings
Browse files Browse the repository at this point in the history
  • Loading branch information
clssn committed Mar 10, 2024
1 parent 6a9d560 commit 2c68b9f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
18 changes: 4 additions & 14 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,7 @@
import serialmock


@pytest.fixture(params=["\r\n", "\n\r", "\r", "\n"], ids=["crlf", "lfcr", "cr", "lf"])
def mock_device(monkeypatch, request):
"""Mock the serial.Serial class with our serialmock.SerialMock.
Parametrized different response-line endings model the different line
endings different numato devices respond with, even with the same firmware
version.
Note:
cr = carriage return = "\r"
lf = line feed = "\n"
"""
monkeypatch.setattr(serial, "Serial", serialmock.gen_serial(request.param))
@pytest.fixture()
def mock_device(monkeypatch):
"""Mock the serial.Serial class with our serialmock.SerialMock."""
monkeypatch.setattr(serial, "Serial", serialmock.gen_serial())
21 changes: 15 additions & 6 deletions tests/serialmock.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import random
import threading


def gen_serial(eol):
def gen_serial():
class SerialMock:
"""Mockup for a Numato USB IO expander device behind a serial device."""

Expand Down Expand Up @@ -46,21 +47,29 @@ def __init__(self, file, speed, timeout):
self.buf = b""
self.lock = threading.RLock()
self.is_open = True
self.eol = eol
self.notify = False
self.notify_inject_at = 0

def write(self, input):
@property
def eol(self) -> str:
"""Return a random number (0 to 10) of choices of line ending characters.
Tests that line endings really don't play a role when reading the device output.
"""
EOL_CHARS="\r\n"
return "".join(random.choices(EOL_CHARS, k=random.randrange(0, 10)))

def write(self, input_):
"""Write to the mocked device.
Processes the written data and generates the output in the buffer."""
with self.lock:

self.buf += self.respond(input)
self.buf += self.respond(input_)

if input == b"gpio notify on\r" and self.ports != 8:
if input_ == b"gpio notify on\r" and self.ports != 8:
self.notify = True
if input == b"gpio notify off\r" and self.ports != 8:
if input_ == b"gpio notify off\r" and self.ports != 8:
self.notify = False

def read(self, size):
Expand Down

0 comments on commit 2c68b9f

Please sign in to comment.