From 6858f64a6473fef280187ed7534be75abfa98925 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Fri, 23 Oct 2026 10:50:05 +0200 Subject: [PATCH 1/5] Initial commit for Switch element (simple ON/OFF switch, for example, for SOFB or tune feedback --- pyaml/apidoc/gen_api.py | 1 + pyaml/common/abstract.py | 17 +++ pyaml/common/holders/element_holder.py | 5 + pyaml/common/switch_element.py | 142 +++++++++++++++++++ pyaml/control/abstract_impl.py | 30 ++++ pyaml/control/controlsystem.py | 8 ++ pyaml/lattice/abstract_impl.py | 15 ++ pyaml/lattice/simulator.py | 5 + tests/common/test_switch_element.py | 103 ++++++++++++++ tests/control/test_switch_controlsystem.py | 156 +++++++++++++++++++++ tests/lattice/test_switch_simulator.py | 139 ++++++++++++++++++ 11 files changed, 621 insertions(+) create mode 100644 pyaml/common/switch_element.py create mode 100644 tests/common/test_switch_element.py create mode 100644 tests/control/test_switch_controlsystem.py create mode 100644 tests/lattice/test_switch_simulator.py diff --git a/pyaml/apidoc/gen_api.py b/pyaml/apidoc/gen_api.py index 4439e85e2..e88570c48 100644 --- a/pyaml/apidoc/gen_api.py +++ b/pyaml/apidoc/gen_api.py @@ -28,6 +28,7 @@ "pyaml.common.holders.element_holder", "pyaml.common.holders.sub_holders", "pyaml.common.holders.rf_holder", + "pyaml.common.switch_element", "pyaml.configuration.factory", "pyaml.configuration.fileloader", "pyaml.configuration.manager", diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 39805038c..1c05be21f 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -10,6 +10,23 @@ from numpy import array, double +# Boolean -------------------------------------------------------------- + + +class BinaryState(metaclass=ABCMeta): + """Define boolean readback and confirmed writes for an enable/disable channel.""" + + @abstractmethod + def readback(self) -> bool: + """Return the actual boolean state, raising if it is unavailable or invalid.""" + pass + + @abstractmethod + def set_and_wait(self, value: bool) -> None: + """Write a boolean state and wait for the backend to confirm it.""" + pass + + # Float ---------------------------------------------------------------- diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index 1cf63dfb1..06b8fae9e 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -33,6 +33,7 @@ from ...configuration.unbound_element import UnboundElement from ...tuning_tools.measurement_tool import MeasurementTool from ...tuning_tools.tuning_tool import TuningTool + from ..switch_element import SwitchElement class ElementHolder(metaclass=ABCMeta): @@ -186,6 +187,10 @@ def fill_device(self, elements: list[Element]): for element in elements: element._fill_device(self) + def _fill_switch_element(self, element: "SwitchElement") -> None: + """Reject switches unless the backend supports their binding.""" + raise PyAMLException(f"{self.__class__.__name__} does not support switch element {element.name}") + @abstractmethod def _fill_magnet(self, magnet: Magnet) -> None: pass diff --git a/pyaml/common/switch_element.py b/pyaml/common/switch_element.py new file mode 100644 index 000000000..30e76123d --- /dev/null +++ b/pyaml/common/switch_element.py @@ -0,0 +1,142 @@ +"""Switchable accelerator functionality without a required lattice counterpart.""" + +import copy +from typing import TYPE_CHECKING, Self + +from ..validation import DynamicValidation, register_schema +from .abstract import BinaryState +from .element import Element +from .exception import PyAMLException + +if TYPE_CHECKING: + from .holders.element_holder import ElementHolder + +PYAMLCLASS = "SwitchElement" + + +@register_schema +class SwitchElement(Element, DynamicValidation): + """ + Enable or disable accelerator functionality through one boolean channel. + + Parameters + ---------- + name : str + Unique element name, for example ``SOFB`` or ``FOFB``. + device : str + Opaque backend reference to one writable boolean channel. Status is + read from that channel's actual readback, not its requested setpoint. + Simulator modes do not resolve this reference. + description : str | None, optional + Human-readable description of the functionality. + + Notes + ----- + Control-system operations delegate waiting and timeouts to the backend, + then verify boolean readback with VALID quality. Numeric 0/1 states are + not accepted; Python and NumPy boolean scalars are supported. Non-VALID + quality, including CHANGING, raises an error. Construction and attachment + never initialize live hardware. + + Each simulator attachment starts disabled and maintains independent state + without looking up or modifying a lattice element. This element does not + implement measurement preparation or automatic state restoration. + + Configuration + ------------- + .. code-block:: yaml + + - class: pyaml.common.switch_element.SwitchElement + name: SOFB + device: SOFB_ENABLED + description: Slow orbit feedback + + Examples + -------- + With this element configured in an accelerator named ``sr``: + + .. code-block:: python + + feedback = sr.live["SOFB"] + feedback.disable() + assert feedback.is_enabled() is False + feedback.enable() + + simulated_feedback = sr.design["SOFB"] + assert simulated_feedback.is_enabled() is False + simulated_feedback.enable() # Does not affect live hardware or the lattice. + """ + + def __init__(self, name: str, device: str, description: str | None = None): + """Initialize the element configuration without accessing hardware.""" + super().__init__(name=name, description=description) + self.device = device + self._state: BinaryState | None = None + + def attach(self, peer: "ElementHolder", state: BinaryState) -> Self: + """ + Return a copy bound to a peer and its boolean state interface. + + Parameters + ---------- + peer : ElementHolder + Control system or simulator owning this runtime element. + state : BinaryState + Boolean state interface owned by this attachment. + + Returns + ------- + Self + Attached copy; the original configuration remains unattached. + """ + obj = copy.copy(self) + obj._state = state + obj._peer = peer + return obj + + def _binding(self) -> BinaryState: + if self._state is None: + raise PyAMLException(f"{self.name} has no attached switch channel") + return self._state + + def _set_enabled(self, enabled: bool) -> None: + self._binding().set_and_wait(enabled) + if self.is_enabled() is not enabled: + raise PyAMLException(f"{self.name}: readback did not confirm enabled={enabled}") + + def enable(self) -> None: + """ + Enable the functionality and verify actual readback. + + Backend waiting, timeout, and access errors propagate to the caller. + Invalid or mismatched readback raises :class:`PyAMLException`. + """ + self._set_enabled(True) + + def disable(self) -> None: + """ + Disable the functionality and verify actual readback. + + Backend waiting, timeout, and access errors propagate to the caller. + Invalid or mismatched readback raises :class:`PyAMLException`. + """ + self._set_enabled(False) + + def is_enabled(self) -> bool: + """ + Return actual boolean readback, not the commanded state. + + Returns + ------- + bool + Whether the functionality is enabled. + + Raises + ------ + PyAMLException + If unattached, or if readback is non-boolean or has non-VALID quality. + """ + return self._binding().readback() + + def _fill_device(self, holder: "ElementHolder") -> None: + holder._fill_switch_element(self) diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 5b1105628..2d46c1bbf 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -17,6 +17,7 @@ from ..common.abstract_aggregator import ScalarAggregator from ..control.deviceaccess import DeviceAccess from ..control.deviceaccesslist import DeviceAccessList +from ..control.readback_value import Quality, Value from ..magnet.magnet import Magnet from ..magnet.model import MagnetModel from ..rf.rf_plant import RFPlant @@ -25,6 +26,35 @@ # ------------------------------------------------------------------------------ +class CSBinaryState(abstract.BinaryState): + """ + Expose one control-system boolean channel with strict readback validation. + + Parameters + ---------- + device : DeviceAccess + Writable boolean channel. Its backend owns waiting and timeout behavior. + """ + + def __init__(self, device: DeviceAccess): + self._device = device + + def set_and_wait(self, value: bool) -> None: + """Delegate the confirmed write to the backend without fallback or polling.""" + self._device.set_and_wait(value) + + def readback(self) -> bool: + """Return actual boolean readback, rejecting non-VALID quality and non-booleans.""" + result = self._device.readback() + if isinstance(result, Value): + if result.quality is not Quality.VALID: + raise PyAMLException(f"{self._device.name()}: expected VALID boolean readback, got quality {result.quality}") + result = result.value + if not isinstance(result, (bool, np.bool_)): + raise PyAMLException(f"{self._device.name()}: expected boolean readback, got {type(result).__name__}") + return bool(result) + + def check_range(values: Any, dev_range: Any) -> bool: """ Check whether values are within given ranges. diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 4800f7967..fa5116a77 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -16,8 +16,10 @@ from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException from ..common.holders.element_holder import ElementHolder +from ..common.switch_element import SwitchElement from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( + CSBinaryState, CSScalarAggregator, CSSparseScalarAggregator, CSStrengthScalarAggregator, @@ -276,6 +278,12 @@ def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None: def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: self.add_tool(tool.attach(self)) + def _fill_switch_element(self, element: SwitchElement) -> None: + device = self.get_device_access(element.device) + if device is None: + raise PyAMLException(f"{element.name}: switch channel {element.device!r} is unavailable") + self._add(self._ALL, element.attach(self, CSBinaryState(device))) + def _fill_unbound_element(self, element: UnboundElement) -> None: if self.name() not in element._control_modes: return diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index a734a5871..f4abc1c62 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -21,6 +21,21 @@ # ------------------------------------------------------------------------------ +class SimulatedBinaryState(abstract.BinaryState): + """Maintain an initially disabled boolean state independent of the lattice.""" + + def __init__(self): + self._enabled = False + + def set_and_wait(self, value: bool) -> None: + """Set the simulated state immediately.""" + self._enabled = value + + def readback(self) -> bool: + """Return the simulated boolean state.""" + return self._enabled + + def _effective_lengths(elements: list[at.Element]) -> list[float]: """ Return the lengths used to convert between integrated strengths and polynom coefficients. diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index e0922ae38..e28b95038 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -16,6 +16,7 @@ from ..common.element import Element, __pyaml_repr__ from ..common.exception import PyAMLException from ..common.holders.element_holder import ElementHolder +from ..common.switch_element import SwitchElement from ..configuration import ROOT from ..diagnostics.tune_monitor import BetatronTuneMonitor from ..lattice.abstract_impl import ( @@ -37,6 +38,7 @@ RWSerializedStrength, RWStrengthArray, RWStrengthScalar, + SimulatedBinaryState, update_bpm_transform_matrix, ) from ..magnet.cfm_magnet import CombinedFunctionMagnet @@ -338,6 +340,9 @@ def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None: def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: self.add_tool(tool.attach(self)) + def _fill_switch_element(self, element: SwitchElement) -> None: + self._add(self._ALL, element.attach(self, SimulatedBinaryState())) + def _fill_unbound_element(self, element: "UnboundElement") -> None: pass diff --git a/tests/common/test_switch_element.py b/tests/common/test_switch_element.py new file mode 100644 index 000000000..89e9f5c67 --- /dev/null +++ b/tests/common/test_switch_element.py @@ -0,0 +1,103 @@ +from unittest.mock import create_autospec + +import pytest + +from pyaml.common.abstract import BinaryState +from pyaml.common.exception import PyAMLConfigException, PyAMLException +from pyaml.common.switch_element import SwitchElement +from pyaml.configuration.factory import Factory +from pyaml.control.controlsystem import ControlSystemAdapter +from pyaml.validation import SchemaGenerator, SchemaRegistry, SchemaValidator +from pyaml.validation.schema_builder import generate_configuration_schema +from tests.common.test_element_holder import DispatchHolder + +CLASS_PATH = "pyaml.common.switch_element.SwitchElement" + + +@pytest.fixture +def switch(): + return SwitchElement("SOFB", "SOFB_ENABLED", description="Slow orbit feedback") + + +@pytest.mark.parametrize("operation", ["enable", "disable", "is_enabled"]) +def test_unattached_operations_raise(switch, operation): + with pytest.raises(PyAMLException, match="SOFB has no attached switch channel"): + getattr(switch, operation)() + + +def test_attachment_copies_configuration_without_io(switch): + state = create_autospec(BinaryState, instance=True) + peer = create_autospec(ControlSystemAdapter, instance=True) + peer.name.return_value = "live" + + attached = switch.attach(peer, state) + + assert attached is not switch + assert attached.peer is peer + assert attached.name == "SOFB" + assert attached.device == "SOFB_ENABLED" + assert attached.description == "Slow orbit feedback" + assert switch.peer is None + assert "SwitchElement(name='SOFB'" in repr(attached) + assert "SOFB_ENABLED" in repr(attached) + assert "unavailable" not in repr(attached) + assert state.mock_calls == [] + + +def test_unsupported_holder_raises_without_new_abstract_requirement(switch): + holder = DispatchHolder() + + with pytest.raises(PyAMLException, match="DispatchHolder does not support switch element SOFB"): + holder.fill_device([switch]) + + assert holder.get().names() == [] + + +@pytest.mark.parametrize( + "declaration", + [ + {"class": CLASS_PATH}, + {"class_path": CLASS_PATH}, + {"type": "pyaml.common.switch_element"}, + ], +) +def test_factory_and_schema_support_class_and_legacy_declarations(declaration): + Factory.clear() + generate_configuration_schema(SwitchElement) + try: + config = {**declaration, "name": "SOFB", "device": "SOFB_ENABLED"} + validated = SchemaValidator.validate_to_dict(config) + switch = Factory.build(validated) + + assert isinstance(switch, SwitchElement) + assert switch.name == "SOFB" + assert switch.device == "SOFB_ENABLED" + assert switch.peer is None + finally: + Factory.clear() + + +def test_schema_is_discoverable_and_requires_one_device(): + registry = SchemaRegistry() + registry.discover() + schema = SchemaGenerator.generate(CLASS_PATH) + + assert registry.get(CLASS_PATH) is not None + assert {"name", "device"} <= set(schema["required"]) + assert schema["properties"]["device"]["type"] == "string" + assert "initial_enabled" not in schema["properties"] + + +@pytest.mark.parametrize("device", [None, True, 1, ["SOFB_ENABLED"]]) +def test_constructor_rejects_non_string_device(device): + with pytest.raises(PyAMLConfigException): + SwitchElement("SOFB", device) + + +def test_schema_rejects_extra_configuration(): + generate_configuration_schema(SwitchElement) + + with pytest.raises(PyAMLConfigException, match="initial_enabled"): + SchemaValidator.validate_to_dict( + {"class": CLASS_PATH, "name": "SOFB", "device": "SOFB_ENABLED", "initial_enabled": True} + ) diff --git a/tests/control/test_switch_controlsystem.py b/tests/control/test_switch_controlsystem.py new file mode 100644 index 000000000..19013cbe4 --- /dev/null +++ b/tests/control/test_switch_controlsystem.py @@ -0,0 +1,156 @@ +from unittest.mock import call, create_autospec + +import numpy as np +import pytest + +from pyaml.common.exception import PyAMLException +from pyaml.common.switch_element import SwitchElement +from pyaml.control.controlsystem import ControlSystemAdapter +from pyaml.control.deviceaccess import DeviceAccess +from pyaml.control.readback_value import Quality, Value + + +@pytest.fixture +def device(): + device = create_autospec(DeviceAccess, instance=True) + device.name.return_value = "feedback/enabled" + device.readback.return_value = Value(True) + + def write(value): + device.readback.return_value = Value(value) + + device.set_and_wait.side_effect = write + return device + + +@pytest.fixture +def live(device, monkeypatch): + holder = ControlSystemAdapter() + monkeypatch.setattr(holder, "name", lambda: "live") + monkeypatch.setattr(holder, "get_device_access", lambda ref: device) + holder.fill_device([SwitchElement("SOFB", "SOFB_ENABLED")]) + return holder + + +def test_attachment_and_representation_do_not_access_channel(live, device): + repr(live["SOFB"]) + live.post_init() + + assert device.mock_calls == [] + + +@pytest.mark.parametrize("enabled,operation", [(True, "enable"), (False, "disable")]) +def test_operation_waits_then_verifies_actual_readback(live, device, enabled, operation): + getattr(live["SOFB"], operation)() + + assert device.mock_calls == [call.set_and_wait(enabled), call.readback()] + assert type(device.set_and_wait.call_args.args[0]) is bool + assert live["SOFB"].is_enabled() is enabled + device.set.assert_not_called() + device.get.assert_not_called() + + +@pytest.mark.parametrize("value", [True, False, np.bool_(True), np.bool_(False)]) +@pytest.mark.parametrize("wrapped", [False, True]) +def test_status_returns_native_boolean_from_actual_readback(live, device, value, wrapped): + device.get.return_value = not bool(value) + device.readback.return_value = Value(value) if wrapped else value + + assert live["SOFB"].is_enabled() is bool(value) + device.get.assert_not_called() + + +@pytest.mark.parametrize( + "value", + [0, 1, 0.0, 1.0, np.int64(1), np.float64(0), "true", "False", None, [True], np.array([True]), np.array(True)], +) +@pytest.mark.parametrize("wrapped", [False, True]) +def test_status_rejects_non_boolean_readback(live, device, value, wrapped): + device.readback.return_value = Value(value) if wrapped else value + + with pytest.raises(PyAMLException, match="feedback/enabled: expected boolean readback"): + live["SOFB"].is_enabled() + + +@pytest.mark.parametrize("quality", [Quality.INVALID, Quality.ALARM, Quality.CHANGING, Quality.WARNING]) +@pytest.mark.parametrize("operation", ["enable", "disable", "is_enabled"]) +def test_non_valid_quality_is_not_reported_as_success(live, device, quality, operation): + device.set_and_wait.side_effect = None + device.readback.return_value = Value(True, quality=quality) + + with pytest.raises(PyAMLException, match=f"feedback/enabled: expected VALID boolean readback, got quality {quality}"): + getattr(live["SOFB"], operation)() + + +@pytest.mark.parametrize("enabled,operation", [(True, "enable"), (False, "disable")]) +def test_confirmation_mismatch_raises(live, device, enabled, operation): + device.set_and_wait.side_effect = None + device.get.return_value = enabled + device.readback.return_value = Value(not enabled) + + with pytest.raises(PyAMLException, match=f"SOFB: readback did not confirm enabled={enabled}"): + getattr(live["SOFB"], operation)() + + device.get.assert_not_called() + + +@pytest.mark.parametrize("operation", ["enable", "disable"]) +def test_non_boolean_confirmation_raises(live, device, operation): + device.set_and_wait.side_effect = None + device.readback.return_value = Value(1) + + with pytest.raises(PyAMLException, match="expected boolean readback"): + getattr(live["SOFB"], operation)() + + +@pytest.mark.parametrize("error", [TimeoutError("timed out"), NotImplementedError("cannot wait"), OSError("disconnected")]) +@pytest.mark.parametrize("operation", ["enable", "disable"]) +def test_backend_wait_errors_propagate_without_fallback(live, device, error, operation): + device.set_and_wait.side_effect = error + + with pytest.raises(type(error)) as exc: + getattr(live["SOFB"], operation)() + + assert exc.value is error + device.set.assert_not_called() + device.readback.assert_not_called() + + +def test_readback_errors_propagate(live, device): + error = OSError("read failed") + device.readback.side_effect = error + + with pytest.raises(OSError) as exc: + live["SOFB"].is_enabled() + + assert exc.value is error + + +def test_missing_device_is_rejected(monkeypatch): + holder = ControlSystemAdapter() + monkeypatch.setattr(holder, "get_device_access", lambda ref: None) + + with pytest.raises(PyAMLException, match="SOFB: switch channel 'MISSING' is unavailable"): + holder.fill_device([SwitchElement("SOFB", "MISSING")]) + + assert holder.get().names() == [] + + +def test_device_resolution_errors_propagate(monkeypatch): + holder = ControlSystemAdapter() + resolver = create_autospec(holder.get_device_access, side_effect=OSError("lookup failed")) + monkeypatch.setattr(holder, "get_device_access", resolver) + + with pytest.raises(OSError, match="lookup failed"): + holder.fill_device([SwitchElement("SOFB", "SOFB_ENABLED")]) + + resolver.assert_called_once_with("SOFB_ENABLED") + + +def test_duplicate_registration_does_not_replace_element(live): + original = live["SOFB"] + + with pytest.raises(PyAMLException, match="Duplicate element"): + live.fill_device([SwitchElement("SOFB", "OTHER_CHANNEL")]) + + assert live["SOFB"] is original diff --git a/tests/lattice/test_switch_simulator.py b/tests/lattice/test_switch_simulator.py new file mode 100644 index 000000000..465b45472 --- /dev/null +++ b/tests/lattice/test_switch_simulator.py @@ -0,0 +1,139 @@ +import json +from unittest.mock import Mock + +import pytest +import yaml + +from pyaml.accelerator import Accelerator +from pyaml.arrays.element_array import ElementArray +from pyaml.common.exception import PyAMLException +from pyaml.common.switch_element import SwitchElement +from pyaml.control.controlsystem import ControlSystemAdapter +from pyaml.lattice.simulator import Simulator +from pyaml.validation import register_schema +from pyaml.validation.schema_builder import generate_configuration_schema + + +@register_schema +class SwitchTestControlSystem(ControlSystemAdapter): + def __init__(self, name: str): + super().__init__() + self._name = name + + def name(self) -> str: + return self._name + + +@pytest.fixture +def design(ebs_lattice_file): + return Simulator(name="design", lattice=str(ebs_lattice_file)) + + +def test_simulated_switch_bypasses_lattice_lookup(design, monkeypatch): + lookup = Mock(side_effect=AssertionError("Switch must not resolve a lattice element")) + monkeypatch.setattr(design, "get_at_elems", lookup) + monkeypatch.setattr(design, "_linker", Mock()) + configured = SwitchElement("NO_LATTICE_EQUIVALENT", "UNRESOLVED_DEVICE") + + design.fill_device([configured]) + switch = design["NO_LATTICE_EQUIVALENT"] + + assert switch is not configured + assert switch.peer is design + assert configured.peer is None + assert switch.is_enabled() is False + for _ in range(2): + switch.enable() + assert switch.is_enabled() is True + switch.disable() + assert switch.is_enabled() is False + lookup.assert_not_called() + assert design._linker.mock_calls == [] + + +def test_simulated_state_is_independent_per_element_and_mode(design, ebs_lattice_file): + configured = SwitchElement("SOFB", "SOFB_ENABLED") + design.fill_device([configured, SwitchElement("FOFB", "FOFB_ENABLED")]) + design["SOFB"].enable() + other = Simulator(name="other", lattice=str(ebs_lattice_file)) + other.fill_device([configured]) + + assert design["SOFB"].is_enabled() is True + assert design["FOFB"].is_enabled() is False + assert other["SOFB"].is_enabled() is False + other["SOFB"].enable() + design["SOFB"].disable() + assert other["SOFB"].is_enabled() is True + assert configured.peer is None + + +def test_generic_lookup_arrays_and_duplicate_names(design): + design.fill_device([SwitchElement("SOFB", "SOFB_ENABLED"), SwitchElement("FOFB", "FOFB_ENABLED")]) + original = design["SOFB"] + + assert design.get().names() == ["SOFB", "FOFB"] + assert type(design["*OFB"]) is ElementArray + assert design["*OFB"].names() == ["SOFB", "FOFB"] + design.fill_element_array("FEEDBACKS", ["SOFB", "FOFB"]) + assert design.get("FEEDBACKS")[0] is original + + with pytest.raises(PyAMLException, match="Duplicate element"): + design.fill_device([SwitchElement("SOFB", "OTHER_CHANNEL")]) + + assert design["SOFB"] is original + + +@pytest.mark.parametrize("extension", ["yaml", "json"]) +@pytest.mark.parametrize("validate", [False, True]) +def test_accelerator_configuration_keeps_live_and_simulated_state_separate( + tmp_path, ebs_lattice_file, extension, validate, monkeypatch +): + from tango.pyaml.attribute import Attribute + from tango.pyaml.attribute import ConfigModel as AttributeConfigModel + from tango.pyaml.attribute_store import get_attribute, set_attribute + + device_name = "switch-tests/feedback/enabled" + set_attribute(device_name, True) + monkeypatch.setattr( + ControlSystemAdapter, + "get_device_access", + lambda self, ref: None if ref is None else Attribute(AttributeConfigModel(attribute=ref)), + ) + for cls in (SwitchElement, SwitchTestControlSystem, Simulator, Accelerator): + generate_configuration_schema(cls) + config = { + "class": "pyaml.accelerator.Accelerator", + "facility": "Test", + "machine": "ring", + "energy": 3e9, + "controls": [{"class": f"{__name__}.SwitchTestControlSystem", "name": "live"}], + "simulators": [{"type": "pyaml.lattice.simulator", "name": "design", "lattice": str(ebs_lattice_file)}], + "devices": [ + {"class": "pyaml.common.switch_element.SwitchElement", "name": "SOFB", "device": device_name}, + {"type": "pyaml.diagnostics.bpm.bpm", "name": "BPM_C04-01"}, + ], + } + config_path = tmp_path / f"switch.{extension}" + config_path.write_text(json.dumps(config) if extension == "json" else yaml.safe_dump(config), encoding="utf-8") + set_spy = Mock(side_effect=AssertionError("Loading must not write live hardware")) + with monkeypatch.context() as patch: + patch.setattr(Attribute, "set", set_spy) + sr = Accelerator.load(str(config_path), validate=validate) + + set_spy.assert_not_called() + assert sr.live["SOFB"].peer is sr.live + assert sr.design["SOFB"].peer is sr.design + assert sr.live["SOFB"].is_enabled() is True + assert sr.design["SOFB"].is_enabled() is False + assert sr.design.diagnostic.bpm["BPM_C04-01"] is not None + sr.design["SOFB"].enable() + sr.design["SOFB"].disable() + assert get_attribute(device_name) is True + + sr.live["SOFB"].disable() + assert sr.live["SOFB"].is_enabled() is False + sr.design["SOFB"].enable() + assert sr.live["SOFB"].is_enabled() is False + sr.live["SOFB"].enable() + assert sr.live["SOFB"].is_enabled() is True + assert sr.design["SOFB"].is_enabled() is True From 6255a8273cd4ed7043a423d614eb7a09f37b7377 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Thu, 26 Nov 2026 00:51:59 +0100 Subject: [PATCH 2/5] Updated to align with interface in IDs --- pyaml/common/abstract.py | 14 ++--- pyaml/common/switch_element.py | 73 ++++++++++------------ pyaml/control/abstract_impl.py | 39 +++++------- pyaml/control/controlsystem.py | 4 +- pyaml/lattice/abstract_impl.py | 17 ++--- pyaml/lattice/simulator.py | 4 +- tests/common/test_switch_element.py | 28 +++++++-- tests/control/test_switch_controlsystem.py | 65 ++++++++++--------- tests/lattice/test_switch_simulator.py | 35 ++++++++--- 9 files changed, 154 insertions(+), 125 deletions(-) diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 1c05be21f..4963cfd1a 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -10,20 +10,18 @@ from numpy import array, double -# Boolean -------------------------------------------------------------- - -class BinaryState(metaclass=ABCMeta): - """Define boolean readback and confirmed writes for an enable/disable channel.""" +class RWScalarBoolean(metaclass=ABCMeta): + """Define backend-independent boolean get/set access.""" @abstractmethod - def readback(self) -> bool: - """Return the actual boolean state, raising if it is unavailable or invalid.""" + def get(self) -> bool: + """Return the boolean state.""" pass @abstractmethod - def set_and_wait(self, value: bool) -> None: - """Write a boolean state and wait for the backend to confirm it.""" + def set(self, value: bool) -> None: + """Write the boolean state.""" pass diff --git a/pyaml/common/switch_element.py b/pyaml/common/switch_element.py index 30e76123d..0c0703416 100644 --- a/pyaml/common/switch_element.py +++ b/pyaml/common/switch_element.py @@ -4,7 +4,7 @@ from typing import TYPE_CHECKING, Self from ..validation import DynamicValidation, register_schema -from .abstract import BinaryState +from . import abstract from .element import Element from .exception import PyAMLException @@ -30,13 +30,18 @@ class SwitchElement(Element, DynamicValidation): description : str | None, optional Human-readable description of the functionality. + Attributes + ---------- + enabled + Boolean get/set accessor, shared by control-system and simulator modes. + Notes ----- - Control-system operations delegate waiting and timeouts to the backend, - then verify boolean readback with VALID quality. Numeric 0/1 states are - not accepted; Python and NumPy boolean scalars are supported. Non-VALID - quality, including CHANGING, raises an error. Construction and attachment - never initialize live hardware. + Control-system access uses the reusable RWScalarBoolean adapter: get() + reads the backend readback (including numeric 0/1 flags) and set() writes + a Python boolean through DeviceAccess.set(). Value metadata is unwrapped; + this interface adds no quality, waiting, or completion policy. Backend + errors propagate. Construction and attachment never initialize hardware. Each simulator attachment starts disabled and maintains independent state without looking up or modifying a lattice element. This element does not @@ -59,21 +64,24 @@ class SwitchElement(Element, DynamicValidation): feedback = sr.live["SOFB"] feedback.disable() - assert feedback.is_enabled() is False + enabled = feedback.enabled.get() + feedback.enabled.set(True) feedback.enable() simulated_feedback = sr.design["SOFB"] - assert simulated_feedback.is_enabled() is False - simulated_feedback.enable() # Does not affect live hardware or the lattice. + assert simulated_feedback.enabled.get() is False + simulated_feedback.enabled.set(True) # Does not affect hardware or the lattice. """ + __pyaml_repr_exclude__ = ("enabled",) + def __init__(self, name: str, device: str, description: str | None = None): """Initialize the element configuration without accessing hardware.""" super().__init__(name=name, description=description) self.device = device - self._state: BinaryState | None = None + self._enabled: abstract.RWScalarBoolean | None = None - def attach(self, peer: "ElementHolder", state: BinaryState) -> Self: + def attach(self, peer: "ElementHolder", enabled: abstract.RWScalarBoolean) -> Self: """ Return a copy bound to a peer and its boolean state interface. @@ -81,8 +89,8 @@ def attach(self, peer: "ElementHolder", state: BinaryState) -> Self: ---------- peer : ElementHolder Control system or simulator owning this runtime element. - state : BinaryState - Boolean state interface owned by this attachment. + enabled : abstract.RWScalarBoolean + Boolean get/set interface owned by this attachment. Returns ------- @@ -90,37 +98,24 @@ def attach(self, peer: "ElementHolder", state: BinaryState) -> Self: Attached copy; the original configuration remains unattached. """ obj = copy.copy(self) - obj._state = state + obj._enabled = enabled obj._peer = peer return obj - def _binding(self) -> BinaryState: - if self._state is None: - raise PyAMLException(f"{self.name} has no attached switch channel") - return self._state - - def _set_enabled(self, enabled: bool) -> None: - self._binding().set_and_wait(enabled) - if self.is_enabled() is not enabled: - raise PyAMLException(f"{self.name}: readback did not confirm enabled={enabled}") + @property + def enabled(self) -> abstract.RWScalarBoolean: + """Return the boolean get/set accessor for this holder.""" + if self._enabled is None: + raise PyAMLException(f"{self.name}: enabled state is unavailable before attachment") + return self._enabled def enable(self) -> None: - """ - Enable the functionality and verify actual readback. - - Backend waiting, timeout, and access errors propagate to the caller. - Invalid or mismatched readback raises :class:`PyAMLException`. - """ - self._set_enabled(True) + """Enable the functionality through its boolean accessor.""" + self.enabled.set(True) def disable(self) -> None: - """ - Disable the functionality and verify actual readback. - - Backend waiting, timeout, and access errors propagate to the caller. - Invalid or mismatched readback raises :class:`PyAMLException`. - """ - self._set_enabled(False) + """Disable the functionality through its boolean accessor.""" + self.enabled.set(False) def is_enabled(self) -> bool: """ @@ -134,9 +129,9 @@ def is_enabled(self) -> bool: Raises ------ PyAMLException - If unattached, or if readback is non-boolean or has non-VALID quality. + If unattached, or if the backend value is not a boolean flag. """ - return self._binding().readback() + return self.enabled.get() def _fill_device(self, holder: "ElementHolder") -> None: holder._fill_switch_element(self) diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 2d46c1bbf..27c32dada 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -17,42 +17,33 @@ from ..common.abstract_aggregator import ScalarAggregator from ..control.deviceaccess import DeviceAccess from ..control.deviceaccesslist import DeviceAccessList -from ..control.readback_value import Quality, Value from ..magnet.magnet import Magnet from ..magnet.model import MagnetModel from ..rf.rf_plant import RFPlant from ..rf.rf_transmitter import RFTransmitter +from .readback_value import Value # ------------------------------------------------------------------------------ -class CSBinaryState(abstract.BinaryState): - """ - Expose one control-system boolean channel with strict readback validation. - - Parameters - ---------- - device : DeviceAccess - Writable boolean channel. Its backend owns waiting and timeout behavior. - """ +class RWScalarBoolean(abstract.RWScalarBoolean): + """Expose a backend boolean through reusable get/set accessors.""" def __init__(self, device: DeviceAccess): self._device = device - def set_and_wait(self, value: bool) -> None: - """Delegate the confirmed write to the backend without fallback or polling.""" - self._device.set_and_wait(value) - - def readback(self) -> bool: - """Return actual boolean readback, rejecting non-VALID quality and non-booleans.""" - result = self._device.readback() - if isinstance(result, Value): - if result.quality is not Quality.VALID: - raise PyAMLException(f"{self._device.name()}: expected VALID boolean readback, got quality {result.quality}") - result = result.value - if not isinstance(result, (bool, np.bool_)): - raise PyAMLException(f"{self._device.name()}: expected boolean readback, got {type(result).__name__}") - return bool(result) + def get(self) -> bool: + value = self._device.readback() + if isinstance(value, Value): + value = value.value + if value not in (False, True): + raise PyAMLException(f"{self._device.name()}: expected a boolean flag, got {value!r}") + return bool(value) + + def set(self, value: bool) -> None: + if not isinstance(value, bool): + raise PyAMLException(f"{self._device.name()}: expected a boolean flag, got {value!r}") + self._device.set(value) def check_range(values: Any, dev_range: Any) -> bool: diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index fa5116a77..fc86626a2 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -19,7 +19,6 @@ from ..common.switch_element import SwitchElement from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( - CSBinaryState, CSScalarAggregator, CSSparseScalarAggregator, CSStrengthScalarAggregator, @@ -32,6 +31,7 @@ RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, + RWScalarBoolean, RWSerializedStrengthScalar, RWStrengthArray, RWStrengthScalar, @@ -282,7 +282,7 @@ def _fill_switch_element(self, element: SwitchElement) -> None: device = self.get_device_access(element.device) if device is None: raise PyAMLException(f"{element.name}: switch channel {element.device!r} is unavailable") - self._add(self._ALL, element.attach(self, CSBinaryState(device))) + self._add(self._ALL, element.attach(self, RWScalarBoolean(device))) def _fill_unbound_element(self, element: UnboundElement) -> None: if self.name() not in element._control_modes: diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index f4abc1c62..eb2e27e06 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -21,20 +21,23 @@ # ------------------------------------------------------------------------------ -class SimulatedBinaryState(abstract.BinaryState): +class RWScalarBoolean(abstract.RWScalarBoolean): """Maintain an initially disabled boolean state independent of the lattice.""" - def __init__(self): + def __init__(self, name: str): + self._name = name self._enabled = False - def set_and_wait(self, value: bool) -> None: - """Set the simulated state immediately.""" - self._enabled = value - - def readback(self) -> bool: + def get(self) -> bool: """Return the simulated boolean state.""" return self._enabled + def set(self, value: bool) -> None: + """Store a boolean without accessing the lattice.""" + if not isinstance(value, bool): + raise PyAMLException(f"{self._name}: expected a boolean flag, got {value!r}") + self._enabled = value + def _effective_lengths(elements: list[at.Element]) -> list[float]: """ diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index e28b95038..ff40de1c5 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -34,11 +34,11 @@ RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, + RWScalarBoolean, RWSerializedHardware, RWSerializedStrength, RWStrengthArray, RWStrengthScalar, - SimulatedBinaryState, update_bpm_transform_matrix, ) from ..magnet.cfm_magnet import CombinedFunctionMagnet @@ -341,7 +341,7 @@ def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: self.add_tool(tool.attach(self)) def _fill_switch_element(self, element: SwitchElement) -> None: - self._add(self._ALL, element.attach(self, SimulatedBinaryState())) + self._add(self._ALL, element.attach(self, RWScalarBoolean(element.name))) def _fill_unbound_element(self, element: "UnboundElement") -> None: pass diff --git a/tests/common/test_switch_element.py b/tests/common/test_switch_element.py index 89e9f5c67..26a8b23cb 100644 --- a/tests/common/test_switch_element.py +++ b/tests/common/test_switch_element.py @@ -2,7 +2,7 @@ import pytest -from pyaml.common.abstract import BinaryState +from pyaml.common import abstract from pyaml.common.exception import PyAMLConfigException, PyAMLException from pyaml.common.switch_element import SwitchElement from pyaml.configuration.factory import Factory @@ -19,14 +19,16 @@ def switch(): return SwitchElement("SOFB", "SOFB_ENABLED", description="Slow orbit feedback") -@pytest.mark.parametrize("operation", ["enable", "disable", "is_enabled"]) +@pytest.mark.parametrize("operation", ["enable", "disable", "is_enabled", "enabled"]) def test_unattached_operations_raise(switch, operation): - with pytest.raises(PyAMLException, match="SOFB has no attached switch channel"): - getattr(switch, operation)() + with pytest.raises(PyAMLException, match="SOFB: enabled state is unavailable before attachment"): + value = getattr(switch, operation) + if operation != "enabled": + value() def test_attachment_copies_configuration_without_io(switch): - state = create_autospec(BinaryState, instance=True) + state = create_autospec(abstract.RWScalarBoolean, instance=True) peer = create_autospec(ControlSystemAdapter, instance=True) peer.name.return_value = "live" @@ -44,6 +46,22 @@ def test_attachment_copies_configuration_without_io(switch): assert state.mock_calls == [] +def test_element_delegates_to_boolean_accessor(switch): + enabled = create_autospec(abstract.RWScalarBoolean, instance=True) + attached = switch.attach(DispatchHolder(), enabled=enabled) + + attached.enable() + enabled.set.assert_called_once_with(True) + enabled.get.assert_not_called() + enabled.reset_mock() + attached.disable() + enabled.set.assert_called_once_with(False) + enabled.get.assert_not_called() + enabled.get.return_value = False + assert attached.is_enabled() is False + enabled.get.assert_called_once_with() + + def test_unsupported_holder_raises_without_new_abstract_requirement(switch): holder = DispatchHolder() diff --git a/tests/control/test_switch_controlsystem.py b/tests/control/test_switch_controlsystem.py index 19013cbe4..4c4c5cff2 100644 --- a/tests/control/test_switch_controlsystem.py +++ b/tests/control/test_switch_controlsystem.py @@ -19,7 +19,7 @@ def device(): def write(value): device.readback.return_value = Value(value) - device.set_and_wait.side_effect = write + device.set.side_effect = write return device @@ -40,79 +40,86 @@ def test_attachment_and_representation_do_not_access_channel(live, device): @pytest.mark.parametrize("enabled,operation", [(True, "enable"), (False, "disable")]) -def test_operation_waits_then_verifies_actual_readback(live, device, enabled, operation): +def test_operation_uses_set_without_waiting_or_completion_checks(live, device, enabled, operation): getattr(live["SOFB"], operation)() - assert device.mock_calls == [call.set_and_wait(enabled), call.readback()] - assert type(device.set_and_wait.call_args.args[0]) is bool + assert device.mock_calls == [call.set(enabled)] + assert type(device.set.call_args.args[0]) is bool assert live["SOFB"].is_enabled() is enabled - device.set.assert_not_called() + device.set_and_wait.assert_not_called() device.get.assert_not_called() -@pytest.mark.parametrize("value", [True, False, np.bool_(True), np.bool_(False)]) +def test_direct_boolean_accessor_writes_and_reads(live, device): + switch = live["SOFB"] + switch.enabled.set(False) + assert switch.enabled.get() is False + switch.enabled.set(True) + assert switch.enabled.get() is True + assert device.mock_calls == [call.set(False), call.readback(), call.set(True), call.readback()] + + +@pytest.mark.parametrize("value", [True, False, np.bool_(True), np.bool_(False), 0, 1, 0.0, 1.0, np.int64(1)]) @pytest.mark.parametrize("wrapped", [False, True]) def test_status_returns_native_boolean_from_actual_readback(live, device, value, wrapped): device.get.return_value = not bool(value) device.readback.return_value = Value(value) if wrapped else value + assert live["SOFB"].enabled.get() is bool(value) assert live["SOFB"].is_enabled() is bool(value) device.get.assert_not_called() @pytest.mark.parametrize( "value", - [0, 1, 0.0, 1.0, np.int64(1), np.float64(0), "true", "False", None, [True], np.array([True]), np.array(True)], + [2, -1, 0.5, np.nan, "true", "False", None, [True], {"enabled": True}], ) @pytest.mark.parametrize("wrapped", [False, True]) def test_status_rejects_non_boolean_readback(live, device, value, wrapped): device.readback.return_value = Value(value) if wrapped else value - with pytest.raises(PyAMLException, match="feedback/enabled: expected boolean readback"): - live["SOFB"].is_enabled() + with pytest.raises(PyAMLException, match="feedback/enabled: expected a boolean flag"): + live["SOFB"].enabled.get() @pytest.mark.parametrize("quality", [Quality.INVALID, Quality.ALARM, Quality.CHANGING, Quality.WARNING]) -@pytest.mark.parametrize("operation", ["enable", "disable", "is_enabled"]) -def test_non_valid_quality_is_not_reported_as_success(live, device, quality, operation): - device.set_and_wait.side_effect = None +def test_boolean_accessor_adds_no_quality_policy(live, device, quality): device.readback.return_value = Value(True, quality=quality) - with pytest.raises(PyAMLException, match=f"feedback/enabled: expected VALID boolean readback, got quality {quality}"): - getattr(live["SOFB"], operation)() + assert live["SOFB"].enabled.get() is True @pytest.mark.parametrize("enabled,operation", [(True, "enable"), (False, "disable")]) -def test_confirmation_mismatch_raises(live, device, enabled, operation): - device.set_and_wait.side_effect = None +def test_write_does_not_claim_completion_or_cache_commanded_state(live, device, enabled, operation): + device.set.side_effect = None device.get.return_value = enabled device.readback.return_value = Value(not enabled) - with pytest.raises(PyAMLException, match=f"SOFB: readback did not confirm enabled={enabled}"): - getattr(live["SOFB"], operation)() + getattr(live["SOFB"], operation)() + device.readback.assert_not_called() + assert live["SOFB"].enabled.get() is not enabled + device.set_and_wait.assert_not_called() device.get.assert_not_called() -@pytest.mark.parametrize("operation", ["enable", "disable"]) -def test_non_boolean_confirmation_raises(live, device, operation): - device.set_and_wait.side_effect = None - device.readback.return_value = Value(1) - - with pytest.raises(PyAMLException, match="expected boolean readback"): - getattr(live["SOFB"], operation)() +@pytest.mark.parametrize("value", [0, 1, 0.0, np.bool_(True), "true", None, [True]]) +def test_direct_writes_require_python_boolean(live, device, value): + with pytest.raises(PyAMLException, match="feedback/enabled: expected a boolean flag"): + live["SOFB"].enabled.set(value) + device.set.assert_not_called() -@pytest.mark.parametrize("error", [TimeoutError("timed out"), NotImplementedError("cannot wait"), OSError("disconnected")]) +@pytest.mark.parametrize("error", [TimeoutError("timed out"), NotImplementedError("read-only"), OSError("disconnected")]) @pytest.mark.parametrize("operation", ["enable", "disable"]) -def test_backend_wait_errors_propagate_without_fallback(live, device, error, operation): - device.set_and_wait.side_effect = error +def test_backend_write_errors_propagate(live, device, error, operation): + device.set.side_effect = error with pytest.raises(type(error)) as exc: getattr(live["SOFB"], operation)() assert exc.value is error - device.set.assert_not_called() + device.set_and_wait.assert_not_called() device.readback.assert_not_called() diff --git a/tests/lattice/test_switch_simulator.py b/tests/lattice/test_switch_simulator.py index 465b45472..3e0095b84 100644 --- a/tests/lattice/test_switch_simulator.py +++ b/tests/lattice/test_switch_simulator.py @@ -33,6 +33,7 @@ def test_simulated_switch_bypasses_lattice_lookup(design, monkeypatch): lookup = Mock(side_effect=AssertionError("Switch must not resolve a lattice element")) monkeypatch.setattr(design, "get_at_elems", lookup) monkeypatch.setattr(design, "_linker", Mock()) + monkeypatch.setattr(design, "ring", Mock()) configured = SwitchElement("NO_LATTICE_EQUIVALENT", "UNRESOLVED_DEVICE") design.fill_device([configured]) @@ -41,20 +42,36 @@ def test_simulated_switch_bypasses_lattice_lookup(design, monkeypatch): assert switch is not configured assert switch.peer is design assert configured.peer is None - assert switch.is_enabled() is False + assert switch.enabled.get() is False for _ in range(2): - switch.enable() - assert switch.is_enabled() is True + switch.enabled.set(True) + assert switch.enabled.get() is True switch.disable() assert switch.is_enabled() is False + switch.enable() + assert switch.enabled.get() is True + switch.enabled.set(False) lookup.assert_not_called() assert design._linker.mock_calls == [] + assert design.ring.mock_calls == [] + + +@pytest.mark.parametrize("value", [0, 1, 0.0, "true", None, [True]]) +def test_simulated_boolean_accessor_rejects_invalid_writes_without_changing_state(design, value): + design.fill_device([SwitchElement("SOFB", "SOFB_ENABLED")]) + switch = design["SOFB"] + switch.enabled.set(True) + + with pytest.raises(PyAMLException, match="SOFB: expected a boolean flag"): + switch.enabled.set(value) + + assert switch.enabled.get() is True def test_simulated_state_is_independent_per_element_and_mode(design, ebs_lattice_file): configured = SwitchElement("SOFB", "SOFB_ENABLED") design.fill_device([configured, SwitchElement("FOFB", "FOFB_ENABLED")]) - design["SOFB"].enable() + design["SOFB"].enabled.set(True) other = Simulator(name="other", lattice=str(ebs_lattice_file)) other.fill_device([configured]) @@ -123,15 +140,15 @@ def test_accelerator_configuration_keeps_live_and_simulated_state_separate( set_spy.assert_not_called() assert sr.live["SOFB"].peer is sr.live assert sr.design["SOFB"].peer is sr.design - assert sr.live["SOFB"].is_enabled() is True - assert sr.design["SOFB"].is_enabled() is False + assert sr.live["SOFB"].enabled.get() is True + assert sr.design["SOFB"].enabled.get() is False assert sr.design.diagnostic.bpm["BPM_C04-01"] is not None - sr.design["SOFB"].enable() + sr.design["SOFB"].enabled.set(True) sr.design["SOFB"].disable() assert get_attribute(device_name) is True - sr.live["SOFB"].disable() - assert sr.live["SOFB"].is_enabled() is False + sr.live["SOFB"].enabled.set(False) + assert sr.live["SOFB"].enabled.get() is False sr.design["SOFB"].enable() assert sr.live["SOFB"].is_enabled() is False sr.live["SOFB"].enable() From f0c540f23250ed928bd0c992d588648c6bfbc322 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Thu, 26 Nov 2026 11:51:41 +0100 Subject: [PATCH 3/5] Renamed RWScalarBoolean to RWBooleanScalar. --- pyaml/common/abstract.py | 2 +- pyaml/common/switch_element.py | 10 +++++----- pyaml/control/abstract_impl.py | 2 +- pyaml/control/controlsystem.py | 4 ++-- pyaml/lattice/abstract_impl.py | 2 +- pyaml/lattice/simulator.py | 4 ++-- tests/common/test_switch_element.py | 4 ++-- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 4963cfd1a..78526abed 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -11,7 +11,7 @@ from numpy import array, double -class RWScalarBoolean(metaclass=ABCMeta): +class RWBooleanScalar(metaclass=ABCMeta): """Define backend-independent boolean get/set access.""" @abstractmethod diff --git a/pyaml/common/switch_element.py b/pyaml/common/switch_element.py index 0c0703416..c4175f5ff 100644 --- a/pyaml/common/switch_element.py +++ b/pyaml/common/switch_element.py @@ -37,7 +37,7 @@ class SwitchElement(Element, DynamicValidation): Notes ----- - Control-system access uses the reusable RWScalarBoolean adapter: get() + Control-system access uses the reusable RWBooleanScalar adapter: get() reads the backend readback (including numeric 0/1 flags) and set() writes a Python boolean through DeviceAccess.set(). Value metadata is unwrapped; this interface adds no quality, waiting, or completion policy. Backend @@ -79,9 +79,9 @@ def __init__(self, name: str, device: str, description: str | None = None): """Initialize the element configuration without accessing hardware.""" super().__init__(name=name, description=description) self.device = device - self._enabled: abstract.RWScalarBoolean | None = None + self._enabled: abstract.RWBooleanScalar | None = None - def attach(self, peer: "ElementHolder", enabled: abstract.RWScalarBoolean) -> Self: + def attach(self, peer: "ElementHolder", enabled: abstract.RWBooleanScalar) -> Self: """ Return a copy bound to a peer and its boolean state interface. @@ -89,7 +89,7 @@ def attach(self, peer: "ElementHolder", enabled: abstract.RWScalarBoolean) -> Se ---------- peer : ElementHolder Control system or simulator owning this runtime element. - enabled : abstract.RWScalarBoolean + enabled : abstract.RWBooleanScalar Boolean get/set interface owned by this attachment. Returns @@ -103,7 +103,7 @@ def attach(self, peer: "ElementHolder", enabled: abstract.RWScalarBoolean) -> Se return obj @property - def enabled(self) -> abstract.RWScalarBoolean: + def enabled(self) -> abstract.RWBooleanScalar: """Return the boolean get/set accessor for this holder.""" if self._enabled is None: raise PyAMLException(f"{self.name}: enabled state is unavailable before attachment") diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 27c32dada..399efdb76 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -26,7 +26,7 @@ # ------------------------------------------------------------------------------ -class RWScalarBoolean(abstract.RWScalarBoolean): +class RWBooleanScalar(abstract.RWBooleanScalar): """Expose a backend boolean through reusable get/set accessors.""" def __init__(self, device: DeviceAccess): diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index fc86626a2..d2ab84dfa 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -24,6 +24,7 @@ CSStrengthScalarAggregator, RBetatronTuneArray, RBpmArray, + RWBooleanScalar, RWBpmOffsetArray, RWBpmTiltScalar, RWHardwareArray, @@ -31,7 +32,6 @@ RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, - RWScalarBoolean, RWSerializedStrengthScalar, RWStrengthArray, RWStrengthScalar, @@ -282,7 +282,7 @@ def _fill_switch_element(self, element: SwitchElement) -> None: device = self.get_device_access(element.device) if device is None: raise PyAMLException(f"{element.name}: switch channel {element.device!r} is unavailable") - self._add(self._ALL, element.attach(self, RWScalarBoolean(device))) + self._add(self._ALL, element.attach(self, RWBooleanScalar(device))) def _fill_unbound_element(self, element: UnboundElement) -> None: if self.name() not in element._control_modes: diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index eb2e27e06..49a484c95 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -21,7 +21,7 @@ # ------------------------------------------------------------------------------ -class RWScalarBoolean(abstract.RWScalarBoolean): +class RWBooleanScalar(abstract.RWBooleanScalar): """Maintain an initially disabled boolean state independent of the lattice.""" def __init__(self, name: str): diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index ff40de1c5..bdf676e4a 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -25,6 +25,7 @@ BPMVScalarAggregator, RBetatronTuneArray, RBpmArray, + RWBooleanScalar, RWBpmOffsetArray, RWBpmTiltScalar, RWHardwareArray, @@ -34,7 +35,6 @@ RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, - RWScalarBoolean, RWSerializedHardware, RWSerializedStrength, RWStrengthArray, @@ -341,7 +341,7 @@ def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: self.add_tool(tool.attach(self)) def _fill_switch_element(self, element: SwitchElement) -> None: - self._add(self._ALL, element.attach(self, RWScalarBoolean(element.name))) + self._add(self._ALL, element.attach(self, RWBooleanScalar(element.name))) def _fill_unbound_element(self, element: "UnboundElement") -> None: pass diff --git a/tests/common/test_switch_element.py b/tests/common/test_switch_element.py index 26a8b23cb..9ab2ccd77 100644 --- a/tests/common/test_switch_element.py +++ b/tests/common/test_switch_element.py @@ -28,7 +28,7 @@ def test_unattached_operations_raise(switch, operation): def test_attachment_copies_configuration_without_io(switch): - state = create_autospec(abstract.RWScalarBoolean, instance=True) + state = create_autospec(abstract.RWBooleanScalar, instance=True) peer = create_autospec(ControlSystemAdapter, instance=True) peer.name.return_value = "live" @@ -47,7 +47,7 @@ def test_attachment_copies_configuration_without_io(switch): def test_element_delegates_to_boolean_accessor(switch): - enabled = create_autospec(abstract.RWScalarBoolean, instance=True) + enabled = create_autospec(abstract.RWBooleanScalar, instance=True) attached = switch.attach(DispatchHolder(), enabled=enabled) attached.enable() From 848e6c75cf1d4bbf94b37c39edb53c9e8ec430e5 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Thu, 26 Nov 2026 16:51:17 +0100 Subject: [PATCH 4/5] Reduced number of tests --- tests/common/test_switch_element.py | 47 ++-------- tests/control/test_switch_controlsystem.py | 103 +++++++++------------ tests/lattice/test_switch_simulator.py | 54 +++++------ 3 files changed, 74 insertions(+), 130 deletions(-) diff --git a/tests/common/test_switch_element.py b/tests/common/test_switch_element.py index 9ab2ccd77..04b506743 100644 --- a/tests/common/test_switch_element.py +++ b/tests/common/test_switch_element.py @@ -3,7 +3,7 @@ import pytest from pyaml.common import abstract -from pyaml.common.exception import PyAMLConfigException, PyAMLException +from pyaml.common.exception import PyAMLException from pyaml.common.switch_element import SwitchElement from pyaml.configuration.factory import Factory from pyaml.control.controlsystem import ControlSystemAdapter @@ -19,15 +19,7 @@ def switch(): return SwitchElement("SOFB", "SOFB_ENABLED", description="Slow orbit feedback") -@pytest.mark.parametrize("operation", ["enable", "disable", "is_enabled", "enabled"]) -def test_unattached_operations_raise(switch, operation): - with pytest.raises(PyAMLException, match="SOFB: enabled state is unavailable before attachment"): - value = getattr(switch, operation) - if operation != "enabled": - value() - - -def test_attachment_copies_configuration_without_io(switch): +def test_attachment_copies_configuration_and_delegates_to_accessor(switch): state = create_autospec(abstract.RWBooleanScalar, instance=True) peer = create_autospec(ControlSystemAdapter, instance=True) peer.name.return_value = "live" @@ -45,21 +37,16 @@ def test_attachment_copies_configuration_without_io(switch): assert "unavailable" not in repr(attached) assert state.mock_calls == [] - -def test_element_delegates_to_boolean_accessor(switch): - enabled = create_autospec(abstract.RWBooleanScalar, instance=True) - attached = switch.attach(DispatchHolder(), enabled=enabled) - attached.enable() - enabled.set.assert_called_once_with(True) - enabled.get.assert_not_called() - enabled.reset_mock() + state.set.assert_called_once_with(True) + state.get.assert_not_called() + state.reset_mock() attached.disable() - enabled.set.assert_called_once_with(False) - enabled.get.assert_not_called() - enabled.get.return_value = False + state.set.assert_called_once_with(False) + state.get.assert_not_called() + state.get.return_value = False assert attached.is_enabled() is False - enabled.get.assert_called_once_with() + state.get.assert_called_once_with() def test_unsupported_holder_raises_without_new_abstract_requirement(switch): @@ -75,7 +62,6 @@ def test_unsupported_holder_raises_without_new_abstract_requirement(switch): "declaration", [ {"class": CLASS_PATH}, - {"class_path": CLASS_PATH}, {"type": "pyaml.common.switch_element"}, ], ) @@ -104,18 +90,3 @@ def test_schema_is_discoverable_and_requires_one_device(): assert {"name", "device"} <= set(schema["required"]) assert schema["properties"]["device"]["type"] == "string" assert "initial_enabled" not in schema["properties"] - - -@pytest.mark.parametrize("device", [None, True, 1, ["SOFB_ENABLED"]]) -def test_constructor_rejects_non_string_device(device): - with pytest.raises(PyAMLConfigException): - SwitchElement("SOFB", device) - - -def test_schema_rejects_extra_configuration(): - generate_configuration_schema(SwitchElement) - - with pytest.raises(PyAMLConfigException, match="initial_enabled"): - SchemaValidator.validate_to_dict( - {"class": CLASS_PATH, "name": "SOFB", "device": "SOFB_ENABLED", "initial_enabled": True} - ) diff --git a/tests/control/test_switch_controlsystem.py b/tests/control/test_switch_controlsystem.py index 4c4c5cff2..df0d4f71d 100644 --- a/tests/control/test_switch_controlsystem.py +++ b/tests/control/test_switch_controlsystem.py @@ -15,11 +15,6 @@ def device(): device = create_autospec(DeviceAccess, instance=True) device.name.return_value = "feedback/enabled" device.readback.return_value = Value(True) - - def write(value): - device.readback.return_value = Value(value) - - device.set.side_effect = write return device @@ -39,84 +34,74 @@ def test_attachment_and_representation_do_not_access_channel(live, device): assert device.mock_calls == [] -@pytest.mark.parametrize("enabled,operation", [(True, "enable"), (False, "disable")]) -def test_operation_uses_set_without_waiting_or_completion_checks(live, device, enabled, operation): - getattr(live["SOFB"], operation)() - - assert device.mock_calls == [call.set(enabled)] - assert type(device.set.call_args.args[0]) is bool - assert live["SOFB"].is_enabled() is enabled - device.set_and_wait.assert_not_called() - device.get.assert_not_called() - - -def test_direct_boolean_accessor_writes_and_reads(live, device): +def test_commands_and_accessor_write_without_waiting_and_read_actual_state(live, device): switch = live["SOFB"] - switch.enabled.set(False) + device.readback.return_value = Value(False) + + switch.enable() assert switch.enabled.get() is False - switch.enabled.set(True) + device.readback.return_value = Value(True) + switch.disable() + assert switch.is_enabled() is True + switch.enabled.set(False) assert switch.enabled.get() is True - assert device.mock_calls == [call.set(False), call.readback(), call.set(True), call.readback()] + device.readback.return_value = Value(False) + assert switch.is_enabled() is False + + assert device.mock_calls == [ + call.set(True), + call.readback(), + call.set(False), + call.readback(), + call.set(False), + call.readback(), + call.readback(), + ] + device.set_and_wait.assert_not_called() + device.get.assert_not_called() -@pytest.mark.parametrize("value", [True, False, np.bool_(True), np.bool_(False), 0, 1, 0.0, 1.0, np.int64(1)]) -@pytest.mark.parametrize("wrapped", [False, True]) -def test_status_returns_native_boolean_from_actual_readback(live, device, value, wrapped): - device.get.return_value = not bool(value) - device.readback.return_value = Value(value) if wrapped else value +@pytest.mark.parametrize( + "value,expected", + [ + pytest.param(False, False, id="boolean"), + pytest.param(Value(True, quality=Quality.INVALID), True, id="wrapped-boolean-invalid-quality"), + pytest.param(0, False, id="numeric-zero"), + pytest.param(Value(1), True, id="wrapped-numeric-one"), + pytest.param(np.bool_(True), True, id="numpy-boolean"), + ], +) +def test_status_returns_native_boolean_from_actual_readback(live, device, value, expected): + device.get.return_value = not expected + device.readback.return_value = value - assert live["SOFB"].enabled.get() is bool(value) - assert live["SOFB"].is_enabled() is bool(value) + assert live["SOFB"].enabled.get() is expected device.get.assert_not_called() @pytest.mark.parametrize( - "value", - [2, -1, 0.5, np.nan, "true", "False", None, [True], {"enabled": True}], + "value", [pytest.param(2, id="numeric"), pytest.param(Value("off"), id="wrapped-string"), pytest.param(None, id="missing")] ) -@pytest.mark.parametrize("wrapped", [False, True]) -def test_status_rejects_non_boolean_readback(live, device, value, wrapped): - device.readback.return_value = Value(value) if wrapped else value +def test_status_rejects_non_boolean_readback(live, device, value): + device.readback.return_value = value with pytest.raises(PyAMLException, match="feedback/enabled: expected a boolean flag"): live["SOFB"].enabled.get() -@pytest.mark.parametrize("quality", [Quality.INVALID, Quality.ALARM, Quality.CHANGING, Quality.WARNING]) -def test_boolean_accessor_adds_no_quality_policy(live, device, quality): - device.readback.return_value = Value(True, quality=quality) - - assert live["SOFB"].enabled.get() is True - - -@pytest.mark.parametrize("enabled,operation", [(True, "enable"), (False, "disable")]) -def test_write_does_not_claim_completion_or_cache_commanded_state(live, device, enabled, operation): - device.set.side_effect = None - device.get.return_value = enabled - device.readback.return_value = Value(not enabled) - - getattr(live["SOFB"], operation)() - - device.readback.assert_not_called() - assert live["SOFB"].enabled.get() is not enabled - device.set_and_wait.assert_not_called() - device.get.assert_not_called() - - -@pytest.mark.parametrize("value", [0, 1, 0.0, np.bool_(True), "true", None, [True]]) +@pytest.mark.parametrize("value", [1, np.bool_(True), "true"]) def test_direct_writes_require_python_boolean(live, device, value): with pytest.raises(PyAMLException, match="feedback/enabled: expected a boolean flag"): live["SOFB"].enabled.set(value) device.set.assert_not_called() -@pytest.mark.parametrize("error", [TimeoutError("timed out"), NotImplementedError("read-only"), OSError("disconnected")]) -@pytest.mark.parametrize("operation", ["enable", "disable"]) -def test_backend_write_errors_propagate(live, device, error, operation): +def test_backend_write_errors_propagate(live, device): + error = OSError("disconnected") device.set.side_effect = error - with pytest.raises(type(error)) as exc: - getattr(live["SOFB"], operation)() + with pytest.raises(OSError) as exc: + live["SOFB"].enable() assert exc.value is error device.set_and_wait.assert_not_called() diff --git a/tests/lattice/test_switch_simulator.py b/tests/lattice/test_switch_simulator.py index 3e0095b84..342e39118 100644 --- a/tests/lattice/test_switch_simulator.py +++ b/tests/lattice/test_switch_simulator.py @@ -1,14 +1,13 @@ -import json from unittest.mock import Mock import pytest import yaml from pyaml.accelerator import Accelerator -from pyaml.arrays.element_array import ElementArray from pyaml.common.exception import PyAMLException from pyaml.common.switch_element import SwitchElement from pyaml.control.controlsystem import ControlSystemAdapter +from pyaml.lattice.abstract_impl import RWBooleanScalar from pyaml.lattice.simulator import Simulator from pyaml.validation import register_schema from pyaml.validation.schema_builder import generate_configuration_schema @@ -43,29 +42,28 @@ def test_simulated_switch_bypasses_lattice_lookup(design, monkeypatch): assert switch.peer is design assert configured.peer is None assert switch.enabled.get() is False - for _ in range(2): - switch.enabled.set(True) - assert switch.enabled.get() is True - switch.disable() - assert switch.is_enabled() is False - switch.enable() - assert switch.enabled.get() is True - switch.enabled.set(False) + switch.enabled.set(True) + assert switch.enabled.get() is True + switch.disable() + assert switch.is_enabled() is False + switch.enable() + assert switch.enabled.get() is True + switch.enabled.set(False) + assert switch.enabled.get() is False lookup.assert_not_called() assert design._linker.mock_calls == [] assert design.ring.mock_calls == [] -@pytest.mark.parametrize("value", [0, 1, 0.0, "true", None, [True]]) -def test_simulated_boolean_accessor_rejects_invalid_writes_without_changing_state(design, value): - design.fill_device([SwitchElement("SOFB", "SOFB_ENABLED")]) - switch = design["SOFB"] - switch.enabled.set(True) +@pytest.mark.parametrize("value", [1, "true"]) +def test_simulated_boolean_accessor_rejects_invalid_writes_without_changing_state(value): + enabled = RWBooleanScalar("SOFB") + enabled.set(True) with pytest.raises(PyAMLException, match="SOFB: expected a boolean flag"): - switch.enabled.set(value) + enabled.set(value) - assert switch.enabled.get() is True + assert enabled.get() is True def test_simulated_state_is_independent_per_element_and_mode(design, ebs_lattice_file): @@ -84,27 +82,17 @@ def test_simulated_state_is_independent_per_element_and_mode(design, ebs_lattice assert configured.peer is None -def test_generic_lookup_arrays_and_duplicate_names(design): - design.fill_device([SwitchElement("SOFB", "SOFB_ENABLED"), SwitchElement("FOFB", "FOFB_ENABLED")]) +def test_duplicate_registration_does_not_replace_simulated_switch(design): + design.fill_device([SwitchElement("SOFB", "SOFB_ENABLED")]) original = design["SOFB"] - assert design.get().names() == ["SOFB", "FOFB"] - assert type(design["*OFB"]) is ElementArray - assert design["*OFB"].names() == ["SOFB", "FOFB"] - design.fill_element_array("FEEDBACKS", ["SOFB", "FOFB"]) - assert design.get("FEEDBACKS")[0] is original - with pytest.raises(PyAMLException, match="Duplicate element"): design.fill_device([SwitchElement("SOFB", "OTHER_CHANNEL")]) assert design["SOFB"] is original -@pytest.mark.parametrize("extension", ["yaml", "json"]) -@pytest.mark.parametrize("validate", [False, True]) -def test_accelerator_configuration_keeps_live_and_simulated_state_separate( - tmp_path, ebs_lattice_file, extension, validate, monkeypatch -): +def test_accelerator_configuration_keeps_live_and_simulated_state_separate(tmp_path, ebs_lattice_file, monkeypatch): from tango.pyaml.attribute import Attribute from tango.pyaml.attribute import ConfigModel as AttributeConfigModel from tango.pyaml.attribute_store import get_attribute, set_attribute @@ -130,12 +118,12 @@ def test_accelerator_configuration_keeps_live_and_simulated_state_separate( {"type": "pyaml.diagnostics.bpm.bpm", "name": "BPM_C04-01"}, ], } - config_path = tmp_path / f"switch.{extension}" - config_path.write_text(json.dumps(config) if extension == "json" else yaml.safe_dump(config), encoding="utf-8") + config_path = tmp_path / "switch.yaml" + config_path.write_text(yaml.safe_dump(config), encoding="utf-8") set_spy = Mock(side_effect=AssertionError("Loading must not write live hardware")) with monkeypatch.context() as patch: patch.setattr(Attribute, "set", set_spy) - sr = Accelerator.load(str(config_path), validate=validate) + sr = Accelerator.load(str(config_path), validate=True) set_spy.assert_not_called() assert sr.live["SOFB"].peer is sr.live From fe3ff8307bd1253a54db11153bc3214c667823e2 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Fri, 27 Nov 2026 11:35:24 +0100 Subject: [PATCH 5/5] Added methods to docstring. Enabled loading switch element without boolean channel in control system (simulator only). --- pyaml/common/switch_element.py | 13 ++++++++ pyaml/control/abstract_impl.py | 25 ++++++++++++---- pyaml/control/controlsystem.py | 5 ++-- tests/control/test_switch_controlsystem.py | 16 +++++++--- tests/lattice/test_switch_simulator.py | 35 +++++++++++++++------- 5 files changed, 71 insertions(+), 23 deletions(-) diff --git a/pyaml/common/switch_element.py b/pyaml/common/switch_element.py index c4175f5ff..5853aee24 100644 --- a/pyaml/common/switch_element.py +++ b/pyaml/common/switch_element.py @@ -35,6 +35,17 @@ class SwitchElement(Element, DynamicValidation): enabled Boolean get/set accessor, shared by control-system and simulator modes. + Methods + ------- + attach(peer, enabled) + Return a copy bound to a peer and its boolean accessor. + enable() + Write True through the boolean accessor. + disable() + Write False through the boolean accessor. + is_enabled() + Return actual boolean readback, not the commanded state. + Notes ----- Control-system access uses the reusable RWBooleanScalar adapter: get() @@ -42,6 +53,8 @@ class SwitchElement(Element, DynamicValidation): a Python boolean through DeviceAccess.set(). Value metadata is unwrapped; this interface adds no quality, waiting, or completion policy. Backend errors propagate. Construction and attachment never initialize hardware. + A missing control-system channel does not prevent configuration loading; + reading or writing its accessor raises an explicit error instead. Each simulator attachment starts disabled and maintains independent state without looking up or modifying a lattice element. This element does not diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 399efdb76..c6e825d64 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -27,23 +27,36 @@ class RWBooleanScalar(abstract.RWBooleanScalar): - """Expose a backend boolean through reusable get/set accessors.""" + """ + Expose a backend boolean through reusable get/set accessors. + + An unavailable device is reported only when read or written. ``name`` gives + diagnostic context when there is no device to supply its own name. + """ - def __init__(self, device: DeviceAccess): + def __init__(self, device: DeviceAccess | None, name: str = "Boolean channel"): self._device = device + self._name = name def get(self) -> bool: - value = self._device.readback() + device = self._require_device() + value = device.readback() if isinstance(value, Value): value = value.value if value not in (False, True): - raise PyAMLException(f"{self._device.name()}: expected a boolean flag, got {value!r}") + raise PyAMLException(f"{device.name()}: expected a boolean flag, got {value!r}") return bool(value) def set(self, value: bool) -> None: + device = self._require_device() if not isinstance(value, bool): - raise PyAMLException(f"{self._device.name()}: expected a boolean flag, got {value!r}") - self._device.set(value) + raise PyAMLException(f"{device.name()}: expected a boolean flag, got {value!r}") + device.set(value) + + def _require_device(self) -> DeviceAccess: + if self._device is None: + raise PyAMLException(f"{self._name} is unavailable") + return self._device def check_range(values: Any, dev_range: Any) -> bool: diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index d2ab84dfa..8c8e216f8 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -280,9 +280,8 @@ def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: def _fill_switch_element(self, element: SwitchElement) -> None: device = self.get_device_access(element.device) - if device is None: - raise PyAMLException(f"{element.name}: switch channel {element.device!r} is unavailable") - self._add(self._ALL, element.attach(self, RWBooleanScalar(device))) + enabled = RWBooleanScalar(device, name=f"{element.name}: switch channel {element.device!r}") + self._add(self._ALL, element.attach(self, enabled)) def _fill_unbound_element(self, element: UnboundElement) -> None: if self.name() not in element._control_modes: diff --git a/tests/control/test_switch_controlsystem.py b/tests/control/test_switch_controlsystem.py index df0d4f71d..5d87c9a80 100644 --- a/tests/control/test_switch_controlsystem.py +++ b/tests/control/test_switch_controlsystem.py @@ -118,14 +118,22 @@ def test_readback_errors_propagate(live, device): assert exc.value is error -def test_missing_device_is_rejected(monkeypatch): +@pytest.mark.parametrize("operation,args", [("get", ()), ("set", (True,))]) +def test_missing_device_is_rejected_only_on_access(monkeypatch, operation, args): holder = ControlSystemAdapter() - monkeypatch.setattr(holder, "get_device_access", lambda ref: None) + resolver = create_autospec(holder.get_device_access, return_value=None) + monkeypatch.setattr(holder, "get_device_access", resolver) + holder.fill_device([SwitchElement("SOFB", "MISSING")]) + switch = holder["SOFB"] + + assert switch.peer is holder + repr(switch) + holder.post_init() with pytest.raises(PyAMLException, match="SOFB: switch channel 'MISSING' is unavailable"): - holder.fill_device([SwitchElement("SOFB", "MISSING")]) + getattr(switch.enabled, operation)(*args) - assert holder.get().names() == [] + resolver.assert_called_once_with("MISSING") def test_device_resolution_errors_propagate(monkeypatch): diff --git a/tests/lattice/test_switch_simulator.py b/tests/lattice/test_switch_simulator.py index 342e39118..75af445cb 100644 --- a/tests/lattice/test_switch_simulator.py +++ b/tests/lattice/test_switch_simulator.py @@ -92,7 +92,10 @@ def test_duplicate_registration_does_not_replace_simulated_switch(design): assert design["SOFB"] is original -def test_accelerator_configuration_keeps_live_and_simulated_state_separate(tmp_path, ebs_lattice_file, monkeypatch): +@pytest.mark.parametrize("missing_live_channel", [False, True], ids=["available-live-channel", "missing-live-channel"]) +def test_accelerator_configuration_keeps_live_and_simulated_state_separate( + tmp_path, ebs_lattice_file, monkeypatch, missing_live_channel +): from tango.pyaml.attribute import Attribute from tango.pyaml.attribute import ConfigModel as AttributeConfigModel from tango.pyaml.attribute_store import get_attribute, set_attribute @@ -102,7 +105,11 @@ def test_accelerator_configuration_keeps_live_and_simulated_state_separate(tmp_p monkeypatch.setattr( ControlSystemAdapter, "get_device_access", - lambda self, ref: None if ref is None else Attribute(AttributeConfigModel(attribute=ref)), + lambda self, ref: ( + None + if ref is None or (missing_live_channel and ref == device_name) + else Attribute(AttributeConfigModel(attribute=ref)) + ), ) for cls in (SwitchElement, SwitchTestControlSystem, Simulator, Accelerator): generate_configuration_schema(cls) @@ -128,17 +135,25 @@ def test_accelerator_configuration_keeps_live_and_simulated_state_separate(tmp_p set_spy.assert_not_called() assert sr.live["SOFB"].peer is sr.live assert sr.design["SOFB"].peer is sr.design - assert sr.live["SOFB"].enabled.get() is True assert sr.design["SOFB"].enabled.get() is False assert sr.design.diagnostic.bpm["BPM_C04-01"] is not None sr.design["SOFB"].enabled.set(True) sr.design["SOFB"].disable() assert get_attribute(device_name) is True - sr.live["SOFB"].enabled.set(False) - assert sr.live["SOFB"].enabled.get() is False - sr.design["SOFB"].enable() - assert sr.live["SOFB"].is_enabled() is False - sr.live["SOFB"].enable() - assert sr.live["SOFB"].is_enabled() is True - assert sr.design["SOFB"].is_enabled() is True + if missing_live_channel: + with pytest.raises(PyAMLException, match="switch channel .* is unavailable"): + sr.live["SOFB"].enabled.get() + with pytest.raises(PyAMLException, match="switch channel .* is unavailable"): + sr.live["SOFB"].enable() + sr.design["SOFB"].enable() + assert sr.design["SOFB"].is_enabled() is True + else: + assert sr.live["SOFB"].enabled.get() is True + sr.live["SOFB"].enabled.set(False) + assert sr.live["SOFB"].enabled.get() is False + sr.design["SOFB"].enable() + assert sr.live["SOFB"].is_enabled() is False + sr.live["SOFB"].enable() + assert sr.live["SOFB"].is_enabled() is True + assert sr.design["SOFB"].is_enabled() is True