Merge branch 'start-gallery-thing' into 'v3'

Start implementing GalleryThing

See merge request openflexure/openflexure-microscope-server!576
This commit is contained in:
Joe Knapper 2026-05-07 09:51:47 +00:00
commit 906b8be82c
13 changed files with 321 additions and 104 deletions

View file

@ -1,6 +1,8 @@
"""Fixtures for all test suites."""
import json
import logging
import os
import re
from collections.abc import Iterable
from contextlib import contextmanager
@ -10,6 +12,24 @@ import pytest
from labthings_fastapi.testing import create_thing_without_server
from .shared_utils.lt_test_utils import LabThingsTestEnv
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.dirname(THIS_DIR)
SIM_CONFIG = os.path.join(REPO_ROOT, "ofm_config_simulation.json")
@pytest.fixture
def simulation_test_env():
"""Yield a server with the configuration from the simulation json."""
with open(SIM_CONFIG, "r", encoding="utf-8") as f_obj:
config_dict = json.load(f_obj)
with LabThingsTestEnv(
things=config_dict["things"],
application_config=config_dict["application_config"],
) as env:
yield env
@pytest.fixture
def check_side_effect(caplog):

View file

@ -12,7 +12,6 @@ it has been moved as it artificaially inflated coverage.
"""
import json
import os
import numpy as np
import piexif
@ -21,29 +20,11 @@ from PIL import Image
import labthings_fastapi as lt
from ..shared_utils.lt_test_utils import LabThingsTestEnv
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.dirname(os.path.dirname(THIS_DIR))
SIM_CONFIG = os.path.join(REPO_ROOT, "ofm_config_simulation.json")
@pytest.fixture
def test_env():
"""Yield a server with a very basic configuration."""
with open(SIM_CONFIG, "r", encoding="utf-8") as f_obj:
config_dict = json.load(f_obj)
with LabThingsTestEnv(
things=config_dict["things"],
application_config=config_dict["application_config"],
) as env:
yield env
def test_autofocus(test_env):
def test_autofocus(simulation_test_env):
"""Test Fast Autofocus can run doesn't raise an exception."""
stage = test_env.get_thing_client("stage")
autofocus = test_env.get_thing_client("autofocus")
stage = simulation_test_env.get_thing_client("stage")
autofocus = simulation_test_env.get_thing_client("autofocus")
assert stage.position["z"] == 0
# Autofocus 5 times and check each ends within 500 steps
for i in range(5):
@ -51,17 +32,17 @@ def test_autofocus(test_env):
assert abs(stage.position["z"]) < 500, f"Autofocus failed on iteration {i}"
def test_grab_jpeg(test_env):
def test_grab_jpeg(simulation_test_env):
"""Check that grab_jpeg returns a blob that can be opened."""
camera = test_env.get_thing_client("camera")
camera = simulation_test_env.get_thing_client("camera")
blob = camera.grab_jpeg()
image = Image.open(blob.open())
assert image.size == (820, 616)
def test_capture_jpeg_metadata(test_env):
def test_capture_jpeg_metadata(simulation_test_env):
"""Check that the position is encoded into the image metadata."""
camera = test_env.get_thing_client("camera")
camera = simulation_test_env.get_thing_client("camera")
blob = camera.capture_jpeg()
image = Image.open(blob.open())
exif_dict = piexif.load(image.info["exif"])
@ -72,9 +53,9 @@ def test_capture_jpeg_metadata(test_env):
assert image.size == (820, 616)
def test_stage(test_env):
def test_stage(simulation_test_env):
"""Test moving the stage forwards and backwards."""
stage = test_env.get_thing_client("stage")
stage = simulation_test_env.get_thing_client("stage")
start = stage.position
move = {"x": 1, "y": 2, "z": 3}
move_back = {"x": -1, "y": -2, "z": -3}
@ -95,20 +76,20 @@ def test_stage(test_env):
assert start["z"] == pos["z"]
def test_capture_array(test_env):
def test_capture_array(simulation_test_env):
"""Capture array from simulation and check the size is as expected."""
camera = test_env.get_thing_client("camera")
camera = simulation_test_env.get_thing_client("camera")
array = np.asarray(camera.capture_array())
assert array.shape == (616, 820, 3)
def test_camera_stage_mapping_calibration(test_env):
def test_camera_stage_mapping_calibration(simulation_test_env):
"""Check that camera stage mapping runs and returns the expected result."""
camera = test_env.get_thing_client("camera")
camera = simulation_test_env.get_thing_client("camera")
# Remove camera settling time for speed.
camera.settling_time = 0
csm = test_env.get_thing_client("camera_stage_mapping")
stage = test_env.get_thing_client("stage")
csm = simulation_test_env.get_thing_client("camera_stage_mapping")
stage = simulation_test_env.get_thing_client("stage")
# Check it starts uncalibrated
assert csm.calibration_required

