summaryrefslogtreecommitdiff
path: root/tests/test_command.py
blob: cbb7aad1f3a542fe1474a51bcccf6d303b5ecad9 (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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import contextlib
import io
import logging
import sys
import unittest

import hazwaz


class MySubCommand(hazwaz.Command):
    """
    A subcommand.

    This does very little.
    """

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "--bar",
            action="store_true",
            help="barfoo things"
        )

    def main(self):
        print("Hello World")


class LoggingSubCommand(hazwaz.Command):
    """
    A subcommand that logs on various levels.
    """

    def main(self):
        logging.debug("This is a DEBUG message")
        logging.info("This is an INFO message")
        logging.warning("This is a WARNING message")


class MyCommand(hazwaz.MainCommand):
    """
    A command that does things.

    This is a command, but honestly it doesn't really do anything.
    """
    commands = (
        MySubCommand(),
        LoggingSubCommand(),
    )

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "--foo",
            action="store_true",
            help="foobar things",
        )


class MyCommandWithNoVerbose(hazwaz.MainCommand):
    """
    A command that always talks.

    This command doesn't have the --verbose and --debug arguments.

    """

    def add_arguments(self, parser):
        # we override add_arguments and don't call
        # super().add_arguments(parser) so that --verbose and --debug
        # are missing.
        parser.add_argument(
            "--foo",
            action="store_true",
            help="foobar things",
        )


class testCommand(unittest.TestCase):
    def _run_with_argv(self, cmd, argv):
        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

    def test_description(self):
        cmd = MyCommand()
        self.assertEqual(
            cmd.parser.description,
            "A command that does things."
        )
        self.assertEqual(
            cmd.parser.epilog,
            "This is a command, but honestly it doesn't really do anything."
        )

    def test_description_none(self):
        class NoHelpCommand(hazwaz.MainCommand):
            pass

        cmd = NoHelpCommand()
        self.assertEqual(cmd.parser.description, None)

    def test_description_empty(self):
        class NoHelpCommand(hazwaz.MainCommand):
            """
            """

        cmd = NoHelpCommand()
        self.assertEqual(cmd.parser.description, '')

    def test_arguments(self):
        cmd = MyCommand()
        cmd_help = cmd.parser.format_help()
        self.assertIn("--verbose", cmd_help)
        self.assertIn("--foo", cmd_help)

    def test_subparser(self):
        cmd = MyCommand()
        sub_parser = cmd.subparsers.choices["mysubcommand"]
        self.assertEqual(sub_parser.description, "A subcommand.")
        self.assertEqual(
            sub_parser.epilog,
            "This does very little.",
        )

    def test_run(self):
        cmd = MyCommand()
        cmd_help = cmd.parser.format_help()
        stream = self._run_with_argv(cmd, ["mycommand"])
        self.assertEqual(stream["stdout"].getvalue(), cmd_help)

    def test_run_with_option(self):
        cmd = MyCommand()
        cmd_help = cmd.parser.format_help()
        stream = self._run_with_argv(cmd, [
            "mycommand",
            "--verbose",
        ])
        self.assertEqual(stream["stdout"].getvalue(), cmd_help)
        stream = self._run_with_argv(cmd, [
            "mycommand",
            "--debug",
        ])
        self.assertEqual(stream["stdout"].getvalue(), cmd_help)

    def test_run_subcommand(self):
        cmd = MyCommand()
        stream = self._run_with_argv(cmd, ["mycommand", "mysubcommand"])
        self.assertEqual(stream["stdout"].getvalue(), "Hello World\n")

    def test_run_subcommand_with_option(self):
        cmd = MyCommand()
        stream = self._run_with_argv(cmd, [
            "mycommand",
            "mysubcommand",
            "--bar",
        ])
        self.assertEqual(stream["stdout"].getvalue(), "Hello World\n")

    def test_run_no_verbose(self):
        cmd = MyCommandWithNoVerbose()
        cmd_help = cmd.parser.format_help()
        stream = self._run_with_argv(cmd, ["mycommand"])
        self.assertEqual(stream["stdout"].getvalue(), cmd_help)

    def test_logging_regular(self):
        cmd = MyCommand()
        with self.assertLogs():
            stream = self._run_with_argv(cmd, [
                "mycommand",
                "loggingsubcommand",
            ])
        log_lines = stream["stderr"].getvalue().strip().split("\n")
        self.assertEqual(len(log_lines), 1)

    def test_logging_verbose(self):
        cmd = MyCommand()
        with self.assertLogs():
            stream = self._run_with_argv(cmd, [
                "mycommand",
                "--verbose",
                "loggingsubcommand",
            ])
        log_lines = stream["stderr"].getvalue().strip().split("\n")
        self.assertEqual(len(log_lines), 2)

    def test_logging_debug(self):
        cmd = MyCommand()
        with self.assertLogs():
            stream = self._run_with_argv(cmd, [
                "mycommand",
                "--debug",
                "loggingsubcommand",
            ])
        log_lines = stream["stderr"].getvalue().strip().split("\n")
        self.assertEqual(len(log_lines), 3)


if __name__ == '__main__':
    unittest.main()