Skip to content

Commit

Permalink
Add comment for RotationDirection (#979)
Browse files Browse the repository at this point in the history
* Add comment for RotationDirection

* Make ruff 0.9.0 happy
  • Loading branch information
rtuck99 authored Jan 9, 2025
1 parent a7a01e7 commit bbd76c6
Show file tree
Hide file tree
Showing 15 changed files with 55 additions and 50 deletions.
6 changes: 3 additions & 3 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def patched_open(*args, **kwargs):
requested_path = Path(args[0])
if requested_path.is_absolute():
for p in BANNED_PATHS:
assert not requested_path.is_relative_to(
p
), f"Attempt to open {requested_path} from inside a unit test"
assert not requested_path.is_relative_to(p), (
f"Attempt to open {requested_path} from inside a unit test"
)
return unpatched_open(*args, **kwargs)

with patch("builtins.open", side_effect=patched_open):
Expand Down
6 changes: 3 additions & 3 deletions src/dodal/common/crystal_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def make_crystal_metadata_from_material(
d_spacing = d_spacing_param or CrystalMetadata.calculate_default_d_spacing(
material.value.lattice_parameter, reflection_plane
)
assert all(
isinstance(i, int) and i > 0 for i in reflection_plane
), "Reflection plane indices must be positive integers"
assert all(isinstance(i, int) and i > 0 for i in reflection_plane), (
"Reflection plane indices must be positive integers"
)
return CrystalMetadata(usage, material.value.name, reflection_plane, d_spacing)
4 changes: 3 additions & 1 deletion src/dodal/common/udc_directory_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ async def update(self, *, directory: Path, suffix: str = "", **kwargs):
self._filename_provider.suffix = suffix

def __call__(self, device_name: str | None = None) -> PathInfo:
assert self._output_directory, "Directory unknown for PandA to write into, update() needs to be called at least once"
assert self._output_directory, (
"Directory unknown for PandA to write into, update() needs to be called at least once"
)
return PathInfo(
directory_path=self._output_directory,
filename=self._filename_provider(device_name),
Expand Down
2 changes: 1 addition & 1 deletion src/dodal/devices/attenuator/attenuator.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def __init__(
with self.add_children_as_readables():
self.filters: DeviceVector[FilterMotor] = DeviceVector(
{
index: FilterMotor(f"{prefix}MP{index+1}:", filter, name)
index: FilterMotor(f"{prefix}MP{index + 1}:", filter, name)
for index, filter in enumerate(filter_selection)
}
)
Expand Down
2 changes: 1 addition & 1 deletion src/dodal/devices/bimorph_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ async def set(self, value: Mapping[int, float], tolerance: float = 0.0001) -> No

if any(key not in self.channels for key in value):
raise ValueError(
f"Attempting to put to non-existent channels: {[key for key in value if (key not in self.channels)]}"
f"Attempting to put to non-existent channels: {[key for key in value if (key not in self.channels)]}"
)

# Write target voltages:
Expand Down
6 changes: 3 additions & 3 deletions src/dodal/devices/eiger_odin.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ def check_frames_dropped(self) -> tuple[bool, str]:
def wait_for_no_errors(self, timeout) -> dict[SubscriptionStatus, str]:
errors = {}
for node_number, node_pv in enumerate(self.nodes):
errors[
await_value(node_pv.error_status, False, timeout)
] = f"Filewriter {node_number} is in an error state with error message\
errors[await_value(node_pv.error_status, False, timeout)] = (
f"Filewriter {node_number} is in an error state with error message\
- {node_pv.error_message.get()}"
)

return errors

Expand Down
7 changes: 6 additions & 1 deletion src/dodal/devices/zebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ class I24Axes:


class RotationDirection(StrictEnum):
"""
Defines for a swept angle whether the scan width (sweep) is to be added or subtracted from
the initial angle to obtain the final angle.
"""

POSITIVE = "Positive"
NEGATIVE = "Negative"

Expand Down Expand Up @@ -281,7 +286,7 @@ def __str__(self) -> str:
for input, (source, invert) in enumerate(
zip(self.sources, self.invert, strict=False)
):
input_strings.append(f"INP{input+1}={'!' if invert else ''}{source}")
input_strings.append(f"INP{input + 1}={'!' if invert else ''}{source}")

return ", ".join(input_strings)

Expand Down
4 changes: 2 additions & 2 deletions src/dodal/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def set_up_graylog_handler(logger: Logger, host: str, port: int):
def set_up_INFO_file_handler(logger, path: Path, filename: str):
"""Set up a file handler for the logger, at INFO level, which will keep 30 days
of logs, rotating once per day. Creates the directory if necessary."""
print(f"Logging to INFO file handler {path/filename}")
print(f"Logging to INFO file handler {path / filename}")
path.mkdir(parents=True, exist_ok=True)
file_handler = TimedRotatingFileHandler(
filename=path / filename, when="MIDNIGHT", backupCount=INFO_LOG_DAYS
Expand All @@ -169,7 +169,7 @@ def set_up_DEBUG_memory_handler(
log file when it sees a message of severity ERROR. Creates the directory if
necessary"""
debug_path = path / "debug"
print(f"Logging to DEBUG handler {debug_path/filename}")
print(f"Logging to DEBUG handler {debug_path / filename}")
debug_path.mkdir(parents=True, exist_ok=True)
file_handler = TimedRotatingFileHandler(
filename=debug_path / filename, when="H", backupCount=DEBUG_LOG_FILES_TO_KEEP
Expand Down
6 changes: 3 additions & 3 deletions src/dodal/plans/wrapped.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ def count(
Wraps bluesky.plans.count(det, num, delay, md=metadata) exposing only serializable
parameters and metadata."""
if isinstance(delay, Sequence):
assert (
len(delay) == num - 1
), f"Number of delays given must be {num - 1}: was given {len(delay)}"
assert len(delay) == num - 1, (
f"Number of delays given must be {num - 1}: was given {len(delay)}"
)
metadata = metadata or {}
metadata["shape"] = (num,)
yield from bp.count(tuple(detectors), num, delay=delay, md=metadata)
12 changes: 6 additions & 6 deletions tests/common/beamlines/test_device_instantiation.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ def test_device_creation(RE, module_and_devices_for_beamline):
for name, device in devices.items()
if not follows_bluesky_protocols(device)
]
assert (
len(devices_not_following_bluesky_protocols) == 0
), f"{devices_not_following_bluesky_protocols} do not follow bluesky protocols"
assert len(devices_not_following_bluesky_protocols) == 0, (
f"{devices_not_following_bluesky_protocols} do not follow bluesky protocols"
)


@pytest.mark.parametrize(
Expand All @@ -56,6 +56,6 @@ def test_devices_are_identical(RE, module_and_devices_for_beamline):
]
total_number_of_devices = len(devices_a)
non_identical_number_of_devies = len(devices_a)
assert (
len(non_identical_names) == 0
), f"{non_identical_number_of_devies}/{total_number_of_devices} devices were not identical: {non_identical_names}"
assert len(non_identical_names) == 0, (
f"{non_identical_number_of_devies}/{total_number_of_devices} devices were not identical: {non_identical_names}"
)
12 changes: 6 additions & 6 deletions tests/devices/unit_tests/detector/test_det_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ def test_resolution(
detector_params.use_roi_mode = roi
get_detector_max_size.return_value = 434.6
actual_res = resolution(detector_params, wavelength_angstroms, det_distance_mm)
assert isclose(
expected_res, actual_res
), f"expected={expected_res}, actual={actual_res}"
assert isclose(expected_res, actual_res), (
f"expected={expected_res}, actual={actual_res}"
)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -126,6 +126,6 @@ def test_resolution_with_roi_realistic(

actual_res = resolution(detector_params, wavelength_angstroms, det_distance_mm)

assert isclose(
actual_res, expected_res, rtol=1e-3
), f"expected={expected_res}, actual={actual_res}"
assert isclose(actual_res, expected_res, rtol=1e-3), (
f"expected={expected_res}, actual={actual_res}"
)
6 changes: 3 additions & 3 deletions tests/devices/unit_tests/test_shutter.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ async def test_set_shutter_open(
reading = await sim_shutter.read()

shutter_position = reading.get("shutter-position_readback", {})
assert (
shutter_position["value"] is new_state
), f"Unexpected value: {shutter_position['value']}"
assert shutter_position["value"] is new_state, (
f"Unexpected value: {shutter_position['value']}"
)


async def test_given_shutter_in_auto_then_when_set_raises(sim_shutter: ZebraShutter):
Expand Down
6 changes: 3 additions & 3 deletions tests/fake_zocalo/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ def get_dcgid_and_prefix(dcid: int, session_maker: sessionmaker) -> tuple[int, s
.filter(DataCollection.dataCollectionId == dcid)
.first()
)
assert (
query is not None
), f"Failed to find dcid {dcid} which matches any in dev ispyb"
assert query is not None, (
f"Failed to find dcid {dcid} which matches any in dev ispyb"
)
dcgid, prefix = query

except Exception as e:
Expand Down
12 changes: 6 additions & 6 deletions tests/plans/test_compliance.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ def assert_hard_requirements(plan: PlanGenerator, signature: inspect.Signature):


def assert_metadata_requirements(plan: PlanGenerator, signature: inspect.Signature):
assert (
"metadata" in signature.parameters
), f"'{plan.__name__}' does not allow metadata"
assert "metadata" in signature.parameters, (
f"'{plan.__name__}' does not allow metadata"
)
metadata = signature.parameters["metadata"]
assert (
metadata.annotation == dict[str, Any] | None and metadata.default is None
), f"'{plan.__name__}' metadata is not optional"
assert metadata.annotation == dict[str, Any] | None and metadata.default is None, (
f"'{plan.__name__}' metadata is not optional"
)
assert metadata.default is None, f"'{plan.__name__}' metadata default is mutable"


Expand Down
14 changes: 6 additions & 8 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,15 +308,13 @@ def test_get_run_number_uses_prefix(mock_list_dir: MagicMock):
OPHYD_ASYNC_DEVICE_B = OphydV2Device(name="OPHYD_ASYNC_DEVICE_B")


def _filtering_test_cases() -> (
Iterable[
tuple[
Mapping[str, AnyDevice],
Mapping[str, OphydV1Device],
Mapping[str, OphydV2Device],
]
def _filtering_test_cases() -> Iterable[
tuple[
Mapping[str, AnyDevice],
Mapping[str, OphydV1Device],
Mapping[str, OphydV2Device],
]
):
]:
yield {}, {}, {}
yield (
{"oa": OPHYD_DEVICE_A},
Expand Down

0 comments on commit bbd76c6

Please sign in to comment.