View file

@ -0,0 +1,122 @@
"""Tests that captures have the expected metadata."""
import logging
from pydantic import BaseModel
from labthings_fastapi.testing import create_thing_without_server
from openflexure_microscope_server.things import OFMThing
from openflexure_microscope_server.things.gallery import (
GalleryCompatibleThing,
GalleryThing,
)
from ..shared_utils.lt_test_utils import LabThingsTestEnv
class MockGalleryData(BaseModel):
"""Mock gallery data."""
mock: str
foobar: int
class MinimalGalleryClass:
"""A class that provides data to the gallery but is NOT a thing.
This should fail the protocol check as it is not an OFMThing
"""
gallery_data_name: str = "Mock"
gallery_data_schema: type[BaseModel] = MockGalleryData
def get_data_for_gallery(self) -> list[BaseModel]:
"""Return a list of Mock Gallery Data."""
return [MockGalleryData(mock="mock", foobar="foobar")]
class MinimalGallerySource(OFMThing, MinimalGalleryClass):
"""Minimal example of a Thing that can show data in the gallery.
Mixes MinimalGalleryClass into OFMThing to be recognised by the protocol.
"""
show_data_in_gallery = True
class BadGallerySource(OFMThing):
"""An OFMThing that almost defines enough to show in the gallery.
Shouldn't match the protocol as ``gallery_data_name`` is missing.
"""
show_data_in_gallery = True
gallery_data_schema: type[BaseModel] = MockGalleryData
def get_data_for_gallery(self) -> list[BaseModel]:
"""Return a list of Mock Gallery Data."""
return [MockGalleryData(mock="mock", foobar="foobar")]
def test_gallery_compatible_protocol():
"""Check the gallery compatible protocol detects compatible classes only."""
# Minimal class has the gallery specific methods but is not an OFMThing.
assert not isinstance(MinimalGalleryClass(), GalleryCompatibleThing)
# BadGallerySource is an OFM Thing but is missing one of the required properties.
assert not isinstance(
create_thing_without_server(BadGallerySource), GalleryCompatibleThing
)
# MinimalGallerySource should match!
assert isinstance(
create_thing_without_server(MinimalGallerySource), GalleryCompatibleThing
)
def test_gallery_thing_finds_all_providers(simulation_test_env):
"""Check the gallery identifies the correct Things that will provide data."""
gallery = simulation_test_env.get_thing_by_name("gallery")
snake_workflow = simulation_test_env.get_thing_by_name("snake_workflow")
smart_scan = simulation_test_env.get_thing_by_name("smart_scan")
camera = simulation_test_env.get_thing_by_name("camera")
assert snake_workflow not in gallery.all_ofm_things.values()
assert camera in gallery.all_ofm_things.values()
assert smart_scan in gallery.all_ofm_things.values()
assert snake_workflow not in gallery.gallery_providing_things.values()
assert camera not in gallery.gallery_providing_things.values()
assert smart_scan in gallery.gallery_providing_things.values()
assert not isinstance(snake_workflow, GalleryCompatibleThing)
assert isinstance(smart_scan, GalleryCompatibleThing)
def test_gallery_logs_for_bad_providers(caplog):
"""Test that an error is logged if a gallery source doesn't match the protocol."""
# Create a config with the minimal Thing and the bad Thing
things = {
"minimal_thing": MinimalGallerySource,
"bad_thing": BadGallerySource,
"gallery": GalleryThing,
}
with caplog.at_level(logging.INFO):
# Start the server
with LabThingsTestEnv(
things=things, application_config={"data_folder": "./openflexure/data/"}
) as env:
gallery = env.get_thing_by_name("gallery")
# Minimal thing is listed as a gallery provider
assert "minimal_thing" in gallery.gallery_providing_things
# Bad thing isn't as the protocol doesn't match
assert "bad_thing" not in gallery.gallery_providing_things
# There is an error logged about bad_thing
assert len(caplog.records) == 1
record = caplog.records[0]
assert "Data from bad_thing cannot be shown in gallery" in record.message
assert record.levelname == "ERROR"