Further improve picamera tests to reuse fixtures and context managers.

This commit is contained in:
Julian Stirling 2025-10-28 21:35:20 +00:00
parent 995a464ba2
commit 2010e8eeb2
4 changed files with 51 additions and 67 deletions

View file

@ -1,52 +1,29 @@
"""Test data collection from the Raspberry Picamera."""
from fastapi.testclient import TestClient
from PIL import Image
import numpy as np
import pytest
import labthings_fastapi as lt
from openflexure_microscope_server.things.camera.picamera import StreamingPiCamera2
@pytest.fixture(scope="module")
def client() -> lt.ThingClient:
"""Initialise a test client for the StreamingPiCamera2 Thing.
This fixture:
* Sets up a ThingServer,
* Registers a StreamingPiCamera2 instance at the "/camera/" endpoint
* Provides a ThingClient for interacting with it during tests.
"""
server = lt.ThingServer()
server.add_thing(StreamingPiCamera2(), "/camera/")
with TestClient(server.app) as test_client:
client = lt.ThingClient.from_url("/camera/", client=test_client)
yield client
def test_jpeg_and_array(client):
def test_jpeg_and_array(picamera_client):
"""Check that a jpeg grabbed from the stream is the same size as other captures.
Compare it to an array capture and a jpeg capture.
"""
# Grab a jpeg from the stream
blob = client.grab_jpeg()
blob = picamera_client.grab_jpeg()
mjpeg_frame = Image.open(blob.open())
# Verify throws an error if there are issues with the image
mjpeg_frame.verify()
assert mjpeg_frame.format == "JPEG"
# Capture a jpeg
blob = client.capture_jpeg(stream_name="main")
blob = picamera_client.capture_jpeg(stream_name="main")
jpeg_capture = Image.open(blob.open())
jpeg_capture.verify()
assert jpeg_capture.format == "JPEG"
# Capture an array
arrlist = client.capture_array(stream_name="main")
arrlist = picamera_client.capture_array(stream_name="main")
array_main = np.array(arrlist)
# Verify image sizes are the same