aboutsummaryrefslogtreecommitdiff
path: root/hazwaz/unittest.py
blob: 2b28cdca80f49ba0c01e0ee64944a23ea6b0d653 (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
import contextlib
import io
import sys
import unittest


class HazwazTestCase(unittest.TestCase):
    def run_with_argv(self, cmd, argv: list[str]) -> dict[str, io.StringIO]:
        """
        Run a command with a list of command line options.

        :param argv: the full command line except for the program name,
                     as a list of strings; e.g. ``["subcommand",
                     "--help"]`` or ``["subcommand", "--option",
                     "value"]``.

        :return: stdout and stderr resulting from the command.
        """
        stream = {
            'stdout': io.StringIO(),
            'stderr': io.StringIO(),
        }
        old_argv = sys.argv
        sys.argv = argv
        with contextlib.redirect_stdout(stream['stdout']):
            with contextlib.redirect_stderr(stream['stderr']):
                cmd.run()
        sys.argv = old_argv
        return stream