summaryrefslogtreecommitdiff
path: root/plugins/ext_test/cmd2_ext_test/cmd2_ext_test.py
blob: c176bb78865f8a27c86409f6781e141dae94106b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#
# coding=utf-8
"""External test interface plugin"""

from typing import (
    TYPE_CHECKING,
    Optional,
)

import cmd2

if TYPE_CHECKING:  # pragma: no cover
    _Base = cmd2.Cmd
else:
    _Base = object


class ExternalTestMixin(_Base):
    """A cmd2 plugin (mixin class) that exposes an interface to execute application commands from python"""

    def __init__(self, *args, **kwargs):
        """

        :type self: cmd2.Cmd
        :param args:
        :param kwargs:
        """
        # code placed here runs before cmd2 initializes
        super().__init__(*args, **kwargs)
        assert isinstance(self, cmd2.Cmd)
        # code placed here runs after cmd2 initializes
        self._pybridge = cmd2.py_bridge.PyBridge(self)

    def app_cmd(self, command: str, echo: Optional[bool] = None) -> cmd2.CommandResult:
        """
        Run the application command

        :param command: The application command as it would be written on the cmd2 application prompt
        :param echo: Flag whether the command's output should be echoed to stdout/stderr
        :return: A CommandResult object that captures stdout, stderr, and the command's result object
        """
        assert isinstance(self, cmd2.Cmd) and isinstance(self, ExternalTestMixin)
        try:
            self._in_py = True

            return self._pybridge(command, echo=echo)

        finally:
            self._in_py = False

    def fixture_setup(self):
        """
        Replicates the behavior of `cmdloop()` preparing the state of the application
        :type self: cmd2.Cmd
        """

        for func in self._preloop_hooks:
            func()
        self.preloop()

    def fixture_teardown(self):
        """
        Replicates the behavior of `cmdloop()` tearing down the application

        :type self: cmd2.Cmd
        """
        # assert isinstance(self, cmd2.Cmd) and isinstance(self, ExternalTestMixin)
        for func in self._postloop_hooks:
            func()
        self.postloop()