Skip to content

Instantly share code, notes, and snippets.

@szczys
Last active April 2, 2024 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szczys/e9c83ab0ac1d575ddb71b01d53b8a031 to your computer and use it in GitHub Desktop.
Save szczys/e9c83ab0ac1d575ddb71b01d53b8a031 to your computer and use it in GitHub Desktop.
Embedded firmware test using pytest
import pytest
import re
import serial
from time import time
# Used to flash binary to nrf52840dk
from pynrfjprog import LowLevel
@pytest.fixture(scope='session')
def anyio_backend():
return 'trio'
def pytest_addoption(parser):
parser.addoption("--port",
help="The port to which the device is attached (eg: /dev/ttyACM0)")
parser.addoption("--baud", type=int, default=115200,
help="Serial port baud rate (default: 115200)")
parser.addoption("--fw-image", type=str,
help="Firmware binary to program to device")
parser.addoption("--serial-number", type=str,
help="Serial number to identify on-board debugger")
@pytest.fixture(scope="session")
def port(request):
return request.config.getoption("--port")
@pytest.fixture(scope="session")
def baud(request):
return request.config.getoption("--baud")
@pytest.fixture(scope="session")
def fw_image(request):
return request.config.getoption("--fw-image")
@pytest.fixture(scope="session")
def serial_number(request):
return request.config.getoption("--serial-number")
class Board():
def __init__(self, port, baud, fw_image, serial_number):
self.port = port
self.baud = baud
self.fw_image = fw_image
self.serial_number = serial_number
#program firmware
self.program(fw_image)
self.serial_device = serial.Serial(port, self.baud, timeout=1, write_timeout=1)
def program(self, fw_image):
with LowLevel.API() as api:
api.connect_to_emu_with_snr(int(self.serial_number))
api.erase_all()
api.program_file(self.fw_image)
api.sys_reset()
api.go()
api.close()
def wait_for_regex_in_line(self, regex, timeout_s=20, log=True):
start_time = time()
while True:
self.serial_device.timeout=timeout_s
line = self.serial_device.read_until().decode('utf-8', errors='replace').replace("\r\n", "")
if line != "" and log:
print(line)
if time() - start_time > timeout_s:
raise RuntimeError('Timeout')
regex_search = re.search(regex, line)
if regex_search:
return regex_search
@pytest.fixture(scope="session")
def board(port, baud, fw_image, serial_number):
return Board(port, baud, fw_image, serial_number)
import pytest
pytestmark = pytest.mark.anyio
async def test_hello(board):
assert None != board.wait_for_regex_in_line("Hello World");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment