Autofix import order

This commit is contained in:
Julian Stirling 2025-12-02 16:26:15 +00:00
parent 98cdb276d8
commit 7bc4c514a6
59 changed files with 244 additions and 236 deletions

View file

@ -2,11 +2,10 @@
"""Create a list of the MRs into v3 (unless specified) since the last release.""" """Create a list of the MRs into v3 (unless specified) since the last release."""
import sys
import argparse import argparse
import sys
import gitlab import gitlab
from gitlab.exceptions import GitlabGetError from gitlab.exceptions import GitlabGetError
PROJECT_ID = 9238334 PROJECT_ID = 9238334

View file

@ -2,8 +2,8 @@
"""Check that the npm version string matches the Python version string exactly.""" """Check that the npm version string matches the Python version string exactly."""
import json import json
import tomllib
import os import os
import tomllib
with open("pyproject.toml", "rb") as toml_f: with open("pyproject.toml", "rb") as toml_f:
pyproject_data = tomllib.load(toml_f) pyproject_data = tomllib.load(toml_f)

View file

@ -1,8 +1,8 @@
"""Utilities to help with testing the camera.""" """Utilities to help with testing the camera."""
from typing import Optional
import tempfile import tempfile
from contextlib import contextmanager from contextlib import contextmanager
from typing import Optional
from fastapi.testclient import TestClient from fastapi.testclient import TestClient

View file

@ -1,7 +1,7 @@
"""Test data collection from the Raspberry Picamera.""" """Test data collection from the Raspberry Picamera."""
from PIL import Image
import numpy as np import numpy as np
from PIL import Image
def test_jpeg_and_array(picamera_client): def test_jpeg_and_array(picamera_client):

View file

@ -1,7 +1,7 @@
"""Test data collection from the Raspberry Picamera.""" """Test data collection from the Raspberry Picamera."""
from copy import deepcopy
import tempfile import tempfile
from copy import deepcopy
from .cam_test_utils import camera_test_client from .cam_test_utils import camera_test_client

View file

@ -4,13 +4,12 @@ This can get very tedious. Recommend running pytest with -s option
to monitor progress. to monitor progress.
""" """
from typing import Any
import logging
import time
import tempfile
import os
import json import json
import logging
import os
import tempfile
import time
from typing import Any
from .cam_test_utils import camera_test_client from .cam_test_utils import camera_test_client

View file

@ -10,7 +10,6 @@ from openflexure_microscope_server.things.camera import (
picamera_tuning_file_utils as tf_utils, picamera_tuning_file_utils as tf_utils,
) )
MODEL = Picamera2.global_camera_info()[0]["Model"] MODEL = Picamera2.global_camera_info()[0]["Model"]

View file

@ -7,11 +7,11 @@ For now, this file should be run directly rather than through a test framework.
They are designed to run on CI and should work on Linux or WSL for local debugging. They are designed to run on CI and should work on Linux or WSL for local debugging.
""" """
from typing import Optional
import subprocess
import os import os
import shutil import shutil
import subprocess
from time import sleep, time from time import sleep, time
from typing import Optional
from PIL import Image from PIL import Image

View file

@ -1,12 +1,12 @@
#! /usr/bin/env python3 #! /usr/bin/env python3
"""Run the Piamera tests and archive the results in the git repository.""" """Run the Piamera tests and archive the results in the git repository."""
import subprocess
import shutil
import os
import posixpath
import argparse import argparse
import json import json
import os
import posixpath
import shutil
import subprocess
import sys import sys
import zipfile import zipfile

View file

@ -10,15 +10,14 @@ If the static directory already exists and contains data, it will be removed bef
extraction. extraction.
""" """
import zipfile import argparse
import io import io
import sys
import os import os
import shutil import shutil
import argparse import sys
import zipfile
import gitlab import gitlab
from gitlab.exceptions import GitlabGetError from gitlab.exceptions import GitlabGetError
THIS_DIR = os.path.dirname(os.path.abspath(__file__)) THIS_DIR = os.path.dirname(os.path.abspath(__file__))

View file

@ -5,11 +5,13 @@ for analysis. Information from these images is used to detect whether an image f
current camera field of view contains sample. current camera field of view contains sample.
""" """
from typing import Optional, Any from typing import Any, Optional
import cv2 import cv2
import numpy as np import numpy as np
from pydantic import BaseModel, Field, ConfigDict from pydantic import BaseModel, ConfigDict, Field
from pydantic.errors import PydanticUserError from pydantic.errors import PydanticUserError
from labthings_fastapi.thing_description import type_to_dataschema from labthings_fastapi.thing_description import type_to_dataschema

View file

