How to test cmd-based programs?
Question: Helo, I wrote some program that uses
[cmd](https://docs.python.org/2/library/cmd.html) module. (The Cmd class
provides a simple framework for writing line-oriented command interpreters.)

My program is cli to api.

My problem is that I can't test it now.

I can run:

    
    
    # ./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...
    

If I wrote test like:

    
    
    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()
    

It's output will be:

    
    
    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()
    


Answer: You use Python [unittest](https://docs.python.org/3.4/library/unittest.html)
package:

    
    
    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 
    

