diff options
-rw-r--r-- | cmd2/pyscript_bridge.py | 13 | ||||
-rw-r--r-- | tests/test_cmd2.py | 16 |
2 files changed, 25 insertions, 4 deletions
diff --git a/cmd2/pyscript_bridge.py b/cmd2/pyscript_bridge.py index 2002ca6d..dcfd9116 100644 --- a/cmd2/pyscript_bridge.py +++ b/cmd2/pyscript_bridge.py @@ -33,9 +33,16 @@ class CommandResult(namedtuple_with_defaults('CommandResult', ['stdout', 'stderr NOTE: Named tuples are immutable. So the contents are there for access, not for modification. """ - def __bool__(self): - """If stderr is None and data is not None the command is considered a success""" - return not self.stderr and self.data is not None + def __bool__(self) -> bool: + """Returns True if the command succeeded, otherwise False""" + + # If data has a __bool__ method, then call it to determine success of command + if self.data is not None and callable(getattr(self.data, '__bool__', None)): + return True if self.data else False + + # Otherwise check if stderr was filled out + else: + return not self.stderr def _exec_cmd(cmd2_app, func: Callable, echo: bool) -> CommandResult: diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index a64f21e4..a2bd6197 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -1576,8 +1576,14 @@ class CommandResultApp(cmd2.Cmd): self._last_result = cmd2.CommandResult(arg, data=True) def do_negative(self, arg): + self._last_result = cmd2.CommandResult(arg, data=False) + + def do_affirmative_no_data(self, arg): self._last_result = cmd2.CommandResult(arg) + def do_negative_no_data(self, arg): + self._last_result = cmd2.CommandResult('', arg) + @pytest.fixture def commandresult_app(): app = CommandResultApp() @@ -1590,11 +1596,19 @@ def test_commandresult_truthy(commandresult_app): assert commandresult_app._last_result assert commandresult_app._last_result == cmd2.CommandResult(arg, data=True) + run_cmd(commandresult_app, 'affirmative_no_data {}'.format(arg)) + assert commandresult_app._last_result + assert commandresult_app._last_result == cmd2.CommandResult(arg) + def test_commandresult_falsy(commandresult_app): arg = 'bar' run_cmd(commandresult_app, 'negative {}'.format(arg)) assert not commandresult_app._last_result - assert commandresult_app._last_result == cmd2.CommandResult(arg) + assert commandresult_app._last_result == cmd2.CommandResult(arg, data=False) + + run_cmd(commandresult_app, 'negative_no_data {}'.format(arg)) + assert not commandresult_app._last_result + assert commandresult_app._last_result == cmd2.CommandResult('', arg) def test_is_text_file_bad_input(base_app): |