mirror of
https://github.com/slsdetectorgroup/slsDetectorPackage.git
synced 2026-02-07 14:58:41 +01:00
Dev/add simulator tests in GitHub workflows (#1337)
All checks were successful
Build on RHEL9 / build (push) Successful in 3m50s
Build on RHEL8 / build (push) Successful in 4m46s
Run Simulator Tests on local RHEL9 / build (push) Successful in 14m37s
Build on local RHEL9 / build (push) Successful in 1m26s
Run Simulator Tests on local RHEL8 / build (push) Successful in 16m57s
Build on local RHEL8 / build (push) Successful in 3m33s
All checks were successful
Build on RHEL9 / build (push) Successful in 3m50s
Build on RHEL8 / build (push) Successful in 4m46s
Run Simulator Tests on local RHEL9 / build (push) Successful in 14m37s
Build on local RHEL9 / build (push) Successful in 1m26s
Run Simulator Tests on local RHEL8 / build (push) Successful in 16m57s
Build on local RHEL8 / build (push) Successful in 3m33s
* added simulator tests in github workflows * indentation error * typo * debug * Logging for debugging * added more debug lines * more debugging * debug * debug * debug * dont throw if process does not exist * debug * added absolute path to sls_detector commands * some refactoring in test scripts * added absolute path to all slsdet command * typo * ../tests/scripts/test_frame_synchronizer.py * raise exception upon failure for github workflows * removed hidden tags * some refactoring in test scripts * some refactoring * fixed CMakeLists * fixed unsuccesful merge * updated python tests using simulators * debug import error * debug module import * python -m runs module pytest as script - everything in path available * removed integartion tests * enable file write not to log files * run tests without log files * increased sleep time for udp packets * added logg level variable to cmake * added testing policies to documenattion * disabled check for num_frames for jungfrau & xilinx * set log level as cmake cached variable * disable tests for jungfrau and xilinx_ctb * check frames for HDF5 * updated Documentation of Testing * changed withdetectorsimulators to detectorintegration * replaced [.cmdcall] with [.detectorintegration] * check_file_size only disabled for jungfrau - disable for all roi tests * changed time to wait after receive to 5 ms * take into account half modules of eiger * num udp interfaces needs to be consistent across modules * suppressed warning enclosing if * config added 2 udp ports per default for moench and jungfrau * write detector output to console * allow jungfrau to tests num frames, remove unused variable (numinterfaces), add comment for future to handle traceback to know which calling function threw the files unmatched, added documentation for tests (examples for .detectoritnegration and how to disable marked tests, removed addditional argumetns to disable for test_simulator as one can just use ~, removed the check that checks for jungfrau checking number of frames at master attributes and at rx test, removed unused advanced_test_settings in test_simulator script, the num_mods check for multiple modules is removed and default num modules set to 1 for test_simulator (to be increased later), back to raising exception for killprocess * removed integration tests from cmakelists.txt and cmk.sh, modified the tests workflow command to reflect the disable argument and removed xilinx_ctb from test (fix fromdeveloper merge to be done) * filtering by actual name for disable certain tests on github workflow * minor refactor * wip * wip * changes to run on local rh9 runner instead of github workfloa * modified yml to remove some leftover from github workflow * test * fix build_dir in scripts (github workflow) and pytest dir in gitea workflow * making the local machine use python3.13 binary * pythonpath added * changes for build_Dir back * allowing ctb api tests * allowed ctb api tests and set up slsdetname envt variable for shared memory being reserved just for these tests * added rh8 workflow for local runner on gitea * remnants from rh9 local runner * remnants from rh9 local runner * conda env for all shell for local runner * allowing hdf5 to build on local runner * run all tests for both the runners * refactored fixtures a bit and merged some tests that use one session for entire server * test fail * test fix * adding github workflow to test without data file checks and without logs * documentation changes * unnecessary import in conftest * allowing the session_simulator to test for multiple modules and interfaces etc * allow test_simulator script to run for 2 modules for all modules except ctb and xilinx ctb * run upon push * removing the disable file check on github workflow * minor adjustment * testing without synch * reverting to previous * with log file * without the space * summary from file and more error extracts from file to terminal * minor * trying nlf for more details * updated with no log file to print everything to screen also for det and rxr * trying a no throw * stoi was more about indent in yaml * tries * wip * debug * number of frames inconsistent fix=>just take first one, only test xilinx * jungfrau tests without frames caught check * extend the disable file check to everywhere that creates files * specify path for test_simulator * withoutprinting == * wip * back with printing===, but not parsing file for errors anymore * lang? * wip * safe log? * wip2 * wip * dont split error as its streaming live, just raise * with log files * lang? * last resort * wip * test no det with general tests * show tests live * also include hidden integration tests * without extra summary? * revert * last resort again * tsquash on int64_t? * tsquash on int64_t? mroe print * writing to /tmp? * all tests * might be the fix? * write to file * fixed a few quiet mode no log file tests * work on any branch for github tests, work on also release candidates for gitea tests * added frame synchronizer tests to github workflow * moved tests to run_tests.yaml from cmake.yaml * documentation * disabled general tests --------- Co-authored-by: Dhanya Thattil <dhanya.thattil@psi.ch>
This commit is contained in:
@@ -10,8 +10,6 @@ scripts_dir = current_dir / "tests" / "scripts"
|
||||
|
||||
sys.path.append(str(scripts_dir))
|
||||
|
||||
print(sys.path)
|
||||
|
||||
from utils_for_test import (
|
||||
Log,
|
||||
LogLevel,
|
||||
@@ -20,66 +18,154 @@ from utils_for_test import (
|
||||
startDetectorVirtualServer,
|
||||
loadConfig,
|
||||
loadBasicSettings,
|
||||
connectToVirtualServers,
|
||||
DEFAULT_UDP_DST_PORTNO,
|
||||
)
|
||||
|
||||
def pytest_addoption(parser):
|
||||
parser.addoption(
|
||||
"--with-detector-simulators", action="store_true", default=False, help="Run tests that require detector simulators"
|
||||
"--detector-integration", action="store_true", default=False, help="Run tests that require detectors"
|
||||
)
|
||||
|
||||
def pytest_configure(config):
|
||||
config.addinivalue_line("markers", "withdetectorsimulators: mark test as needing detector simulators to run")
|
||||
config.addinivalue_line("markers", "detectorintegration: mark test as needing detectors to run")
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
if config.getoption("--with-detector-simulators"):
|
||||
if config.getoption("--detector-integration"):
|
||||
return
|
||||
skip = pytest.mark.skip(reason="need --with-detector-simulators option to run")
|
||||
skip = pytest.mark.skip(reason="need --detector-integration option to run")
|
||||
for item in items:
|
||||
if "withdetectorsimulators" in item.keywords:
|
||||
if "detectorintegration" in item.keywords:
|
||||
item.add_marker(skip)
|
||||
|
||||
|
||||
DEFAULT_SIMULATOR_CONFIGS = [
|
||||
("eiger", 1, 1),
|
||||
("eiger", 1, 2),
|
||||
("jungfrau", 1, 1),
|
||||
("jungfrau", 1, 2),
|
||||
("jungfrau", 2, 1),
|
||||
("jungfrau", 2, 2),
|
||||
("mythen3", 1, 1),
|
||||
("mythen3", 1, 2),
|
||||
("gotthard2", 1, 1),
|
||||
("gotthard2", 1, 2),
|
||||
("moench", 1, 1),
|
||||
("moench", 1, 2),
|
||||
("ctb", 1, 1),
|
||||
("xilinx_ctb", 1, 1),
|
||||
]
|
||||
|
||||
SIMULATOR_IDS = [f"{det_type}_{num_interface}if_{num_mod}mod" for det_type, num_interface, num_mod in DEFAULT_SIMULATOR_CONFIGS]
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def session_simulator(request):
|
||||
"""
|
||||
Fixture to start the detector server once and clean up at the end.
|
||||
Expects request.param = (det_type, num_interfaces, num_mods)
|
||||
"""
|
||||
det_type, num_interfaces, num_mods = request.param
|
||||
fp = sys.stdout
|
||||
|
||||
# set up: once per server
|
||||
Log(LogLevel.INFOBLUE,
|
||||
f'---- {det_type} | interfaces={num_interfaces} | modules={num_mods} ----', fp)
|
||||
|
||||
cleanup(fp)
|
||||
startDetectorVirtualServer(det_type, num_mods, fp, True)
|
||||
startReceiver(num_mods, fp, True)
|
||||
|
||||
Log(LogLevel.INFOBLUE, f'Waiting for server to start up and connect', fp)
|
||||
d = loadConfig(
|
||||
name=det_type,
|
||||
log_file_fp=fp,
|
||||
num_mods=num_mods,
|
||||
num_frames=1,
|
||||
num_interfaces=num_interfaces,
|
||||
)
|
||||
|
||||
loadBasicSettings(name=det_type, d=d, fp=fp)
|
||||
|
||||
yield det_type, num_interfaces, num_mods, d
|
||||
|
||||
cleanup(fp)
|
||||
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc):
|
||||
if "session_simulator" not in metafunc.fixturenames:
|
||||
return # nothing to do
|
||||
|
||||
# Check if session_simulator is already parametrized
|
||||
markers = metafunc.definition.iter_markers(name="parametrize")
|
||||
for m in markers:
|
||||
if m.args and m.args[0] == "session_simulator":
|
||||
return # already parametrized, skip defaults
|
||||
|
||||
# Apply default configs only for session_simulator
|
||||
metafunc.parametrize(
|
||||
"session_simulator",
|
||||
DEFAULT_SIMULATOR_CONFIGS,
|
||||
ids=SIMULATOR_IDS,
|
||||
indirect=True
|
||||
)
|
||||
|
||||
'''
|
||||
for more specific parameters
|
||||
@pytest.mark.detectorintegration
|
||||
@pytest.mark.parametrize(
|
||||
"session_simulator",
|
||||
[
|
||||
("ctb", 1, 1),
|
||||
("xilinx_ctb", 1, 1),
|
||||
],
|
||||
indirect=True,
|
||||
)
|
||||
def test_define_reg(session_simulator):
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
'''
|
||||
|
||||
#helper fixture for servers
|
||||
@pytest.fixture
|
||||
def servers(request):
|
||||
@pytest.fixture(scope='module')
|
||||
def setup_parameters(request): # only setup once per module if same parameters used for the scopes
|
||||
try:
|
||||
return request.param # comes from @pytest.mark.parametrize(..., indirect=True)
|
||||
servers, nmods = request.param # comes from @pytest.mark.parametrize(..., indirect=True)
|
||||
return servers, nmods
|
||||
except AttributeError:
|
||||
# fallback default if the test did not parametrize
|
||||
return ['eiger', 'jungfrau', 'mythen3', 'gotthard2', 'ctb', 'moench', 'xilinx_ctb']
|
||||
return request.param
|
||||
|
||||
@pytest.fixture
|
||||
def test_with_simulators(servers):
|
||||
return (['eiger', 'jungfrau', 'mythen3', 'gotthard2', 'ctb', 'moench', 'xilinx_ctb'], 2)
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def test_with_simulators(setup_parameters):
|
||||
""" Fixture to automatically setup virtual detector servers for testing. """
|
||||
|
||||
LOG_PREFIX_FNAME = '/tmp/slsDetectorPackage_virtual_PythonAPI_test'
|
||||
MAIN_LOG_FNAME = LOG_PREFIX_FNAME + '_log.txt'
|
||||
fp = sys.stdout
|
||||
|
||||
with open(MAIN_LOG_FNAME, 'w') as fp:
|
||||
try:
|
||||
nmods = 2
|
||||
for server in servers:
|
||||
for ninterfaces in range(1,2):
|
||||
if ninterfaces == 2 and server != 'jungfrau' and server != 'moench':
|
||||
continue
|
||||
servers, nmods = setup_parameters
|
||||
print("servers:", servers)
|
||||
print("nmods:", nmods)
|
||||
try:
|
||||
for server in servers:
|
||||
for ninterfaces in range(1,2):
|
||||
if ninterfaces == 2 and server != 'jungfrau' and server != 'moench':
|
||||
continue
|
||||
|
||||
msg = f'Starting Python API Tests for {server}'
|
||||
msg = f'Starting Python API Tests for {server}'
|
||||
|
||||
if server == 'jungfrau' or server == 'moench':
|
||||
msg += f' with {ninterfaces} interfaces'
|
||||
if server == 'jungfrau' or server == 'moench':
|
||||
msg += f' with {ninterfaces} interfaces'
|
||||
|
||||
Log(LogLevel.INFOBLUE, msg, fp)
|
||||
cleanup(fp)
|
||||
startDetectorVirtualServer(server, nmods, fp)
|
||||
startReceiver(nmods, fp)
|
||||
d = loadConfig(name=server, log_file_fp=fp, num_mods=nmods, num_frames=1, num_interfaces=ninterfaces)
|
||||
loadBasicSettings(name=server, d=d, fp=fp)
|
||||
yield # run test
|
||||
cleanup(fp) # teardown
|
||||
except Exception as e:
|
||||
with open(MAIN_LOG_FNAME, 'a') as fp_error:
|
||||
traceback.print_exc(file=fp_error)
|
||||
Log(LogLevel.ERROR, f'Tests Failed.', fp)
|
||||
cleanup(fp)
|
||||
Log(LogLevel.INFOBLUE, msg, fp)
|
||||
cleanup(fp)
|
||||
startDetectorVirtualServer(server, nmods, fp)
|
||||
startReceiver(nmods, fp)
|
||||
d = loadConfig(name=server, log_file_fp=fp, num_mods=nmods, num_frames=1, num_interfaces=ninterfaces)
|
||||
#loadBasicSettings(name=server, d=d, fp=fp)
|
||||
yield # run test
|
||||
cleanup(fp) # teardown
|
||||
except Exception as e:
|
||||
traceback.print_exc(file=fp)
|
||||
Log(LogLevel.ERROR, f'Tests Failed.', fp)
|
||||
cleanup(fp)
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,3 @@
|
||||
'''
|
||||
cd python/tests
|
||||
Specific test: pytest -s -x test_CtbAPI.py::test_define_bit #-x=abort on first failure
|
||||
Specific test with specific server: pytest -s -x test_CtbAPI.py::test_define_reg[ctb]
|
||||
|
||||
'''
|
||||
|
||||
import pytest, sys, traceback
|
||||
|
||||
from pathlib import Path
|
||||
@@ -16,48 +9,20 @@ print(sys.path)
|
||||
from utils_for_test import (
|
||||
Log,
|
||||
LogLevel,
|
||||
cleanup,
|
||||
startDetectorVirtualServer,
|
||||
connectToVirtualServers,
|
||||
SERVER_START_PORTNO,
|
||||
)
|
||||
|
||||
from slsdet import Detector, detectorType
|
||||
from slsdet import Detector
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
scope="session",
|
||||
params=['ctb', 'xilinx_ctb', 'mythen3', 'jungfrau']
|
||||
)
|
||||
def simulator(request):
|
||||
"""Fixture to start the detector server once and clean up at the end."""
|
||||
det_name = request.param
|
||||
num_mods = 1
|
||||
fp = sys.stdout
|
||||
|
||||
# set up: once per server
|
||||
Log(LogLevel.INFOBLUE, f'---- {det_name} ----')
|
||||
cleanup(fp)
|
||||
startDetectorVirtualServer(det_name, num_mods, fp)
|
||||
|
||||
Log(LogLevel.INFOBLUE, f'Waiting for server to start up and connect')
|
||||
connectToVirtualServers(det_name, num_mods)
|
||||
|
||||
yield det_name # tests run here
|
||||
|
||||
cleanup(fp)
|
||||
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
def test_define_reg(simulator, request):
|
||||
@pytest.mark.detectorintegration
|
||||
def test_define_reg(session_simulator, request):
|
||||
""" Test setting define_reg for ctb and xilinx_ctb."""
|
||||
det_name = simulator
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
from slsdet import RegisterAddress
|
||||
|
||||
d = Detector()
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}"
|
||||
|
||||
if det_name in ['ctb', 'xilinx_ctb']:
|
||||
if det_type in ['ctb', 'xilinx_ctb']:
|
||||
prev_reg_defs = d.getRegisterDefinitions()
|
||||
prev_bit_defs = d.getBitDefinitions()
|
||||
d.clearRegisterDefinitions()
|
||||
@@ -109,17 +74,15 @@ def test_define_reg(simulator, request):
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
def test_define_bit(simulator, request):
|
||||
@pytest.mark.detectorintegration
|
||||
def test_define_bit(session_simulator, request):
|
||||
""" Test setting define_bit for ctb and xilinx_ctb."""
|
||||
det_name = simulator
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
from slsdet import RegisterAddress, BitAddress
|
||||
|
||||
# setup
|
||||
d = Detector()
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}"
|
||||
|
||||
if det_name in ['ctb', 'xilinx_ctb']:
|
||||
if det_type in ['ctb', 'xilinx_ctb']:
|
||||
prev_reg_defs = d.getRegisterDefinitions()
|
||||
prev_bit_defs = d.getBitDefinitions()
|
||||
d.clearRegisterDefinitions()
|
||||
@@ -201,17 +164,15 @@ def test_define_bit(simulator, request):
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
def test_using_defined_reg_and_bit(simulator, request):
|
||||
@pytest.mark.detectorintegration
|
||||
def test_using_defined_reg_and_bit(session_simulator, request):
|
||||
""" Test using defined reg and bit define_bit for ctb and xilinx_ctb."""
|
||||
det_name = simulator
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
from slsdet import RegisterAddress, BitAddress, RegisterValue
|
||||
|
||||
# setup
|
||||
d = Detector()
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}"
|
||||
|
||||
if det_name in ['ctb', 'xilinx_ctb']:
|
||||
if det_type in ['ctb', 'xilinx_ctb']:
|
||||
prev_reg_defs = d.getRegisterDefinitions()
|
||||
prev_bit_defs = d.getBitDefinitions()
|
||||
d.clearRegisterDefinitions()
|
||||
@@ -287,17 +248,15 @@ def test_using_defined_reg_and_bit(simulator, request):
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
def test_definelist_reg(simulator, request):
|
||||
@pytest.mark.detectorintegration
|
||||
def test_definelist_reg(session_simulator, request):
|
||||
""" Test using definelist_reg for ctb and xilinx_ctb."""
|
||||
det_name = simulator
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
from slsdet import RegisterAddress, BitAddress, RegisterValue
|
||||
|
||||
# setup
|
||||
d = Detector()
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}"
|
||||
|
||||
if det_name in ['ctb', 'xilinx_ctb']:
|
||||
if det_type in ['ctb', 'xilinx_ctb']:
|
||||
prev_reg_defs = d.getRegisterDefinitions()
|
||||
prev_bit_defs = d.getBitDefinitions()
|
||||
d.clearRegisterDefinitions()
|
||||
@@ -332,17 +291,15 @@ def test_definelist_reg(simulator, request):
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
def test_definelist_bit(simulator, request):
|
||||
@pytest.mark.detectorintegration
|
||||
def test_definelist_bit(session_simulator, request):
|
||||
""" Test using definelist_bit for ctb and xilinx_ctb."""
|
||||
det_name = simulator
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
from slsdet import RegisterAddress, BitAddress, RegisterValue
|
||||
|
||||
# setup
|
||||
d = Detector()
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}"
|
||||
|
||||
if det_name in ['ctb', 'xilinx_ctb']:
|
||||
if det_type in ['ctb', 'xilinx_ctb']:
|
||||
prev_reg_defs = d.getRegisterDefinitions()
|
||||
prev_bit_defs = d.getBitDefinitions()
|
||||
d.clearRegisterDefinitions()
|
||||
@@ -385,19 +342,55 @@ def test_definelist_bit(simulator, request):
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
def test_patternstart(simulator, request):
|
||||
""" Test using patternstart for ctb, xilinx_ctb and mythen3."""
|
||||
det_name = simulator
|
||||
# setup
|
||||
d = Detector()
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}"
|
||||
@pytest.mark.detectorintegration
|
||||
def test_parameters_file(session_simulator, request):
|
||||
""" Test using test_parameters_file."""
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
if det_name in ['ctb', 'xilinx_ctb', 'mythen3']:
|
||||
with open("/tmp/params.det", "w") as f:
|
||||
f.write("frames 2\n")
|
||||
f.write("fwrite 1\n")
|
||||
|
||||
# this should not throw
|
||||
d.parameters = "/tmp/params.det"
|
||||
|
||||
assert d.frames == 2
|
||||
assert d.fwrite == 1
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed. Command: parameters")
|
||||
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_include_file(session_simulator, request):
|
||||
""" Test using test_include_file."""
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
with open("/tmp/params.det", "w") as f:
|
||||
f.write("frames 3\n")
|
||||
f.write("fwrite 0\n")
|
||||
|
||||
# this should not throw
|
||||
d.include = "/tmp/params.det"
|
||||
|
||||
assert d.frames == 3
|
||||
assert d.fwrite == 0
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed. Command: include")
|
||||
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_patternstart(session_simulator, request):
|
||||
""" Test using patternstart for ctb, xilinx_ctb and mythen3."""
|
||||
det_type, num_interfaces, num_mods, d = session_simulator
|
||||
assert d is not None
|
||||
|
||||
if det_type in ['ctb', 'xilinx_ctb', 'mythen3']:
|
||||
d.patternstart()
|
||||
else:
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
d.patternstart()
|
||||
assert "not implemented" in str(exc_info.value)
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
Log(LogLevel.INFOGREEN, f"✅ {request.node.name} passed")
|
||||
166
python/tests/test_free.py
Normal file
166
python/tests/test_free.py
Normal file
@@ -0,0 +1,166 @@
|
||||
# SPDX-License-Identifier: LGPL-3.0-or-other
|
||||
# Copyright (C) 2021 Contributors to the SLS Detector Package
|
||||
'''
|
||||
This file is used to start up simulators and test for freeing shm and accessing it from python.
|
||||
Run this using: pytest -s test_free.py
|
||||
'''
|
||||
|
||||
import pytest, sys
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parents[2]
|
||||
|
||||
scripts_dir = current_dir / "tests" / "scripts"
|
||||
|
||||
sys.path.append(str(scripts_dir))
|
||||
|
||||
|
||||
from slsdet import Detector, Ctb, freeSharedMemory
|
||||
from utils_for_test import (
|
||||
Log,
|
||||
LogLevel,
|
||||
cleanup,
|
||||
startDetectorVirtualServer,
|
||||
connectToVirtualServers,
|
||||
SERVER_START_PORTNO
|
||||
)
|
||||
|
||||
'''
|
||||
scope = module =>Once per test file/module
|
||||
to share expensive setup like startDetectorVirtualServer
|
||||
'''
|
||||
@pytest.fixture(scope="module")
|
||||
def det_config():
|
||||
return {
|
||||
"name": "ctb",
|
||||
"num_mods": 1
|
||||
}
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def setup_simulator(det_config):
|
||||
"""Fixture to start the detector server once and clean up at the end."""
|
||||
fp = sys.stdout
|
||||
|
||||
cleanup(fp)
|
||||
startDetectorVirtualServer(det_config["name"], det_config["num_mods"], fp)
|
||||
|
||||
Log(LogLevel.INFOBLUE, f'Waiting for server to start up and connect')
|
||||
connectToVirtualServers(det_config["name"], det_config["num_mods"])
|
||||
Log(LogLevel.INFOBLUE, f'Freeing shm before tests')
|
||||
freeSharedMemory()
|
||||
|
||||
yield # tests run here
|
||||
|
||||
cleanup(fp)
|
||||
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_exptime_after_free_should_raise(setup_simulator):
|
||||
Log(LogLevel.INFOBLUE, f'\nRunning test_exptime_after_free_should_raise')
|
||||
|
||||
|
||||
d = Ctb() # creates multi shm (assuming no shm exists)
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}" # hostname command creates mod shm, d maps to it
|
||||
|
||||
d.free() # frees the shm, d should not map to it anymore
|
||||
|
||||
# accessing invalid shm should throw
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
_ = d.exptime
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed, exception was: {exc_info.value}")
|
||||
assert str(exc_info.value) == "Shared memory is invalid or freed. Close resources before access."
|
||||
|
||||
|
||||
def free_and_create_shm():
|
||||
k = Ctb() # opens existing shm if it exists
|
||||
k.hostname = f"localhost:{SERVER_START_PORTNO}" # free and recreate shm, maps to local shm struct
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_exptime_after_not_passing_var_should_raise(setup_simulator):
|
||||
Log(LogLevel.INFOBLUE, f'\nRunning test_exptime_after_not_passing_var_should_raise')
|
||||
|
||||
|
||||
d = Ctb() # creates multi shm (assuming no shm exists)
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}" # hostname command creates mod shm, d maps to it
|
||||
|
||||
free_and_create_shm() # ctb() opens multi shm, hostname command frees and recreates mod shm but shm struct is local. d still maps to old shm struct
|
||||
|
||||
# accessing invalid shm should throw
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
_ = d.exptime
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed, exception was: {exc_info.value}")
|
||||
assert str(exc_info.value) == "Shared memory is invalid or freed. Close resources before access."
|
||||
|
||||
|
||||
|
||||
|
||||
def free_and_create_shm_passing_ctb_var(k):
|
||||
k = Ctb() # opens existing shm if it exists (disregards k as its new Ctb only local to this function)
|
||||
k.hostname = f"localhost:{SERVER_START_PORTNO}" # free and recreate shm, maps to local shm struct
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_exptime_after_passing_ctb_var_should_raise(setup_simulator):
|
||||
Log(LogLevel.INFOBLUE, f'\nRunning test_exptime_after_passing_ctb_var_should_raise')
|
||||
|
||||
d = Ctb() # creates multi shm (assuming no shm exists)
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}" # hostname command creates mod shm, d maps to it
|
||||
|
||||
free_and_create_shm_passing_ctb_var(d) # ctb() opens multi shm, hostname command frees and recreates mod shm but shm struct is local. d still maps to old shm struct
|
||||
|
||||
# accessing invalid shm should throw
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
_ = d.exptime
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed, exception was: {exc_info.value}")
|
||||
assert str(exc_info.value) == "Shared memory is invalid or freed. Close resources before access."
|
||||
|
||||
|
||||
|
||||
def free_and_create_shm_returning_ctb():
|
||||
k = Ctb() # opens existing shm if it exists (disregards k as its new Ctb only local to this function)
|
||||
k.hostname = f"localhost:{SERVER_START_PORTNO}" # free and recreate shm, maps to local shm struct
|
||||
return k
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_exptime_after_returning_ctb_should_raise(setup_simulator):
|
||||
Log(LogLevel.INFOBLUE, f'\nRunning test_exptime_after_returning_ctb_should_raise')
|
||||
|
||||
d = Ctb() # creates multi shm (assuming no shm exists)
|
||||
|
||||
d = free_and_create_shm_returning_ctb() # ctb() opens multi shm, hostname command frees and recreates mod shm but shm struct is local but returned. d now maps to the new sturct
|
||||
|
||||
# this should not throw
|
||||
exptime_val = d.exptime
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed, exptime was: {exptime_val}")
|
||||
assert isinstance(exptime_val, float)
|
||||
|
||||
free_and_create_shm_returning_ctb() # this time d is not updated, it maps to the old shm struct
|
||||
|
||||
# accessing invalid shm should throw
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
_ = d.exptime
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed, exception was: {exc_info.value}")
|
||||
assert str(exc_info.value) == "Shared memory is invalid or freed. Close resources before access."
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
def test_hostname_twice_acess_old_should_raise(setup_simulator):
|
||||
Log(LogLevel.INFOBLUE, f'\nRunning test_hostname_twice_acess_old_should_raise')
|
||||
|
||||
d = Ctb() # creates multi shm (assuming no shm exists)
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}" # hostname command creates mod shm, d maps to it
|
||||
d.hostname = f"localhost:{SERVER_START_PORTNO}" # Freeing and recreating shm while mapping d to it (old shm is out of scope)
|
||||
|
||||
# this should not throw
|
||||
exptime_val = d.exptime
|
||||
|
||||
Log(LogLevel.INFOGREEN, f"✅ Test passed, exptime was: {exptime_val}")
|
||||
assert isinstance(exptime_val, float)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -5,9 +5,14 @@ from conftest import test_with_simulators
|
||||
|
||||
from slsdet import Detector
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
@pytest.mark.parametrize("servers", [["moench"]], indirect=True)
|
||||
def test_rx_ROI_moench(test_with_simulators, servers):
|
||||
from utils_for_test import (
|
||||
Log,
|
||||
LogLevel,
|
||||
)
|
||||
|
||||
@pytest.mark.detectorintegration
|
||||
@pytest.mark.parametrize("setup_parameters", [(["moench"], 2)], indirect=True)
|
||||
def test_rx_ROI_moench(test_with_simulators, setup_parameters):
|
||||
""" Test setting and getting rx_ROI property of Detector class for moench. """
|
||||
|
||||
d = Detector()
|
||||
@@ -28,9 +33,9 @@ def test_rx_ROI_moench(test_with_simulators, servers):
|
||||
roi = d.rx_roi
|
||||
assert roi == [(-1,-1,-1,-1)]
|
||||
|
||||
@pytest.mark.withdetectorsimulators
|
||||
@pytest.mark.parametrize("servers", [["mythen3"]], indirect=True)
|
||||
def test_rx_ROI_mythen(test_with_simulators, servers):
|
||||
@pytest.mark.detectorintegration
|
||||
@pytest.mark.parametrize("setup_parameters", [(["mythen3"], 1)], indirect=True)
|
||||
def test_rx_ROI_mythen(test_with_simulators, setup_parameters):
|
||||
""" Test setting and getting rx_ROI property of Detector class for mythen. """
|
||||
|
||||
d = Detector()
|
||||
@@ -44,5 +49,3 @@ def test_rx_ROI_mythen(test_with_simulators, servers):
|
||||
|
||||
assert d.rx_roi == [(0,10,-1,-1)]
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user