如何测试基于cmd的程序?

时间:2015-03-25 05:33:49

标签: python python-2.7

直升机, 我写了一些使用cmd模块的程序。 (Cmd类为编写面向行的命令解释器提供了一个简单的框架。)

我的程序是api的cli。

我的问题是我现在无法测试它。

我可以跑:

# ./cli
   CLI Interface


    ------------
    Help may be requested at any point in a command by entering
    a question mark '?'.  If nothing matches, the help list will
    be empty and you must backup until entering a '?' shows the
    available options.
    Two styles of help are provided:
    1. Full help is available when you are ready to enter a
       command argument (e.g. 'show ?') and describes each possible
       argument.
    2. Partial help is provided when an abbreviated argument is entered
       and you want to know what arguments match the input
       (e.g. 'show pr?'.)

#role
Current Roles
rde:
   - base functionality
test:
   - Test
#quit
Exiting...

如果我写的测试如下:

from cli import Cli

class TestCliClass(unittest.TestCase):
    def setUp(self):
        self.cmdLine = Cli()
    def test_role(self):
        self.assertEqual("",self.cmdLine.do_role())
        #a=self.cmdLine.do_role()
        #print a
if __name__ == '__main__':
    unittest.main()

它的输出将是:

test_cli.py
-----------------------------
 current logs in /var/log/test_rdepyui.log
-----------------------------
Current Roles
rde:
   - base functionality
test:
   - Test
F
======================================================================
FAIL: test_role (__main__.TestCliClass)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/test_cli.py", line 23, in test_role
    self.assertEqual("",self.cmdLine.do_role())
AssertionError: '' != None

----------------------------------------------------------------------
Ran 1 test in 0.040s

FAILED (failures=1)

    import sys
    import os
    from cmd import Cmd
    USING_READLINE = True

    class Cli(Cmd,object):
    def __init__(self):
        Cmd.__init__(self)
        if not USING_READLINE:
            self.completekey = None
        self._hist=[]
        self.prompt = "#"
        self.intro  = """   CLI Interface """
    def default(self, line):
        cmd, arg, line = self.parseline(line)
        cmds = self.completenames(cmd)
        num_cmds = len(cmds)
        if num_cmds == 1:
            getattr(self, 'do_'+cmds[0])(arg)
        elif num_cmds > 1:
            sys.stdout.write('%% Ambiguous command:\t"%s"\n' % cmd)
        else:
            sys.stdout.write('% Unrecognized command\n')
    def emptyline(self):
        pass

def do_role(self,args=None):
        try:            
            if args is None or args == 'show' or args.startswith('show') or args =='':
                roles = self.rderole.getRole()
                print "Current Roles"
                output=""
                #max_l=0
                for role in roles:

                    role_str="%s:" % (role)
                    output +=role_str+"\n"
                    #if len(role_str)>max_l:
                    #    max_l=len(role_str)
                    description=""
                    for subroles in roles[role]: 
                        print   subroles                 
                        if self.rderole.PLAYBOOK_DESCRIPTION in subroles:
                            description=subroles[self.rderole.PLAYBOOK_DESCRIPTION]
                            subrole_str="   - %s" % description
                            #if len(subrole_str)>max_l:
                            #    max_l=len(subrole_str)
                            output +=subrole_str+"\n"
                            #print subrole_str
                            #subrole_str.ljust(len(role_str))
                            #print subrole_str
                print output.strip()
            elif args == 'help' :
                Cmd.do_help(self, "role")
        except Exception as e:
            print "<ERROR>Can't show role: %s" % e
    if __name__ == '__main__':
        cmdLine = Cli()
        cmdLine.cmdloop()

1 个答案:

答案 0 :(得分:0)

您使用Python unittest包:

import unittest 

from mymodule import Cli

class MyTest(unittest.TestCase):

    def test_cli(self):
       cli = Cli()
       cli.do_foofail()  # foofail must return something sensible which you can check with self.assertXXX() methods