Add include_local_unit option to get_all_unit_values

Currently `get_all_unit_values` will return the values set by
remote units. The new `include_local_unit` option will add the
value that the local unit has set to the list.

Change-Id: I9c75535c7b71af7585bbb31dda86035f5216c08e
This commit is contained in:
Liam Young 2023-02-17 07:31:43 +00:00
parent c5c284274b
commit 9d918cdae1
2 changed files with 47 additions and 2 deletions

View File

@ -125,8 +125,13 @@ class OperatorPeers(Object):
"""Return all the app data from the relation."""
return self._app_data_bag
def get_all_unit_values(self, key: str) -> List[str]:
"""Retrieve value for key from all related units."""
def get_all_unit_values(
self, key: str, include_local_unit: bool = False
) -> List[str]:
"""Retrieve value for key from all related units.
:param include_local_unit: Include value set by local unit
"""
values = []
if not self.peers_rel:
return values
@ -134,6 +139,9 @@ class OperatorPeers(Object):
value = self.peers_rel.data[unit].get(key)
if value is not None:
values.append(value)
local_unit_value = self.peers_rel.data[self.model.unit].get(key)
if include_local_unit and local_unit_value:
values.append(local_unit_value)
return values
def set_unit_data(self, settings: Dict[str, str]) -> None:

View File

@ -241,6 +241,43 @@ class TestOSBaseOperatorAPICharm(_TestOSBaseOperatorAPICharm):
self.assertEqual(self.harness.charm.leader_get("foo"), "bar")
self.assertEqual(self.harness.charm.leader_get("ginger"), "biscuit")
def test_peer_unit_data(self) -> None:
"""Test interacting with peer app db."""
rel_id = self.harness.add_relation("peers", "my-service")
self.harness.add_relation_unit(rel_id, "my-service/1")
self.harness.update_relation_data(
rel_id, "my-service/1", {"today": "monday"}
)
self.assertEqual(
self.harness.charm.peers.interface.get_all_unit_values(
"today",
include_local_unit=False,
),
["monday"],
)
self.assertEqual(
self.harness.charm.peers.interface.get_all_unit_values(
"today",
include_local_unit=True,
),
["monday"],
)
self.harness.charm.peers.interface.set_unit_data({"today": "friday"})
self.assertEqual(
self.harness.charm.peers.interface.get_all_unit_values(
"today",
include_local_unit=False,
),
["monday"],
)
self.assertEqual(
self.harness.charm.peers.interface.get_all_unit_values(
"today",
include_local_unit=True,
),
["monday", "friday"],
)
def test_peer_leader_ready(self) -> None:
"""Test peer leader ready methods."""
rel_id = self.harness.add_relation("peers", "my-service")