summaryrefslogtreecommitdiff
path: root/tests/test_command.py
blob: eed6e1f469d78496f20d70c1bf85104907bb4ca1 (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
import contextlib
import io
import sys
import unittest

import hazwaz


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

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

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "--foo",
            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.main()
        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_run(self):
        cmd = MyCommand()
        cmd_help = cmd.parser.format_help()
        stream = self._run_with_argv(cmd, ["mycommand"])
        self.assertEqual(stream["stdout"].getvalue(), cmd_help)



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