import subprocess from unittest.mock import MagicMock, call, patch import pytest from aarecommon.math.coordinate import Coordinate, SmargonCoordinate from aarecommon.models.auth import BatonStatus from aarecommon.models.raster_grid import CompletedRasterGrid, RasterGridRequest from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest from mx_bec.aaredaq import DEFAULT_URLS, AareDaq, AareDaqError URL, CERT, TOKEN = "https://daq.test", "/certs/daq.crt", "eyJ.abc.def" def _curl_result(stdout='{"access_token": "' + TOKEN + '"}', returncode=0, stderr=""): return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr) def _response(status_code=200, json_data=None, text=""): resp = MagicMock(status_code=status_code, ok=200 <= status_code < 300, text=text) resp.json.return_value = json_data return resp @pytest.fixture def curl(): with patch("mx_bec.aaredaq.subprocess.run", return_value=_curl_result()) as run: yield run def _status(you_are_holder: bool) -> dict: return BatonStatus(you_are_holder=you_are_holder).model_dump(mode="json") @pytest.fixture def daq(curl): """Client with a mocked HTTP session: by default this session holds the baton and every POST answers "OK".""" daq = AareDaq(MagicMock(), url=URL, cert_path=CERT) daq._session = MagicMock() responses = {"GET": _response(json_data=_status(True)), "POST": _response(json_data="OK")} daq._session.request.side_effect = lambda method, *a, **k: responses[method] daq._responses = responses return daq def _calls(daq, method): """(url, kwargs) of the recorded requests of the given method, in order.""" return [ (c.args[1], c.kwargs) for c in daq._session.request.call_args_list if c.args[0] == method ] def _set_posts(daq, *responses): """Make successive POSTs answer with the given responses (GETs keep the default).""" posts = iter(responses) daq._session.request.side_effect = lambda method, *a, **k: ( next(posts) if method == "POST" else daq._responses["GET"] ) def _raster_request(): return RasterGridRequest( n_x=2, n_y=1, grid_size_mm=Coordinate(x=0.05, y=0.05), file_prefix="t", exp_time_s=0.1, dtz=150, transmission=1, smargon_top_left=SmargonCoordinate(), omega_deg=0.0, ) def test_url_and_cert_are_resolved_from_beamline_config_on_first_use(curl, monkeypatch): monkeypatch.delenv("BEAMLINE", raising=False) daq = AareDaq(MagicMock()) # must not need the beamline environment yet with ( patch("mx_bec.aaredaq.mx_beamline", return_value="X10SA"), patch("mx_bec.aaredaq.cfg_get", side_effect=lambda key, default: default) as cfg_get, ): assert daq.url == DEFAULT_URLS["X10SA"] assert daq.cert_path == "/sls/x10sa/misc/.cert/10s.crt" assert cfg_get.call_args_list[0].args[0] == "gui.daq.daq_url" def test_token_is_requested_lazily_by_kerberos_curl(daq, curl): curl.assert_not_called() assert daq.token == TOKEN assert daq.token == TOKEN curl.assert_called_once() cmd = curl.call_args.args[0] assert cmd[0] == "curl" and "--negotiate" in cmd and cmd[-1] == f"{URL}/token" assert cmd[cmd.index("--cacert") + 1] == CERT @pytest.mark.parametrize( "result, match", [ (_curl_result(returncode=6, stderr="could not resolve"), "curl exit 6"), (_curl_result(stdout=""), "not JSON"), (_curl_result(stdout="{}"), "no access_token"), ], ) def test_token_request_failures(daq, curl, result, match): curl.return_value = result with pytest.raises(AareDaqError, match=match): _ = daq.token def test_token_request_timeout(daq, curl): curl.side_effect = subprocess.TimeoutExpired(cmd="curl", timeout=120) with pytest.raises(AareDaqError, match="token request failed"): _ = daq.token def test_mount_sample(daq): daq.mount_sample(42) assert _calls(daq, "POST") == [ ( f"{URL}/sample/mount", { "params": {"dbid": 42, "reference": False}, "json": None, "headers": {"Authorization": f"Bearer {TOKEN}"}, "verify": CERT, "timeout": 600.0, }, ) ] def test_raster_scan(daq): request = _raster_request() completed = CompletedRasterGrid(r=[]) _set_posts(daq, _response(json_data=completed.model_dump(mode="json"))) assert daq.raster_scan(request, auto_center=True) == completed [(url, kwargs)] = _calls(daq, "POST") assert url == f"{URL}/scan/raster" assert kwargs["params"] == {"auto_center": True} assert kwargs["json"] == request.model_dump(mode="json") assert kwargs["timeout"] == 3600.0 def test_rotation_scan(daq): request = RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=100) completed = CompletedRotationScan(request=request, result={"images": []}) _set_posts(daq, _response(json_data=completed.model_dump(mode="json"))) assert daq.rotation_scan(request) == completed [(url, kwargs)] = _calls(daq, "POST") assert url == f"{URL}/scan/rotation" assert kwargs["json"] == request.model_dump(mode="json") def test_expired_token_is_renewed_once(daq, curl): curl.side_effect = [_curl_result(), _curl_result('{"access_token": "new"}')] _set_posts(daq, _response(401), _response(json_data="OK")) daq.mount_sample(1) headers = [kwargs["headers"]["Authorization"] for _, kwargs in _calls(daq, "POST")] assert headers == [f"Bearer {TOKEN}", "Bearer new"] assert daq.token == "new" def test_persistent_401_is_an_error(daq): _set_posts(daq, _response(401, text="nope"), _response(401, text="nope")) with pytest.raises(AareDaqError, match="401"): daq.mount_sample(1) assert len(_calls(daq, "POST")) == 2 def test_http_error_reports_status_and_body(daq): _set_posts(daq, _response(422, text='{"detail": "bad request"}')) with pytest.raises(AareDaqError, match="422.*bad request"): daq.rotation_scan(RotationScanRequest(exp_time_s=0.05, incr_omega_deg=0.1, steps=1)) # ---- baton ---- def test_baton_status(daq): assert daq.baton_status() == BatonStatus(you_are_holder=True) [(url, kwargs)] = _calls(daq, "GET") assert url == f"{URL}/baton/status" and kwargs["timeout"] == 30.0 def test_hardware_calls_skip_the_baton_request_when_already_holder(daq): daq.mount_sample(1) assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/sample/mount"] def test_hardware_calls_take_the_baton_first(daq): daq._responses["GET"] = _response(json_data=_status(False)) _set_posts(daq, _response(json_data={"granted": True}), _response(json_data="OK")) daq.mount_sample(1) assert [url for url, _ in _calls(daq, "POST")] == [ f"{URL}/baton/request", f"{URL}/sample/mount", ] @pytest.mark.parametrize("result", [{"granted": True}, {"already_holder": True}]) def test_take_baton_immediately(daq, result): _set_posts(daq, _response(json_data=result)) daq.take_baton() assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/request"] def test_take_baton_refused_by_policy(daq): _set_posts(daq, _response(json_data={"error": True, "message": "disabled by policy"})) with pytest.raises(AareDaqError, match="disabled by policy"): daq.take_baton() def test_take_baton_waits_for_the_holder(daq): _set_posts(daq, _response(json_data={"pending": True, "message": "asked"})) checks = iter([{"pending": True, "remaining_seconds": 20}, {"granted": True}]) daq._responses["GET"] = MagicMock() daq._responses["GET"].ok, daq._responses["GET"].status_code = True, 200 daq._responses["GET"].json.side_effect = lambda: next(checks) with patch("mx_bec.aaredaq.time.sleep") as sleep: daq.take_baton(poll_interval_s=0.5) assert [url for url, _ in _calls(daq, "GET")] == [f"{URL}/baton/check_timeout"] * 2 sleep.assert_called_with(0.5) def test_take_baton_refused_by_holder(daq): _set_posts(daq, _response(json_data={"pending": True})) daq._responses["GET"] = _response(json_data={"refused": True}) with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="refused"): daq.take_baton() def test_take_baton_gives_up_after_wait(daq): _set_posts(daq, _response(json_data={"queued": True})) daq._responses["GET"] = _response(json_data={"queued": True}) with patch("mx_bec.aaredaq.time.sleep"), pytest.raises(AareDaqError, match="not granted"): daq.take_baton(wait_s=0) def test_release_baton(daq): daq.release_baton() assert [url for url, _ in _calls(daq, "POST")] == [f"{URL}/baton/release"]