| 1 |
"""Cmd2 unit/functional testing""" |
| 2 |
|
| 3 |
import sys |
| 4 |
from collections.abc import Callable |
| 5 |
from contextlib import redirect_stderr |
| 6 |
from typing import ( |
| 7 |
TYPE_CHECKING, |
| 8 |
ParamSpec, |
| 9 |
TextIO, |
| 10 |
TypeVar, |
| 11 |
cast, |
| 12 |
) |
| 13 |
|
| 14 |
import pytest |
| 15 |
|
| 16 |
import cmd2 |
| 17 |
from cmd2 import rich_utils as ru |
| 18 |
from cmd2.utils import StdSim |
| 19 |
|
| 20 |
|
| 21 |
P = ParamSpec("P") |
| 22 |
T = TypeVar("T") |
| 23 |
|
| 24 |
|
| 25 |
def verify_help_text(cmd_app: cmd2.Cmd, help_output: str | list[str], verbose_strings: list[str] | None = None) -> None: |
| 26 |
"""This function verifies that all expected commands are present in the help text. |
| 27 |
|
| 28 |
:param cmd_app: instance of cmd2.Cmd |
| 29 |
:param help_output: output of help, either as a string or list of strings |
| 30 |
:param verbose_strings: optional list of verbose strings to search for |
| 31 |
""" |
| 32 |
help_text = help_output if isinstance(help_output, str) else "".join(help_output) |
| 33 |
commands = cmd_app.get_visible_commands() |
| 34 |
for command in commands: |
| 35 |
assert command in help_text |
| 36 |
|
| 37 |
if verbose_strings: |
| 38 |
for verbose_string in verbose_strings: |
| 39 |
assert verbose_string in help_text |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
SHORTCUTS_TXT = """Shortcuts for other commands: |
| 44 |
!: shell |
| 45 |
?: help |
| 46 |
@: run_script |
| 47 |
@@: _relative_run_script |
| 48 |
""" |
| 49 |
|
| 50 |
|
| 51 |
def normalize(block: str) -> list[str]: |
| 52 |
"""Normalize a block of text to perform comparison. |
| 53 |
|
| 54 |
Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace |
| 55 |
from each line. |
| 56 |
""" |
| 57 |
assert isinstance(block, str) |
| 58 |
block = block.strip("\n") |
| 59 |
return [line.rstrip() for line in block.splitlines()] |
| 60 |
|
| 61 |
|
| 62 |
def run_cmd(app: cmd2.Cmd, cmd: str) -> tuple[list[str], list[str]]: |
| 63 |
"""Run the command in app and return what it writes to app.stdout and sys.stderr.""" |
| 64 |
|
| 65 |
|
| 66 |
copy_cmd_stdout = StdSim(cast(TextIO, app.stdout)) |
| 67 |
|
| 68 |
|
| 69 |
copy_stderr = StdSim(sys.stderr) |
| 70 |
|
| 71 |
try: |
| 72 |
app.stdout = cast(TextIO, copy_cmd_stdout) |
| 73 |
with redirect_stderr(cast(TextIO, copy_stderr)): |
| 74 |
app.onecmd_plus_hooks(cmd) |
| 75 |
finally: |
| 76 |
app.stdout = cast(TextIO, copy_cmd_stdout.inner_stream) |
| 77 |
|
| 78 |
out = copy_cmd_stdout.getvalue() |
| 79 |
err = copy_stderr.getvalue() |
| 80 |
return normalize(out), normalize(err) |
| 81 |
|
| 82 |
|
| 83 |
@pytest.fixture |
| 84 |
def base_app() -> cmd2.Cmd: |
| 85 |
return cmd2.Cmd(include_py=True, include_ipy=True) |
| 86 |
|
| 87 |
|
| 88 |
def with_ansi_style(style: ru.AllowStyle) -> Callable[[Callable[P, T]], Callable[P, T]]: |
| 89 |
"""Decorator which sets ru.ALLOW_STYLE before a function runs and restores it when it's done.""" |
| 90 |
|
| 91 |
def arg_decorator(func: Callable[P, T]) -> Callable[P, T]: |
| 92 |
import functools |
| 93 |
|
| 94 |
@functools.wraps(func) |
| 95 |
def cmd_wrapper(*args: P.args, **kwargs: P.kwargs) -> T: |
| 96 |
old = ru.ALLOW_STYLE |
| 97 |
ru.ALLOW_STYLE = style |
| 98 |
try: |
| 99 |
retval = func(*args, **kwargs) |
| 100 |
finally: |
| 101 |
ru.ALLOW_STYLE = old |
| 102 |
return retval |
| 103 |
|
| 104 |
return cmd_wrapper |
| 105 |
|
| 106 |
return arg_decorator |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
odd_file_names = ["nothingweird", "has spaces", '"is_double_quoted"', "'is_single_quoted'"] |
| 111 |
|
| 112 |
|
| 113 |
if TYPE_CHECKING: |
| 114 |
_Base = cmd2.Cmd |
| 115 |
else: |
| 116 |
_Base = object |
| 117 |
|
| 118 |
|
| 119 |
class ExternalTestMixin(_Base): |
| 120 |
"""A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python""" |
| 121 |
|
| 122 |
def __init__(self, *args, **kwargs): |
| 123 |
"""Initializes the ExternalTestMixin. |
| 124 |
|
| 125 |
This class is intended to be used in multiple inheritance alongside `cmd2.Cmd` for an application class. |
| 126 |
When doing this multiple inheritance, it is imperative that this mixin class come first. |
| 127 |
|
| 128 |
:type self: cmd2.Cmd |
| 129 |
:param args: arguments to pass to the superclass |
| 130 |
:param kwargs: keyword arguments to pass to the superclass |
| 131 |
""" |
| 132 |
|
| 133 |
super().__init__(*args, **kwargs) |
| 134 |
if not isinstance(self, cmd2.Cmd): |
| 135 |
raise TypeError("The ExternalTestMixin class is intended to be used in multiple inheritance with cmd2.Cmd") |
| 136 |
|
| 137 |
self._pybridge = cmd2.py_bridge.PyBridge(self) |
| 138 |
|
| 139 |
def app_cmd(self, command: str, echo: bool | None = None) -> cmd2.CommandResult: |
| 140 |
""" |
| 141 |
Run the application command |
| 142 |
|
| 143 |
:param command: The application command as it would be written on the cmd2 application prompt |
| 144 |
:param echo: Flag whether the command's output should be echoed to stdout/stderr |
| 145 |
:return: A CommandResult object that captures stdout, stderr, and the command's result object |
| 146 |
""" |
| 147 |
try: |
| 148 |
self._in_py = True |
| 149 |
return self._pybridge(command, echo=echo) |
| 150 |
|
| 151 |
finally: |
| 152 |
self._in_py = False |
| 153 |
|
| 154 |
def fixture_setup(self): |
| 155 |
"""Replicates the behavior of `cmdloop()` to prepare the application state for testing. |
| 156 |
|
| 157 |
This method runs all preloop hooks and the preloop method to ensure the |
| 158 |
application is in the correct state before running a test. |
| 159 |
|
| 160 |
:type self: cmd2.Cmd |
| 161 |
""" |
| 162 |
|
| 163 |
for func in self._preloop_hooks: |
| 164 |
func() |
| 165 |
self.preloop() |
| 166 |
|
| 167 |
def fixture_teardown(self): |
| 168 |
"""Replicates the behavior of `cmdloop()` to tear down the application after a test. |
| 169 |
|
| 170 |
This method runs all postloop hooks and the postloop method to clean up |
| 171 |
the application state and ensure test isolation. |
| 172 |
|
| 173 |
:type self: cmd2.Cmd |
| 174 |
""" |
| 175 |
for func in self._postloop_hooks: |
| 176 |
func() |
| 177 |
self.postloop() |
| 178 |
|
| 179 |
|
| 180 |
class WithCommandSets(ExternalTestMixin, cmd2.Cmd): |
| 181 |
"""Class for testing custom help_* methods which override docstring help.""" |
| 182 |
|
| 183 |
def __init__(self, *args, **kwargs) -> None: |
| 184 |
super().__init__(*args, **kwargs) |
| 185 |
|
| 186 |
|
| 187 |
@pytest.fixture |
| 188 |
def autoload_command_sets_app(): |
| 189 |
return WithCommandSets(auto_load_commands=True) |
| 190 |
|
| 191 |
|
| 192 |
@pytest.fixture |
| 193 |
def manual_command_sets_app(): |
| 194 |
return WithCommandSets(auto_load_commands=False) |