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 1e4c881c8..498a72ffa 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -12,6 +12,21 @@ from .units import AcceptsQuantity + +class RWBooleanScalar(metaclass=ABCMeta): + """Define backend-independent boolean get/set access.""" + + @abstractmethod + def get(self) -> bool: + """Return the boolean state.""" + pass + + @abstractmethod + def set(self, value: bool) -> None: + """Write the boolean state.""" + pass + + # Float ---------------------------------------------------------------- diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index f73783719..4f121f4ed 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -34,6 +34,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): @@ -197,6 +198,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..5853aee24 --- /dev/null +++ b/pyaml/common/switch_element.py @@ -0,0 +1,150 @@ +"""Switchable accelerator functionality without a required lattice counterpart.""" + +import copy +from typing import TYPE_CHECKING, Self + +from ..validation import DynamicValidation, register_schema +from . import abstract +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. + + Attributes + ---------- + 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() + 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. + 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 + 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() + enabled = feedback.enabled.get() + feedback.enabled.set(True) + feedback.enable() + + simulated_feedback = sr.design["SOFB"] + 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._enabled: abstract.RWBooleanScalar | None = None + + def attach(self, peer: "ElementHolder", enabled: abstract.RWBooleanScalar) -> Self: + """ + Return a copy bound to a peer and its boolean state interface. + + Parameters + ---------- + peer : ElementHolder + Control system or simulator owning this runtime element. + enabled : abstract.RWBooleanScalar + Boolean get/set interface owned by this attachment. + + Returns + ------- + Self + Attached copy; the original configuration remains unattached. + """ + obj = copy.copy(self) + obj._enabled = enabled + obj._peer = peer + return obj + + @property + 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") + return self._enabled + + def enable(self) -> None: + """Enable the functionality through its boolean accessor.""" + self.enabled.set(True) + + def disable(self) -> None: + """Disable the functionality through its boolean accessor.""" + self.enabled.set(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 the backend value is not a boolean flag. + """ + 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 fff6d236e..4d1d36718 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -23,10 +23,44 @@ from ..magnet.model import MagnetModel from ..rf.rf_plant import RFPlant from ..rf.rf_transmitter import RFTransmitter +from .readback_value import Value # ------------------------------------------------------------------------------ +class RWBooleanScalar(abstract.RWBooleanScalar): + """ + 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 | None, name: str = "Boolean channel"): + self._device = device + self._name = name + + def get(self) -> bool: + device = self._require_device() + value = device.readback() + if isinstance(value, Value): + value = value.value + if value not in (False, True): + 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"{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: """ Check whether values are within given ranges. diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index b053df942..91f7bc39f 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -16,6 +16,7 @@ from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLConfigException, PyAMLException from ..common.holders.element_holder import ElementHolder +from ..common.switch_element import SwitchElement from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, is_frequency_unit from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( @@ -25,6 +26,7 @@ CSStrengthScalarAggregator, RBetatronTuneArray, RBpmArray, + RWBooleanScalar, RWBpmOffsetArray, RWBpmTiltScalar, RWHardwareArray, @@ -360,6 +362,11 @@ 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) + 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: return diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index 82031078b..d8c7cdc8a 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -28,6 +28,24 @@ # ------------------------------------------------------------------------------ +class RWBooleanScalar(abstract.RWBooleanScalar): + """Maintain an initially disabled boolean state independent of the lattice.""" + + def __init__(self, name: str): + self._name = name + self._enabled = False + + 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]: """ 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 aea7921e9..ac9b08062 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 ( @@ -24,6 +25,7 @@ BPMVScalarAggregator, RBetatronTuneArray, RBpmArray, + RWBooleanScalar, RWBpmOffsetArray, RWBpmTiltScalar, RWHardwareArray, @@ -340,6 +342,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, 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 new file mode 100644 index 000000000..04b506743 --- /dev/null +++ b/tests/common/test_switch_element.py @@ -0,0 +1,92 @@ +from unittest.mock import create_autospec + +import pytest + +from pyaml.common import abstract +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 +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") + + +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" + + 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 == [] + + attached.enable() + state.set.assert_called_once_with(True) + state.get.assert_not_called() + state.reset_mock() + attached.disable() + state.set.assert_called_once_with(False) + state.get.assert_not_called() + state.get.return_value = False + assert attached.is_enabled() is False + state.get.assert_called_once_with() + + +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}, + {"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"] diff --git a/tests/control/test_switch_controlsystem.py b/tests/control/test_switch_controlsystem.py new file mode 100644 index 000000000..5d87c9a80 --- /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) + 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 == [] + + +def test_commands_and_accessor_write_without_waiting_and_read_actual_state(live, device): + switch = live["SOFB"] + device.readback.return_value = Value(False) + + switch.enable() + assert switch.enabled.get() is False + device.readback.return_value = Value(True) + switch.disable() + assert switch.is_enabled() is True + switch.enabled.set(False) + assert switch.enabled.get() is True + 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,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 expected + device.get.assert_not_called() + + +@pytest.mark.parametrize( + "value", [pytest.param(2, id="numeric"), pytest.param(Value("off"), id="wrapped-string"), pytest.param(None, id="missing")] +) +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("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() + + +def test_backend_write_errors_propagate(live, device): + error = OSError("disconnected") + device.set.side_effect = error + + with pytest.raises(OSError) as exc: + live["SOFB"].enable() + + assert exc.value is error + device.set_and_wait.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 + + +@pytest.mark.parametrize("operation,args", [("get", ()), ("set", (True,))]) +def test_missing_device_is_rejected_only_on_access(monkeypatch, operation, args): + holder = ControlSystemAdapter() + 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"): + getattr(switch.enabled, operation)(*args) + + resolver.assert_called_once_with("MISSING") + + +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..75af445cb --- /dev/null +++ b/tests/lattice/test_switch_simulator.py @@ -0,0 +1,159 @@ +from unittest.mock import Mock + +import pytest +import yaml + +from pyaml.accelerator import Accelerator +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 + + +@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()) + monkeypatch.setattr(design, "ring", 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.enabled.get() is 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", [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"): + enabled.set(value) + + assert 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"].enabled.set(True) + 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_duplicate_registration_does_not_replace_simulated_switch(design): + design.fill_device([SwitchElement("SOFB", "SOFB_ENABLED")]) + original = design["SOFB"] + + with pytest.raises(PyAMLException, match="Duplicate element"): + design.fill_device([SwitchElement("SOFB", "OTHER_CHANNEL")]) + + assert design["SOFB"] is original + + +@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 + + 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 or (missing_live_channel and ref == device_name) + 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 / "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=True) + + set_spy.assert_not_called() + assert sr.live["SOFB"].peer is sr.live + assert sr.design["SOFB"].peer is sr.design + 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 + + 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