changeset 257:d62bb3dd58a0

multiple test files still not quite working, yet works when run through debugger, aaargh
author Catherine Devlin <catherine.devlin@gmail.com>
date Thu, 02 Apr 2009 15:55:33 -0400
parents 9ec55d2b3e99
children 7a98d7f2da30
files cmd2.py example/example.py example/exampleSession.txt
diffstat 3 files changed, 129 insertions(+), 37 deletions(-) [+]
line wrap: on
line diff
--- a/cmd2.py	Thu Apr 02 13:41:58 2009 -0400
+++ b/cmd2.py	Thu Apr 02 15:55:33 2009 -0400
@@ -27,6 +27,9 @@
 from code import InteractiveConsole, InteractiveInterpreter, softspace
 from optparse import make_option
 __version__ = '0.5.1'
+import logging
+
+logging.basicConfig(filename='log.txt')
 
 class OptionParser(optparse.OptionParser):
     def exit(self, status=0, msg=None):
@@ -289,13 +292,16 @@
         })
         
     def do_help(self, arg):
-        funcname = self.func_named(arg)
-        if funcname:
-            fn = getattr(self, funcname)
-            try:
-                fn.optionParser.print_help(file=self.stdout)
-            except AttributeError:
-                cmd.Cmd.do_help(self, funcname[3:])
+        if arg:
+            funcname = self.func_named(arg)
+            if funcname:
+                fn = getattr(self, funcname)
+                try:
+                    fn.optionParser.print_help(file=self.stdout)
+                except AttributeError:
+                    cmd.Cmd.do_help(self, funcname[3:])
+        else:
+            cmd.Cmd.do_help(self, arg)
         
     def __init__(self, *args, **kwargs):        
         cmd.Cmd.__init__(self, *args, **kwargs)
@@ -1105,31 +1111,21 @@
         sys.stdout = self.old_stdout
 
 class Cmd2TestCase(unittest.TestCase):