@ -12,11 +12,11 @@ output to STDOUT/STDERR are captured by ``systemd``. These can be viewed by usin
""" """
import logging import logging
from logging.handlers import RotatingFileHandler
import os import os
from logging.handlers import RotatingFileHandler
from fastapi.responses import PlainTextResponse
from fastapi import HTTPException from fastapi import HTTPException
from fastapi.responses import PlainTextResponse
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
OFM_LOG_FILE = None OFM_LOG_FILE = None

View file

@ -1,25 +1,24 @@
"""Functionality to manage file system operations for scan directories.""" """Functionality to manage file system operations for scan directories."""
from typing import Optional, Any, Mapping import json
import logging
import os import os
import re import re
import shutil import shutil
import zipfile
import threading import threading
import json import zipfile
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging from typing import Any, Mapping, Optional
from pydantic import ( from pydantic import (
BaseModel, BaseModel,
field_validator,
field_serializer,
ConfigDict, ConfigDict,
ValidationError, ValidationError,
field_serializer,
field_validator,
) )
from openflexure_microscope_server.utilities import requires_lock from openflexure_microscope_server.utilities import make_name_safe, requires_lock
from openflexure_microscope_server.utilities import make_name_safe
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)

View file

@ -9,9 +9,9 @@ subclassing the ScanPlanner
# would be to import Union and use a string. # would be to import Union and use a string.
from __future__ import annotations from __future__ import annotations
from typing import TypeAlias, Optional, Any
import logging import logging
from copy import copy from copy import copy
from typing import Any, Optional, TypeAlias
import numpy as np import numpy as np

View file

@ -2,20 +2,22 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional, Callable, Any
from functools import wraps
from copy import copy
import logging import logging
from argparse import Namespace from argparse import Namespace
from copy import copy
from functools import wraps
from typing import Any, Callable, Optional
import labthings_fastapi as lt
import uvicorn import uvicorn
from uvicorn.main import Server from uvicorn.main import Server
import labthings_fastapi as lt
from openflexure_microscope_server.utilities import load_patched_config from openflexure_microscope_server.utilities import load_patched_config
from .serve_static_files import add_static_files
from .legacy_api import add_v2_endpoints
from ..logging import configure_logging, retrieve_log, retrieve_log_from_file from ..logging import configure_logging, retrieve_log, retrieve_log_from_file
from .legacy_api import add_v2_endpoints
from .serve_static_files import add_static_files
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)

View file

@ -1,9 +1,11 @@
"""Provide endpoints that mimic the v2 API for OpenFlexure Connect discoverability.""" """Provide endpoints that mimic the v2 API for OpenFlexure Connect discoverability."""
import labthings_fastapi as lt
from fastapi import Response
from socket import gethostname from socket import gethostname
from fastapi import Response
import labthings_fastapi as lt
FAKE_ROUTES = [ FAKE_ROUTES = [
"/api/v2/", "/api/v2/",
"/api/v2/streams/snapshot", "/api/v2/streams/snapshot",

View file

@ -3,9 +3,9 @@
import os import os
from typing import Optional from typing import Optional
from fastapi import FastAPI
from fastapi.responses import FileResponse, RedirectResponse from fastapi.responses import FileResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI
THIS_DIR = os.path.dirname(os.path.abspath(__file__)) THIS_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_PATH = os.path.normpath(os.path.join(THIS_DIR, "..", "static")) STATIC_PATH = os.path.normpath(os.path.join(THIS_DIR, "..", "static"))

View file

@ -6,13 +6,13 @@ CPU intensity of stitching causing scanning problems due to the Python Global
Interpreter Lock (GIL). May be possible to shift to multiprocessing in the future. Interpreter Lock (GIL). May be possible to shift to multiprocessing in the future.
""" """
from typing import Optional, Any
import threading
import subprocess
import signal
import os import os
from io import TextIOWrapper
import shlex import shlex
import signal
import subprocess
import threading
from io import TextIOWrapper
from typing import Any, Optional
import labthings_fastapi as lt import labthings_fastapi as lt

View file

@ -7,22 +7,22 @@ of images (a 'z-stack').
See repository root for licensing information. See repository root for licensing information.
""" """
from contextlib import contextmanager
import logging import logging
import time
from typing import Annotated, Mapping, Optional, Sequence, Literal
import os import os
import time
from contextlib import contextmanager
from dataclasses import dataclass from dataclasses import dataclass
from typing import Annotated, Literal, Mapping, Optional, Sequence
from fastapi import Depends
import numpy as np import numpy as np
from pydantic import BaseModel, field_validator, computed_field, model_validator from fastapi import Depends
from pydantic import BaseModel, computed_field, field_validator, model_validator
import labthings_fastapi as lt import labthings_fastapi as lt
from labthings_fastapi.types.numpy import NDArray from labthings_fastapi.types.numpy import NDArray
from .camera import RawCameraDependency as RawCamera
from .camera import CameraDependency as CameraClient from .camera import CameraDependency as CameraClient
from .camera import RawCameraDependency as RawCamera
from .stage import StageDependency as Stage from .stage import StageDependency as Stage
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)

View file

@ -7,31 +7,32 @@ See repository root for licensing information.
""" """
from __future__ import annotations from __future__ import annotations
from typing import Literal, Optional, Tuple, Any, Mapping
from types import TracebackType
import json
import io import io
import time import json
import logging import logging
from datetime import datetime
import tempfile
import os import os
import tempfile
import time
from datetime import datetime
from types import TracebackType
from typing import Any, Literal, Mapping, Optional, Tuple
import numpy as np import numpy as np
from pydantic import RootModel
from PIL import Image
import piexif import piexif
from PIL import Image
from pydantic import RootModel
import labthings_fastapi as lt import labthings_fastapi as lt
from labthings_fastapi.types.numpy import NDArray from labthings_fastapi.types.numpy import NDArray
from openflexure_microscope_server.ui import ActionButton, PropertyControl
from openflexure_microscope_server.background_detect import ( from openflexure_microscope_server.background_detect import (
ColourChannelDetectLUV,
ChannelDeviationLUV,
BackgroundDetectAlgorithm, BackgroundDetectAlgorithm,
BackgroundDetectorStatus, BackgroundDetectorStatus,
ChannelDeviationLUV,
ColourChannelDetectLUV,
) )
from openflexure_microscope_server.ui import ActionButton, PropertyControl
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)

