Skip to content

Commit

Permalink
Merge pull request #70 from canonical/action-output-success
Browse files Browse the repository at this point in the history
ActionOutput.success sugar
  • Loading branch information
PietroPasotti authored Oct 24, 2023
2 parents 3a5284d + 90f7cc6 commit 22feb6b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -850,9 +850,15 @@ def test_backup_action():
out: ActionOutput = ctx.run_action("do_backup_action", State())

# you can assert action results, logs, failure using the ActionOutput interface
assert out.results == {'foo': 'bar'}
assert out.logs == ['baz', 'qux']
assert out.failure == 'boo-hoo'

if out.success:
# if the action did not fail, we can read the results:
assert out.results == {'foo': 'bar'}

else:
# if the action fails, we can read a failure message
assert out.failure == 'boo-hoo'
```

## Parametrized Actions
Expand Down
28 changes: 23 additions & 5 deletions scenario/context.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
# Copyright 2023 Canonical Ltd.
# See LICENSE file for licensing details.
import dataclasses
import tempfile
from collections import namedtuple
from contextlib import contextmanager
from pathlib import Path
from typing import (
Expand Down Expand Up @@ -34,7 +34,25 @@

logger = scenario_logger.getChild("runtime")

ActionOutput = namedtuple("ActionOutput", ("state", "logs", "results", "failure"))

@dataclasses.dataclass
class ActionOutput:
"""Wraps the results of running an action event with `run_action`."""

state: "State"
"""The charm state after the action has been handled.
In most cases, actions are not expected to be affecting it."""
logs: List[str]
"""Any logs associated with the action output, set by the charm."""
results: Dict[str, Any]
"""Key-value mapping assigned by the charm as a result of the action."""
failure: Optional[str] = None
"""If the action is not a success: the message the charm set when failing the action."""

@property
def success(self) -> bool:
"""Return whether this action was a success."""
return self.failure is None


class InvalidEventError(RuntimeError):
Expand Down Expand Up @@ -254,7 +272,7 @@ def __init__(
# ephemeral side effects from running an action
self._action_logs = []
self._action_results = None
self._action_failure = ""
self._action_failure = None

def _set_output_state(self, output_state: "State"):
"""Hook for Runtime to set the output state."""
Expand All @@ -281,7 +299,7 @@ def clear(self):
self.requested_storages = {}
self._action_logs = []
self._action_results = None
self._action_failure = ""
self._action_failure = None
self._output_state = None

def _record_status(self, state: "State", is_app: bool):
Expand Down Expand Up @@ -463,7 +481,7 @@ def _finalize_action(self, state_out: "State"):
# reset all action-related state
self._action_logs = []
self._action_results = None
self._action_failure = ""
self._action_failure = None

return ao

Expand Down
2 changes: 2 additions & 0 deletions tests/test_e2e/test_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ def handle_evt(charm: CharmBase, evt: ActionEvent):
out = ctx.run_action(action, State())

assert out.results == res_value
assert out.success is True


@pytest.mark.parametrize("res_value", ({"a": {"b": {"c"}}}, {"d": "e"}))
Expand All @@ -128,3 +129,4 @@ def handle_evt(charm: CharmBase, evt: ActionEvent):

assert out.failure == "failed becozz"
assert out.logs == ["log1", "log2"]
assert out.success is False

0 comments on commit 22feb6b

Please sign in to comment.