test_cmd.py 6.11 KB
Newer Older
1 2 3 4 5 6 7 8
"""
Test script for the 'cmd' module
Original by Michael Schneider
"""


import cmd
import sys
9
import re
10 11
import unittest
import io
12
from test import support
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

class samplecmdclass(cmd.Cmd):
    """
    Instance the sampleclass:
    >>> mycmd = samplecmdclass()

    Test for the function parseline():
    >>> mycmd.parseline("")
    (None, None, '')
    >>> mycmd.parseline("?")
    ('help', '', 'help ')
    >>> mycmd.parseline("?help")
    ('help', 'help', 'help help')
    >>> mycmd.parseline("!")
    ('shell', '', 'shell ')
    >>> mycmd.parseline("!command")
    ('shell', 'command', 'shell command')
    >>> mycmd.parseline("func")
    ('func', '', 'func')
    >>> mycmd.parseline("func arg1")
    ('func', 'arg1', 'func arg1')


    Test for the function onecmd():
    >>> mycmd.onecmd("")
    >>> mycmd.onecmd("add 4 5")
    9
    >>> mycmd.onecmd("")
    9
    >>> mycmd.onecmd("test")
    *** Unknown syntax: test

    Test for the function emptyline():
    >>> mycmd.emptyline()
    *** Unknown syntax: test

    Test for the function default():
    >>> mycmd.default("default")
    *** Unknown syntax: default

    Test for the function completedefault():
    >>> mycmd.completedefault()
    This is the completedefault methode
    >>> mycmd.completenames("a")
    ['add']

    Test for the function completenames():
    >>> mycmd.completenames("12")
    []
    >>> mycmd.completenames("help")
63
    ['help']
64 65 66 67 68

    Test for the function complete_help():
    >>> mycmd.complete_help("a")
    ['add']
    >>> mycmd.complete_help("he")
69
    ['help']
70 71
    >>> mycmd.complete_help("12")
    []
72 73
    >>> sorted(mycmd.complete_help(""))
    ['add', 'exit', 'help', 'shell']
74 75 76 77 78 79 80 81 82 83 84 85

    Test for the function do_help():
    >>> mycmd.do_help("testet")
    *** No help on testet
    >>> mycmd.do_help("add")
    help text for add
    >>> mycmd.onecmd("help add")
    help text for add
    >>> mycmd.do_help("")
    <BLANKLINE>
    Documented commands (type help <topic>):
    ========================================
86
    add  help
87 88 89
    <BLANKLINE>
    Undocumented commands:
    ======================
90
    exit  shell
91 92 93 94 95 96 97 98 99 100 101
    <BLANKLINE>

    Test for the function print_topics():
    >>> mycmd.print_topics("header", ["command1", "command2"], 2 ,10)
    header
    ======
    command1
    command2
    <BLANKLINE>

    Test for the function columnize():
102
    >>> mycmd.columnize([str(i) for i in range(20)])
103
    0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19
104
    >>> mycmd.columnize([str(i) for i in range(20)], 10)
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    0  7   14
    1  8   15
    2  9   16
    3  10  17
    4  11  18
    5  12  19
    6  13

    This is a interactive test, put some commands in the cmdqueue attribute
    and let it execute
    This test includes the preloop(), postloop(), default(), emptyline(),
    parseline(), do_help() functions
    >>> mycmd.use_rawinput=0
    >>> mycmd.cmdqueue=["", "add", "add 4 5", "help", "help add","exit"]
    >>> mycmd.cmdloop()
    Hello from preloop
    help text for add
    *** invalid number of arguments
    9
    <BLANKLINE>
    Documented commands (type help <topic>):
    ========================================
127
    add  help
128 129 130
    <BLANKLINE>
    Undocumented commands:
    ======================
131
    exit  shell
132 133 134 135 136 137
    <BLANKLINE>
    help text for add
    Hello from postloop
    """

    def preloop(self):
138
        print("Hello from preloop")
139 140

    def postloop(self):
141
        print("Hello from postloop")
142 143

    def completedefault(self, *ignored):
144
        print("This is the completedefault methode")
145 146

    def complete_command(self):
147
        print("complete command")
148

149
    def do_shell(self, s):
150 151 152 153 154
        pass

    def do_add(self, s):
        l = s.split()
        if len(l) != 2:
155
            print("*** invalid number of arguments")
156 157 158 159
            return
        try:
            l = [int(i) for i in l]
        except ValueError:
160
            print("*** arguments should be numbers")
161
            return
162
        print(l[0]+l[1])
163 164

    def help_add(self):
165
        print("help text for add")
166 167 168 169 170
        return

    def do_exit(self, arg):
        return True

171 172 173 174 175 176 177 178 179 180 181

class TestAlternateInput(unittest.TestCase):

    class simplecmd(cmd.Cmd):

        def do_print(self, args):
            print(args, file=self.stdout)

        def do_EOF(self, args):
            return True

Jesus Cea's avatar
Jesus Cea committed
182 183 184 185 186 187 188 189

    class simplecmd2(simplecmd):

        def do_EOF(self, args):
            print('*** Unknown syntax: EOF', file=self.stdout)
            return True


190 191 192 193 194 195 196 197 198 199 200 201
    def test_file_with_missing_final_nl(self):
        input = io.StringIO("print test\nprint test2")
        output = io.StringIO()
        cmd = self.simplecmd(stdin=input, stdout=output)
        cmd.use_rawinput = False
        cmd.cmdloop()
        self.assertMultiLineEqual(output.getvalue(),
            ("(Cmd) test\n"
             "(Cmd) test2\n"
             "(Cmd) "))


Jesus Cea's avatar
Jesus Cea committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    def test_input_reset_at_EOF(self):
        input = io.StringIO("print test\nprint test2")
        output = io.StringIO()
        cmd = self.simplecmd2(stdin=input, stdout=output)
        cmd.use_rawinput = False
        cmd.cmdloop()
        self.assertMultiLineEqual(output.getvalue(),
            ("(Cmd) test\n"
             "(Cmd) test2\n"
             "(Cmd) *** Unknown syntax: EOF\n"))
        input = io.StringIO("print \n\n")
        output = io.StringIO()
        cmd.stdin = input
        cmd.stdout = output
        cmd.cmdloop()
        self.assertMultiLineEqual(output.getvalue(),
            ("(Cmd) \n"
             "(Cmd) \n"
             "(Cmd) *** Unknown syntax: EOF\n"))


223
def test_main(verbose=None):
224
    from test import test_cmd
225
    support.run_doctest(test_cmd, verbose)
226
    support.run_unittest(TestAlternateInput)
227 228

def test_coverage(coverdir):
229
    trace = support.import_module('trace')
230
    tracer=trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,],
231
                        trace=0, count=1)
232
    tracer.run('import importlib; importlib.reload(cmd); test_main()')
233
    r=tracer.results()
234
    print("Writing coverage results...")
235 236 237 238 239
    r.write_results(show_missing=True, summary=True, coverdir=coverdir)

if __name__ == "__main__":
    if "-c" in sys.argv:
        test_coverage('/tmp/cmd.cover')
240 241
    elif "-i" in sys.argv:
        samplecmdclass().cmdloop()
242 243
    else:
        test_main()