View file

@ -9,9 +9,9 @@ See repository root for licensing information.
from __future__ import annotations from __future__ import annotations
import logging import logging
from typing import Literal, Optional
from types import TracebackType
from threading import Thread from threading import Thread
from types import TracebackType
from typing import Literal, Optional
import cv2 import cv2
from PIL import Image from PIL import Image

View file

@ -15,39 +15,40 @@ https://datasheets.raspberrypi.com/camera/raspberry-pi-camera-guide.pdf
""" """
from __future__ import annotations from __future__ import annotations
from typing import Annotated, Iterator, Literal, Mapping, Optional, Any
from types import TracebackType import copy
import json import json
import logging import logging
import os import os
import copy
import tempfile import tempfile
import time import time
from contextlib import contextmanager from contextlib import contextmanager
from threading import RLock from threading import RLock
from types import TracebackType
from typing import Annotated, Any, Iterator, Literal, Mapping, Optional
from pydantic import BaseModel, BeforeValidator
import numpy as np import numpy as np
from PIL import Image
from picamera2 import Picamera2 from picamera2 import Picamera2
from picamera2.encoders import MJPEGEncoder from picamera2.encoders import MJPEGEncoder
from picamera2.outputs import Output from picamera2.outputs import Output
from PIL import Image
from pydantic import BaseModel, BeforeValidator
import labthings_fastapi as lt import labthings_fastapi as lt
from labthings_fastapi.exceptions import NotConnectedToServerError from labthings_fastapi.exceptions import NotConnectedToServerError
from openflexure_microscope_server.background_detect import ChannelBlankError
from openflexure_microscope_server.ui import ( from openflexure_microscope_server.ui import (
ActionButton, ActionButton,
PropertyControl, PropertyControl,
action_button_for, action_button_for,
property_control_for, property_control_for,
) )
from openflexure_microscope_server.background_detect import ChannelBlankError
from . import ArrayModel, BaseCamera
from . import picamera_recalibrate_utils as recalibrate_utils from . import picamera_recalibrate_utils as recalibrate_utils
from . import picamera_tuning_file_utils as tf_utils from . import picamera_tuning_file_utils as tf_utils
from . import BaseCamera, ArrayModel
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
SUPPORTED_CAMS_SENSOR_INFO = { SUPPORTED_CAMS_SENSOR_INFO = {

View file

@ -41,16 +41,17 @@ reliable. The three steps above can be accomplished by:
# ruff: noqa: N806 N803 # ruff: noqa: N806 N803
from __future__ import annotations from __future__ import annotations
import gc import gc
import logging import logging
import time import time
from typing import List, Tuple from typing import List, Tuple
from pydantic import BaseModel
import numpy as np
from scipy.ndimage import zoom
from picamera2 import Picamera2 import numpy as np
import picamera2 import picamera2
from picamera2 import Picamera2
from pydantic import BaseModel
from scipy.ndimage import zoom
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)

View file

@ -3,14 +3,13 @@
The functions that edit the tuning files return a new dictionary that is updated. The functions that edit the tuning files return a new dictionary that is updated.
""" """
from typing import Any, Optional
from copy import deepcopy
import os
import json import json
import os
from copy import deepcopy
from typing import Any, Optional
from pydantic import BaseModel
import numpy as np import numpy as np
from pydantic import BaseModel
THIS_DIR = os.path.dirname(os.path.abspath(__file__)) THIS_DIR = os.path.dirname(os.path.abspath(__file__))

View file

@ -7,12 +7,13 @@ See repository root for licensing information.
""" """
from __future__ import annotations from __future__ import annotations
import logging
from typing import Literal, Optional, Mapping
from types import TracebackType
from threading import Thread
import time
import io import io
import logging
import time
from threading import Thread
from types import TracebackType
from typing import Literal, Mapping, Optional
import numpy as np import numpy as np
from PIL import Image, ImageFilter from PIL import Image, ImageFilter
@ -26,8 +27,8 @@ from openflexure_microscope_server.ui import (
property_control_for, property_control_for,
) )
from . import BaseCamera, ArrayModel
from ..stage import BaseStage from ..stage import BaseStage
from . import ArrayModel, BaseCamera
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)

