Files
mx_bec/tests/unit/test_jfjoch.py
perl_dandx10sa d18c33f3b6
CI for mx_bec / e2e tests with pxi_bec (push) Failing after 1m4s
CI for mx_bec / e2e tests with pxii_bec (push) Failing after 1m17s
CI for mx_bec / e2e tests with pxiii_bec (push) Failing after 1m17s
CI for mx_bec / unit tests with pxiii_bec (push) Failing after 1m47s
CI for mx_bec / unit tests with pxii_bec (push) Failing after 1m55s
CI for mx_bec / unit tests with pxi_bec (push) Failing after 1m55s
AareBec task service (#2)
# MX task architecture: AareBec service, tasks, queues and widgets

Brings the AareBec task architecture into `mx_bec`

## Components

- **AareBec service** (`service.py`, `main.py`): custom BEC client that owns the task queue,
  the actor manager and the external API clients.
- **Task framework** (`tasks/core.py`): `@task` decorator and `TaskManager` with `Server` and
  `Client` roles. The server runs tasks one at a time and pauses the queue on failure; clients
  request tasks over Redis. `MxTaskQueue` works off the execution list.
- **MX tasks** (`tasks/mx_tasks.py`): sample mount, optical centering, raster and multi-raster
  scans, X-ray centering, rotation data collection, beamline state change and cleanup.
- **Automation actors** (`actors/`, `actor_manager.py`): actors that react to sequence
  milestones and queue the next task, each switchable through a Redis config value.
- **External clients**: `AareDaq` REST client (Kerberos token, baton handling), `JFJoch`
  raster client, `OpticalPrediction` (AareLC). The `AareDaq` client is to be replaced with native BEC
  implementations.
- **Devices** (`devices/`): Aerotech, Smargon (smargopolo), HTTP device base, simulated stages
  and sample changer, plus a demo config.
- **Widgets** (`bec_widgets/widgets/aare_bec/`): actor config, task queue, task panel, sample
  queue and sample spreadsheet display - for development and admin use.
- **Endpoints and messages** for task requests, the execution list, queue-change
  notifications and sequence state.

## Notes

- BEC-driven optical centering was removed; it will be reimplemented from scratch.
- The sample spreadsheet is copied between Redis instances by a hack in the service, to be
  replaced by the sample database connection module.
- CI installs from the MX Gitea package index (`jfjoch_client` is pre-release only).

---------

Co-authored-by: x10sa <x10sa@psi.ch>
Reviewed-on: #2
Co-authored-by: David Perl <david.perl@psi.ch>
2026-11-24 14:41:31 +01:00

153 lines
5.4 KiB
Python

from unittest.mock import MagicMock, patch
import pytest
from pydantic import ValidationError
from mx_bec.jfjoch import JFJoch, JFJochError, RasterScan
@pytest.fixture
def api():
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
yield jfjoch_client.DefaultApi.return_value
@pytest.fixture
def client():
client = MagicMock()
client.aare_config.jfjoch.n_images_per_file = 100
return client
@pytest.fixture
def jfjoch(client, api):
return JFJoch(client, url="http://jfjoch:8080")
def _scan(**overrides) -> RasterScan:
params = dict(
n_x=3,
n_y=2,
step_x_mm=0.05,
step_y_mm=0.04,
omega_deg=12.0,
exp_time_s=0.1,
detector_distance_mm=150.0,
transmission=0.5,
file_prefix="test",
energy_keV=12.658,
beam_center_pxl=(1000.0, 1100.0),
beam_size_mm=(0.02, 0.01),
ring_current_mA=400.0,
flux_ph_s=1e12,
sample_temperature_K=100.0,
smargon_phi_deg=10.0,
smargon_chi_deg=-5.0,
)
return RasterScan(**{**params, **overrides})
def test_url_is_resolved_from_beamline_config_on_first_use(client, monkeypatch):
monkeypatch.delenv("BEAMLINE", raising=False)
jfjoch = JFJoch(client) # must not need BEAMLINE yet
with (
patch("mx_bec.jfjoch.mx_beamline", return_value="X10SA") as beamline,
patch("mx_bec.jfjoch.get_jfjoch_url", return_value="http://gpu:8080") as get_url,
):
assert jfjoch.url == "http://gpu:8080"
assert jfjoch.url == "http://gpu:8080"
get_url.assert_called_once_with("X10SA")
beamline.assert_called_once()
def test_connects_lazily_and_cancels_once(jfjoch, api):
api.cancel_post.assert_not_called()
jfjoch.measure_raster(_scan())
jfjoch.measure_raster(_scan())
api.cancel_post.assert_called_once()
assert api.start_post.call_count == 2
def test_failed_cancel_on_connect_leaves_it_disconnected(jfjoch, api):
api.cancel_post.side_effect = RuntimeError("down")
with pytest.raises(JFJochError, match="cancel_post failed: down"):
jfjoch.wait_till_done(timeout_s=1)
assert jfjoch._api is None
def test_wait_till_running_reports_existing_output_file(jfjoch, api):
api.wait_until_running_post_with_http_info.side_effect = RuntimeError(
"Output file already exists"
)
with pytest.raises(JFJochError, match="output file already exists"):
jfjoch.wait_till_running(timeout_s=1.5)
api.wait_until_running_post_with_http_info.assert_called_once_with(timeout=2)
def test_wait_till_running_raises_on_error_status(jfjoch, api):
api.status_get.return_value.message_severity = "error"
api.status_get.return_value.message = "detector unhappy"
with pytest.raises(JFJochError, match="detector unhappy"):
jfjoch.wait_till_running()
def test_wait_till_done_returns_scan_result(jfjoch, api):
assert jfjoch.wait_till_done(timeout_s=10.2) is api.result_scan_get.return_value
api.wait_till_done_post_with_http_info.assert_called_once_with(timeout=11)
def test_measure_raster_builds_grid_dataset_settings(jfjoch):
# re-patch to capture the DatasetSettings constructor; connect() happens inside, so the
# API mock to check is this patch's, not the `api` fixture's
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
jfjoch.measure_raster(_scan())
settings = jfjoch_client.DatasetSettings.call_args.kwargs
assert settings["ntrigger"] == 2 and settings["images_per_trigger"] == 3
assert settings["file_prefix"] == "p16371/raw/raster/test"
assert settings["experiment_group"] == "p16371"
assert settings["sample_name"] == "unknown_sample"
assert settings["image_time_us"] == 100_000
assert settings["total_flux"] == 5e11
assert settings["beam_x_pxl"] == 1000.0 and settings["beam_y_pxl"] == 1100.0
assert settings["beam_size_x_um"] == 20.0 and settings["beam_size_y_um"] == 10.0
assert settings["images_per_file"] == 100
jfjoch_client.GridScan.assert_called_once_with(
n_fast=3, snake=True, step_x_um=50.0, step_y_um=40.0, vertical=False
)
jfjoch_client.RotationAxis.assert_called_once_with(
step=0, start=12.0, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0
)
jfjoch_client.DefaultApi.return_value.start_post.assert_called_once_with(
dataset_settings=jfjoch_client.DatasetSettings.return_value
)
def test_single_column_raster_is_one_trigger(jfjoch):
with patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client:
jfjoch.dataset_settings(_scan(n_x=1, n_y=4))
settings = jfjoch_client.DatasetSettings.call_args.kwargs
assert settings["ntrigger"] == 1 and settings["images_per_trigger"] == 4
def test_dataset_settings_clamps_negative_chi(jfjoch):
with patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon:
jfjoch.dataset_settings(_scan())
smargon.assert_called_once_with(phi_deg=10.0, chi_deg=0)
def test_dataset_settings_without_smargon_angles(jfjoch):
with (
patch("mx_bec.jfjoch.jfjoch_client") as jfjoch_client,
patch("mx_bec.jfjoch.DatasetSettingsSmargon") as smargon,
):
jfjoch.dataset_settings(_scan(smargon_phi_deg=None))
smargon.assert_not_called()
assert jfjoch_client.DatasetSettings.call_args.kwargs["smargon"] is None
def test_raster_scan_validates_fields():
with pytest.raises(ValidationError):
_scan(n_x=0)
with pytest.raises(ValidationError):
_scan(transmission=1.5)