feat: run tests against all beamlines
CI for mx_bec / e2e tests with pxi_bec (push) Failing after 1m30s
CI for mx_bec / e2e tests with pxii_bec (pull_request) Failing after 1m29s
CI for mx_bec / e2e tests with pxi_bec (pull_request) Failing after 1m30s
CI for mx_bec / e2e tests with pxiii_bec (push) Failing after 1m33s
CI for mx_bec / e2e tests with pxii_bec (push) Failing after 1m33s
CI for mx_bec / unit tests with pxi_bec (pull_request) Failing after 2m9s
CI for mx_bec / unit tests with pxii_bec (pull_request) Failing after 2m9s
CI for mx_bec / unit tests with pxi_bec (push) Failing after 2m13s
CI for mx_bec / unit tests with pxii_bec (push) Failing after 2m13s
CI for mx_bec / unit tests with pxiii_bec (push) Failing after 2m12s
CI for mx_bec / e2e tests with pxiii_bec (pull_request) Failing after 1m5s
CI for mx_bec / unit tests with pxiii_bec (pull_request) Failing after 1m36s

This commit is contained in:
perl_d committed 2026-11-24 14:33:36 +01:00
1 parent 7eb7854165
commit c237f0b730
9 files changed
+249 -23

No files matched your search

+62 -1
View File
@@ -24,6 +24,11 @@ on:
required: false
type: string
default: "main"
BEAMLINE_PLUGIN_BRANCH:
description: "Branch of the beamline plugins (pxi_bec, pxii_bec, pxiii_bec) to install"
required: false
type: string
default: "main"
PYTHON_VERSION:
description: "Python version to use"
required: false
@@ -36,6 +41,15 @@ permissions:
jobs:
test:
runs-on: ubuntu-latest
name: "${{ matrix.suite }} tests with ${{ matrix.plugin }}"
strategy:
fail-fast: false
matrix:
# unit: tests/unit; e2e: tests/e2e, against BEC servers running the simulated beamline
suite: [unit, e2e]
# BEC works with exactly one beamline plugin installed, which is what the device server
# loads the mx_bec devices through: run against each of them individually
plugin: [pxi_bec, pxii_bec, pxiii_bec]
env:
QTWEBENGINE_DISABLE_SANDBOX: 1
QT_QPA_PLATFORM: "offscreen"
@@ -58,6 +72,29 @@ jobs:
# Find all Copier conflicts except this line
run: '! grep -r "<<<<<<< before updating" | grep -v "grep -r \"<<<<<<< before updating"'
# Use the same-named branch of the beamline plugin if it exists (e.g. a feature developed in both repos), otherwise main.
- name: Resolve beamline plugin branch
id: plugin
shell: bash
run: |
ref="${{ inputs.BEAMLINE_PLUGIN_BRANCH || github.head_ref || github.ref_name }}"
auth="$(printf 'x-access-token:%s' '${{ github.token }}' | base64 -w0)"
if git -c "http.extraheader=Authorization: Basic ${auth}" ls-remote --exit-code --heads \
"${{ github.server_url }}/bec/${{ matrix.plugin }}.git" "refs/heads/${ref}" >/dev/null; then
echo "Using ${{ matrix.plugin }} branch '${ref}'"
else
echo "${{ matrix.plugin }} has no branch '${ref}', using main"
ref=main
fi
echo "ref=${ref}" >> "$GITHUB_OUTPUT"
- name: Checkout beamline plugin
uses: actions/checkout@v4
with:
repository: "bec/${{ matrix.plugin }}"
ref: "${{ steps.plugin.outputs.ref }}"
path: "./${{ matrix.plugin }}"
- name: Checkout BEC Core
uses: actions/checkout@v4
with:
@@ -85,6 +122,8 @@ jobs:
sudo apt-get update
sudo apt-get install -y libgl1 libegl1 x11-utils libxkbcommon-x11-0 libdbus-1-3 xvfb
sudo apt-get -y install libnss3 libxdamage1 libasound2t64 libatomic1 libxcursor1
# the end-to-end tests start their own redis server
sudo apt-get -y install redis-server
- name: Install Python dependencies
shell: bash
@@ -94,15 +133,37 @@ jobs:
uv pip install --system -e ./bec/bec_lib[dev]
uv pip install --system -e ./bec/bec_ipython_client
uv pip install --system -e ./bec/bec_server[dev]
uv pip install --system -e ./bec/pytest_bec_e2e
uv pip install --system -e ./bec_widgets[dev]
# MX-internal dependencies (aarecommon, aare_config, jfjoch_client, ...) come from gitea
uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./mx_bec[dev]
uv pip install --system --extra-index-url https://gitea.psi.ch/api/packages/mx/pypi/simple/ -e ./${{ matrix.plugin }}
- name: Run Pytest with Coverage
if: matrix.suite == 'unit'
id: coverage
run: |
if coverage run --rcfile=./mx_bec/pyproject.toml --branch --source=./mx_bec -m pytest --random-order ./mx_bec/tests/; then
if coverage run --rcfile=./mx_bec/pyproject.toml --branch --source=./mx_bec -m pytest --random-order ./mx_bec/tests/unit; then
coverage xml --rcfile=./mx_bec/pyproject.toml
else
test $? -eq 5
fi
- name: Run end-to-end tests
if: matrix.suite == 'e2e'
shell: bash
run: |
mkdir -p ./e2e_files
pytest -v --start-servers --files-path ./e2e_files ./mx_bec/tests/e2e
- name: Show server logs if the end-to-end tests fail
if: failure() && matrix.suite == 'e2e'
shell: bash
run: |
shopt -s nullglob
# the BEC services write their logs next to the bec checkout
for log in ./e2e_files/*.log ./bec/logs/*.log; do
echo "::group::${log}"
tail -n 200 "${log}"
echo "::endgroup::"
done
+29 -6
View File
@@ -1,8 +1,11 @@
from __future__ import annotations
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from bec_lib import plugin_helper
if TYPE_CHECKING:
from bec_lib.client import BECClient
@@ -11,17 +14,37 @@ MX_DEMO_CONFIG = Path(__file__).parent / "mx_demo_config.yaml"
MX_SIMULATED_DEVICES = Path(__file__).parent / "simulated_devices.yaml"
MX_SIMULATED_STATES = Path(__file__).parent / "simulated_states.yaml"
PLUGIN_PLACEHOLDER = "${BEC_PLUGIN}"
def render_config(config: Path, plugin: str | None = None) -> Path:
"""Write a copy of a device config in which `${BEC_PLUGIN}` is replaced by the package name
of the beamline plugin (by default the one which is installed), and return its path.
The device server can only load device classes from ophyd_devices or from the installed
beamline plugin, so the simulated devices of mx_bec are named in the configs as
`${BEC_PLUGIN}.devices.<class>`: the plugin has to re-export them from its `devices` module.
"""
if plugin is None:
# raises ValueError unless exactly one beamline plugin is installed
plugin = plugin_helper.plugin_package_name()
rendered = Path(tempfile.mkdtemp(prefix="mx_bec_config_")) / config.name
rendered.write_text(config.read_text().replace(PLUGIN_PLACEHOLDER, plugin))
return rendered
def _load(client: BECClient, config: Path, force: bool) -> None:
if client.config is None:
raise RuntimeError("BEC client is not started")
client.config.update_session_with_file(str(render_config(config)), force=force)
def load_mx_demo_config(client: BECClient, force: bool = False) -> None:
"""Replace the current BEC session's device config with the simulated MX beamline."""
if client.config is None:
raise RuntimeError("BEC client is not started")
client.config.update_session_with_file(str(MX_DEMO_CONFIG), force=force)
_load(client, MX_DEMO_CONFIG, force)
def load_mx_simulated_config(client: BECClient, force: bool = False) -> None:
"""Replace the current BEC session's device config with the simulated beamline for
development, which has the devices the beamline states are made of (BEAMLINE=SIMULATED)."""
if client.config is None:
raise RuntimeError("BEC client is not started")
client.config.update_session_with_file(str(MX_SIMULATED_DEVICES), force=force)
_load(client, MX_SIMULATED_DEVICES, force)
+7 -5
View File
@@ -2,8 +2,10 @@
# Simulated MX beamline for the AareBEC prototype.
#
# Every device here is a simulation: either from ophyd_devices.sim or from
# mx_bec.devices (re-exported through the pxii_bec plugin, which is what the
# device server can load). Load it into a running BEC with
# mx_bec.devices. The device server can only load the latter through the beamline
# plugin which is installed (pxi_bec, pxii_bec, pxiii_bec), which has to re-export
# them from its `devices` module: ${BEC_PLUGIN} stands for that plugin and is filled
# in when the config is loaded. Load it into a running BEC with
# from mx_bec.configs import load_mx_demo_config
# load_mx_demo_config(bec)
############################################################
@@ -30,7 +32,7 @@ eiger:
# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg).
aerotech:
readoutPriority: baseline
deviceClass: pxii_bec.devices.SimAerotechStage
deviceClass: ${BEC_PLUGIN}.devices.SimAerotechStage
deviceConfig:
deviceTags:
- sample stage
@@ -41,7 +43,7 @@ aerotech:
# Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg).
gonio:
readoutPriority: baseline
deviceClass: pxii_bec.devices.SimGoniometer
deviceClass: ${BEC_PLUGIN}.devices.SimGoniometer
deviceConfig:
deviceTags:
- sample stage
@@ -55,7 +57,7 @@ gonio:
robot:
readoutPriority: baseline
deviceClass: pxii_bec.devices.SimSampleChanger
deviceClass: ${BEC_PLUGIN}.devices.SimSampleChanger
deviceConfig:
mount_time: 2.0
deviceTags:
+7 -5
View File
@@ -5,8 +5,10 @@
# (mx_bec.device_planner) then takes the positions of the sample environment devices from the
# userParameter entries in this file, and the beamline states from simulated_states.yaml.
#
# Every device here is a simulation: either from ophyd_devices.sim or from mx_bec.devices
# (re-exported through the pxii_bec plugin, which is what the device server can load). The
# Every device here is a simulation: either from ophyd_devices.sim or from mx_bec.devices. The
# device server can only load the latter through the beamline plugin which is installed
# (pxi_bec, pxii_bec, pxiii_bec), which has to re-export them from its `devices` module:
# ${BEC_PLUGIN} stands for that plugin and is filled in when the config is loaded. The
# names and the named positions follow the PXII device config; the positions of the simulated
# stages are scaled down to fit their travel. Load it into a running BEC with
# from mx_bec.configs import load_mx_simulated_config
@@ -70,7 +72,7 @@ det_cov:
# Aerotech rotation stage: x/y/z translation (mm) under the omega rotation axis u (deg).
aerotech:
readoutPriority: baseline
deviceClass: pxii_bec.devices.SimAerotechStage
deviceClass: ${BEC_PLUGIN}.devices.SimAerotechStage
deviceConfig:
deviceTags:
- sample stage
@@ -96,7 +98,7 @@ aerotech:
# Smargon mini-kappa goniometer head on top of the aerotech: x/y/z (mm), phi/chi (deg).
smargon:
readoutPriority: baseline
deviceClass: pxii_bec.devices.SimGoniometer
deviceClass: ${BEC_PLUGIN}.devices.SimGoniometer
deviceConfig:
deviceTags:
- sample stage
@@ -122,7 +124,7 @@ smargon:
robot:
readoutPriority: baseline
deviceClass: pxii_bec.devices.SimSampleChanger
deviceClass: ${BEC_PLUGIN}.devices.SimSampleChanger
deviceConfig:
mount_time: 2.0
deviceTags:
+1
View File
@@ -41,6 +41,7 @@ dev = [
"pytest-mock",
"pytest-asyncio",
"pytest-timeout",
"pytest-bec-e2e", # fixtures which start BEC servers for the end-to-end tests
"fakeredis[lua]",
"fastapi",
"uvicorn",
+56
View File
@@ -0,0 +1,56 @@
"""Fixtures for the end-to-end tests, which run against real BEC servers with the simulated MX
beamline loaded. They build on the `pytest_bec_e2e` plugin; run them with
pytest --start-servers --files-path <dir> tests/e2e
which starts a Redis server and the BEC servers for the test session (without `--start-servers`
they have to be running already).
"""
import pytest
from bec_lib.client import BECClient
from bec_lib.redis_connector import RedisConnector
from bec_lib.service_config import ServiceConfig
from bec_lib.tests.utils import wait_for_empty_queue
from mx_bec.configs import MX_SIMULATED_DEVICES, load_mx_simulated_config, render_config
from mx_bec.device_planner import SIMULATED
CLIENT_SHUTDOWN_TIMEOUT_S = 10
@pytest.fixture(scope="session")
def test_config_yaml_file_path():
"""The device config which `bec_servers` (pytest_bec_e2e) copies next to the service config."""
return render_config(MX_SIMULATED_DEVICES)
@pytest.fixture(scope="session")
def simulated_bec_session(bec_redis_fixture, bec_services_config_file_path, bec_servers):
"""A BEC client connected to the test servers, with the simulated beamline loaded once for
the whole session."""
config = ServiceConfig(bec_services_config_file_path)
bec = BECClient(config, RedisConnector, forced=True, wait_for_server=True)
bec.start()
load_mx_simulated_config(bec, force=True)
try:
yield bec
finally:
bec.shutdown(per_thread_timeout_s=CLIENT_SHUTDOWN_TIMEOUT_S)
bec._client._reset_singleton()
@pytest.fixture
def bec(simulated_bec_session):
"""The client on the simulated beamline, with an empty, running scan queue."""
bec = simulated_bec_session
bec.queue.request_queue_reset()
bec.queue.request_scan_continuation()
wait_for_empty_queue(bec)
return bec
@pytest.fixture
def simulated_beamline(monkeypatch):
"""Select the simulated beamline for the device planner."""
monkeypatch.setenv("BEAMLINE", SIMULATED)
+74
View File
@@ -0,0 +1,74 @@
"""The simulated beamline for development (BEAMLINE=SIMULATED), on real BEC servers."""
import pytest
import yaml
from mx_bec.configs import MX_SIMULATED_DEVICES
from mx_bec.device_planner import BeamlineState, TemperatureMode, init_beamline_environment
MOVE_TIMEOUT_S = 30
def _value(device) -> float:
return next(iter(device.read(cached=False).values()))["value"]
def test_all_simulated_devices_are_loaded(bec):
config = yaml.safe_load(MX_SIMULATED_DEVICES.read_text())
assert set(config) <= set(bec.device_manager.devices.keys())
@pytest.mark.parametrize(
"name, target",
[("bl_pos", 1), ("bl_pos", 0), ("det_cov", 2), ("cryo_pos", 0), ("bl_bright", 1.3)],
)
def test_simulated_signals_can_be_moved_with_a_scan(bec, name, target):
device = bec.device_manager.devices[name]
bec.scans.mv(device, target, relative=False).wait(timeout=MOVE_TIMEOUT_S)
assert _value(device) == pytest.approx(target)
def test_simulated_signals_can_be_written_directly(bec):
"""What the device planner does for a device with `move_method: signal`."""
shutter = bec.device_manager.devices.bcu_shutter
for target in (1, 0):
shutter.put(target)
assert _value(shutter) == target
@pytest.mark.parametrize(
"path, target, tolerance",
[
("bs_z", 45.1, 0.1),
("aerotech.x", -2.0, 0.01),
("aerotech.u", 90.0, 0.01),
("smargon.z", 1.8, 0.01),
("smargon.chi", 10.0, 0.01),
],
)
def test_simulated_positioners_reach_their_target(bec, path, target, tolerance):
"""The stages have to get as close to a named position as the device planner checks it."""
device = bec.device_manager.devices
for part in path.split("."):
device = getattr(device, part)
bec.scans.mv(device, target, relative=False).wait(timeout=MOVE_TIMEOUT_S)
assert _value(device) == pytest.approx(target, abs=tolerance)
def test_device_planner_moves_between_beamline_states(bec, simulated_beamline):
env, devices, planner = init_beamline_environment(bec.device_manager.devices, bec.scans)
assert env.simulated
assert set(planner.available_states()) == set(BeamlineState)
for state, modifier in [
(BeamlineState.ROBOT_SAMPLE_EXCHANGE, TemperatureMode.CRYO),
(BeamlineState.DATA_COLLECTION, TemperatureMode.CRYO),
(BeamlineState.BEAM_VISUALISATION, None),
(BeamlineState.MANUAL_SAMPLE_EXCHANGE, TemperatureMode.ROOM_TEMP),
(BeamlineState.SAMPLE_ALIGNMENT, TemperatureMode.CRYO),
]:
planner.move_to(state, modifier)
assert planner.is_state(state), (state, planner.get_positions())
target = planner._merged_state(state, modifier)
assert all(devices[name].is_at(position) for name, position in target.items())
assert _value(bec.device_manager.devices.bcu_shutter) == 0 # closed before anything moves
+9 -2
View File
@@ -1,13 +1,20 @@
from ophyd_devices.utils.static_device_test import StaticDeviceTest
from mx_bec.configs import MX_DEMO_CONFIG
from mx_bec.configs import MX_DEMO_CONFIG, render_config
def test_all_demo_devices_construct_and_connect():
"""Instantiate every device in the demo config the way the device server would."""
results = StaticDeviceTest(config_file=str(MX_DEMO_CONFIG)).run_with_list_output(
results = StaticDeviceTest(config_file=str(render_config(MX_DEMO_CONFIG))).run_with_list_output(
connect=True, timeout_per_device=10
)
failed = {r.name: r.message for r in results if not r.success}
assert not failed, failed
assert {r.name for r in results} >= {"eiger", "aerotech", "gonio", "robot"}
def test_render_config_fills_in_the_plugin(tmp_path):
assert "${BEC_PLUGIN}" in MX_DEMO_CONFIG.read_text()
rendered = render_config(MX_DEMO_CONFIG, plugin="some_bec").read_text()
assert "${BEC_PLUGIN}" not in rendered
assert "deviceClass: some_bec.devices.SimAerotechStage" in rendered
+4 -4
View File
@@ -4,7 +4,7 @@ from unittest.mock import MagicMock
import pytest
import yaml
from mx_bec.configs import MX_SIMULATED_DEVICES, MX_SIMULATED_STATES
from mx_bec.configs import MX_SIMULATED_DEVICES, MX_SIMULATED_STATES, render_config
from mx_bec.device_planner import (
SIMULATED,
BeamlineState,
@@ -200,9 +200,9 @@ def simulated_dev():
def test_simulated_devices_are_valid_for_the_device_server():
from ophyd_devices.utils.static_device_test import StaticDeviceTest
results = StaticDeviceTest(config_file=str(MX_SIMULATED_DEVICES)).run_with_list_output(
connect=True, timeout_per_device=10
)
results = StaticDeviceTest(
config_file=str(render_config(MX_SIMULATED_DEVICES))
).run_with_list_output(connect=True, timeout_per_device=10)
failed = {r.name: r.message for r in results if not r.success}
assert not failed, failed