View file

@ -15,23 +15,23 @@ from typing import (
Any, Any,
Dict, Dict,
List, List,
Mapping,
NamedTuple, NamedTuple,
Optional, Optional,
Tuple, Tuple,
Mapping,
) )
from fastapi import HTTPException
import numpy as np import numpy as np
from fastapi import HTTPException
import labthings_fastapi as lt
from camera_stage_mapping.camera_stage_calibration_1d import ( from camera_stage_mapping.camera_stage_calibration_1d import (
calibrate_backlash_1d, calibrate_backlash_1d,
image_to_stage_displacement_from_1d, image_to_stage_displacement_from_1d,
) )
from camera_stage_mapping.exceptions import MappingError
import labthings_fastapi as lt
from labthings_fastapi.types.numpy import DenumpifyingDict
from camera_stage_mapping.camera_stage_tracker import Tracker from camera_stage_mapping.camera_stage_tracker import Tracker
from camera_stage_mapping.exceptions import MappingError
from labthings_fastapi.types.numpy import DenumpifyingDict
from .camera import CameraDependency as CameraClient from .camera import CameraDependency as CameraClient
from .stage import StageDependency as Stage from .stage import StageDependency as Stage

View file

@ -7,37 +7,35 @@ It also controls external processes for live stitching composite images, and
the creation of the final stitched images. the creation of the final stitched images.
""" """
from typing import (
Optional,
Self,
TypeVar,
ParamSpec,
Callable,
Concatenate,
Mapping,
Any,
)
import threading
import os import os
import threading
import time import time
from datetime import datetime from datetime import datetime
from subprocess import SubprocessError from subprocess import SubprocessError
from typing import (
Any,
Callable,
Concatenate,
Mapping,
Optional,
ParamSpec,
Self,
TypeVar,
)
import numpy as np
from fastapi import HTTPException from fastapi import HTTPException
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
import numpy as np
from pydantic import BaseModel from pydantic import BaseModel
import labthings_fastapi as lt import labthings_fastapi as lt
from openflexure_microscope_server import scan_directories from openflexure_microscope_server import scan_directories, scan_planners, stitching
from openflexure_microscope_server import scan_planners
from openflexure_microscope_server import stitching
# Things # Things
from .autofocus import AutofocusThing, StackParams from .autofocus import AutofocusThing, StackParams
from .camera_stage_mapping import CameraStageMapper
from .camera import CameraDependency as CameraClient from .camera import CameraDependency as CameraClient
from .camera_stage_mapping import CameraStageMapper
from .stage import StageDependency as StageDep from .stage import StageDependency as StageDep
T = TypeVar("T") T = TypeVar("T")

View file

@ -10,8 +10,9 @@ As the object will be used as a context manager create the hardware connection i
""" """
from __future__ import annotations from __future__ import annotations
from collections.abc import Sequence, Mapping
from typing import Literal, Never, Any from collections.abc import Mapping, Sequence
from typing import Any, Literal, Never
import labthings_fastapi as lt import labthings_fastapi as lt

View file

@ -2,10 +2,10 @@
from __future__ import annotations from __future__ import annotations
from typing import Optional, Any
from types import TracebackType
from collections.abc import Mapping
import time import time
from collections.abc import Mapping
from types import TracebackType
from typing import Any, Optional
import labthings_fastapi as lt import labthings_fastapi as lt

View file

