Skip to content
22 changes: 20 additions & 2 deletions src/blueapi/client/device_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,35 @@ class DeviceRef(ClientObjectRef):

name: str
model: DeviceModel
parent: "DeviceRef | None" = None
children: dict[str, "DeviceRef"]
_cache: DeviceCache

def __init__(self, name: str, cache: DeviceCache, model: DeviceModel):
def __init__(
self,
name: str,
cache: DeviceCache,
model: DeviceModel,
parent: "DeviceRef | None" = None,
):
self.name = name
self.model = model
self._cache = cache
self.parent = parent
self.children = {}

def __getattr__(self, name: str) -> "DeviceRef":
if name.startswith("_"):
raise AttributeError(f"No child device named {name}")
return self._cache[f"{self.name}.{name}"]
try:
return self.children[name]
except KeyError as e:
raise AttributeError(
f"{self.name} doesn't have a child named {name}"
) from e

def __dir__(self):
return [*super().__dir__(), *self.children]

def __repr__(self):
return f"Device({self.name})"
5 changes: 5 additions & 0 deletions src/blueapi/service/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ class DeviceModel(BlueapiBaseModel):
protocols: list[ProtocolInfo] = Field(
description="Protocols that a device conforms to, indicating its capabilities"
)
children: dict[str, str] = Field(
description="Direct children that a device has, "
"with attribute as a key with the value of the child device's name",
default_factory=dict,
)

@classmethod
def from_device(cls, device: Device) -> "DeviceModel":
Expand Down
3 changes: 2 additions & 1 deletion tests/unit_tests/cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -812,7 +812,8 @@ def test_device_output_formatting():
"ComplexType"
]
}
]
],
"children": {}
}
]
""")
Expand Down
19 changes: 10 additions & 9 deletions tests/unit_tests/client/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
EnvironmentResponse,
PlanModel,
PlanResponse,
ProtocolInfo,
TaskRequest,
TaskResponse,
WorkerTask,
Expand Down Expand Up @@ -120,15 +119,17 @@ def test_get_nonexistent_device(


def test_get_child_device(mock_rest: Mock, client: BlueapiClient):
mock_rest.get_device.side_effect = lambda name: (
DeviceModel(name="foo.x", protocols=[ProtocolInfo(name="One")])
if name == "foo.x"
else None
mock_rest.get_devices.return_value = DeviceResponse(
devices=[
DeviceModel(name="stage", protocols=[], children={"x": "stage-x"}),
DeviceModel(name="stage-x", protocols=[], children={}),
]
)
foo = client.devices.foo
assert foo.model.name == "foo"
x = client.devices.foo.x
assert x.model.name == "foo.x"
stage = client.devices.stage
assert stage.model.name == "stage"
x = client.devices.stage.x
assert x.model.name == "stage-x"
assert x.parent is stage


def test_state_property(client: BlueapiClient):
Expand Down
17 changes: 17 additions & 0 deletions tests/unit_tests/client/test_device_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,23 @@ def test_device_cache_repr(client):
assert repr(client.devices) == "DeviceCache(2 devices)"


def test_child_devices_has_parent():
cache = MagicMock()
model = Mock()
model.name = "stage"
parent = DeviceRef(name="stage", cache=cache, model=Mock())
child = DeviceRef(name="stage-x", cache=cache, model=Mock(), parent=parent)
assert child.parent is parent


def test_parent_devices_has_no_parent():
cache = MagicMock()
model = Mock()
model.name = "stage"
parent = DeviceRef(name="stage", cache=cache, model=Mock(), parent=None)
assert parent.parent is None


def test_device_repr():
cache = Mock()
model = Mock()
Expand Down
4 changes: 3 additions & 1 deletion tests/unit_tests/service/test_rest_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,9 @@ def test_get_devices(mock_runner: Mock, client: TestClient) -> None:
{
"name": "my-device",
"protocols": [{"name": "Stoppable", "types": []}],
"children": {},
}
]
],
}


Expand All @@ -270,6 +271,7 @@ def test_get_device_by_name(mock_runner: Mock, client: TestClient) -> None:
assert response.json() == {
"name": "my-device",
"protocols": [{"name": "Stoppable", "types": []}],
"children": {},
}


Expand Down
Loading