Skip to content

Commit

Permalink
Handle the situation when no data in relation yet (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
weiiwang01 authored Sep 25, 2024
1 parent b8b064a commit 434d050
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions lib/charms/smtp_integrator/v0/smtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def _on_config_changed(self, _) -> None:

# Increment this PATCH version before using `charmcraft publish-lib` or reset
# to 0 if you are raising the major API version
LIBPATCH = 11
LIBPATCH = 12

PYDEPS = ["pydantic>=2"]

Expand Down Expand Up @@ -280,7 +280,7 @@ def get_relation_data(self) -> Optional[SmtpRelationData]:
relation = self.model.get_relation(self.relation_name)
return self._get_relation_data_from_relation(relation) if relation else None

def _get_relation_data_from_relation(self, relation: ops.Relation) -> SmtpRelationData:
def _get_relation_data_from_relation(self, relation: ops.Relation) -> SmtpRelationData | None:
"""Retrieve the relation data.
Args:
Expand All @@ -291,6 +291,8 @@ def _get_relation_data_from_relation(self, relation: ops.Relation) -> SmtpRelati
"""
assert relation.app
relation_data = relation.data[relation.app]
if not relation_data:
return None
return SmtpRelationData(
host=typing.cast(str, relation_data.get("host")),
port=typing.cast(int, relation_data.get("port")),
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/test_library_smtp.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,3 +278,16 @@ def test_requirer_charm_with_invalid_relation_data_doesnt_emit_event(is_leader):
harness.add_relation("smtp-legacy", "smtp-provider", app_data=relation_data)

assert len(harness.charm.events) == 0


def test_requirer_charm_get_relation_data_without_relation_data():
"""
arrange: set up a charm with smtp relation without any relation data.
act: call get_relation_data function.
assert: get_relation_data should return None.
"""
harness = Harness(SmtpRequirerCharm, meta=REQUIRER_METADATA)
harness.begin()
harness.set_leader(True)
harness.add_relation("smtp", "smtp-provider", app_data={})
assert harness.charm.smtp.get_relation_data() is None

0 comments on commit 434d050

Please sign in to comment.