Skip to content

Commit

Permalink
feat: make it an error to call CollectStatusEvent.add_status with err…
Browse files Browse the repository at this point in the history
…or or unknown (#1386)

Add a runtime check to immediately raise an InvalidStatusError if add_status is
called with ErrorStatus or UnknownStatus. Previously these statuses would (in
the case of ErrorStatus) or might (in the case of UnknownStatus) lead to an
InvalidStatusError when it came time to set the status after the collect-status
observer returned. It was never valid to set either status, this just means that
the user will get an immediate exception that points to the line adding the bad
status.
  • Loading branch information
james-garner-canonical authored Sep 25, 2024
1 parent 98a4e4f commit 64d9565
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
9 changes: 7 additions & 2 deletions ops/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,12 +1105,13 @@ class CollectStatusEvent(LifecycleEvent):
The order of priorities is as follows, from highest to lowest:
* error
* blocked
* maintenance
* waiting
* active
* unknown
It is an error to call :meth:`add_status` with an instance of
:class:`ErrorStatus` or :class:`UnknownStatus`.
If there are multiple statuses with the same priority, the first one added
wins (and if an event is observed multiple times, the handlers are called
Expand Down Expand Up @@ -1151,6 +1152,10 @@ def add_status(self, status: model.StatusBase):
"""
if not isinstance(status, model.StatusBase):
raise TypeError(f'status should be a StatusBase, not {type(status).__name__}')
if status.name not in model._SETTABLE_STATUS_NAMES:
raise model.InvalidStatusError(
f'status.name must be in {model._SETTABLE_STATUS_NAMES}, not {status.name!r}'
)
model_ = self.framework.model
if self.handle.kind == 'collect_app_status':
if not isinstance(status, model.ActiveStatus):
Expand Down
4 changes: 2 additions & 2 deletions test/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -959,7 +959,6 @@ def _on_collect_status(self, event: ops.CollectStatusEvent):
(['waiting', 'blocked'], 'blocked'),
(['waiting', 'maintenance'], 'maintenance'),
(['active', 'waiting'], 'waiting'),
(['active', 'unknown'], 'active'),
],
)
def test_collect_status_priority_valid(
Expand Down Expand Up @@ -994,6 +993,7 @@ def _on_collect_status(self, event: ops.CollectStatusEvent):
[
['blocked', 'error'],
['unknown'],
['active', 'unknown'],
],
)
def test_collect_status_priority_invalid(
Expand All @@ -1015,7 +1015,7 @@ def _on_collect_status(self, event: ops.CollectStatusEvent):

framework = create_framework(request)
charm = MyCharm(framework, statuses=statuses)
with pytest.raises(ModelError):
with pytest.raises(ops.InvalidStatusError):
ops.charm._evaluate_status(charm)


Expand Down

0 comments on commit 64d9565

Please sign in to comment.