-    '''Subclass this, setting CmdApp and transcriptFileName, to make a unittest.TestCase class
-       that will execute the commands in transcriptFileName and expect the results shown.
+    '''Subclass this, setting CmdApp, to make a unittest.TestCase class
+       that will execute the commands in a transcript file and expect the results shown.
        See example.py'''
     CmdApp = None
-    transcriptFileName = ''
-    transcriptExtension = ''
     def fetchTranscripts(self):
-        import pdb; pdb.set_trace()
-        self.transcripts = []
-        #if self.CmdApp.testfile:
-        #    transcriptfilenames = [self.CmdApp.testfile]
-        if self.transcriptExtension:
-            transcriptfilenames = glob.glob('*.' + self.transcriptExtension)
-        elif self.transcriptFileName:
-            transcriptfilenames = [self.transcriptFileName]
-        for fname in transcriptfilenames:
+        self.transcripts = {}
+        for fname in glob.glob(self.CmdApp.testfile):
             tfile = open(fname)
-            self.transcripts.append(iter(tfile.readlines()))
+            self.transcripts[fname] = iter(tfile.readlines())
             tfile.close()
             
     def setUp(self):
         if self.CmdApp:
             self.outputTrap = OutputTrap()
             self.cmdapp = self.CmdApp()
-            import pdb; pdb.set_trace()
             self.fetchTranscripts()
     def assertEqualEnough(self, got, expected, message):
         got = got.strip().splitlines()
@@ -1141,9 +1137,13 @@
             self.assert_(re.match(matchme, linegot.strip()), message)
     def testall(self):
         if self.CmdApp:
-            for transcript in self.transcripts:
-                self._test_transcript(transcript)
-    def _test_transcript(self, transcript):
+            its = sorted(self.transcripts.items())
+            logging.error(str(its))
+            for (fname, transcript) in its:
+                logging.error(fname)
+                self._test_transcript(fname, transcript)
+                logging.error('finished')
+    def _test_transcript(self, fname, transcript):
         lineNum = 0
         try:
             line = transcript.next()
@@ -1161,7 +1161,7 @@
                 if line.startswith(self.cmdapp.prompt):
                     self.assertEqualEnough(result.strip(), '', 
                         '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing) \nGot:\n%s\n' % 
-                        (self.transcriptFileName, lineNum, command, result))    
+                        (fname, lineNum, command, result))    
                     continue
                 expected = []
                 while not line.startswith(self.cmdapp.prompt):
@@ -1170,7 +1170,7 @@
                 expected = ''.join(expected)
                 self.assertEqualEnough(expected.strip(), result.strip(), 
                     '\nFile %s, line %d\nCommand was:\n%s\nExpected:\n%s\nGot:\n%s\n' % 
-                    (self.transcriptFileName, lineNum, command, expected, result))    
+                    (fname, lineNum, command, expected, result))    
                 # this needs to account for a line-by-line strip()ping
         except StopIteration:
             pass
--- a/example/example.py	Thu Apr 02 13:41:58 2009 -0400
+++ b/example/example.py	Thu Apr 02 15:55:33 2009 -0400
@@ -32,18 +32,14 @@
 
 class TestMyAppCase(Cmd2TestCase):
     CmdApp = CmdLineApp
-    transcriptExtension = 'test'
 
 parser = optparse.OptionParser()
-parser.add_option('-a', '--alltests', dest='test', action="store_true", 
-                  help='Run all transcript tests')
-parser.add_option('-t', '--testfile', dest='testfile', metavar='FILE',
-                  help='Run a single transcript from file FILE')
+parser.add_option('-t', '--test', dest='test', metavar='FILE', 
+                  help='''Test against transcript(s) in FILE (wildcards OK)''')                  
 (callopts, callargs) = parser.parse_args()
-if callopts.testfile or callopts.test:
-    CmdLineApp.testfile = callopts.testfile
-    sys.argv = [sys.argv[0]]  # the --test argument upsets unittest.main()
+if callopts.test:
+    CmdLineApp.testfile = callopts.test
+    sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()
     unittest.main()
 else:
-    app = CmdLineApp()
-    app.cmdloop()
\ No newline at end of file
+    CmdLineApp().cmdloop()
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/example/exampleSession.txt	Thu Apr 02 15:55:33 2009 -0400
@@ -0,0 +1,96 @@
+(Cmd) help
+
+Documented commands (type help <topic>):
+========================================
+_load           ed    history  list   pause  run   set        show
+_relative_load  edit  l        load   py     save  shell      speak
+cmdenvironment  hi    li       orate  r      say   shortcuts
+
+Undocumented commands:
+======================
+EOF  eof  exit  help  q  quit
+
+(Cmd) help say
+Repeats what you tell me to.
+Usage: speak [options] arg
+
+Options:
+  -h, --help            show this help message and exit
+  -p, --piglatin        atinLay
+  -s, --shout           N00B EMULATION MODE
+  -r REPEAT, --repeat=REPEAT
+                        output [n] times
+
+(Cmd) say goodnight, Gracie
+goodnight, Gracie
+(Cmd) say -ps --repeat=5 goodnight, Gracie
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+(Cmd) set
+abbrev: True
+case_insensitive: True
+continuation_prompt: >
+default_file_name: command.txt
+echo: False
+editor: gedit
+prompt: (Cmd)
+timing: False
+maxrepeats: 3
+(Cmd) set maxrepeats 5
+maxrepeats - was: 3
+now: 5
+(Cmd) say -ps --repeat=5 goodnight, Gracie
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+(Cmd) hi
+-------------------------[1]
+help
+
+-------------------------[2]
+help say
+
+-------------------------[3]
+say goodnight, Gracie
+
+-------------------------[4]
+say -ps --repeat=5 goodnight, Gracie
+
+-------------------------[5]
+set
+
+-------------------------[6]
+set maxrepeats 5
+
+-------------------------[7]
+say -ps --repeat=5 goodnight, Gracie
+(Cmd) run 4
+say -ps --repeat=5 goodnight, Gracie
+
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+OODNIGHT, GRACIEGAY
+(Cmd) orate Four score and
+> seven releases ago
+> our BDFL
+> blah blah blah
+
+Four score and
+seven releases ago
+our BDFL
+blah blah blah
+(Cmd) & look, a shortcut!
+look, a shortcut!
+(Cmd) say put this in a file > myfile.txt
+(Cmd) say < myfile.txt
+put this in a file
+(Cmd) set prompt "---> "
+prompt - was: (Cmd)
+now: --->
+---> say goodbye
+goodbye
\ No newline at end of file