Rearrange Picamera tests to start using server context manager.

This commit is contained in:
Julian Stirling 2025-10-28 21:02:26 +00:00
parent 815b112069
commit 995a464ba2
2 changed files with 38 additions and 25 deletions

View file

@ -0,0 +1,36 @@
"""Utilities to help with testing the camera."""
from typing import Optional
import tempfile
from contextlib import contextmanager
from fastapi.testclient import TestClient
from labthings_fastapi.server import ThingServer
from labthings_fastapi.client import ThingClient
from openflexure_microscope_server.things.camera.picamera import StreamingPiCamera2
@contextmanager
def camera_test_client(settings_folder: Optional[str] = None):
"""Yield a camera ThingClient on a camera server.
This is a context manager not a pytest fixture as it needs to be created
multiple times in some tests.
"""
# Create a temp dir, if the setting folder is set it isn't really needed
# but doesn't add much overhead.
with tempfile.TemporaryDirectory() as tmpdir:
if settings_folder is None:
settings_folder = tmpdir
cam = StreamingPiCamera2()
server = ThingServer(settings_folder=settings_folder)
server.add_thing(cam, "/camera/")
with TestClient(server.app) as test_client:
client = ThingClient.from_url("/camera/", client=test_client)
yield client
del server
del cam

View file

@ -4,20 +4,15 @@ This can get very tedious. Recommend running pytest with -s option
to monitor progress. to monitor progress.
""" """
from typing import Optional, Any from typing import Any
import logging import logging
import time import time
import tempfile import tempfile
import os import os
import json import json
from contextlib import contextmanager
from fastapi.testclient import TestClient
from labthings_fastapi.server import ThingServer from .cam_test_utils import camera_test_client
from labthings_fastapi.client import ThingClient
from openflexure_microscope_server.things.camera.picamera import StreamingPiCamera2
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
@ -29,24 +24,6 @@ logging.basicConfig(level=logging.DEBUG)
EXPOSURE_TOL = 30 EXPOSURE_TOL = 30
@contextmanager
def camera_test_client(settings_folder: Optional[str] = None):
"""Yield a camera ThingClient on a camera server.
This is a context manager not a pytest fixture as it needs to be created
multiple times in some tests.
"""
cam = StreamingPiCamera2()
server = ThingServer(settings_folder=settings_folder)
server.add_thing(cam, "/camera/")
with TestClient(server.app) as test_client:
client = ThingClient.from_url("/camera/", client=test_client)
yield client
del server
del cam
def _test_exposure_time_drift(desired_time: int) -> None: def _test_exposure_time_drift(desired_time: int) -> None:
"""Capture 10 full res images and check that the exposure time remains constant. """Capture 10 full res images and check that the exposure time remains constant.