@ -1,18 +1,20 @@
"""Provide a LabThings-FastAPI interface to the Sangaboard motor controller.""" """Provide a LabThings-FastAPI interface to the Sangaboard motor controller."""
from __future__ import annotations from __future__ import annotations
import logging import logging
import threading import threading
import time import time
from copy import copy
from typing import Iterator, Literal, Optional, Any
from types import TracebackType
from contextlib import contextmanager
from collections.abc import Mapping from collections.abc import Mapping
from contextlib import contextmanager
from copy import copy
from types import TracebackType
from typing import Any, Iterator, Literal, Optional
import semver import semver
import sangaboard
import labthings_fastapi as lt import labthings_fastapi as lt
import sangaboard
from . import BaseStage from . import BaseStage

View file

@ -13,20 +13,20 @@ is tracked and an error is raised if it exceeds a minimum amount. Currently
this is 10% of the expected motion is the measured axis. this is 10% of the expected motion is the measured axis.
""" """
from typing import Literal, Any, Optional, overload
import time import time
from dataclasses import dataclass from dataclasses import dataclass
from threading import Lock from threading import Lock
from typing import Any, Literal, Optional, overload
import numpy as np import numpy as np
from camera_stage_mapping import fft_image_tracking
import labthings_fastapi as lt import labthings_fastapi as lt
from camera_stage_mapping import fft_image_tracking
# Things # Things
from .autofocus import AutofocusThing from .autofocus import AutofocusThing
from .camera_stage_mapping import CameraStageMapper
from .camera import CameraDependency as CamDep from .camera import CameraDependency as CamDep
from .camera_stage_mapping import CameraStageMapper
from .stage import StageDependency as StageDep from .stage import StageDependency as StageDep
CSMDep = lt.deps.direct_thing_client_dependency( CSMDep = lt.deps.direct_thing_client_dependency(

View file

@ -4,14 +4,14 @@ A module to control the underlying microscope system and to expose information a
the microscope, server, and thing states to the web API. the microscope, server, and thing states to the web API.
""" """
from collections.abc import Mapping
import socket
from typing import Optional, Any
from uuid import UUID, uuid4
import subprocess
import os import os
from signal import SIGTERM import socket
import subprocess
import time import time
from collections.abc import Mapping
from signal import SIGTERM
from typing import Any, Optional
from uuid import UUID, uuid4
from pydantic import BaseModel from pydantic import BaseModel

View file

@ -1,6 +1,6 @@
"""Functionality for communicating the required user interface for a thing.""" """Functionality for communicating the required user interface for a thing."""
from typing import Callable, Any from typing import Any, Callable
from pydantic import BaseModel from pydantic import BaseModel

View file

@ -1,26 +1,26 @@
"""Utility functions and classes.""" """Utility functions and classes."""
from typing import ( import json
TypeVar, import logging
Callable,
ParamSpec,
Optional,
Any,
Concatenate,
Self,
overload,
TypeAlias,
Literal,
)
import os import os
import re import re
import sys import sys
from threading import Thread
import logging
from importlib.metadata import version
import tomllib import tomllib
from functools import wraps from functools import wraps
import json from importlib.metadata import version
from threading import Thread
from typing import (
Any,
Callable,
Concatenate,
Literal,
Optional,
ParamSpec,
Self,
TypeAlias,
TypeVar,
overload,
)
from pydantic import BaseModel from pydantic import BaseModel

View file

@ -7,11 +7,12 @@ The mocks do not subclass Things. Instead, they return predefined
answers to functions. answers to functions.
""" """
from unittest.mock import Mock, PropertyMock
from openflexure_microscope_server.background_detect import ( from openflexure_microscope_server.background_detect import (
BackgroundDetectorStatus, BackgroundDetectorStatus,
ColourChannelDetectSettings, ColourChannelDetectSettings,
) )
from unittest.mock import Mock, PropertyMock
class MockCameraThing(Mock): class MockCameraThing(Mock):

View file

@ -3,8 +3,8 @@
This doesn't check the behaviour of the JPEG shaprness monitor. This doesn't check the behaviour of the JPEG shaprness monitor.
""" """
import pytest
import numpy as np import numpy as np
import pytest
from openflexure_microscope_server.things.autofocus import ( from openflexure_microscope_server.things.autofocus import (
AutofocusThing, AutofocusThing,

View file

@ -5,19 +5,19 @@ This tests both the base class an individual algorithms.
import re import re
import numpy as np
import pytest import pytest
from pydantic import BaseModel from pydantic import BaseModel
import numpy as np
from openflexure_microscope_server.background_detect import ( from openflexure_microscope_server.background_detect import (
MissingBackgroundDataError,
BackgroundDetectAlgorithm, BackgroundDetectAlgorithm,
ChannelDistributions,
ColourChannelDetectSettings,
ColourChannelDetectLUV,
_chunked_stds,
ChannelDeviationLUV,
ChannelBlankError, ChannelBlankError,
ChannelDeviationLUV,
ChannelDistributions,
ColourChannelDetectLUV,
ColourChannelDetectSettings,
MissingBackgroundDataError,
_chunked_stds,
) )
RNG = np.random.default_rng() RNG = np.random.default_rng()

View file

@ -3,9 +3,9 @@
import tempfile import tempfile
from contextlib import contextmanager from contextlib import contextmanager
import numpy as np
import pytest import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
import numpy as np
from PIL import Image from PIL import Image
import labthings_fastapi as lt import labthings_fastapi as lt

View file

@ -3,9 +3,8 @@
from random import randint from random import randint
import numpy as np import numpy as np
from PIL import Image
import pytest import pytest
from PIL import Image
from openflexure_microscope_server.things.camera import ( from openflexure_microscope_server.things.camera import (
CameraMemoryBuffer, CameraMemoryBuffer,

View file

@ -7,8 +7,8 @@ on camera functionality using the simulation camera are in "test_camera".
import pytest import pytest
from openflexure_microscope_server.things.camera import BaseCamera from openflexure_microscope_server.things.camera import BaseCamera
from openflexure_microscope_server.things.camera.simulation import SimulatedCamera
from openflexure_microscope_server.things.camera.opencv import OpenCVCamera from openflexure_microscope_server.things.camera.opencv import OpenCVCamera
from openflexure_microscope_server.things.camera.simulation import SimulatedCamera
@pytest.fixture @pytest.fixture

View file

@ -1,10 +1,11 @@
"""Test the configuration handling functions in utilities.""" """Test the configuration handling functions in utilities."""
import pytest
import os
import json import json
import os
from json import JSONDecodeError from json import JSONDecodeError
import pytest
from openflexure_microscope_server import utilities from openflexure_microscope_server import utilities

View file

@ -12,18 +12,18 @@ import json
import os import os
import tempfile import tempfile
from fastapi.testclient import TestClient
from PIL import Image
import numpy as np import numpy as np
import piexif import piexif
import pytest import pytest
from fastapi.testclient import TestClient
from PIL import Image
import labthings_fastapi as lt import labthings_fastapi as lt
from openflexure_microscope_server.things.camera.simulation import SimulatedCamera
from openflexure_microscope_server.things.stage.dummy import DummyStage
from openflexure_microscope_server.things.autofocus import AutofocusThing from openflexure_microscope_server.things.autofocus import AutofocusThing
from openflexure_microscope_server.things.camera.simulation import SimulatedCamera
from openflexure_microscope_server.things.camera_stage_mapping import CameraStageMapper from openflexure_microscope_server.things.camera_stage_mapping import CameraStageMapper
from openflexure_microscope_server.things.stage.dummy import DummyStage
@pytest.fixture @pytest.fixture

View file

@ -1,7 +1,7 @@
"""Test server booting and shut down.""" """Test server booting and shut down."""
from socket import gethostname
import asyncio import asyncio
from socket import gethostname
# Import as ofm server to attempt to minimise confusion with server as a var in other # Import as ofm server to attempt to minimise confusion with server as a var in other
# functions and also FastAPI `Server`. # functions and also FastAPI `Server`.

View file

@ -1,12 +1,12 @@
"""Test the server's logging configuration and handling.""" """Test the server's logging configuration and handling."""
import logging
import os import os
import tempfile import tempfile
import logging
from fastapi.responses import PlainTextResponse
from fastapi import HTTPException
import pytest import pytest
from fastapi import HTTPException
from fastapi.responses import PlainTextResponse
from openflexure_microscope_server import logging as ofm_logging from openflexure_microscope_server import logging as ofm_logging

View file

@ -2,9 +2,8 @@
from copy import deepcopy from copy import deepcopy
import pytest
import numpy as np import numpy as np
import pytest
from openflexure_microscope_server.things.camera import ( from openflexure_microscope_server.things.camera import (
picamera_tuning_file_utils as tf_utils, picamera_tuning_file_utils as tf_utils,

View file

@ -5,9 +5,9 @@ import logging
import pytest import pytest
from openflexure_microscope_server.things.stage.sangaboard import ( from openflexure_microscope_server.things.stage.sangaboard import (
SangaboardThing,
REQUIRED_VERSION,
RECOMMENDED_VERSION, RECOMMENDED_VERSION,
REQUIRED_VERSION,
SangaboardThing,
) )

View file

@ -1,8 +1,8 @@
"""Test the functionality in the scan_directories module.""" """Test the functionality in the scan_directories module."""
from datetime import datetime, timedelta
from copy import copy
import json import json
from copy import copy
from datetime import datetime, timedelta
from math import floor from math import floor
from openflexure_microscope_server.scan_directories import ScanData from openflexure_microscope_server.scan_directories import ScanData

View file

@ -1,24 +1,24 @@
"""Test the functionality in the scan_directories module.""" """Test the functionality in the scan_directories module."""
import tempfile
import os
import math
import shutil
import logging
import random
import time
import json import json
import logging
import math
import os
import random
import shutil
import tempfile
import time
from collections import namedtuple from collections import namedtuple
import pytest import pytest
from openflexure_microscope_server.scan_directories import ( from openflexure_microscope_server.scan_directories import (
ScanDirectoryManager, SCAN_DATA_FILENAME,
NotEnoughFreeSpaceError,
ScanDirectory, ScanDirectory,
ScanDirectoryManager,
ScanInfo, ScanInfo,
get_files_in_zip, get_files_in_zip,
NotEnoughFreeSpaceError,
SCAN_DATA_FILENAME,
) )
from .test_scan_data import _fake_scan_data from .test_scan_data import _fake_scan_data

View file

@ -4,10 +4,12 @@ As well as low level function by function tests, this test suite also provides t
that simulate scanning a sample, checking that the expected path is followed. that simulate scanning a sample, checking that the expected path is followed.
""" """
import pytest
from copy import copy from copy import copy
import pytest
from openflexure_microscope_server import scan_planners from openflexure_microscope_server import scan_planners
from .utilities import scan_test_helpers from .utilities import scan_test_helpers

View file

@ -1,9 +1,9 @@
"""Test the code that mounts static files to the server, without creating a server.""" """Test the code that mounts static files to the server, without creating a server."""
import asyncio
import os import os
import shutil import shutil
import tempfile import tempfile
import asyncio
import pytest import pytest
from starlette.responses import FileResponse, RedirectResponse from starlette.responses import FileResponse, RedirectResponse

View file

@ -1,7 +1,7 @@
"""Test server booting and shut down.""" """Test server booting and shut down."""
import os
import json import json
import os
from copy import deepcopy from copy import deepcopy
import pytest import pytest

View file

@ -13,31 +13,31 @@ For these tests to reliably represent real behaviour the mock Things will need t
be tested for matching signatures with dynamically generated clients. be tested for matching signatures with dynamically generated clients.
""" """
from typing import Callable, Optional import logging
import tempfile
import os import os
import shutil import shutil
import logging import tempfile
from datetime import datetime from datetime import datetime
from typing import Callable, Optional
from fastapi import HTTPException
import pytest import pytest
from fastapi import HTTPException
from labthings_fastapi.exceptions import InvocationCancelledError from labthings_fastapi.exceptions import InvocationCancelledError
from openflexure_microscope_server.things.smart_scan import (
SmartScanThing,
ScanNotRunningError,
)
from openflexure_microscope_server.scan_directories import ( from openflexure_microscope_server.scan_directories import (
ScanData,
NotEnoughFreeSpaceError, NotEnoughFreeSpaceError,
ScanData,
)
from openflexure_microscope_server.things.smart_scan import (
ScanNotRunningError,
SmartScanThing,
) )
from .mock_things.mock_csm import MockCSMThing
from .mock_things.mock_autofocus import MockAutoFocusThing from .mock_things.mock_autofocus import MockAutoFocusThing
from .mock_things.mock_stage import MockStageThing
from .mock_things.mock_camera import MockCameraThing from .mock_things.mock_camera import MockCameraThing
from .mock_things.mock_csm import MockCSMThing
from .mock_things.mock_stage import MockStageThing
# A global logger to pass in as an Invocation Logger # A global logger to pass in as an Invocation Logger
LOGGER = logging.getLogger("mock-invocation_logger") LOGGER = logging.getLogger("mock-invocation_logger")

View file

@ -1,31 +1,32 @@
"""Tests for the smart and fast stacking.""" """Tests for the smart and fast stacking."""
from typing import Optional import logging
import tempfile import tempfile
from random import randint from random import randint
import logging from typing import Optional
import pytest
import numpy as np import numpy as np
from hypothesis import given, strategies as st import pytest
from fastapi.testclient import TestClient from fastapi.testclient import TestClient
from hypothesis import given
from hypothesis import strategies as st
import labthings_fastapi as lt import labthings_fastapi as lt
from openflexure_microscope_server.scan_directories import IMAGE_REGEX
from openflexure_microscope_server.things.autofocus import ( from openflexure_microscope_server.things.autofocus import (
AutofocusThing, EXTRA_STACK_CAPTURES,
StackParams,
CaptureInfo,
MIN_TEST_IMAGE_COUNT,
MAX_TEST_IMAGE_COUNT, MAX_TEST_IMAGE_COUNT,
MIN_TEST_IMAGE_COUNT,
AutofocusThing,
CaptureInfo,
NotAPeakError,
StackParams,
_count_turning_points,
_get_capture_by_id, _get_capture_by_id,
_get_capture_index_by_id, _get_capture_index_by_id,
EXTRA_STACK_CAPTURES,
NotAPeakError,
_get_peak_turning_point, _get_peak_turning_point,
_count_turning_points,
) )
from openflexure_microscope_server.scan_directories import IMAGE_REGEX
LOGGER = logging.getLogger("mock-invocation_logger") LOGGER = logging.getLogger("mock-invocation_logger")
RANDOM_GENERATOR = np.random.default_rng() RANDOM_GENERATOR = np.random.default_rng()

View file

@ -1,12 +1,13 @@
"""Test the stage without creating a full HTTP server and socket connection.""" """Test the stage without creating a full HTTP server and socket connection."""
import tempfile
import itertools import itertools
import tempfile
from fastapi.testclient import TestClient
import pytest import pytest
from fastapi.testclient import TestClient
from httpx import HTTPStatusError from httpx import HTTPStatusError
from hypothesis import given, settings, HealthCheck, strategies as st from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
import labthings_fastapi as lt import labthings_fastapi as lt
from labthings_fastapi.exceptions import NotConnectedToServerError from labthings_fastapi.exceptions import NotConnectedToServerError
@ -17,7 +18,6 @@ from openflexure_microscope_server.things.stage import (
) )
from openflexure_microscope_server.things.stage.dummy import DummyStage from openflexure_microscope_server.things.stage.dummy import DummyStage
from .mock_things.mock_cancel import MockCancel from .mock_things.mock_cancel import MockCancel
# Keep the size and number of moves fairly small or the tests can take forever # Keep the size and number of moves fairly small or the tests can take forever

View file

@ -1,13 +1,13 @@
"""File contains unit tests for stage_measure.""" """File contains unit tests for stage_measure."""
from copy import copy
import logging
import dataclasses import dataclasses
import logging
import tempfile import tempfile
from copy import copy
from fastapi.testclient import TestClient
import numpy as np import numpy as np
import pytest import pytest
from fastapi.testclient import TestClient
import labthings_fastapi as lt import labthings_fastapi as lt

View file

@ -6,20 +6,20 @@ generated, and the subprocess calling works as expected.
import logging import logging
import os import os
from copy import copy
import uuid
import threading import threading
import time import time
import uuid
from copy import copy
import pytest import pytest
import labthings_fastapi as lt import labthings_fastapi as lt
from openflexure_microscope_server.stitching import ( from openflexure_microscope_server.stitching import (
BaseStitcher,
PreviewStitcher,
FinalStitcher,
STITCHING_RESOLUTION, STITCHING_RESOLUTION,
BaseStitcher,
FinalStitcher,
PreviewStitcher,
StitcherValidationError, StitcherValidationError,
) )

View file

@ -1,16 +1,16 @@
"""Tests that version strings can be produced reliably.""" """Tests that version strings can be produced reliably."""
import subprocess import logging
import os import os
import re import re
import tempfile
import shutil import shutil
import subprocess
import tempfile
import warnings import warnings
import logging
import pytest
from hypothesis import strategies as st from hypothesis import strategies as st
from hypothesis.errors import NonInteractiveExampleWarning from hypothesis.errors import NonInteractiveExampleWarning
import pytest
from openflexure_microscope_server import utilities from openflexure_microscope_server import utilities

View file

@ -4,8 +4,8 @@ At the top level are some basic testing functions. More specific testing utiliti
provided by modules inside the package. provided by modules inside the package.
""" """
from typing import Protocol, Iterable
from collections.abc import Hashable from collections.abc import Hashable
from typing import Iterable, Protocol
class SizedIterableHashable(Iterable[Hashable], Protocol): class SizedIterableHashable(Iterable[Hashable], Protocol):

View file

@ -11,11 +11,11 @@ import os
import pickle import pickle
import numpy as np import numpy as np
from scipy import interpolate
from matplotlib import pyplot as plt from matplotlib import pyplot as plt
from matplotlib.path import Path as MatPath
from matplotlib.patches import PathPatch
from matplotlib.figure import Figure from matplotlib.figure import Figure
from matplotlib.patches import PathPatch
from matplotlib.path import Path as MatPath
from scipy import interpolate
from openflexure_microscope_server import scan_planners from openflexure_microscope_server import scan_planners
@ -145,8 +145,8 @@ def example_smart_spiral(
def profile_example_smart_spiral(): def profile_example_smart_spiral():
"""Profile running an example scan and print the cumulative profile stats.""" """Profile running an example scan and print the cumulative profile stats."""
import pstats
import cProfile import cProfile
import pstats
profiler = cProfile.Profile() profiler = cProfile.Profile()
profiler.runcall(example_smart_spiral) profiler.runcall(example_smart_spiral)