remove unused rest methods
CI / lint (push) Skipped
CI / test (3.12) (push) Skipped
CI / test (3.13) (push) Skipped
CI / lint (push) Skipped
CI / test (3.12) (push) Skipped
CI / test (3.13) (push) Skipped
This commit is contained in:
1 parent
a24f89c885
commit
99aa2be118
12 files changed
+272
-6066
No files matched your search
@@ -1,5 +1,5 @@
|
||||
name: "Install"
|
||||
description: "Setup system and python environment and install repo"
|
||||
description: "Setup python environment and install repo"
|
||||
inputs:
|
||||
python_version:
|
||||
required: false
|
||||
@@ -17,18 +17,6 @@ inputs:
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Install Libraries
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
libgl1 \
|
||||
libegl1 \
|
||||
libxkbcommon-x11-0 \
|
||||
libdbus-1-3 \
|
||||
libxcb-cursor0 \
|
||||
libx11-xcb1
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
|
||||
+1
-43
@@ -68,53 +68,12 @@ jobs:
|
||||
|
||||
- name: Run Pytest
|
||||
env:
|
||||
QT_QPA_PLATFORM: offscreen
|
||||
BEAMLINE: SIMULATED
|
||||
run: |
|
||||
source .venv/bin/activate
|
||||
# -vv: one line per test, so a hung job shows the exact test it
|
||||
# died in, not just a file of dots. -s: no output capture — prints
|
||||
# and logs stream live instead of vanishing with a wedged worker
|
||||
# (a pxiii_bec job once sat silent at 81% for hours).
|
||||
pytest -s -vv ./tests/unit
|
||||
|
||||
test-with-beamline-plugins:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
plugin_repo: ["pxi_bec", "pxii_bec", "pxiii_bec"]
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: https://github.com/actions/checkout@v5
|
||||
|
||||
- name: Setup
|
||||
uses: ./.gitea/actions/install
|
||||
with:
|
||||
python_version: "3.12"
|
||||
index_username: ${{ secrets.GITEA_USER }}
|
||||
index_password: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: Install beamline plugin
|
||||
run: |
|
||||
source .venv/bin/activate
|
||||
git clone https://gitea.psi.ch/bec/mx_bec.git
|
||||
git clone https://gitea.psi.ch/bec/${{ matrix.plugin_repo }}.git
|
||||
uv pip install -e ./mx_bec
|
||||
uv pip install -e ./${{ matrix.plugin_repo }}
|
||||
# The bec plugin deps drag PySide6 up to >=6.10, which segfaults
|
||||
# the unit suite in teardown (see the pyproject pin). Force the
|
||||
# project's capped version back after the plugin install.
|
||||
uv pip install "pyside6<6.10"
|
||||
|
||||
- name: Run Pytest
|
||||
env:
|
||||
QT_QPA_PLATFORM: offscreen
|
||||
BEAMLINE: SIMULATED
|
||||
run: |
|
||||
source .venv/bin/activate
|
||||
# Same -s -vv rationale as the plain test job: live, per-test
|
||||
# output so a plugin-variant hang is diagnosable from the log.
|
||||
# and logs stream live instead of vanishing with a wedged worker.
|
||||
pytest -s -vv ./tests/unit
|
||||
|
||||
test-with-coverage:
|
||||
@@ -138,7 +97,6 @@ jobs:
|
||||
|
||||
- name: Run Pytest with Coverage
|
||||
env:
|
||||
QT_QPA_PLATFORM: offscreen
|
||||
BEAMLINE: SIMULATED
|
||||
run: |
|
||||
source .venv/bin/activate
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
# AareDAQ
|
||||
|
||||
AareDAQ is the Data Acquisition system for MX beamlines at PSI.
|
||||
AareDAQ is the authentication/authorization service for the MX beamline DAQ at PSI: it issues
|
||||
JWTs for Kerberos-authenticated users and answers which aareDB samples a user may work on.
|
||||
The acquisition logic itself lives in BEC.
|
||||
+1
-28
@@ -1,39 +1,18 @@
|
||||
[project]
|
||||
name = "aaredaq"
|
||||
version = "1.5.1"
|
||||
description = "AareDAQ (with GUI)"
|
||||
description = "Authentication/authorization service for the MX beamline DAQ"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"uv",
|
||||
"aarecommon>=0.9.0",
|
||||
"pydantic>=2.11",
|
||||
"numpy",
|
||||
"jfjoch_client>=1.0.0rc166",
|
||||
"pyJWT",
|
||||
"pyzmq",
|
||||
"opencv-python-headless",
|
||||
# <6.10: 6.11.2 (what the unpinned CI resolves) segfaults the unit suite
|
||||
# in teardown on ~half the runs — on plain main too, not this branch.
|
||||
# Drop the cap once the teardown crash is hunted down.
|
||||
"PySide6<6.10",
|
||||
"requests",
|
||||
"pyepics~=3.5",
|
||||
"redis",
|
||||
"fastapi",
|
||||
"uvicorn",
|
||||
"aaredb>=0.83.1",
|
||||
"python_multipart",
|
||||
"websocket-client",
|
||||
"sseclient",
|
||||
"psi-pshell==2.1.0",
|
||||
"bec_lib>=3.130.3",
|
||||
"bec-ipython-client>=3.130.3",
|
||||
"aarescan-client>=1.0.0rc15",
|
||||
"aarelcinfer-client==0.1.1a8",
|
||||
"matplotlib>=3.10.3",
|
||||
"httpx>=0.28.1",
|
||||
"aare-config>=0.1.7",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -42,10 +21,8 @@ test = [
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"pytest-mock",
|
||||
"pytest-qt",
|
||||
"pytest-asyncio",
|
||||
"pytest-timeout",
|
||||
"fakeredis[lua]",
|
||||
"diff-cover",
|
||||
"ruff>=0.15",
|
||||
]
|
||||
@@ -87,10 +64,6 @@ markers = ["integration: tests that require external systems or secrets"]
|
||||
requires = ["setuptools>=75.6.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"aare.gui.graphics" = ["*.svg", "*.png"]
|
||||
"*" = ["*.json"]
|
||||
|
||||
[tool.black]
|
||||
line-length = 100
|
||||
skip-magic-trailing-comma = true
|
||||
|
||||
+11
-398
@@ -1,41 +1,10 @@
|
||||
import datetime
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
|
||||
import aareDB
|
||||
import cv2
|
||||
import numpy as np
|
||||
import requests
|
||||
from aarecommon.config.logger import setup_logger
|
||||
from aarecommon.config.logger_events import log_timing
|
||||
from aarecommon.math.coordinate import Coordinate
|
||||
from aarecommon.math.sample_geometry import SampleGeometryModel
|
||||
from aarecommon.models.beamline import MXBeamline
|
||||
from aarecommon.models.gridscan_decision import GridScanDecision
|
||||
from aarecommon.models.models import (
|
||||
DAQStatusModel,
|
||||
PuckLoadedInfo,
|
||||
SampleShortInfo,
|
||||
ScanResultPayloadModel,
|
||||
)
|
||||
from aarecommon.models.raster_grid import CenterOfMassModel, RasterGridRequest, RasterPayloadModel
|
||||
from aarecommon.models.rotation_scan import RotationScanRequest
|
||||
from aareDB import (
|
||||
BeamlineParametersInput,
|
||||
CharacterizationParameters,
|
||||
Datasets,
|
||||
ExperimentParametersCreate,
|
||||
GridScanParameters,
|
||||
RotationParameters,
|
||||
SampleEventCreate,
|
||||
SampleEventType,
|
||||
SetTellPosition,
|
||||
SetTellPositionRequest,
|
||||
)
|
||||
from aareDB import Detector as DetectorParameters
|
||||
from jfjoch_client.models import ScanResult
|
||||
from pydantic import StrictInt
|
||||
from aareDB.models import Sample
|
||||
|
||||
logger = setup_logger("aareDAQ")
|
||||
|
||||
@@ -65,373 +34,17 @@ class AareWrapper:
|
||||
self.client.default_headers["X-Shared-Password"] = os.getenv("AAREDB_SHARED_PASSWORD")
|
||||
self._host = host
|
||||
self._tell_api = aareDB.TellsRunnerApi(self.client)
|
||||
self._sample_api = aareDB.SamplesRunnerApi(self.client)
|
||||
self._proc_api = aareDB.ProcessingsRunnerApi(self.client)
|
||||
self._raster_api = aareDB.GridscanRunnerApi(self.client)
|
||||
self._bl = bl
|
||||
|
||||
self._ssl_ca_cert = configuration.ssl_ca_cert
|
||||
self._cert_file = configuration.cert_file
|
||||
self._key_file = configuration.key_file
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def set_pucks_beamline(self, input_list: list[PuckLoadedInfo]):
|
||||
o = []
|
||||
def find_loaded_sample(self, sample_id: int) -> Sample | None:
|
||||
"""Look up a sample among the pucks currently loaded in this beamline's TELL.
|
||||
|
||||
for i in input_list:
|
||||
t = SetTellPosition(
|
||||
puck_name=i.puck_name, segment=i.location.segment, puck_in_segment=i.location.pos
|
||||
)
|
||||
o.append(t)
|
||||
payload = SetTellPositionRequest(pucks=o, tell=self._bl.value.upper())
|
||||
ret = self._tell_api.set_tell_positions(set_tell_position_request=payload)
|
||||
logger.debug(ret)
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def create_manual_sample(self, s: SampleShortInfo):
|
||||
from aareDB.models import ManualSampleCreate
|
||||
|
||||
manual_sample = ManualSampleCreate(
|
||||
pgroup=s.user, sample_name=s.sample_name, data_collection_parameters=s.aaredb_params
|
||||
)
|
||||
|
||||
try:
|
||||
s.db_id = self._sample_api.insert_sample(manual_sample).id
|
||||
except Exception:
|
||||
logger.exception("Error inserting sample")
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def send_sample_event(
|
||||
self, sample_id: StrictInt, event_type: SampleEventType, comment: str | None = None
|
||||
) -> None:
|
||||
if sample_id is None or sample_id < 0:
|
||||
if sample_id is None:
|
||||
logger.debug(f"Sample db_id is None, skipping sample event {event_type!s}")
|
||||
elif sample_id < 0:
|
||||
logger.debug(
|
||||
f"Sample db_id is invalid ({sample_id}), skipping sample event {event_type!s}"
|
||||
)
|
||||
return
|
||||
try:
|
||||
self._sample_api.create_sample_event(
|
||||
sample_id=sample_id,
|
||||
sample_event_create=SampleEventCreate(event_type=event_type, comment=comment),
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(f"Error sending sample event {event_type!s} to db")
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def upload_image(
|
||||
self, sample_id: int, filename: str, bgr_image: np.ndarray, message: str | None = None
|
||||
):
|
||||
_, buffer = cv2.imencode(".jpg", bgr_image)
|
||||
jpeg_bytes = io.BytesIO(buffer)
|
||||
url = f"{self._host}/protected_router/sample_runner/{sample_id}/upload-images"
|
||||
headers = {
|
||||
"accept": "application/json",
|
||||
"X-Shared-Password": os.getenv("AAREDB_SHARED_PASSWORD"),
|
||||
}
|
||||
|
||||
request_kwargs = {
|
||||
"files": {"uploaded_file": (filename + ".jpg", jpeg_bytes, "image/jpeg")},
|
||||
"verify": self._ssl_ca_cert,
|
||||
"cert": (self._cert_file, self._key_file),
|
||||
"headers": headers,
|
||||
}
|
||||
if message is not None:
|
||||
request_kwargs["data"] = {"comment": message}
|
||||
response = requests.post(url, **request_kwargs)
|
||||
logger.debug(f"Response status code: {response.status_code}")
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def upload_jpg(self, sample_id: int, filename: str, jpg_image, message: str | None = None):
|
||||
logger.debug(f"jppg_image of type: {type(jpg_image)}")
|
||||
url = f"{self._host}/protected_router/sample_runner/{sample_id}/upload-images"
|
||||
headers = {
|
||||
"accept": "application/json",
|
||||
"X-Shared-Password": os.getenv("AAREDB_SHARED_PASSWORD"),
|
||||
}
|
||||
request_kwargs = {
|
||||
"files": {"uploaded_file": (filename + ".jpg", jpg_image, "image/jpeg")},
|
||||
"verify": self._ssl_ca_cert,
|
||||
"cert": (self._cert_file, self._key_file),
|
||||
"headers": headers,
|
||||
}
|
||||
if message is not None:
|
||||
request_kwargs["data"] = {"comment": message}
|
||||
response = requests.post(url, **request_kwargs)
|
||||
logger.debug(f"Response status code: {response.status_code}")
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def create_rotation_run(
|
||||
self, s: SampleShortInfo | None, r: RotationScanRequest, d: DAQStatusModel
|
||||
):
|
||||
if s is None:
|
||||
return
|
||||
|
||||
try:
|
||||
if r.screening:
|
||||
characterization = CharacterizationParameters(
|
||||
omegaStart_deg=round(r.start_omega_deg, 3),
|
||||
omegaStep=r.incr_omega_deg,
|
||||
phi=round(d.geom.smargon.phi_deg, 3),
|
||||
chi=round(d.geom.smargon.chi_deg, 3),
|
||||
numberOfImages=r.steps,
|
||||
exposureTime_s=r.exp_time_s,
|
||||
oscillation_deg=r.wedge_omega_deg,
|
||||
)
|
||||
rotation = None
|
||||
else:
|
||||
rotation = RotationParameters(
|
||||
omegaStart_deg=round(r.start_omega_deg, 3),
|
||||
omegaStep=r.incr_omega_deg,
|
||||
phi=round(d.geom.smargon.phi_deg, 3),
|
||||
chi=round(d.geom.smargon.chi_deg, 3),
|
||||
numberOfImages=r.steps,
|
||||
exposureTime_s=r.exp_time_s,
|
||||
)
|
||||
characterization = None
|
||||
dataset = Datasets(
|
||||
filepath=r.file_prefix, status="written", written_at=datetime.datetime.now()
|
||||
)
|
||||
detector_data = DetectorParameters(
|
||||
manufacturer="DECTRIS",
|
||||
model=d.diffraction.detector_description,
|
||||
type="photon-counting",
|
||||
serialNumber=d.diffraction.detector_serial_number,
|
||||
detectorDistance_mm=r.dtz,
|
||||
resolution_at_edge_Ang=d.diffraction.max_resolution_angstrom,
|
||||
beamCenterX_px=d.diffraction.beam_center_pxl[0],
|
||||
beamCenterY_px=d.diffraction.beam_center_pxl[1],
|
||||
pixelSizeX_um=d.diffraction.pixel_size_mm * 1000,
|
||||
pixelSizeY_um=d.diffraction.pixel_size_mm * 1000,
|
||||
dataset=dataset,
|
||||
)
|
||||
beamline_params = BeamlineParametersInput(
|
||||
synchrotron="Swiss Light Source",
|
||||
beamline=d.bl.name,
|
||||
detector=detector_data,
|
||||
energy_keV=d.diffraction.energy_keV,
|
||||
wavelength_Ang=d.diffraction.wavelength_angstrom,
|
||||
ringCurrent_mA=d.bl.ring_current_mA,
|
||||
ringMode="Beamline Development",
|
||||
monochromator="Si111",
|
||||
transmission=d.bl.transmission,
|
||||
focusingOptic="Kirkpatrick-Baez",
|
||||
beamlineFluxAtSample_ph_s=d.bl.flux_ph_s,
|
||||
beamSizeWidth=d.geom.beam_size_mm.x * 1000,
|
||||
beamSizeHeight=d.geom.beam_size_mm.y * 1000,
|
||||
cryojetTemperature_K=d.bl.cryojet_K,
|
||||
rotation=rotation,
|
||||
characterization=characterization,
|
||||
)
|
||||
experiment_params_payload = ExperimentParametersCreate(
|
||||
type="standard", beamline_parameters=beamline_params, sample_id=s.db_id
|
||||
)
|
||||
self._sample_api.create_experiment_parameters_for_sample(
|
||||
sample_id=s.db_id, experiment_parameters_create=experiment_params_payload
|
||||
)
|
||||
# logger.debug("Experiment parameters created:", response)
|
||||
except Exception:
|
||||
logger.exception("Error creating experiment parameters for rotation run")
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def create_gridscan_run(
|
||||
self, s: SampleShortInfo | None, r: RasterGridRequest, d: DAQStatusModel
|
||||
):
|
||||
if s is None:
|
||||
return
|
||||
|
||||
try:
|
||||
gridscan = GridScanParameters(
|
||||
# xStart=90.0,
|
||||
xStep=r.grid_size_mm.x,
|
||||
# yStart=0.0,
|
||||
yStep=r.grid_size_mm.y,
|
||||
x_col=r.n_x,
|
||||
y_row=r.n_y,
|
||||
omegaStart_deg=round(r.omega_deg, 2),
|
||||
numberOfImages=round(r.n_x * r.n_y, 0),
|
||||
exposureTime_s=round(r.exp_time_s, 4),
|
||||
)
|
||||
dataset = Datasets(
|
||||
filepath=r.file_prefix, status="written", written_at=datetime.datetime.now()
|
||||
)
|
||||
detector_data = DetectorParameters(
|
||||
manufacturer="DECTRIS",
|
||||
model=d.diffraction.detector_description,
|
||||
type="photon-counting",
|
||||
serialNumber=d.diffraction.detector_serial_number,
|
||||
detectorDistance_mm=round(r.dtz, 3),
|
||||
resolution_at_edge_Ang=round(d.diffraction.max_resolution_angstrom, 3),
|
||||
beamCenterX_px=round(d.diffraction.beam_center_pxl[0], 2),
|
||||
beamCenterY_px=round(d.diffraction.beam_center_pxl[1], 2),
|
||||
pixelSizeX_um=round(d.diffraction.pixel_size_mm * 1000, 2),
|
||||
pixelSizeY_um=round(d.diffraction.pixel_size_mm * 1000, 2),
|
||||
dataset=dataset,
|
||||
)
|
||||
beamline_params = BeamlineParametersInput(
|
||||
synchrotron="Swiss Light Source",
|
||||
beamline=d.bl.name,
|
||||
detector=detector_data,
|
||||
energy_keV=d.diffraction.energy_keV,
|
||||
wavelength_Ang=d.diffraction.wavelength_angstrom,
|
||||
ringCurrent_mA=round(d.bl.ring_current_mA, 3),
|
||||
ringMode="Beamline Development",
|
||||
monochromator="Si111",
|
||||
transmission=d.bl.transmission,
|
||||
focusingOptic="Kirkpatrick-Baez",
|
||||
beamlineFluxAtSample_ph_s=d.bl.flux_ph_s,
|
||||
beamSizeWidth=d.geom.beam_size_mm.x * 1000,
|
||||
beamSizeHeight=d.geom.beam_size_mm.y * 1000,
|
||||
cryojetTemperature_K=d.bl.cryojet_K,
|
||||
gridScan=gridscan,
|
||||
)
|
||||
experiment_params_payload = ExperimentParametersCreate(
|
||||
type="standard", beamline_parameters=beamline_params, sample_id=s.db_id
|
||||
)
|
||||
self._sample_api.create_experiment_parameters_for_sample(
|
||||
sample_id=s.db_id, experiment_parameters_create=experiment_params_payload
|
||||
)
|
||||
# logger.info("Experiment parameters created:", response)
|
||||
except Exception as e:
|
||||
logger.debug(e, exc_info=True)
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def ingest_gridscan(
|
||||
self,
|
||||
sample: SampleShortInfo | None,
|
||||
raster_result: ScanResult,
|
||||
raster_request: RasterGridRequest,
|
||||
analysis_image_scores: list[float | None] | None,
|
||||
geom: SampleGeometryModel,
|
||||
com: CenterOfMassModel,
|
||||
beam_mark_pxl: tuple[float, float],
|
||||
decision: GridScanDecision | None,
|
||||
):
|
||||
|
||||
if sample is None:
|
||||
logger.error("No sample for DB gridscan ingestion request!")
|
||||
return
|
||||
|
||||
payload = self.format_gridscan_payload(
|
||||
sample,
|
||||
raster_result,
|
||||
raster_request,
|
||||
geom,
|
||||
com,
|
||||
analysis_image_scores,
|
||||
beam_mark_pxl,
|
||||
decision,
|
||||
).model_dump_json()
|
||||
|
||||
url = f"{self._host}/protected_router/gridscan_runner/ingest"
|
||||
headers = {
|
||||
"accept": "application/json",
|
||||
"X-Shared-Password": os.getenv("AAREDB_SHARED_PASSWORD"),
|
||||
}
|
||||
response = requests.post(
|
||||
url,
|
||||
auth=(os.getenv("AAREDB_USERNAME"), os.getenv("AAREDB_PASSWORD")),
|
||||
headers=headers,
|
||||
data=payload,
|
||||
timeout=30,
|
||||
verify=self._ssl_ca_cert,
|
||||
cert=(self._cert_file, self._key_file),
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.info(f"AareDB gridscan ingestion response status code: {response.status_code}")
|
||||
|
||||
def format_gridscan_payload(
|
||||
self,
|
||||
sample: SampleShortInfo | None,
|
||||
raster_result: ScanResult,
|
||||
raster_request: RasterGridRequest,
|
||||
geom: SampleGeometryModel,
|
||||
com: CenterOfMassModel | None,
|
||||
analysis_image_scores: list[float | None] | None,
|
||||
beam_mark_pxl: tuple[float, float],
|
||||
decision: GridScanDecision | None,
|
||||
) -> RasterPayloadModel:
|
||||
cell_size_pxl = Coordinate(
|
||||
x=raster_request.grid_size_mm.x / geom.pixel_in_mm,
|
||||
y=raster_request.grid_size_mm.y / geom.pixel_in_mm,
|
||||
)
|
||||
|
||||
if raster_request.smargon_top_left is None:
|
||||
beam_loc = geom.smargon.sh_mm
|
||||
else:
|
||||
beam_loc = raster_request.smargon_top_left.sh_mm
|
||||
|
||||
start_pxl = geom.smargon_to_picture(beam_loc)
|
||||
if com:
|
||||
com_grid_pxl = com.get_com_pxl(raster_request, geom)
|
||||
center_pxl = Coordinate(x=start_pxl.x + com_grid_pxl.x, y=start_pxl.y + com_grid_pxl.y)
|
||||
else:
|
||||
com_grid_pxl, center_pxl = None, None
|
||||
return RasterPayloadModel(
|
||||
request=raster_request,
|
||||
result=raster_result,
|
||||
sample_id=sample.db_id,
|
||||
attach_image=True,
|
||||
centre_of_mass=com,
|
||||
raster_score=analysis_image_scores,
|
||||
start_pxl=start_pxl,
|
||||
center_pxl=center_pxl,
|
||||
cell_size_pxl=cell_size_pxl,
|
||||
beam_mark_pxl=beam_mark_pxl,
|
||||
beam_size_mm=geom.beam_size_mm,
|
||||
decision=decision,
|
||||
)
|
||||
|
||||
@log_timing(logger, "AareDB call")
|
||||
def ingest_scan(
|
||||
self,
|
||||
sample: SampleShortInfo | None,
|
||||
result: ScanResult,
|
||||
geom: SampleGeometryModel,
|
||||
beam_mark_pxl: tuple[float, float],
|
||||
):
|
||||
|
||||
if sample is None:
|
||||
return
|
||||
|
||||
payload_model = self.format_scan_payload(sample, result, geom, beam_mark_pxl)
|
||||
if payload_model is None:
|
||||
return
|
||||
payload = payload_model.model_dump()
|
||||
|
||||
url = f"{self._host}/protected_router/scan_runner/ingest"
|
||||
headers = {
|
||||
"accept": "application/json",
|
||||
"X-Shared-Password": os.getenv("AAREDB_SHARED_PASSWORD"),
|
||||
}
|
||||
response = requests.post(
|
||||
url,
|
||||
auth=(os.getenv("AAREDB_USERNAME"), os.getenv("AAREDB_PASSWORD")),
|
||||
headers=headers,
|
||||
data=json.dumps(payload),
|
||||
timeout=30,
|
||||
verify=self._ssl_ca_cert,
|
||||
cert=(self._cert_file, self._key_file),
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
logger.info(f"Response status code: {response.status_code}")
|
||||
|
||||
def format_scan_payload(
|
||||
self,
|
||||
sample: SampleShortInfo | None,
|
||||
result: ScanResult,
|
||||
geom: SampleGeometryModel,
|
||||
beam_mark_pxl: tuple[float, float],
|
||||
) -> ScanResultPayloadModel | None:
|
||||
payload = ScanResultPayloadModel(
|
||||
result=result,
|
||||
sample_id=sample.db_id,
|
||||
attach_image=True,
|
||||
beam_mark_pxl=beam_mark_pxl,
|
||||
beam_size_mm=geom.beam_size_mm,
|
||||
)
|
||||
|
||||
return payload
|
||||
Returns None when no loaded puck holds a sample with that database id.
|
||||
"""
|
||||
pucks = self._tell_api.get_pucks_with_tell_position(tell=self._bl.value.upper())
|
||||
for puck in pucks:
|
||||
for sample in puck.samples or []:
|
||||
if sample.id == sample_id:
|
||||
return sample
|
||||
return None
|
||||
+48
-347
@@ -4,8 +4,7 @@ import grp
|
||||
import logging
|
||||
import os
|
||||
import pwd
|
||||
import time
|
||||
import uuid
|
||||
import secrets
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
@@ -14,22 +13,15 @@ from aarecommon.errors.exception_handler import (
|
||||
AuthErrorCode,
|
||||
UserRightsException,
|
||||
)
|
||||
from aarecommon.models.auth import BatonRequest, BatonRequestStatus, BatonStatus, BatonTransferQueue
|
||||
from aarecommon.models.models import SessionsStateEnum
|
||||
from fastapi import Depends, Request
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from pydantic import BaseModel
|
||||
|
||||
from aare.beamline_dispatch.protocols import AuthDispatch
|
||||
from aare.daq.config import BeamlineConfig
|
||||
|
||||
logger = logging.getLogger("aareDAQ")
|
||||
|
||||
_SECRET_KEY: str | None = None
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 24 * 60 * 7 # 1 week
|
||||
SESSION_EXPIRE_SECONDS = 60 * 10
|
||||
BATON_REQUEST_TIMEOUT_SECONDS = 30
|
||||
|
||||
STAFF_GROUP = "unx-sls_mx_bs" # unx-mxgroup no longer exists
|
||||
SUPER_USERS = ["e10019", "e11206", "e18747"]
|
||||
@@ -44,9 +36,22 @@ class TokenData(BaseModel):
|
||||
staff: bool = False
|
||||
|
||||
|
||||
def init_jwt_key(dispatch: AuthDispatch):
|
||||
class SampleAccess(BaseModel):
|
||||
"""Result of asking whether a user may work on a given aareDB sample."""
|
||||
|
||||
sample_id: int
|
||||
allowed: bool
|
||||
pgroup: str | None = None
|
||||
reason: str
|
||||
|
||||
|
||||
def init_jwt_key() -> None:
|
||||
global _SECRET_KEY
|
||||
_SECRET_KEY = dispatch.get_jwt_key()
|
||||
if (key := os.environ.get("JWT_AAREDAQ_KEY")) is None:
|
||||
raise RuntimeError(
|
||||
"JWT_AAREDAQ_KEY environment variable not set, cannot guarantee safe authentication."
|
||||
)
|
||||
_SECRET_KEY = key
|
||||
|
||||
|
||||
def jwt_key() -> str:
|
||||
@@ -84,7 +89,16 @@ def authenticate_from_proxy_header(request: Request) -> str:
|
||||
return remote_user
|
||||
|
||||
|
||||
def authenticate_user(cfg: BeamlineConfig, username: str) -> str:
|
||||
def generate_session() -> int:
|
||||
"""Identifier distinguishing one issued token (i.e. one client instance) from another.
|
||||
|
||||
Was a Redis counter when this service owned the baton; now that baton handling lives
|
||||
in BEC a random value is enough, consumers only need it to be unique per token.
|
||||
"""
|
||||
return secrets.randbits(31)
|
||||
|
||||
|
||||
def authenticate_user(username: str) -> str:
|
||||
user_info = pwd.getpwnam(username)
|
||||
|
||||
groups = os.getgrouplist(user_info.pw_name, user_info.pw_gid)
|
||||
@@ -94,7 +108,7 @@ def authenticate_user(cfg: BeamlineConfig, username: str) -> str:
|
||||
staff = (
|
||||
"unx-mxgroup" in supplementary_groups or "unx-sls_mx" in supplementary_groups or super_user
|
||||
)
|
||||
token = TokenData(sub=username, pgroups=pgroups, staff=staff, session=cfg.generate_session())
|
||||
token = TokenData(sub=username, pgroups=pgroups, staff=staff, session=generate_session())
|
||||
return create_access_token(token)
|
||||
|
||||
|
||||
@@ -112,35 +126,6 @@ def parse_token(token: str = Depends(oauth2_scheme)) -> TokenData:
|
||||
) from e
|
||||
|
||||
|
||||
def check_jwt_ro(cfg: BeamlineConfig, data: TokenData) -> None:
|
||||
active_pgroup = cfg.pgroup
|
||||
if not data.staff and (active_pgroup is None or active_pgroup not in data.pgroups):
|
||||
raise UserRightsException(
|
||||
message="Not member of a currently active p-group.",
|
||||
status_code=403,
|
||||
code=AuthErrorCode.NOT_IN_ACTIVE_PGROUP,
|
||||
)
|
||||
|
||||
|
||||
def check_jwt_rw(cfg: BeamlineConfig, data: TokenData) -> None:
|
||||
check_jwt_ro(cfg, data)
|
||||
|
||||
holder = cfg.baton_holder
|
||||
if holder is None or holder.session != data.session:
|
||||
raise UserRightsException(
|
||||
message="You do not hold the baton.",
|
||||
status_code=403,
|
||||
code=AuthErrorCode.NOT_BATON_HOLDER,
|
||||
)
|
||||
|
||||
try:
|
||||
cfg.try_extend_active_session(data.session, SESSION_EXPIRE_SECONDS)
|
||||
except Exception:
|
||||
# In case something is wrong but you are holder (maybe redis expiry?)
|
||||
logger.debug("Could not extend the active session; claiming it instead", exc_info=True)
|
||||
cfg.try_set_active_session(data.session, SESSION_EXPIRE_SECONDS)
|
||||
|
||||
|
||||
def check_jwt_staff_only(data: TokenData) -> None:
|
||||
if not data.staff:
|
||||
raise UserRightsException(
|
||||
@@ -148,314 +133,30 @@ def check_jwt_staff_only(data: TokenData) -> None:
|
||||
)
|
||||
|
||||
|
||||
def check_jwt_staff(cfg: BeamlineConfig, data: TokenData) -> None:
|
||||
check_jwt_staff_only(data)
|
||||
def check_sample_access(data: TokenData, sample_id: int, sample_pgroup: str | None) -> SampleAccess:
|
||||
"""Decide whether the token's user may work on a sample owned by ``sample_pgroup``.
|
||||
|
||||
holder = cfg.baton_holder
|
||||
if holder and holder.session != data.session:
|
||||
# Staff can take over if they don't have it, but they need to use force_current_session
|
||||
# or request_baton (which does staff override).
|
||||
# If they are calling a RW endpoint, they SHOULD already be the holder.
|
||||
pass
|
||||
|
||||
try:
|
||||
cfg.try_extend_active_session(data.session, SESSION_EXPIRE_SECONDS)
|
||||
except Exception:
|
||||
logger.debug("Could not extend the active session; claiming it instead", exc_info=True)
|
||||
cfg.try_set_active_session(data.session, SESSION_EXPIRE_SECONDS)
|
||||
|
||||
|
||||
def force_current_sesion(cfg: BeamlineConfig, data: TokenData) -> None:
|
||||
cfg.execute_baton_transfer(
|
||||
to_session=data.session,
|
||||
to_username=data.sub,
|
||||
to_is_staff=data.staff,
|
||||
to_pgroup=cfg.pgroup,
|
||||
expiry_sec=SESSION_EXPIRE_SECONDS,
|
||||
)
|
||||
|
||||
|
||||
def _finalize_expired_baton_request(cfg: BeamlineConfig, pending: BatonRequest) -> BatonStatus:
|
||||
Staff may access anything; everyone else only samples belonging to one of their
|
||||
p-groups. ``sample_pgroup`` is None when the sample is not known at this beamline.
|
||||
"""
|
||||
Resolve an expired baton request in one place.
|
||||
|
||||
Rules:
|
||||
- staff can override immediately if beamline is free
|
||||
- otherwise the transfer is queued
|
||||
- pending request is cleared once it is no longer pending
|
||||
"""
|
||||
requester_is_staff = bool(pending.requester_is_staff)
|
||||
|
||||
if cfg.can_transfer_baton_now():
|
||||
cfg.execute_baton_transfer(
|
||||
to_session=pending.requester_session,
|
||||
to_username=pending.requester_username,
|
||||
to_is_staff=requester_is_staff,
|
||||
to_pgroup=cfg.pgroup,
|
||||
expiry_sec=SESSION_EXPIRE_SECONDS,
|
||||
if sample_pgroup is None:
|
||||
return SampleAccess(
|
||||
sample_id=sample_id, allowed=False, reason="Sample is not loaded at this beamline."
|
||||
)
|
||||
else:
|
||||
cfg.queued_baton_transfer = BatonTransferQueue(
|
||||
target_session=pending.requester_session,
|
||||
target_username=pending.requester_username,
|
||||
target_is_staff=requester_is_staff,
|
||||
target_pgroup=cfg.pgroup,
|
||||
queued_at=time.time(),
|
||||
reason="timeout_beamline_busy",
|
||||
)
|
||||
|
||||
cfg.clear_pending_baton_request()
|
||||
return get_baton_status(
|
||||
cfg,
|
||||
TokenData(
|
||||
sub=pending.requester_username,
|
||||
pgroups=[],
|
||||
session=pending.requester_session,
|
||||
staff=requester_is_staff,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def resolve_baton_timeout_if_needed(cfg: BeamlineConfig) -> BatonStatus | None:
|
||||
"""
|
||||
Check the current pending request and resolve it if expired.
|
||||
Returns the updated BatonStatus when a timeout was processed, else None.
|
||||
"""
|
||||
pending = cfg.pending_baton_request
|
||||
if pending is None or pending.status != BatonRequestStatus.PENDING:
|
||||
return None
|
||||
|
||||
elapsed = time.time() - pending.created_at
|
||||
if elapsed < pending.timeout_seconds:
|
||||
return None
|
||||
|
||||
return _finalize_expired_baton_request(cfg, pending)
|
||||
|
||||
|
||||
def get_baton_status(cfg: BeamlineConfig, data: TokenData) -> BatonStatus:
|
||||
"""
|
||||
Build baton status scoped to the requesting session.
|
||||
|
||||
Important:
|
||||
- requester sees you_have_pending_request
|
||||
- holder sees incoming_request
|
||||
- nobody else sees the request as actionable
|
||||
"""
|
||||
holder = cfg.baton_holder
|
||||
pending = cfg.pending_baton_request
|
||||
|
||||
is_requester = bool(
|
||||
pending
|
||||
and pending.status in (BatonRequestStatus.PENDING, BatonRequestStatus.REFUSED)
|
||||
and pending.requester_session == data.session
|
||||
)
|
||||
|
||||
is_holder = bool(
|
||||
pending
|
||||
and pending.status == BatonRequestStatus.PENDING
|
||||
and pending.holder_session == data.session
|
||||
)
|
||||
|
||||
# Only expose the pending request object to the two relevant sessions
|
||||
scoped_pending = pending if (is_requester or is_holder) else None
|
||||
|
||||
return BatonStatus(
|
||||
holder=holder,
|
||||
pending_request=scoped_pending,
|
||||
queued_transfer=cfg.queued_baton_transfer,
|
||||
you_are_holder=bool(holder and holder.session == data.session),
|
||||
you_have_pending_request=is_requester,
|
||||
incoming_request=is_holder,
|
||||
allow_non_staff_request=cfg.allow_non_staff_request_from_staff,
|
||||
)
|
||||
|
||||
|
||||
def request_baton(cfg: BeamlineConfig, data: TokenData) -> dict:
|
||||
resolve_baton_timeout_if_needed(cfg)
|
||||
|
||||
session_state = cfg.session_state(data.session)
|
||||
|
||||
if session_state == SessionsStateEnum.Vacant:
|
||||
# State: VACANT -> OWNED (B)
|
||||
cfg.execute_baton_transfer(
|
||||
to_session=data.session,
|
||||
to_username=data.sub,
|
||||
to_is_staff=data.staff,
|
||||
to_pgroup=cfg.pgroup,
|
||||
expiry_sec=SESSION_EXPIRE_SECONDS,
|
||||
)
|
||||
return {"granted": True, "message": "Baton acquired (beamline was vacant)"}
|
||||
|
||||
if session_state == SessionsStateEnum.OwnedByYou:
|
||||
cfg.try_extend_active_session(data.session, SESSION_EXPIRE_SECONDS)
|
||||
return {"already_holder": True, "message": "You already hold the baton"}
|
||||
|
||||
if session_state == SessionsStateEnum.PendingYouToElse:
|
||||
# Already requested, waiting for holder response or timeout
|
||||
existing_request = cfg.pending_baton_request
|
||||
if existing_request:
|
||||
elapsed = time.time() - existing_request.created_at
|
||||
remaining = existing_request.timeout_seconds - elapsed
|
||||
return {
|
||||
"pending": True,
|
||||
"existing": True,
|
||||
"remaining_seconds": max(0, remaining),
|
||||
"message": f"Request already pending ({remaining:.0f}s remaining)",
|
||||
}
|
||||
|
||||
holder = cfg.baton_holder
|
||||
# Handle Staff override
|
||||
if data.staff:
|
||||
if not cfg.can_transfer_baton_now():
|
||||
# State: OWNED (A) -> PENDING (A -> B, B=staff) -> Queue -> OWNED (B)
|
||||
cfg.queued_baton_transfer = BatonTransferQueue(
|
||||
target_session=data.session,
|
||||
target_username=data.sub,
|
||||
target_is_staff=data.staff,
|
||||
target_pgroup=cfg.pgroup,
|
||||
queued_at=time.time(),
|
||||
reason="beamline_busy_staff_override",
|
||||
)
|
||||
return {
|
||||
"queued": True,
|
||||
"message": "Staff override queued - will transfer when beamline is available",
|
||||
}
|
||||
|
||||
# State: OWNED (A) -> OWNED (B, B=staff)
|
||||
cfg.execute_baton_transfer(
|
||||
to_session=data.session,
|
||||
to_username=data.sub,
|
||||
to_is_staff=data.staff,
|
||||
to_pgroup=cfg.pgroup,
|
||||
expiry_sec=SESSION_EXPIRE_SECONDS,
|
||||
return SampleAccess(
|
||||
sample_id=sample_id, allowed=True, pgroup=sample_pgroup, reason="Staff."
|
||||
)
|
||||
return {"granted": True, "override": True, "message": "Staff override - baton acquired"}
|
||||
|
||||
# Policy check: non-staff requesting from staff
|
||||
if holder and holder.is_staff and not data.staff and not cfg.allow_non_staff_request_from_staff:
|
||||
return {
|
||||
"error": True,
|
||||
"message": "Requesting baton from staff is disabled by backend policy.",
|
||||
}
|
||||
|
||||
# State: OWNED (A) -> PENDING (A -> B)
|
||||
existing_request = cfg.pending_baton_request
|
||||
if existing_request and existing_request.status == BatonRequestStatus.PENDING:
|
||||
# Someone else already has a request pending
|
||||
return {
|
||||
"error": True,
|
||||
"message": f"Another user ({existing_request.requester_username}) already has a pending request",
|
||||
}
|
||||
|
||||
# Beamline busy notification
|
||||
is_busy = not cfg.can_transfer_baton_now()
|
||||
|
||||
request = BatonRequest(
|
||||
request_id=str(uuid.uuid4()),
|
||||
requester_username=data.sub,
|
||||
requester_session=data.session,
|
||||
requester_is_staff=data.staff,
|
||||
holder_username=holder.username if holder else None,
|
||||
holder_session=holder.session if holder else None,
|
||||
created_at=time.time(),
|
||||
timeout_seconds=BATON_REQUEST_TIMEOUT_SECONDS,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
if sample_pgroup in data.pgroups:
|
||||
return SampleAccess(
|
||||
sample_id=sample_id,
|
||||
allowed=True,
|
||||
pgroup=sample_pgroup,
|
||||
reason=f"Member of p-group {sample_pgroup}.",
|
||||
)
|
||||
return SampleAccess(
|
||||
sample_id=sample_id,
|
||||
allowed=False,
|
||||
pgroup=sample_pgroup,
|
||||
reason=f"Not a member of p-group {sample_pgroup}.",
|
||||
)
|
||||
cfg.set_pending_baton_request(request, timeout_sec=BATON_REQUEST_TIMEOUT_SECONDS)
|
||||
|
||||
msg = f"Request sent to {holder.username if holder else 'current holder'}"
|
||||
if is_busy:
|
||||
msg += " (Note: beamline is currently busy, transfer will be queued if accepted)"
|
||||
|
||||
return {
|
||||
"pending": True,
|
||||
"request_id": request.request_id,
|
||||
"timeout_seconds": BATON_REQUEST_TIMEOUT_SECONDS,
|
||||
"message": msg,
|
||||
"beamline_busy": is_busy,
|
||||
}
|
||||
|
||||
|
||||
def respond_to_baton_request(cfg: BeamlineConfig, data: TokenData, accept: bool) -> dict:
|
||||
"""
|
||||
Current baton holder responds to a pending request.
|
||||
"""
|
||||
resolve_baton_timeout_if_needed(cfg)
|
||||
|
||||
holder = cfg.baton_holder
|
||||
if holder is None or holder.session != data.session:
|
||||
return {"error": True, "message": "You are not the current baton holder"}
|
||||
|
||||
pending = cfg.pending_baton_request
|
||||
if pending is None or pending.status != BatonRequestStatus.PENDING:
|
||||
return {"error": True, "message": "No pending request to respond to"}
|
||||
|
||||
if accept:
|
||||
# State: PENDING (A -> B) -> OWNED (B)
|
||||
if cfg.can_transfer_baton_now():
|
||||
cfg.execute_baton_transfer(
|
||||
to_session=pending.requester_session,
|
||||
to_username=pending.requester_username,
|
||||
to_is_staff=pending.requester_is_staff,
|
||||
to_pgroup=cfg.pgroup,
|
||||
expiry_sec=SESSION_EXPIRE_SECONDS,
|
||||
)
|
||||
return {"accepted": True, "transferred": True, "message": "Baton transferred"}
|
||||
else:
|
||||
# Beamline busy, queue the transfer
|
||||
cfg.queued_baton_transfer = BatonTransferQueue(
|
||||
target_session=pending.requester_session,
|
||||
target_username=pending.requester_username,
|
||||
target_is_staff=pending.requester_is_staff,
|
||||
target_pgroup=cfg.pgroup,
|
||||
queued_at=time.time(),
|
||||
reason="accepted_beamline_busy",
|
||||
)
|
||||
cfg.clear_pending_baton_request()
|
||||
return {
|
||||
"accepted": True,
|
||||
"queued": True,
|
||||
"message": "Request accepted. Baton will be transferred as soon as beamline is available.",
|
||||
}
|
||||
else:
|
||||
# State: PENDING (A -> B) -> OWNED (A)
|
||||
pending.status = BatonRequestStatus.REFUSED
|
||||
cfg.set_pending_baton_request(pending, timeout_sec=10)
|
||||
return {"refused": True, "message": "Baton request refused"}
|
||||
|
||||
|
||||
def release_baton(cfg: BeamlineConfig, data: TokenData) -> dict:
|
||||
"""
|
||||
Voluntarily release the baton (set session to free).
|
||||
"""
|
||||
resolve_baton_timeout_if_needed(cfg)
|
||||
|
||||
holder = cfg.baton_holder
|
||||
if holder is None:
|
||||
return {"released": True, "message": "Baton was already vacant"}
|
||||
|
||||
if holder.session != data.session:
|
||||
return {"info": True, "message": "You don't hold the baton"}
|
||||
|
||||
cfg.end_active_session(data.session)
|
||||
cfg.baton_holder = None
|
||||
cfg.clear_pending_baton_request()
|
||||
|
||||
return {"released": True, "message": "Baton released - beamline is now vacant"}
|
||||
|
||||
|
||||
def cancel_baton_request(cfg: BeamlineConfig, data: TokenData) -> dict:
|
||||
"""
|
||||
Cancel your own pending baton request.
|
||||
"""
|
||||
resolve_baton_timeout_if_needed(cfg)
|
||||
|
||||
pending = cfg.pending_baton_request
|
||||
if pending is None:
|
||||
return {"error": True, "message": "No pending request to cancel"}
|
||||
|
||||
if pending.requester_session != data.session:
|
||||
return {"error": True, "message": "You can only cancel your own request"}
|
||||
|
||||
cfg.clear_pending_baton_request()
|
||||
return {"cancelled": True, "message": "Request cancelled"}
|
||||
+28
-2545
File diff suppressed because it is too large.
Load diff
+7
-147
@@ -1,17 +1,11 @@
|
||||
import os
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from aarecommon.models.models import DewarAddress, SampleShortInfo
|
||||
from fastapi.testclient import TestClient
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
# Ensure safe defaults during tests
|
||||
os.environ.setdefault("BEAMLINE", "SIMULATED")
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
os.environ.setdefault("JWT_AAREDAQ_KEY", "test_key_for_unit_testing")
|
||||
|
||||
|
||||
@@ -21,32 +15,7 @@ def mock_logger():
|
||||
|
||||
|
||||
# -------------------------
|
||||
# Qt app fixture
|
||||
# -------------------------
|
||||
@pytest.fixture(scope="session")
|
||||
def qapp():
|
||||
app = QApplication.instance()
|
||||
if app is None:
|
||||
app = QApplication(sys.argv)
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_info():
|
||||
return SampleShortInfo(
|
||||
db_id=1,
|
||||
puck_name="puck1",
|
||||
dewar_name="dew1",
|
||||
sample_name="sample1",
|
||||
run_number=1,
|
||||
user="group1",
|
||||
pin=3,
|
||||
location=DewarAddress(segment="A", pos=2),
|
||||
)
|
||||
|
||||
|
||||
# -------------------------
|
||||
# Shared DAQ server fixtures
|
||||
# Shared auth server fixtures
|
||||
# -------------------------
|
||||
@pytest.fixture(scope="session")
|
||||
def server_module():
|
||||
@@ -56,23 +25,10 @@ def server_module():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_backend(server_module):
|
||||
with (
|
||||
patch.object(server_module, "daq", create=True) as m_daq,
|
||||
patch.object(server_module, "bl", create=True) as m_bl,
|
||||
patch.object(server_module, "cfg", create=True) as m_cfg,
|
||||
):
|
||||
m_daq.busy = False
|
||||
m_daq.camera_image = np.zeros((10, 10, 3), dtype=np.uint8)
|
||||
|
||||
m_cfg.pgroup = "p12345"
|
||||
m_cfg.session_state.return_value = "ACTIVE"
|
||||
m_cfg.GUI_SESSION_EXPIRE_SECONDS = 10
|
||||
m_cfg.get_open_gui_sessions.return_value = []
|
||||
m_cfg.get_gui_session.return_value = None
|
||||
m_cfg.touch_gui_session.return_value = None
|
||||
|
||||
yield {"daq": m_daq, "bl": m_bl, "cfg": m_cfg}
|
||||
def mock_aaredb():
|
||||
db = MagicMock()
|
||||
db.find_loaded_sample.return_value = None
|
||||
return db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -83,106 +39,10 @@ def auth_token_data():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(server_module, mock_backend, auth_token_data):
|
||||
def client(server_module, mock_aaredb, auth_token_data):
|
||||
with (
|
||||
patch("aare.daq.auth.parse_token", return_value=auth_token_data),
|
||||
patch("cv2.imencode", return_value=(True, np.array([1, 2, 3], dtype=np.uint8))),
|
||||
patch.object(server_module, "mx_beamline", return_value=mock_backend["bl"]),
|
||||
patch.object(server_module, "BeamlineConfig", return_value=mock_backend["cfg"]),
|
||||
patch.object(server_module, "AareDAQ", return_value=mock_backend["daq"]),
|
||||
patch.object(server_module, "AareWrapper", return_value=mock_aaredb),
|
||||
TestClient(server_module.app) as c,
|
||||
):
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(client, mock_backend):
|
||||
return SimpleNamespace(
|
||||
client=client, daq=mock_backend["daq"], bl=mock_backend["bl"], cfg=mock_backend["cfg"]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daq_status_factory():
|
||||
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
|
||||
from aarecommon.math.diffraction_geometry import DiffractionGeometry
|
||||
from aarecommon.models.models import (
|
||||
BeamlineStateEnum,
|
||||
BeamlineStatus,
|
||||
CrystalSize,
|
||||
DAQStatusModel,
|
||||
SampleCameraSettings,
|
||||
SampleGeometryModel,
|
||||
SessionsStateEnum,
|
||||
SessionStatus,
|
||||
)
|
||||
|
||||
def _build(
|
||||
*,
|
||||
state=BeamlineStateEnum.Maintenance,
|
||||
busy=False,
|
||||
current_pgroup="p12345",
|
||||
staff=True,
|
||||
session_state=SessionsStateEnum.Vacant,
|
||||
sample=None,
|
||||
open_guis=None,
|
||||
):
|
||||
geom = SampleGeometryModel(
|
||||
beam_location_pxl=Coordinate(x=500, y=500),
|
||||
pixel_in_mm=0.001,
|
||||
aerotech=Coordinate(x=0, y=0, z=0),
|
||||
aerotech_meas=Coordinate(x=0, y=0, z=0),
|
||||
smargon=SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=0), phi_deg=0.0, chi_deg=0.0),
|
||||
omega_deg=0.0,
|
||||
beam_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
)
|
||||
|
||||
diff = DiffractionGeometry(
|
||||
energy_keV=12.0,
|
||||
dtz_mm=150.0,
|
||||
pixel_size_mm=0.075,
|
||||
beam_center_pxl=(1000.0, 1000.0),
|
||||
detector_size_pxl=(2000, 2000),
|
||||
detector_description="Eiger 16M",
|
||||
detector_serial_number="123",
|
||||
poni_rot1_rad=0.0,
|
||||
poni_rot2_rad=0.0,
|
||||
)
|
||||
|
||||
bl_status = BeamlineStatus(
|
||||
name="X06DA",
|
||||
ring_current_mA=400.0,
|
||||
omega=0.0,
|
||||
front_light=0.0,
|
||||
back_light=0.0,
|
||||
cryojet_K=100.0,
|
||||
shutter_open=False,
|
||||
exp_shutter_open=False,
|
||||
flux_ph_s=1e12,
|
||||
transmission=1.0,
|
||||
zoom=1.0,
|
||||
sample_camera=SampleCameraSettings(exposure=0.1, gain=1.0),
|
||||
commissioning_mode=False,
|
||||
dtz_min=120.0,
|
||||
dtz_max=1600.0,
|
||||
)
|
||||
|
||||
session = SessionStatus(session=session_state, current_pgroup=current_pgroup, staff=staff)
|
||||
|
||||
status = DAQStatusModel(
|
||||
geom=geom,
|
||||
diffraction=diff,
|
||||
bl=bl_status,
|
||||
state=state,
|
||||
busy=busy,
|
||||
session=session,
|
||||
crystal_size=CrystalSize(x=0, y=0, z=0),
|
||||
sample=sample,
|
||||
)
|
||||
|
||||
if open_guis is not None:
|
||||
status.open_guis = open_guis
|
||||
|
||||
return status
|
||||
|
||||
return _build
|
||||
+29
-348
@@ -1,14 +1,6 @@
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
|
||||
from aarecommon.math.sample_geometry import SampleGeometryModel
|
||||
from aarecommon.models.gridscan_decision import GridScanDecision, GridScanResult
|
||||
from aarecommon.models.models import DewarAddress, PuckLoadedInfo, SampleShortInfo
|
||||
from aarecommon.models.raster_grid import CenterOfMassModel, RasterGridRequest
|
||||
from aarecommon.models.rotation_scan import RotationScanRequest
|
||||
from jfjoch_client.models import ScanResult
|
||||
|
||||
from aare.daq.aaredb import AareWrapper
|
||||
|
||||
@@ -22,351 +14,40 @@ def mock_bl():
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_info():
|
||||
return SampleShortInfo(
|
||||
db_id=123,
|
||||
puck_name="P1",
|
||||
dewar_name="D1",
|
||||
sample_name="S1",
|
||||
run_number=1,
|
||||
user="testuser",
|
||||
pin=5,
|
||||
location=DewarAddress(segment="A", pos=1),
|
||||
)
|
||||
def wrapper(mock_bl):
|
||||
with (
|
||||
patch("aare.daq.aaredb.aareDB.ApiClient"),
|
||||
patch("aare.daq.aaredb.aareDB.TellsRunnerApi") as tell_api,
|
||||
):
|
||||
w = AareWrapper(mock_bl)
|
||||
w._tell_api = tell_api.return_value
|
||||
yield w
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def daq_status(mock_bl):
|
||||
status = MagicMock()
|
||||
status.bl = mock_bl
|
||||
status.diffraction.detector_description = "EIGER2 16M"
|
||||
status.diffraction.detector_serial_number = "1234"
|
||||
status.diffraction.dtz_mm = 200.0
|
||||
status.diffraction.max_resolution_angstrom = 1.5
|
||||
status.diffraction.beam_center_pxl = [1000.0, 1000.0]
|
||||
status.diffraction.pixel_size_mm = 0.075
|
||||
status.diffraction.energy_keV = 12.658
|
||||
status.diffraction.wavelength_angstrom = 0.979
|
||||
status.bl.ring_current_mA = 400.0
|
||||
status.bl.transmission = 1.0
|
||||
status.bl.flux_ph_s = 1e12
|
||||
status.bl.cryojet_K = 100.0
|
||||
status.geom.beam_size_mm = Coordinate(x=0.01, y=0.01)
|
||||
status.geom.smargon = SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=0), phi_deg=0, chi_deg=0)
|
||||
return status
|
||||
def _puck(*sample_ids, pgroup="p12345"):
|
||||
puck = MagicMock()
|
||||
puck.samples = [MagicMock(id=i, pgroup=pgroup) for i in sample_ids]
|
||||
return puck
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def geom_model():
|
||||
return SampleGeometryModel(
|
||||
beam_location_pxl=Coordinate(x=1000, y=1000),
|
||||
pixel_in_mm=0.001,
|
||||
aerotech=Coordinate(x=0, y=0),
|
||||
aerotech_meas=Coordinate(x=0, y=0),
|
||||
smargon=SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=0), phi_deg=0, chi_deg=0),
|
||||
omega_deg=0,
|
||||
beam_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
)
|
||||
def test_find_loaded_sample_found(wrapper):
|
||||
wrapper._tell_api.get_pucks_with_tell_position.return_value = [
|
||||
_puck(1, 2),
|
||||
_puck(3, pgroup="p67890"),
|
||||
]
|
||||
sample = wrapper.find_loaded_sample(3)
|
||||
assert sample is not None
|
||||
assert sample.pgroup == "p67890"
|
||||
wrapper._tell_api.get_pucks_with_tell_position.assert_called_once_with(tell="X10SA")
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.TellsRunnerApi")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
@patch("aareDB.ProcessingsRunnerApi")
|
||||
@patch("aareDB.GridscanRunnerApi")
|
||||
def test_aare_wrapper_init(mock_grid, mock_proc, mock_sample, mock_tell, mock_api, mock_bl):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_api.assert_called_once()
|
||||
assert wrapper._bl == mock_bl
|
||||
def test_find_loaded_sample_missing(wrapper):
|
||||
wrapper._tell_api.get_pucks_with_tell_position.return_value = [_puck(1, 2)]
|
||||
assert wrapper.find_loaded_sample(99) is None
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.TellsRunnerApi")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
@patch("aareDB.ProcessingsRunnerApi")
|
||||
@patch("aareDB.GridscanRunnerApi")
|
||||
def test_set_pucks_beamline(mock_grid, mock_proc, mock_sample, mock_tell, mock_api, mock_bl):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
pucks = [PuckLoadedInfo(puck_name="P1", location=DewarAddress(segment="A", pos=1))]
|
||||
wrapper.set_pucks_beamline(pucks)
|
||||
mock_tell.return_value.set_tell_positions.assert_called_once()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_manual_sample(mock_sample, mock_api, mock_bl, sample_info):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_sample.return_value.insert_sample.return_value.id = 456
|
||||
wrapper.create_manual_sample(sample_info)
|
||||
assert sample_info.db_id == 456
|
||||
mock_sample.return_value.insert_sample.assert_called_once()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_send_sample_event(mock_sample, mock_api, mock_bl, sample_info):
|
||||
from aareDB import SampleEventType
|
||||
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
wrapper.send_sample_event(sample_info.db_id, SampleEventType.MOUNTED, "Test comment")
|
||||
mock_sample.return_value.create_sample_event.assert_called_once()
|
||||
|
||||
# Test None sample
|
||||
mock_sample.return_value.create_sample_event.reset_mock()
|
||||
wrapper.send_sample_event(None, SampleEventType.MOUNTED)
|
||||
mock_sample.return_value.create_sample_event.assert_not_called()
|
||||
|
||||
# Test invalid ID
|
||||
sample_info.db_id = -1
|
||||
wrapper.send_sample_event(sample_info.db_id, SampleEventType.MOUNTED)
|
||||
mock_sample.return_value.create_sample_event.assert_not_called()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_manual_sample_error(mock_sample, mock_api, mock_bl, sample_info, caplog):
|
||||
import logging
|
||||
|
||||
caplog.set_level(logging.ERROR)
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_sample.return_value.insert_sample.side_effect = Exception("DB Error")
|
||||
wrapper.create_manual_sample(sample_info)
|
||||
assert "Error inserting sample" in caplog.text
|
||||
# the cause now arrives via the logged traceback rather than the message
|
||||
assert "DB Error" in caplog.text
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_send_sample_event_error(mock_sample, mock_api, mock_bl, sample_info, caplog):
|
||||
import logging
|
||||
|
||||
from aareDB import SampleEventType
|
||||
|
||||
caplog.set_level(logging.ERROR)
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_sample.return_value.create_sample_event.side_effect = Exception("Event Error")
|
||||
wrapper.send_sample_event(sample_info.db_id, SampleEventType.MOUNTED)
|
||||
assert "Error sending sample event" in caplog.text
|
||||
assert "MOUNTED" in caplog.text
|
||||
assert "Event Error" in caplog.text
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("requests.post")
|
||||
def test_upload_image(mock_post, mock_api, mock_bl):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_post.return_value.status_code = 200
|
||||
img = np.zeros((100, 100, 3), dtype=np.uint8)
|
||||
wrapper.upload_image(123, "test_img", img, "test message")
|
||||
mock_post.assert_called_once()
|
||||
assert "test_img.jpg" in str(mock_post.call_args)
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("requests.post")
|
||||
def test_upload_jpg(mock_post, mock_api, mock_bl):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_post.return_value.status_code = 200
|
||||
wrapper.upload_jpg(123, "test_img", b"fake jpeg bytes")
|
||||
mock_post.assert_called_once()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_rotation_run(mock_sample, mock_api, mock_bl, sample_info, daq_status):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
# Standard rotation
|
||||
req = RotationScanRequest(
|
||||
exp_time_s=0.1, incr_omega_deg=0.1, steps=100, file_prefix="test_prefix", dtz=200.0
|
||||
)
|
||||
wrapper.create_rotation_run(sample_info, req, daq_status)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.assert_called_once()
|
||||
|
||||
# None sample - should return early
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.reset_mock()
|
||||
wrapper.create_rotation_run(None, req, daq_status)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.assert_not_called()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_rotation_run_screening(mock_sample, mock_api, mock_bl, sample_info, daq_status):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
req = RotationScanRequest(
|
||||
exp_time_s=0.1,
|
||||
incr_omega_deg=0.1,
|
||||
steps=100,
|
||||
file_prefix="test_prefix",
|
||||
screening=True,
|
||||
wedge_omega_deg=5.0,
|
||||
dtz=200.0,
|
||||
)
|
||||
wrapper.create_rotation_run(sample_info, req, daq_status)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.assert_called_once()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_rotation_run_error(mock_sample, mock_api, mock_bl, sample_info, daq_status, caplog):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
req = RotationScanRequest(
|
||||
exp_time_s=0.1, incr_omega_deg=0.1, steps=100, file_prefix="test_prefix", dtz=200.0
|
||||
)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.side_effect = Exception(
|
||||
"Rotation error"
|
||||
)
|
||||
wrapper.create_rotation_run(sample_info, req, daq_status)
|
||||
assert "Rotation error" in caplog.text
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_gridscan_run(mock_sample, mock_api, mock_bl, sample_info, daq_status):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
req = RasterGridRequest(
|
||||
exp_time_s=0.1,
|
||||
n_x=10,
|
||||
n_y=10,
|
||||
grid_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
smargon_top_left=None,
|
||||
file_prefix="test_grid_prefix",
|
||||
dtz=200.0,
|
||||
)
|
||||
wrapper.create_gridscan_run(sample_info, req, daq_status)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.assert_called_once()
|
||||
|
||||
# None sample
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.reset_mock()
|
||||
wrapper.create_gridscan_run(None, req, daq_status)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.assert_not_called()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("aareDB.SamplesRunnerApi")
|
||||
def test_create_gridscan_run_error(mock_sample, mock_api, mock_bl, sample_info, daq_status, caplog):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
req = RasterGridRequest(
|
||||
exp_time_s=0.1,
|
||||
n_x=10,
|
||||
n_y=10,
|
||||
grid_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
smargon_top_left=None,
|
||||
file_prefix="test_grid_prefix",
|
||||
dtz=200.0,
|
||||
)
|
||||
mock_sample.return_value.create_experiment_parameters_for_sample.side_effect = Exception(
|
||||
"Grid error"
|
||||
)
|
||||
wrapper.create_gridscan_run(sample_info, req, daq_status)
|
||||
assert "Grid error" in caplog.text
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("requests.post")
|
||||
def test_ingest_gridscan(mock_post, mock_api, mock_bl, sample_info, geom_model):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_post.return_value.status_code = 200
|
||||
raster_result = MagicMock(spec=ScanResult)
|
||||
raster_request = RasterGridRequest(
|
||||
exp_time_s=0.1,
|
||||
n_x=10,
|
||||
n_y=10,
|
||||
grid_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
smargon_top_left=None,
|
||||
)
|
||||
com = CenterOfMassModel(n_x=5.0, n_y=5.0)
|
||||
|
||||
wrapper.ingest_gridscan(
|
||||
sample_info,
|
||||
raster_result,
|
||||
raster_request,
|
||||
[],
|
||||
geom_model,
|
||||
com,
|
||||
(500.0, 500.0),
|
||||
GridScanDecision(algorithm="none", result=GridScanResult(found=False)),
|
||||
)
|
||||
mock_post.assert_called_once()
|
||||
|
||||
# None sample
|
||||
mock_post.reset_mock()
|
||||
wrapper.ingest_gridscan(
|
||||
None,
|
||||
raster_result,
|
||||
raster_request,
|
||||
[],
|
||||
geom_model,
|
||||
com,
|
||||
(500.0, 500.0),
|
||||
GridScanDecision(algorithm="none", result=GridScanResult(found=False)),
|
||||
)
|
||||
mock_post.assert_not_called()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
@patch("requests.post")
|
||||
def test_ingest_scan(mock_post, mock_api, mock_bl, sample_info, geom_model):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
mock_post.return_value.status_code = 200
|
||||
result = MagicMock(spec=ScanResult)
|
||||
|
||||
wrapper.ingest_scan(sample_info, result, geom_model, (500.0, 500.0))
|
||||
mock_post.assert_called_once()
|
||||
|
||||
# None sample
|
||||
mock_post.reset_mock()
|
||||
wrapper.ingest_scan(None, result, geom_model, (500.0, 500.0))
|
||||
mock_post.assert_not_called()
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
def test_format_gridscan_payload_no_com(mock_api, mock_bl, sample_info, geom_model):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
raster_result = MagicMock(spec=ScanResult)
|
||||
raster_request = RasterGridRequest(
|
||||
exp_time_s=0.1,
|
||||
n_x=10,
|
||||
n_y=10,
|
||||
grid_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
smargon_top_left=None,
|
||||
)
|
||||
|
||||
payload = wrapper.format_gridscan_payload(
|
||||
sample_info,
|
||||
raster_result,
|
||||
raster_request,
|
||||
geom_model,
|
||||
None,
|
||||
[],
|
||||
(500.0, 500.0),
|
||||
GridScanDecision(algorithm="none", result=GridScanResult(found=False)),
|
||||
)
|
||||
assert payload.center_pxl is None
|
||||
assert payload.sample_id == sample_info.db_id
|
||||
|
||||
|
||||
@patch("aareDB.ApiClient")
|
||||
def test_format_gridscan_payload_with_top_left(mock_api, mock_bl, sample_info, geom_model):
|
||||
wrapper = AareWrapper(bl=mock_bl)
|
||||
raster_result = MagicMock(spec=ScanResult)
|
||||
top_left = SmargonCoordinate(sh_mm=Coordinate(x=0.1, y=0.1, z=0.1), phi_deg=0, chi_deg=0)
|
||||
raster_request = RasterGridRequest(
|
||||
exp_time_s=0.1,
|
||||
n_x=10,
|
||||
n_y=10,
|
||||
grid_size_mm=Coordinate(x=0.01, y=0.01),
|
||||
smargon_top_left=top_left,
|
||||
)
|
||||
|
||||
payload = wrapper.format_gridscan_payload(
|
||||
sample_info,
|
||||
raster_result,
|
||||
raster_request,
|
||||
geom_model,
|
||||
None,
|
||||
[],
|
||||
(500.0, 500.0),
|
||||
GridScanDecision(algorithm="none", result=GridScanResult(found=False)),
|
||||
)
|
||||
assert payload.sample_id == sample_info.db_id
|
||||
def test_find_loaded_sample_puck_without_samples(wrapper):
|
||||
puck = MagicMock()
|
||||
puck.samples = None
|
||||
wrapper._tell_api.get_pucks_with_tell_position.return_value = [puck]
|
||||
assert wrapper.find_loaded_sample(1) is None
|
||||
+105
-277
@@ -1,41 +1,28 @@
|
||||
import time
|
||||
from unittest.mock import MagicMock, patch
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
|
||||
# Mock environment variable before importing auth
|
||||
with patch.dict("os.environ", {"JWT_AAREDAQ_KEY": "test_secret"}):
|
||||
from aare.daq.auth import (
|
||||
TokenData,
|
||||
authenticate_user,
|
||||
cancel_baton_request,
|
||||
check_jwt_ro,
|
||||
check_jwt_rw,
|
||||
check_jwt_staff_only,
|
||||
create_access_token,
|
||||
force_current_sesion,
|
||||
get_baton_status,
|
||||
parse_token,
|
||||
release_baton,
|
||||
request_baton,
|
||||
resolve_baton_timeout_if_needed,
|
||||
respond_to_baton_request,
|
||||
)
|
||||
from aarecommon.errors.exception_handler import AuthenticationException, UserRightsException
|
||||
from aarecommon.models.auth import BatonHolderInfo, BatonRequest, BatonRequestStatus, BatonStatus
|
||||
from aarecommon.models.models import SessionsStateEnum
|
||||
|
||||
from aare.daq import auth
|
||||
from aare.daq.auth import (
|
||||
TokenData,
|
||||
authenticate_from_proxy_header,
|
||||
authenticate_user,
|
||||
check_jwt_staff_only,
|
||||
check_sample_access,
|
||||
create_access_token,
|
||||
parse_token,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_cfg():
|
||||
cfg = MagicMock()
|
||||
cfg.pgroup = "p12345"
|
||||
cfg.generate_session.return_value = 100
|
||||
cfg.queued_baton_transfer = None
|
||||
cfg.baton_holder = None
|
||||
cfg.pending_baton_request = None
|
||||
return cfg
|
||||
@pytest.fixture(autouse=True)
|
||||
def jwt_key():
|
||||
with patch.dict(os.environ, {"JWT_AAREDAQ_KEY": "test_secret"}):
|
||||
auth.init_jwt_key()
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -45,87 +32,92 @@ def token_data():
|
||||
|
||||
@pytest.fixture
|
||||
def staff_token_data():
|
||||
return TokenData(sub="staffuser", pgroups=["p12345"], session=101, staff=True)
|
||||
return TokenData(sub="staffuser", pgroups=["p11111"], session=101, staff=True)
|
||||
|
||||
|
||||
def test_create_access_token(token_data):
|
||||
with patch("aare.daq.auth.jwt_key", return_value="test_secret"):
|
||||
token = create_access_token(token_data)
|
||||
assert isinstance(token, str)
|
||||
payload = jwt.decode(token, "test_secret", algorithms=["HS256"])
|
||||
assert payload["sub"] == "testuser"
|
||||
assert payload["session"] == 100
|
||||
|
||||
|
||||
def test_authenticate_user(mock_cfg):
|
||||
def test_init_jwt_key_requires_env():
|
||||
with (
|
||||
patch("pwd.getpwnam") as mock_pwd,
|
||||
patch("os.getgrouplist") as mock_groups,
|
||||
patch("grp.getgrgid") as mock_grp,
|
||||
patch("aare.daq.auth.jwt_key", return_value="test_secret"),
|
||||
patch.dict(os.environ, {}, clear=True),
|
||||
pytest.raises(RuntimeError, match="JWT_AAREDAQ_KEY"),
|
||||
):
|
||||
mock_pwd.return_value.pw_name = "testuser"
|
||||
mock_pwd.return_value.pw_gid = 1000
|
||||
mock_groups.return_value = [1000, 1001]
|
||||
|
||||
def get_group(gid):
|
||||
m = MagicMock()
|
||||
if gid == 1000:
|
||||
m.gr_name = "p12345"
|
||||
else:
|
||||
m.gr_name = "unx-MXgroup"
|
||||
return m
|
||||
|
||||
mock_grp.side_effect = get_group
|
||||
|
||||
token = authenticate_user(mock_cfg, "testuser")
|
||||
assert isinstance(token, str)
|
||||
|
||||
payload = jwt.decode(token, "test_secret", algorithms=["HS256"])
|
||||
assert payload["sub"] == "testuser"
|
||||
assert "p12345" in payload["pgroups"]
|
||||
assert payload["staff"] is True
|
||||
auth.init_jwt_key()
|
||||
|
||||
|
||||
def test_parse_token():
|
||||
with patch("aare.daq.auth.jwt_key", return_value="test_secret"):
|
||||
token = jwt.encode(
|
||||
{"sub": "user", "pgroups": [], "session": 1, "staff": False}, "test_secret"
|
||||
)
|
||||
data = parse_token(token)
|
||||
assert data.sub == "user"
|
||||
def test_create_and_parse_token_roundtrip(token_data):
|
||||
token = create_access_token(token_data)
|
||||
assert parse_token(token) == token_data
|
||||
|
||||
|
||||
def test_parse_token_invalid():
|
||||
def test_parse_token_rejects_wrong_key(token_data):
|
||||
token = jwt.encode(token_data.model_dump(), "other_secret", algorithm=auth.ALGORITHM)
|
||||
with pytest.raises(AuthenticationException):
|
||||
parse_token(token)
|
||||
|
||||
|
||||
def test_parse_token_rejects_garbage():
|
||||
with pytest.raises(AuthenticationException):
|
||||
parse_token("not-a-token")
|
||||
|
||||
|
||||
def test_authenticate_from_proxy_header():
|
||||
request = SimpleNamespace(client=None, headers={"X-Remote-User": "someone"})
|
||||
assert authenticate_from_proxy_header(request) == "someone"
|
||||
|
||||
|
||||
def test_authenticate_from_proxy_header_missing():
|
||||
request = SimpleNamespace(client=None, headers={})
|
||||
with pytest.raises(AuthenticationException):
|
||||
authenticate_from_proxy_header(request)
|
||||
|
||||
|
||||
def _fake_groups(names):
|
||||
by_gid = {gid: SimpleNamespace(gr_name=name) for gid, name in enumerate(names, start=1000)}
|
||||
return list(by_gid), lambda gid: by_gid[gid]
|
||||
|
||||
|
||||
def test_authenticate_user_collects_pgroups():
|
||||
gids, getgrgid = _fake_groups(["users", "p12345", "p67890"])
|
||||
with (
|
||||
patch("aare.daq.auth.jwt_key", return_value="test_secret"),
|
||||
pytest.raises(AuthenticationException),
|
||||
patch("aare.daq.auth.pwd.getpwnam", return_value=SimpleNamespace(pw_name="u", pw_gid=1000)),
|
||||
patch("aare.daq.auth.os.getgrouplist", return_value=gids),
|
||||
patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid),
|
||||
):
|
||||
parse_token("invalid.token.here")
|
||||
data = parse_token(authenticate_user("u"))
|
||||
assert data.sub == "u"
|
||||
assert data.pgroups == ["p12345", "p67890"]
|
||||
assert data.staff is False
|
||||
|
||||
|
||||
def test_check_jwt_ro(mock_cfg, token_data):
|
||||
# Success
|
||||
check_jwt_ro(mock_cfg, token_data)
|
||||
|
||||
# Fail
|
||||
mock_cfg.pgroup = "p99999"
|
||||
with pytest.raises(UserRightsException):
|
||||
check_jwt_ro(mock_cfg, token_data)
|
||||
|
||||
# Staff success even if not in pgroup
|
||||
staff_data = TokenData(sub="staff", pgroups=[], session=2, staff=True)
|
||||
check_jwt_ro(mock_cfg, staff_data)
|
||||
def test_authenticate_user_staff_group():
|
||||
gids, getgrgid = _fake_groups(["unx-sls_mx", "p12345"])
|
||||
with (
|
||||
patch("aare.daq.auth.pwd.getpwnam", return_value=SimpleNamespace(pw_name="u", pw_gid=1000)),
|
||||
patch("aare.daq.auth.os.getgrouplist", return_value=gids),
|
||||
patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid),
|
||||
):
|
||||
assert parse_token(authenticate_user("u")).staff is True
|
||||
|
||||
|
||||
def test_check_jwt_rw(mock_cfg, token_data):
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=100, username="testuser", is_staff=False)
|
||||
check_jwt_rw(mock_cfg, token_data)
|
||||
def test_authenticate_user_super_user():
|
||||
gids, getgrgid = _fake_groups(["users"])
|
||||
with (
|
||||
patch("aare.daq.auth.pwd.getpwnam", return_value=SimpleNamespace(pw_name="u", pw_gid=1000)),
|
||||
patch("aare.daq.auth.os.getgrouplist", return_value=gids),
|
||||
patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid),
|
||||
):
|
||||
assert parse_token(authenticate_user(auth.SUPER_USERS[0])).staff is True
|
||||
|
||||
# Not holder
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=200, username="other", is_staff=False)
|
||||
with pytest.raises(UserRightsException):
|
||||
check_jwt_rw(mock_cfg, token_data)
|
||||
|
||||
def test_sessions_differ_between_tokens():
|
||||
gids, getgrgid = _fake_groups(["users"])
|
||||
with (
|
||||
patch("aare.daq.auth.pwd.getpwnam", return_value=SimpleNamespace(pw_name="u", pw_gid=1000)),
|
||||
patch("aare.daq.auth.os.getgrouplist", return_value=gids),
|
||||
patch("aare.daq.auth.grp.getgrgid", side_effect=getgrgid),
|
||||
):
|
||||
first = parse_token(authenticate_user("u")).session
|
||||
second = parse_token(authenticate_user("u")).session
|
||||
assert first != second
|
||||
|
||||
|
||||
def test_check_jwt_staff_only(token_data, staff_token_data):
|
||||
@@ -134,188 +126,24 @@ def test_check_jwt_staff_only(token_data, staff_token_data):
|
||||
check_jwt_staff_only(token_data)
|
||||
|
||||
|
||||
def test_force_current_sesion(mock_cfg, token_data):
|
||||
force_current_sesion(mock_cfg, token_data)
|
||||
mock_cfg.execute_baton_transfer.assert_called_once()
|
||||
def test_check_sample_access_member(token_data):
|
||||
res = check_sample_access(token_data, 7, "p67890")
|
||||
assert res.allowed is True
|
||||
assert res.pgroup == "p67890"
|
||||
assert res.sample_id == 7
|
||||
|
||||
|
||||
def test_get_baton_status(mock_cfg, token_data):
|
||||
mock_cfg.baton_holder = None
|
||||
mock_cfg.pending_baton_request = None
|
||||
mock_cfg.queued_baton_transfer = None
|
||||
|
||||
status = get_baton_status(mock_cfg, token_data)
|
||||
assert isinstance(status, BatonStatus)
|
||||
assert status.you_are_holder is False
|
||||
def test_check_sample_access_other_pgroup(token_data):
|
||||
res = check_sample_access(token_data, 7, "p99999")
|
||||
assert res.allowed is False
|
||||
assert res.pgroup == "p99999"
|
||||
|
||||
|
||||
def test_request_baton_vacant(mock_cfg, token_data):
|
||||
mock_cfg.session_state.return_value = SessionsStateEnum.Vacant
|
||||
res = request_baton(mock_cfg, token_data)
|
||||
assert res["granted"] is True
|
||||
mock_cfg.execute_baton_transfer.assert_called_once()
|
||||
def test_check_sample_access_staff_any_pgroup(staff_token_data):
|
||||
assert check_sample_access(staff_token_data, 7, "p99999").allowed is True
|
||||
|
||||
|
||||
def test_request_baton_owned_by_you(mock_cfg, token_data):
|
||||
mock_cfg.session_state.return_value = SessionsStateEnum.OwnedByYou
|
||||
res = request_baton(mock_cfg, token_data)
|
||||
assert res["already_holder"] is True
|
||||
|
||||
|
||||
def test_request_baton_pending(mock_cfg, token_data):
|
||||
mock_cfg.session_state.return_value = SessionsStateEnum.OwnedByElse
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=200, username="other", is_staff=False)
|
||||
mock_cfg.pending_baton_request = None
|
||||
mock_cfg.can_transfer_baton_now.return_value = True
|
||||
mock_cfg.allow_non_staff_request_from_staff = True
|
||||
|
||||
res = request_baton(mock_cfg, token_data)
|
||||
assert res["pending"] is True
|
||||
mock_cfg.set_pending_baton_request.assert_called_once()
|
||||
|
||||
|
||||
def test_respond_to_baton_request_accept(mock_cfg, token_data):
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=100, username="testuser", is_staff=False)
|
||||
mock_cfg.pending_baton_request = BatonRequest(
|
||||
request_id="1",
|
||||
requester_username="other",
|
||||
requester_session=200,
|
||||
requester_is_staff=False,
|
||||
holder_username="testuser",
|
||||
holder_session=100,
|
||||
created_at=time.time(),
|
||||
timeout_seconds=30,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
)
|
||||
mock_cfg.can_transfer_baton_now.return_value = True
|
||||
|
||||
res = respond_to_baton_request(mock_cfg, token_data, accept=True)
|
||||
assert res["transferred"] is True
|
||||
mock_cfg.execute_baton_transfer.assert_called_once()
|
||||
|
||||
|
||||
def test_release_baton(mock_cfg, token_data):
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=100, username="testuser", is_staff=False)
|
||||
res = release_baton(mock_cfg, token_data)
|
||||
assert res["released"] is True
|
||||
mock_cfg.end_active_session.assert_called_with(100)
|
||||
|
||||
|
||||
def test_request_baton_staff_override(mock_cfg, staff_token_data):
|
||||
mock_cfg.session_state.return_value = SessionsStateEnum.OwnedByElse
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=200, username="other", is_staff=False)
|
||||
mock_cfg.can_transfer_baton_now.return_value = True
|
||||
|
||||
res = request_baton(mock_cfg, staff_token_data)
|
||||
assert res["granted"] is True
|
||||
assert res["override"] is True
|
||||
|
||||
|
||||
def test_request_baton_staff_override_busy(mock_cfg, staff_token_data):
|
||||
mock_cfg.session_state.return_value = SessionsStateEnum.OwnedByElse
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=200, username="other", is_staff=False)
|
||||
mock_cfg.can_transfer_baton_now.return_value = False
|
||||
|
||||
res = request_baton(mock_cfg, staff_token_data)
|
||||
assert res["queued"] is True
|
||||
|
||||
|
||||
def test_resolve_baton_timeout_if_needed(mock_cfg):
|
||||
# Case: No pending request
|
||||
mock_cfg.pending_baton_request = None
|
||||
assert resolve_baton_timeout_if_needed(mock_cfg) is None
|
||||
|
||||
# Case: Request not expired
|
||||
mock_cfg.pending_baton_request = BatonRequest(
|
||||
request_id="1",
|
||||
requester_username="other",
|
||||
requester_session=200,
|
||||
requester_is_staff=False,
|
||||
holder_username="testuser",
|
||||
holder_session=100,
|
||||
created_at=time.time(),
|
||||
timeout_seconds=30,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
)
|
||||
assert resolve_baton_timeout_if_needed(mock_cfg) is None
|
||||
|
||||
# Case: Request expired, beamline not busy
|
||||
mock_cfg.pending_baton_request.created_at = time.time() - 40
|
||||
mock_cfg.can_transfer_baton_now.return_value = True
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=100, username="testuser", is_staff=False)
|
||||
|
||||
resolve_baton_timeout_if_needed(mock_cfg)
|
||||
mock_cfg.execute_baton_transfer.assert_called_once()
|
||||
mock_cfg.clear_pending_baton_request.assert_called_once()
|
||||
|
||||
|
||||
def test_respond_to_baton_request_refuse(mock_cfg, token_data):
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=100, username="testuser", is_staff=False)
|
||||
mock_cfg.pending_baton_request = BatonRequest(
|
||||
request_id="1",
|
||||
requester_username="other",
|
||||
requester_session=200,
|
||||
requester_is_staff=False,
|
||||
holder_username="testuser",
|
||||
holder_session=100,
|
||||
created_at=time.time(),
|
||||
timeout_seconds=30,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
)
|
||||
res = respond_to_baton_request(mock_cfg, token_data, accept=False)
|
||||
assert res["refused"] is True
|
||||
assert mock_cfg.pending_baton_request.status == BatonRequestStatus.REFUSED
|
||||
|
||||
|
||||
def test_respond_to_baton_request_accept_busy(mock_cfg, token_data):
|
||||
mock_cfg.baton_holder = BatonHolderInfo(session=100, username="testuser", is_staff=False)
|
||||
mock_cfg.pending_baton_request = BatonRequest(
|
||||
request_id="1",
|
||||
requester_username="other",
|
||||
requester_session=200,
|
||||
requester_is_staff=False,
|
||||
holder_username="testuser",
|
||||
holder_session=100,
|
||||
created_at=time.time(),
|
||||
timeout_seconds=30,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
)
|
||||
mock_cfg.can_transfer_baton_now.return_value = False
|
||||
|
||||
res = respond_to_baton_request(mock_cfg, token_data, accept=True)
|
||||
assert res["queued"] is True
|
||||
assert mock_cfg.queued_baton_transfer is not None
|
||||
|
||||
|
||||
def test_cancel_baton_request(mock_cfg, token_data):
|
||||
mock_cfg.pending_baton_request = BatonRequest(
|
||||
request_id="1",
|
||||
requester_username="testuser",
|
||||
requester_session=100,
|
||||
requester_is_staff=False,
|
||||
holder_username="other",
|
||||
holder_session=200,
|
||||
created_at=time.time(),
|
||||
timeout_seconds=30,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
)
|
||||
res = cancel_baton_request(mock_cfg, token_data)
|
||||
assert res["cancelled"] is True
|
||||
mock_cfg.clear_pending_baton_request.assert_called_once()
|
||||
|
||||
|
||||
def test_resolve_baton_timeout_busy(mock_cfg):
|
||||
mock_cfg.pending_baton_request = BatonRequest(
|
||||
request_id="1",
|
||||
requester_username="other",
|
||||
requester_session=200,
|
||||
requester_is_staff=False,
|
||||
holder_username="testuser",
|
||||
holder_session=100,
|
||||
created_at=time.time() - 40,
|
||||
timeout_seconds=30,
|
||||
status=BatonRequestStatus.PENDING,
|
||||
)
|
||||
mock_cfg.can_transfer_baton_now.return_value = False
|
||||
resolve_baton_timeout_if_needed(mock_cfg)
|
||||
assert mock_cfg.queued_baton_transfer is not None
|
||||
def test_check_sample_access_unknown_sample(token_data, staff_token_data):
|
||||
assert check_sample_access(token_data, 7, None).allowed is False
|
||||
# Even staff cannot act on a sample that is not loaded here.
|
||||
assert check_sample_access(staff_token_data, 7, None).allowed is False
|
||||
+37
-246
@@ -1,8 +1,8 @@
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
os.environ["JWT_AAREDAQ_KEY"] = "test_key_for_unit_testing"
|
||||
import pytest
|
||||
|
||||
from aare.daq.auth import TokenData
|
||||
|
||||
|
||||
def test_meta_error_codes(client):
|
||||
@@ -12,50 +12,10 @@ def test_meta_error_codes(client):
|
||||
assert "AuthErrorCode" in data
|
||||
|
||||
|
||||
def test_status(api, daq_status_factory, monkeypatch):
|
||||
from aarecommon.models.models import BeamlineStateEnum, SessionsStateEnum
|
||||
|
||||
from aare.daq import server
|
||||
|
||||
monkeypatch.setattr(server.auth, "resolve_baton_timeout_if_needed", lambda cfg: None)
|
||||
monkeypatch.setattr(server.auth, "get_baton_status", lambda cfg, data: {"dummy": "status"})
|
||||
|
||||
api.cfg.pending_baton_request = None
|
||||
api.cfg.queued_baton_transfer = None
|
||||
api.cfg.baton_holder = None
|
||||
api.cfg.allow_non_staff_request_from_staff = False
|
||||
|
||||
api.daq.status = daq_status_factory(
|
||||
state=BeamlineStateEnum.Maintenance, current_pgroup="p12345", staff=True
|
||||
)
|
||||
# ... rest of the setup
|
||||
api.daq.status.sample = None
|
||||
api.daq.status.box = None
|
||||
api.daq.status.last_best_res = None
|
||||
api.daq.status.last_best_b_factor = None
|
||||
api.daq.status.crystal_size = SimpleNamespace(x=0, y=0, z=0)
|
||||
api.daq.status.open_guis = []
|
||||
|
||||
api.cfg.pgroup = "p12345"
|
||||
api.cfg.session_state.return_value = SessionsStateEnum.OwnedByYou
|
||||
api.cfg.get_open_gui_sessions.return_value = []
|
||||
|
||||
response = api.client.get("/status", headers={"Authorization": "Bearer fake-token"})
|
||||
def test_installed_version(client):
|
||||
response = client.get("/about/installed_version")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["state"] == BeamlineStateEnum.Maintenance.value
|
||||
assert data["session"]["current_pgroup"] == "p12345"
|
||||
assert data["session"]["session"] == SessionsStateEnum.OwnedByYou.value
|
||||
|
||||
|
||||
def test_omega_put(client):
|
||||
with patch("aare.daq.auth.check_jwt_rw"), patch("aare.daq.server.daq") as mock_daq:
|
||||
response = client.put(
|
||||
"/beamline/omega?val=10.5", headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == "OK"
|
||||
assert mock_daq.omega == 10.5
|
||||
assert isinstance(response.json(), str)
|
||||
|
||||
|
||||
def test_login_success(client):
|
||||
@@ -72,210 +32,41 @@ def test_login_success(client):
|
||||
assert response.json() == {"access_token": "fake-access-token", "token_type": "bearer"}
|
||||
|
||||
|
||||
def test_mount_returns_tell_exception_when_mount_precheck_fails(client, mock_backend, monkeypatch):
|
||||
from aarecommon.errors.exception_handler import TellCommunicationError
|
||||
|
||||
from aare.daq import server
|
||||
|
||||
monkeypatch.setattr(server.auth, "check_jwt_rw", lambda *_args, **_kwargs: None)
|
||||
|
||||
mock_daq = mock_backend["daq"]
|
||||
mock_daq.check_tell_mount_start_conditions.side_effect = TellCommunicationError(
|
||||
"Mount can't start: system check failed: Exception('Psys safety not released',); TELL doors are open"
|
||||
)
|
||||
|
||||
response = client.post(
|
||||
"/sample/mount?dbid=1&reference=false", headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 503
|
||||
payload = response.json()
|
||||
assert payload["exception_class"] == "TellCommunicationError"
|
||||
assert payload["code"] == "TELL_COMMUNICATION_ERROR"
|
||||
assert "Mount can't start:" in payload["message"]
|
||||
def test_login_without_proxy_header_is_401(client):
|
||||
response = client.post("/token", data={"username": "user", "password": "pwd"})
|
||||
assert response.status_code == 401
|
||||
assert response.json()["code"] == "INVALID_TOKEN"
|
||||
|
||||
|
||||
def test_mount_calls_tell_mount_precheck_before_mount(client, mock_backend, monkeypatch):
|
||||
from aare.daq import server
|
||||
def test_sample_access_requires_token(client):
|
||||
assert client.get("/access/sample/1").status_code == 401
|
||||
|
||||
monkeypatch.setattr(server.auth, "check_jwt_rw", lambda *_args, **_kwargs: None)
|
||||
|
||||
mock_daq = mock_backend["daq"]
|
||||
|
||||
sample = SimpleNamespace(db_id=1, user="p12345")
|
||||
mock_daq.sample_spreadsheet = SimpleNamespace(s=[sample])
|
||||
mock_daq.reference_tools = SimpleNamespace(s=[])
|
||||
|
||||
response = client.post(
|
||||
"/sample/mount?dbid=1&reference=false", headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("staff", "pgroups", "sample_pgroup", "allowed"),
|
||||
[
|
||||
(False, ["p12345"], "p12345", True),
|
||||
(False, ["p12345"], "p99999", False),
|
||||
(True, ["p12345"], "p99999", True),
|
||||
],
|
||||
)
|
||||
def test_sample_access_decision(client, mock_aaredb, staff, pgroups, sample_pgroup, allowed):
|
||||
mock_aaredb.find_loaded_sample.return_value = MagicMock(id=42, pgroup=sample_pgroup)
|
||||
data = TokenData(sub="u", pgroups=pgroups, session=1, staff=staff)
|
||||
with patch("aare.daq.auth.parse_token", return_value=data):
|
||||
response = client.get("/access/sample/42", headers={"Authorization": "Bearer t"})
|
||||
assert response.status_code == 200
|
||||
mock_daq.check_tell_mount_start_conditions.assert_called_once_with()
|
||||
assert mock_daq.sample == sample
|
||||
body = response.json()
|
||||
assert body["sample_id"] == 42
|
||||
assert body["allowed"] is allowed
|
||||
assert body["pgroup"] == sample_pgroup
|
||||
mock_aaredb.find_loaded_sample.assert_called_once_with(42)
|
||||
|
||||
|
||||
def test_auto_scan_returns_tell_exception_when_mount_precheck_fails(
|
||||
client, mock_backend, monkeypatch
|
||||
):
|
||||
from aarecommon.errors.exception_handler import TellCommunicationError
|
||||
|
||||
from aare.daq import server
|
||||
|
||||
monkeypatch.setattr(server.auth, "check_jwt_rw", lambda *_args, **_kwargs: None)
|
||||
|
||||
mock_daq = mock_backend["daq"]
|
||||
mock_daq.check_tell_mount_start_conditions.side_effect = TellCommunicationError(
|
||||
"Mount can't start: TELL is not in remote mode; TELL doors are open"
|
||||
)
|
||||
|
||||
body = {
|
||||
"db_id": 1,
|
||||
"puck_name": "puck1",
|
||||
"dewar_name": "dewar1",
|
||||
"sample_name": "sample1",
|
||||
"run_number": 1,
|
||||
"user": "p12345",
|
||||
"pin": 1,
|
||||
"location": {"segment": "A", "pos": 1},
|
||||
}
|
||||
|
||||
response = client.post("/scan/auto", json=body, headers={"Authorization": "Bearer fake-token"})
|
||||
|
||||
assert response.status_code == 503
|
||||
payload = response.json()
|
||||
assert payload["exception_class"] == "TellCommunicationError"
|
||||
assert payload["code"] == "TELL_COMMUNICATION_ERROR"
|
||||
assert "Mount can't start:" in payload["message"]
|
||||
|
||||
|
||||
def test_auto_scan_calls_tell_mount_precheck_before_measure(client, mock_backend, monkeypatch):
|
||||
from aare.daq import server
|
||||
|
||||
monkeypatch.setattr(server.auth, "check_jwt_rw", lambda *_args, **_kwargs: None)
|
||||
|
||||
mock_daq = mock_backend["daq"]
|
||||
mock_daq.measure.return_value = 12.345
|
||||
|
||||
body = {
|
||||
"db_id": 1,
|
||||
"puck_name": "puck1",
|
||||
"dewar_name": "dewar1",
|
||||
"sample_name": "sample1",
|
||||
"run_number": 1,
|
||||
"user": "p12345",
|
||||
"pin": 1,
|
||||
"location": {"segment": "A", "pos": 1},
|
||||
}
|
||||
|
||||
response = client.post("/scan/auto", json=body, headers={"Authorization": "Bearer fake-token"})
|
||||
|
||||
def test_sample_access_unknown_sample(client, mock_aaredb):
|
||||
mock_aaredb.find_loaded_sample.return_value = None
|
||||
response = client.get("/access/sample/42", headers={"Authorization": "Bearer t"})
|
||||
assert response.status_code == 200
|
||||
mock_daq.check_tell_mount_start_conditions.assert_called_once_with()
|
||||
mock_daq.measure.assert_called_once()
|
||||
|
||||
|
||||
def test_get_pgroup(api):
|
||||
api.cfg.pgroup = "p12345"
|
||||
response = api.client.get("/access/pgroup", headers={"Authorization": "Bearer fake-token"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == "p12345"
|
||||
|
||||
|
||||
def test_set_pgroup(api):
|
||||
api.cfg.baton_holder = None
|
||||
response = api.client.put(
|
||||
"/access/pgroup?val=p54321", headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == "OK"
|
||||
assert api.cfg.pgroup == "p54321"
|
||||
|
||||
|
||||
def test_delete_pgroup(api):
|
||||
api.client.delete("/access/pgroup", headers={"Authorization": "Bearer fake-token"})
|
||||
assert api.cfg.pgroup is None
|
||||
|
||||
|
||||
def test_set_commissioning_mode(api):
|
||||
response = api.client.put(
|
||||
"/beamline/commissioning_mode?val=true", headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == "OK"
|
||||
assert api.cfg.commissioning_mode is True
|
||||
|
||||
|
||||
def test_get_settings(api):
|
||||
from aarecommon.models.models import BeamlineSettingsModel
|
||||
|
||||
mock_settings = BeamlineSettingsModel()
|
||||
api.cfg.settings = mock_settings
|
||||
response = api.client.get("/beamline/settings", headers={"Authorization": "Bearer fake-token"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == mock_settings.model_dump()
|
||||
|
||||
|
||||
def test_put_settings(api):
|
||||
from aarecommon.models.models import BeamlineSettingsModel
|
||||
|
||||
settings_data = BeamlineSettingsModel().model_dump()
|
||||
response = api.client.put(
|
||||
"/beamline/settings", json=settings_data, headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert api.cfg.settings.model_dump() == settings_data
|
||||
|
||||
|
||||
def test_get_cryo_settings(api):
|
||||
from aarecommon.models.models import CryojetSettingsModel
|
||||
|
||||
mock_cryo = CryojetSettingsModel()
|
||||
api.cfg.cryojet_settings = mock_cryo
|
||||
response = api.client.get(
|
||||
"/beamline/cryo_settings", headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == mock_cryo.model_dump()
|
||||
|
||||
|
||||
def test_put_cryo_settings(api):
|
||||
from aarecommon.models.models import CryojetSettingsModel
|
||||
|
||||
cryo_data = CryojetSettingsModel().model_dump()
|
||||
response = api.client.put(
|
||||
"/beamline/cryo_settings", json=cryo_data, headers={"Authorization": "Bearer fake-token"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert api.cfg.cryojet_settings.model_dump() == cryo_data
|
||||
|
||||
|
||||
def test_baton_status(api):
|
||||
from aarecommon.models.auth import BatonStatus
|
||||
|
||||
mock_baton = BatonStatus(holder=None, request=None, allow_non_staff_request=True)
|
||||
api.cfg.baton_status = mock_baton
|
||||
api.cfg.baton_holder = None
|
||||
api.cfg.queued_baton_transfer = None
|
||||
api.cfg.allow_non_staff_request_from_staff = True
|
||||
response = api.client.get("/baton/status", headers={"Authorization": "Bearer fake-token"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == mock_baton.model_dump()
|
||||
|
||||
|
||||
def test_baton_request(api, monkeypatch):
|
||||
from aare.daq import server
|
||||
|
||||
monkeypatch.setattr(server.auth, "request_baton", lambda cfg, data: {"granted": True})
|
||||
response = api.client.post("/baton/request", headers={"Authorization": "Bearer fake-token"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"granted": True}
|
||||
|
||||
|
||||
def test_baton_release(api, monkeypatch):
|
||||
from aare.daq import server
|
||||
|
||||
monkeypatch.setattr(server.auth, "release_baton", lambda cfg, data: {"released": True})
|
||||
response = api.client.post("/baton/release", headers={"Authorization": "Bearer fake-token"})
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"released": True}
|
||||
body = response.json()
|
||||
assert body["allowed"] is False
|
||||
assert body["pgroup"] is None
|
||||
Reference in new issue
Block a user