provide sample info
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
f779a41007
commit
042938548d
5 files changed
+144
-94
No files matched your search
@@ -1,10 +1,17 @@
|
||||
[
|
||||
{"sample_id": 1, "sample_name": "lyso_01", "pgroup": "p12345"},
|
||||
{"sample_id": 2, "sample_name": "lyso_02", "pgroup": "p12345"},
|
||||
{"sample_id": 3, "sample_name": "thaumatin_01", "pgroup": "p12345"},
|
||||
{"sample_id": 4, "sample_name": "insulin_01", "pgroup": "p67890"},
|
||||
{"sample_id": 5, "sample_name": "insulin_02", "pgroup": "p67890"},
|
||||
{"sample_id": 6, "sample_name": "proteinaseK_01", "pgroup": "p20001"},
|
||||
{"sample_id": 7, "sample_name": "proteinaseK_02", "pgroup": "p20001"},
|
||||
{"sample_id": 8, "sample_name": "trypsin_01", "pgroup": "p20002"}
|
||||
]
|
||||
{
|
||||
"samples": [
|
||||
{"db_id": 1, "puck_name": "PSI-001", "dewar_name": "DEWAR-A", "sample_name": "lyso_01", "run_number": 1, "user": "p12345", "pin": 1, "location": {"segment": "A", "pos": 1}, "priority": 1.0, "comment": "tetragonal lysozyme, 20% glycerol", "mount_count": 0},
|
||||
{"db_id": 2, "puck_name": "PSI-001", "dewar_name": "DEWAR-A", "sample_name": "lyso_02", "run_number": 1, "user": "p12345", "pin": 2, "location": {"segment": "A", "pos": 1}, "priority": 1.0, "comment": null, "mount_count": 1, "screening_count": 1},
|
||||
{"db_id": 3, "puck_name": "PSI-001", "dewar_name": "DEWAR-A", "sample_name": "thaumatin_01", "run_number": 2, "user": "p12345", "pin": 3, "location": {"segment": "A", "pos": 1}, "priority": 2.0, "comment": "large crystal, collect 360 deg", "mount_count": 2, "raster_count": 1, "rotation_count": 1},
|
||||
{"db_id": 4, "puck_name": "PSI-002", "dewar_name": "DEWAR-A", "sample_name": "insulin_01", "run_number": 1, "user": "p67890", "pin": 1, "location": {"segment": "A", "pos": 2}, "priority": 1.0, "comment": null},
|
||||
{"db_id": 5, "puck_name": "PSI-002", "dewar_name": "DEWAR-A", "sample_name": "insulin_02", "run_number": 1, "user": "p67890", "pin": 2, "location": {"segment": "A", "pos": 2}, "priority": 0.5, "comment": "small, may be twinned"},
|
||||
{"db_id": 6, "puck_name": "UNI-017", "dewar_name": "DEWAR-B", "sample_name": "proteinaseK_01", "run_number": 1, "user": "p20001", "pin": 5, "location": {"segment": "B", "pos": 1}, "priority": 1.0, "comment": null},
|
||||
{"db_id": 7, "puck_name": "UNI-017", "dewar_name": "DEWAR-B", "sample_name": "proteinaseK_02", "run_number": 1, "user": "p20001", "pin": 6, "location": {"segment": "B", "pos": 1}, "priority": 1.0, "comment": "soaked with ligand L3"},
|
||||
{"db_id": 8, "puck_name": "UNI-018", "dewar_name": "DEWAR-B", "sample_name": "trypsin_01", "run_number": 3, "user": "p20002", "pin": 16, "location": {"segment": "B", "pos": 2}, "priority": 1.0, "comment": null, "mount_count": 3, "rotation_count": 3}
|
||||
],
|
||||
"reference_tools": [
|
||||
{"db_id": 9001, "puck_name": "REF-TOOLS", "dewar_name": "BEAMLINE", "sample_name": "beam_location_pin", "run_number": 1, "user": "p11206", "pin": 1, "location": {"segment": "X", "pos": 1}, "priority": 1.0, "comment": "YAG screen for beam location"},
|
||||
{"db_id": 9002, "puck_name": "REF-TOOLS", "dewar_name": "BEAMLINE", "sample_name": "calibration_lyso", "run_number": 1, "user": "p11206", "pin": 2, "location": {"segment": "X", "pos": 1}, "priority": 1.0, "comment": "beam centre / detector distance calibration"},
|
||||
{"db_id": 9003, "puck_name": "REF-TOOLS", "dewar_name": "BEAMLINE", "sample_name": "empty_pin", "run_number": 1, "user": "p11206", "pin": 3, "location": {"segment": "X", "pos": 1}, "priority": 1.0, "comment": "gripper / mount test"}
|
||||
]
|
||||
}
|
||||
+23
-23
@@ -1,7 +1,9 @@
|
||||
"""Stand-in sample catalogue used while the real sample source lives in BEC/aareDB.
|
||||
|
||||
The data is a static JSON file shipped with the package; each entry maps an aareDB-style
|
||||
sample id to the p-group that owns it.
|
||||
The data is a static JSON file shipped with the package, in the same two lists the DAQ
|
||||
used to keep in Redis: the sample spreadsheet (user pucks in the TELL) and the reference
|
||||
tools (beamline-owned pins in the "X" segment). Entries are ``SampleShortInfo``, so the
|
||||
``user`` field is the owning p-group.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -9,34 +11,32 @@ from __future__ import annotations
|
||||
from importlib.resources import files
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, TypeAdapter
|
||||
from aarecommon.models.models import SampleShortInfo, SampleShortInfoList
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class DummySample(BaseModel):
|
||||
sample_id: int
|
||||
sample_name: str
|
||||
pgroup: str
|
||||
|
||||
|
||||
class MountResult(BaseModel):
|
||||
mounted: bool
|
||||
sample_id: int
|
||||
sample_name: str
|
||||
pgroup: str
|
||||
|
||||
|
||||
_SAMPLE_LIST = TypeAdapter(list[DummySample])
|
||||
class DummySampleData(BaseModel):
|
||||
samples: list[SampleShortInfo]
|
||||
reference_tools: list[SampleShortInfo]
|
||||
|
||||
|
||||
class DummySampleStore:
|
||||
def __init__(self, path: Path | None = None) -> None:
|
||||
if path is None:
|
||||
path = Path(str(files("aare.daq") / "dummy_samples.json"))
|
||||
samples = _SAMPLE_LIST.validate_json(path.read_text())
|
||||
self._by_id = {s.sample_id: s for s in samples}
|
||||
data = DummySampleData.model_validate_json(path.read_text())
|
||||
self._samples = {s.db_id: s for s in data.samples}
|
||||
self._reference_tools = {s.db_id: s for s in data.reference_tools}
|
||||
|
||||
def find_sample(self, sample_id: int) -> DummySample | None:
|
||||
return self._by_id.get(sample_id)
|
||||
def find_sample(self, db_id: int, reference: bool = False) -> SampleShortInfo | None:
|
||||
"""Look a sample up by database id, in the spreadsheet or the reference tools."""
|
||||
source = self._reference_tools if reference else self._samples
|
||||
return source.get(db_id)
|
||||
|
||||
def all_samples(self) -> list[DummySample]:
|
||||
return list(self._by_id.values())
|
||||
@property
|
||||
def spreadsheet(self) -> SampleShortInfoList:
|
||||
return SampleShortInfoList(s=list(self._samples.values()))
|
||||
|
||||
@property
|
||||
def reference_tools(self) -> SampleShortInfoList:
|
||||
return SampleShortInfoList(s=list(self._reference_tools.values()))
|
||||
+22
-19
@@ -9,6 +9,7 @@ from aarecommon.config.beamline import mx_beamline
|
||||
from aarecommon.config.logger import get_uvicorn_logging_config, setup_logger
|
||||
from aarecommon.errors.codes import AuthErrorCode
|
||||
from aarecommon.errors.exception_handler import SampleException, UserRightsException
|
||||
from aarecommon.models.models import SampleShortInfo
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
@@ -16,7 +17,7 @@ from fastapi.security import OAuth2PasswordBearer
|
||||
from aare.daq import auth
|
||||
from aare.daq.aaredb import AareWrapper, LoadedSampleInfo
|
||||
from aare.daq.auth import SampleAccess
|
||||
from aare.daq.samples import DummySampleStore, MountResult
|
||||
from aare.daq.samples import DummySampleStore
|
||||
from aare.daq.server_exception_handler import register_exception_handlers
|
||||
|
||||
logger = setup_logger("aareDAQ")
|
||||
@@ -130,37 +131,39 @@ async def sample_info(sample_id: int, token: str = Depends(oauth2_scheme)) -> Lo
|
||||
return info
|
||||
|
||||
|
||||
@app.post("/sample/mount/{sample_id}")
|
||||
async def mount_sample(sample_id: int, token: str = Depends(oauth2_scheme)) -> MountResult:
|
||||
@app.post("/sample/mount")
|
||||
async def mount(
|
||||
dbid: int, reference: bool = False, token: str = Depends(oauth2_scheme)
|
||||
) -> SampleShortInfo:
|
||||
"""
|
||||
Mount a sample on behalf of the token's user.
|
||||
Mount a sample from the spreadsheet onto the goniometer.
|
||||
|
||||
The sample is looked up in the dummy sample catalogue and the user must be allowed
|
||||
to work on it (member of its p-group, or staff). Nothing moves yet; this only
|
||||
exercises the authorization path.
|
||||
The sample is looked up in the dummy catalogue and the user must be allowed to work
|
||||
on it (member of its p-group, or staff). Nothing moves yet; this only exercises the
|
||||
authorization path.
|
||||
|
||||
Args:
|
||||
sample_id: Database identifier of the sample to mount.
|
||||
token: OAuth2 access token of the user asking.
|
||||
dbid: Database ID of the sample to mount.
|
||||
token: OAuth2 access token.
|
||||
reference: Whether to look for the sample in the reference tools list.
|
||||
|
||||
Returns:
|
||||
MountResult on success.
|
||||
The mounted sample's info.
|
||||
|
||||
Raises:
|
||||
SampleException: the sample id is not in the catalogue (400).
|
||||
SampleException: no such sample in the requested list (400).
|
||||
UserRightsException: the user may not work on this sample (403).
|
||||
"""
|
||||
data = auth.parse_token(token)
|
||||
sample = samples.find_sample(sample_id)
|
||||
token_data = auth.parse_token(token)
|
||||
logger.debug(f"Mount {dbid}")
|
||||
sample = samples.find_sample(dbid, reference=reference)
|
||||
if sample is None:
|
||||
raise SampleException(f"Unknown sample id {sample_id}.")
|
||||
access = auth.check_sample_access(data, sample_id, sample.pgroup)
|
||||
raise SampleException(message="Sample not found")
|
||||
access = auth.check_sample_access(token_data, dbid, sample.user)
|
||||
if not access.allowed:
|
||||
raise UserRightsException(message=access.reason, code=AuthErrorCode.FORBIDDEN)
|
||||
logger.info(f"{data.sub} mounted sample {sample_id} ({sample.sample_name}, {sample.pgroup})")
|
||||
return MountResult(
|
||||
mounted=True, sample_id=sample_id, sample_name=sample.sample_name, pgroup=sample.pgroup
|
||||
)
|
||||
logger.info(f"{token_data.sub} mounted sample {dbid} ({sample.sample_name}, {sample.user})")
|
||||
return sample
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -1,28 +1,42 @@
|
||||
import pytest
|
||||
from aarecommon.models.models import SampleShortInfo
|
||||
|
||||
from aare.daq.samples import DummySample, DummySampleStore
|
||||
from aare.daq.samples import DummySampleStore
|
||||
|
||||
|
||||
def test_shipped_catalogue_loads():
|
||||
store = DummySampleStore()
|
||||
samples = store.all_samples()
|
||||
assert samples, "shipped dummy_samples.json should not be empty"
|
||||
assert all(isinstance(s, DummySample) for s in samples)
|
||||
assert len({s.sample_id for s in samples}) == len(samples), "sample ids must be unique"
|
||||
samples = store.spreadsheet.s
|
||||
tools = store.reference_tools.s
|
||||
assert samples and tools, "shipped dummy_samples.json should fill both lists"
|
||||
assert all(isinstance(s, SampleShortInfo) for s in samples + tools)
|
||||
ids = [s.db_id for s in samples + tools]
|
||||
assert len(set(ids)) == len(ids), "db_ids must be unique across both lists"
|
||||
assert all(s.location and s.location.segment == "X" for s in tools)
|
||||
assert all(s.location and s.location.segment != "X" for s in samples)
|
||||
assert all(s.user.startswith("p") for s in samples + tools)
|
||||
|
||||
|
||||
def test_find_sample(tmp_path):
|
||||
def test_find_sample_in_each_list(tmp_path):
|
||||
path = tmp_path / "samples.json"
|
||||
path.write_text('[{"sample_id": 7, "sample_name": "x", "pgroup": "p1"}]')
|
||||
path.write_text(
|
||||
"""{
|
||||
"samples": [{"db_id": 7, "puck_name": "P", "dewar_name": "D", "sample_name": "x",
|
||||
"run_number": 1, "user": "p1", "pin": 1}],
|
||||
"reference_tools": [{"db_id": 8, "puck_name": "R", "dewar_name": "D", "sample_name": "y",
|
||||
"run_number": 1, "user": "p2", "pin": 1}]
|
||||
}"""
|
||||
)
|
||||
store = DummySampleStore(path)
|
||||
found = store.find_sample(7)
|
||||
assert found is not None
|
||||
assert found.pgroup == "p1"
|
||||
assert store.find_sample(7).user == "p1"
|
||||
assert store.find_sample(7, reference=True) is None
|
||||
assert store.find_sample(8, reference=True).user == "p2"
|
||||
assert store.find_sample(8) is None
|
||||
assert store.find_sample(99) is None
|
||||
|
||||
|
||||
def test_invalid_catalogue_rejected(tmp_path):
|
||||
path = tmp_path / "samples.json"
|
||||
path.write_text('[{"sample_id": "seven", "sample_name": "x"}]')
|
||||
path.write_text('{"samples": [{"db_id": "seven"}], "reference_tools": []}')
|
||||
with pytest.raises(ValueError):
|
||||
DummySampleStore(path)
|
||||
@@ -1,11 +1,11 @@
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from aarecommon.models.models import DewarAddress, SampleShortInfo
|
||||
from aareDB.models.sample import Sample
|
||||
|
||||
from aare.daq.aaredb import LoadedSampleInfo
|
||||
from aare.daq.auth import TokenData
|
||||
from aare.daq.samples import DummySample
|
||||
|
||||
|
||||
def test_installed_version(client):
|
||||
@@ -87,32 +87,51 @@ def _as_user(pgroups, staff=False):
|
||||
)
|
||||
|
||||
|
||||
def test_mount_requires_token(client):
|
||||
assert client.post("/sample/mount/1").status_code == 401
|
||||
|
||||
|
||||
def test_mount_own_pgroup_succeeds(client, mock_samples):
|
||||
mock_samples.find_sample.return_value = DummySample(
|
||||
sample_id=1, sample_name="lyso_01", pgroup="p12345"
|
||||
def _short_info(db_id, pgroup, name="lyso_01"):
|
||||
return SampleShortInfo(
|
||||
db_id=db_id,
|
||||
puck_name="PSI-001",
|
||||
dewar_name="DEWAR-A",
|
||||
sample_name=name,
|
||||
run_number=1,
|
||||
user=pgroup,
|
||||
pin=1,
|
||||
location=DewarAddress(segment="A", pos=1),
|
||||
)
|
||||
|
||||
|
||||
def test_mount_requires_token(client):
|
||||
assert client.post("/sample/mount?dbid=1").status_code == 401
|
||||
|
||||
|
||||
def test_mount_own_pgroup_returns_sample_info(client, mock_samples):
|
||||
mock_samples.find_sample.return_value = _short_info(1, "p12345")
|
||||
with _as_user(["p12345"]):
|
||||
response = client.post("/sample/mount/1", headers=AUTH)
|
||||
response = client.post("/sample/mount", params={"dbid": 1}, headers=AUTH)
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"mounted": True,
|
||||
"sample_id": 1,
|
||||
"sample_name": "lyso_01",
|
||||
"pgroup": "p12345",
|
||||
}
|
||||
mock_samples.find_sample.assert_called_once_with(1)
|
||||
body = response.json()
|
||||
assert body["db_id"] == 1
|
||||
assert body["sample_name"] == "lyso_01"
|
||||
assert body["user"] == "p12345"
|
||||
assert body["location"] == {"segment": "A", "pos": 1}
|
||||
mock_samples.find_sample.assert_called_once_with(1, reference=False)
|
||||
|
||||
|
||||
def test_mount_reference_flag_is_forwarded(client, mock_samples):
|
||||
mock_samples.find_sample.return_value = _short_info(9001, "p11206", name="beam_location_pin")
|
||||
with _as_user(["p11206"]):
|
||||
response = client.post(
|
||||
"/sample/mount", params={"dbid": 9001, "reference": "true"}, headers=AUTH
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["sample_name"] == "beam_location_pin"
|
||||
mock_samples.find_sample.assert_called_once_with(9001, reference=True)
|
||||
|
||||
|
||||
def test_mount_other_pgroup_is_403(client, mock_samples):
|
||||
mock_samples.find_sample.return_value = DummySample(
|
||||
sample_id=4, sample_name="insulin_01", pgroup="p67890"
|
||||
)
|
||||
mock_samples.find_sample.return_value = _short_info(4, "p67890")
|
||||
with _as_user(["p12345"]):
|
||||
response = client.post("/sample/mount/4", headers=AUTH)
|
||||
response = client.post("/sample/mount", params={"dbid": 4}, headers=AUTH)
|
||||
assert response.status_code == 403
|
||||
body = response.json()
|
||||
assert body["code"] == "FORBIDDEN"
|
||||
@@ -120,35 +139,42 @@ def test_mount_other_pgroup_is_403(client, mock_samples):
|
||||
|
||||
|
||||
def test_mount_staff_any_pgroup(client, mock_samples):
|
||||
mock_samples.find_sample.return_value = DummySample(
|
||||
sample_id=4, sample_name="insulin_01", pgroup="p67890"
|
||||
)
|
||||
mock_samples.find_sample.return_value = _short_info(4, "p67890")
|
||||
with _as_user(["p11111"], staff=True):
|
||||
response = client.post("/sample/mount/4", headers=AUTH)
|
||||
response = client.post("/sample/mount", params={"dbid": 4}, headers=AUTH)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["mounted"] is True
|
||||
assert response.json()["db_id"] == 4
|
||||
|
||||
|
||||
def test_mount_unknown_sample_is_400(client, mock_samples):
|
||||
mock_samples.find_sample.return_value = None
|
||||
with _as_user(["p12345"]):
|
||||
response = client.post("/sample/mount/999", headers=AUTH)
|
||||
response = client.post("/sample/mount", params={"dbid": 999}, headers=AUTH)
|
||||
assert response.status_code == 400
|
||||
assert response.json()["exception_class"] == "SampleException"
|
||||
|
||||
|
||||
def test_mount_against_shipped_catalogue(server_module, mock_aaredb):
|
||||
"""End-to-end over the real dummy_samples.json: owner succeeds, outsider is refused."""
|
||||
"""End-to-end over the real dummy_samples.json."""
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
with (
|
||||
patch.object(server_module, "AareWrapper", return_value=mock_aaredb),
|
||||
TestClient(server_module.app) as c,
|
||||
_as_user(["p12345"]),
|
||||
):
|
||||
assert c.post("/sample/mount/1", headers=AUTH).status_code == 200
|
||||
assert c.post("/sample/mount/4", headers=AUTH).status_code == 403
|
||||
assert c.post("/sample/mount/999", headers=AUTH).status_code == 400
|
||||
with _as_user(["p12345"]):
|
||||
# own sample, someone else's sample, nonexistent sample
|
||||
assert c.post("/sample/mount", params={"dbid": 1}, headers=AUTH).status_code == 200
|
||||
assert c.post("/sample/mount", params={"dbid": 4}, headers=AUTH).status_code == 403
|
||||
assert c.post("/sample/mount", params={"dbid": 999}, headers=AUTH).status_code == 400
|
||||
# reference tools are only found with reference=true, and belong to the beamline
|
||||
assert c.post("/sample/mount", params={"dbid": 9001}, headers=AUTH).status_code == 400
|
||||
ref = c.post("/sample/mount", params={"dbid": 9001, "reference": "true"}, headers=AUTH)
|
||||
assert ref.status_code == 403
|
||||
with _as_user([], staff=True):
|
||||
ref = c.post("/sample/mount", params={"dbid": 9001, "reference": "true"}, headers=AUTH)
|
||||
assert ref.status_code == 200
|
||||
assert ref.json()["location"]["segment"] == "X"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user