diff options
author | Zearin <zearin@gonk.net> | 2011-11-12 12:46:59 -0500 |
---|---|---|
committer | Zearin <zearin@gonk.net> | 2011-11-12 12:46:59 -0500 |
commit | e3a26c6d709e0e13270aa46d8f8136e93508137c (patch) | |
tree | ddf13a74da910414a1779b2b71f95f9a0bc746b0 | |
parent | 8622b7d1bf68b91af9ad039dd0b9e994d7101775 (diff) | |
download | cmd2-e3a26c6d709e0e13270aa46d8f8136e93508137c.tar.gz |
Docstring stubs added. (Non-leading!) Whitespace for readability.
-rwxr-xr-x | cmd2/cmd2.py | 103 | ||||
-rw-r--r-- | cmd2/commands.py | 123 | ||||
-rw-r--r-- | cmd2/errors.py | 19 | ||||
-rw-r--r-- | cmd2/ignoreBug.py | 6 | ||||
-rw-r--r-- | cmd2/parsers.py | 30 | ||||
-rw-r--r-- | cmd2/tests.py | 38 |
6 files changed, 206 insertions, 113 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 4c976ac..594ad05 100755 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -77,7 +77,7 @@ class Cmd(cmd.Cmd): # while still limiting their scope to this class... - _STOP_AND_EXIT = True # distinguish script file's end from actual exit + _STOP_AND_EXIT = True # distinguish script's end from actual exit _STOP_SCRIPT_NO_EXIT = -999 @@ -159,8 +159,8 @@ class Cmd(cmd.Cmd): # @FIXME # # Add docstring describing what gets __init__'ed, - # and what Cmd2 users might want to do with - # __init__ in their own Cmd2-based program. + # and what a cmd2 subclass might want to do with + # its own __init__. # cmd.Cmd.__init__(self, *args, **kwargs) self.initial_stdout = sys.stdout @@ -178,7 +178,6 @@ class Cmd(cmd.Cmd): off the received input, and dispatch to action methods, passing them the remainder of the line as argument. ''' - # An almost-perfect copy from Cmd. # # However, the `pseudo_raw_input` portion has been @@ -220,6 +219,8 @@ class Cmd(cmd.Cmd): def _default(self, statement): + # @FIXME + # Add docstring description arg = statement.full_parsed_statement() if self.default_to_shell: result = os.system(arg) @@ -479,14 +480,20 @@ class Cmd(cmd.Cmd): def preparse(self, raw, **kwargs): + # @FIXME + # Add docstring description return raw def postparse(self, parseResult): + # @FIXME + # Add docstring description return parseResult def parsed(self, raw, **kwargs): + # @FIXME + # Add docstring description if isinstance(raw, ParsedString): p = raw else: @@ -498,24 +505,32 @@ class Cmd(cmd.Cmd): if s.lower().startswith(shortcut): s = s.replace(shortcut, expansion + ' ', 1) break - result = self.parser.parseString(s) - result['raw'] = raw - result['command'] = result.multilineCommand or result.command - result = self.postparse(result) - p = ParsedString(result.args) - p.parsed = result - p.parser = self.parsed + + result = self.parser.parseString(s) + result['raw'] = raw + result['command'] = result.multilineCommand or result.command + result = self.postparse(result) + + p = ParsedString(result.args) + p.parsed = result + p.parser = self.parsed + for (key, val) in kwargs.items(): p.parsed[key] = val + return p def postparsing_precmd(self, statement): + # @FIXME + # Add docstring description stop = 0 return stop, statement def postparsing_postcmd(self, stop): + # @FIXME + # Add docstring description return stop @@ -530,9 +545,11 @@ class Cmd(cmd.Cmd): def perror(self, errmsg, statement=None): + # @FIXME + # Add docstring description if self.debug: traceback.print_exc() - print (str(errmsg)) + print( str(errmsg) ) def pfeedback(self, msg): @@ -548,7 +565,7 @@ class Cmd(cmd.Cmd): print (msg) - colorcodes = { 'bold' :{True:'\x1b[1m' ,False:'\x1b[22m'}, + colorcodes = { 'bold' :{True:'\x1b[1m' ,False:'\x1b[22m'}, 'cyan' :{True:'\x1b[36m',False:'\x1b[39m'}, 'blue' :{True:'\x1b[34m',False:'\x1b[39m'}, 'red' :{True:'\x1b[31m',False:'\x1b[39m'}, @@ -558,7 +575,7 @@ class Cmd(cmd.Cmd): } - colors = (platform.system() != 'Windows') + colors = (platform.system() != 'Windows') def colorize(self, val, color): @@ -578,21 +595,28 @@ class Cmd(cmd.Cmd): def func_named(self, arg): - '''This method is responsible for locating `do_*` for commands.''' + ''' + This method is responsible for locating `do_*` for commands. + ''' + + result = None + target = 'do_' + arg - result = None - target = 'do_' + arg if target in dir(self): - result = target + result = target else: if self.abbrev: # accept shortened versions of commands funcs = [fname for fname in self.keywords if fname.startswith(arg)] if len(funcs) == 1: result = 'do_' + funcs[0] + return result def onecmd_plus_hooks(self, line): + # @FIXME + # Add docstring description + # The outermost level of try/finally nesting can be condensed once # Python 2.4 support can be dropped. # @@ -601,18 +625,18 @@ class Cmd(cmd.Cmd): try: try: - statement = self.complete_statement(line) - (stop, statement) = self.postparsing_precmd(statement) + statement = self.complete_statement(line) + (stop, statement) = self.postparsing_precmd(statement) if stop: return self.postparsing_postcmd(stop) if statement.parsed.command not in self.excludeFromHistory: self.history.append(statement.parsed.raw) try: self.redirect_output(statement) - timestart = datetime.datetime.now() - statement = self.precmd(statement) - stop = self.onecmd(statement) - stop = self.postcmd(stop, statement) + timestart = datetime.datetime.now() + statement = self.precmd(statement) + stop = self.onecmd(statement) + stop = self.postcmd(stop, statement) if self.timing: self.pfeedback('Elapsed: %s' % str(datetime.datetime.now() - timestart)) finally: @@ -629,21 +653,28 @@ class Cmd(cmd.Cmd): ''' Continue accepting lines of input until the command is complete. ''' - if (not line) or ( - not pyparsing.Or(self.commentGrammars). - setParseAction(lambda x: '').transformString(line)): + if (not line) or ( \ + not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line) \ + ): raise EmptyStatement + statement = self.parsed(line) + while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): - statement = '%s\n%s' % (statement.parsed.raw, + statement = '%s\n%s' % (statement.parsed.raw, self.pseudo_raw_input(self.continuation_prompt)) - statement = self.parsed(statement) + statement = self.parsed(statement) + if not statement.parsed.command: raise EmptyStatement + return statement def redirect_output(self, statement): + # @FIXME + # Add docstring description + if statement.parsed.pipeTo: self.kept_state = Statekeeper(self, ('stdout',)) self.kept_sys = Statekeeper(sys, ('stdout',)) @@ -668,6 +699,8 @@ class Cmd(cmd.Cmd): def restore_output(self, statement): + # @FIXME + # Add docstring description if self.kept_state: if statement.parsed.output: if not statement.parsed.outputTo: @@ -774,6 +807,8 @@ class Cmd(cmd.Cmd): def last_matching(self, arg): + # @FIXME + # Add docstring description try: if arg: return self.history.get(arg)[-1] @@ -784,6 +819,9 @@ class Cmd(cmd.Cmd): def read_file_or_url(self, fname): + # @FIXME + # Add docstring description + # @TODO : not working on localhost if isinstance(fname, file): result = open(fname, 'r') @@ -819,6 +857,7 @@ class Cmd(cmd.Cmd): # Add docstring class TestMyAppCase(Cmd2TestCase): CmdApp = self.__class__ + self.__class__.testfiles = callargs sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() testcase = TestMyAppCase() @@ -836,12 +875,16 @@ class Cmd(cmd.Cmd): def cmdloop(self): - parser = optparse.OptionParser() + # @FIXME + # Add docstring description + + parser = optparse.OptionParser() parser.add_option('-t', '--test', dest ='test', action ='store_true', help ='Test against transcript(s) in FILE (wildcards OK)') (callopts, callargs) = parser.parse_args() + if callopts.test: self.runTranscriptTests(callargs) else: diff --git a/cmd2/commands.py b/cmd2/commands.py index 61f5170..0c40ced 100644 --- a/cmd2/commands.py +++ b/cmd2/commands.py @@ -1,5 +1,5 @@ ''' -This file should contain all the built-in `do_*` commands of Cmd2. +This file should contain all builtin `do_*` commands of Cmd2. ''' @@ -10,13 +10,16 @@ def do__relative_load(self, arg=None): already-running script's directory. ''' if arg: - arg = arg.split(None, 1) - targetname, args = arg[0], (arg[1:] or [''])[0] - targetname = os.path.join(self.current_script_dir or '', targetname) + arg = arg.split(None, 1) + targetname = arg[0] + args = (arg[1:] or [''])[0] + targetname = os.path.join(self.current_script_dir or '', targetname) self.do__load('%s %s' % (targetname, args)) + urlre = re.compile('(https?://[-\\w\\./]+)') + def do_cmdenvironment(self, args): ''' Summary report of interactive parameters. @@ -27,17 +30,20 @@ def do_cmdenvironment(self, args): Commands may be terminated with: %(terminators)s Settable parameters: %(settable)s\n""" % \ - { 'casesensitive' : (self.case_insensitive and 'not ') or '', - 'terminators' : str(self.terminators), - 'settable' : ' '.join(self.settable) - }) + { 'casesensitive' : (self.case_insensitive and 'not ') or '', + 'terminators' : str(self.terminators), + 'settable' : ' '.join(self.settable) + } + ) def do_help(self, arg): + # @FIXME + # Add docstring description if arg: funcname = self.func_named(arg) if funcname: - fn = getattr(self, funcname) + fn = getattr(self, funcname) try: fn.optionParser.print_help(file=self.stdout) except AttributeError: @@ -50,19 +56,21 @@ def do_shortcuts(self, args): ''' Lists single-key shortcuts available. ''' - result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) + result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) def do_EOF(self, arg): return self._STOP_SCRIPT_NO_EXIT # End of script; should not exit app + do_eof = do_EOF def do_quit(self, arg): return self._STOP_AND_EXIT + do_exit = do_quit do_q = do_quit @@ -76,13 +84,15 @@ def do_show(self, arg, opts): ''' Show the value of a parameter. ''' - param = arg.strip().lower() - result = {} - maxlen = 0 + param = arg.strip().lower() + result = {} + maxlen = 0 + for p in self.settable: if (not param) or p.startswith(param): - result[p] = '%s: %s' % (p, str(getattr(self, p))) - maxlen = max(maxlen, len(result[p])) + result[p] = '%s: %s' % (p, str(getattr(self, p))) + maxlen = max(maxlen, len(result[p])) + if result: for p in sorted(result): if opts.long: @@ -101,8 +111,8 @@ def do_set(self, arg): ''' try: statement, paramName, val = arg.parsed.raw.split(None, 2) - val = val.strip() - paramName = paramName.strip().lower() + val = val.strip() + paramName = paramName.strip().lower() if paramName not in self.settable: hits = [p for p in self.settable if p.startswith(paramName)] @@ -110,6 +120,7 @@ def do_set(self, arg): paramName = hits[0] else: return self.do_show(paramName) + currentVal = getattr(self, paramName) if (val[0] == val[-1]) and val[0] in ("'", '"'): @@ -131,7 +142,9 @@ def do_set(self, arg): def do_pause(self, arg): - '''Display the provided text, then wait for the user to press RETURN.''' + ''' + Display the provided text, then wait for the user to press RETURN. + ''' raw_input(arg + '\n') @@ -153,9 +166,9 @@ def do_py(self, arg): Run python code from external files with ``run("filename.py")`` ''' self.pystate['self'] = self - arg = arg.parsed.raw[2:].strip() - localvars = (self.locals_in_py and self.pystate) or {} - interp = InteractiveConsole(locals=localvars) + arg = arg.parsed.raw[2:].strip() + localvars = (self.locals_in_py and self.pystate) or {} + interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') if arg.strip(): @@ -163,8 +176,10 @@ def do_py(self, arg): else: def quit(): raise EmbeddedConsoleExit + def onecmd_plus_hooks(arg): return self.onecmd_plus_hooks(arg + '\n') + def run(arg): try: file = open(arg) @@ -172,10 +187,11 @@ def do_py(self, arg): file.close() except IOError, e: self.perror(e) - self.pystate['quit'] = quit - self.pystate['exit'] = quit - self.pystate['cmd'] = onecmd_plus_hooks - self.pystate['run'] = run + + self.pystate['quit'] = quit + self.pystate['exit'] = quit + self.pystate['cmd'] = onecmd_plus_hooks + self.pystate['run'] = run try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' @@ -186,6 +202,7 @@ def do_py(self, arg): (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) except EmbeddedConsoleExit: pass + keepstate.restore() @@ -194,7 +211,7 @@ def do_py(self, arg): '-s', '--script', action = 'store_true', help = 'Script format; no separation lines'),], - arg_desc = '(limit on which commands to include)') + arg_desc = '(limit which commands to include)') def do_history(self, arg, opts): ''' history [arg]: lists past commands issued @@ -208,6 +225,7 @@ def do_history(self, arg, opts): history = self.history.get(arg) else: history = self.history + for hi in history: if opts.script: self.poutput(hi) @@ -216,7 +234,8 @@ def do_history(self, arg, opts): def do_list(self, arg): - '''list [arg]: lists last command issued + ''' + list [arg]: lists last command issued no arg -> list most recent command arg is integer -> list one history item, by index @@ -228,9 +247,11 @@ def do_list(self, arg): history = self.history.span(arg or '-1') except IndexError: history = self.history.search(arg) + for hi in history: self.poutput(hi.pr()) + do_hi = do_history do_l = do_list do_li = do_list @@ -249,7 +270,9 @@ def do_ed(self, arg): ''' if not self.editor: raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.") + filename = self.default_file_name + if arg: try: buffer = self.last_matching(int(arg)) @@ -263,12 +286,13 @@ def do_ed(self, arg): f = open(os.path.expanduser(filename), 'w') f.write(buffer or '') f.close() + os.system('%s %s' % (self.editor, filename)) self.do__load(filename) -do_edit = do_ed -saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") + +do_edit = do_ed +saveparser =(pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") + pyparsing.Optional(pyparsing.Word(legalChars + '/\\'))("fname") + pyparsing.stringEnd) @@ -291,11 +315,11 @@ def do_save(self, arg): fname = args.fname or self.default_file_name if args.idx == '*': - saveme = '\n\n'.join(self.history[:]) + saveme = '\n\n'.join(self.history[:]) elif args.idx: - saveme = self.history[int(args.idx)-1] + saveme = self.history[int(args.idx)-1] else: - saveme = self.history[-1] + saveme = self.history[-1] try: f = open(os.path.expanduser(fname), 'w') @@ -312,29 +336,40 @@ def do_load(self, arg=None): Runs script of command(s) from a file or URL. ''' if arg is None: - targetname = self.default_file_name + targetname = self.default_file_name else: - arg = arg.split(None, 1) - targetname, args = arg[0], (arg[1:] or [''])[0].strip() + arg = arg.split(None, 1) + targetname = arg[0] + args = (arg[1:] or [''])[0].strip() try: - target = self.read_file_or_url(targetname) + target = self.read_file_or_url(targetname) except IOError, e: self.perror('Problem accessing script from %s: \n%s' % (targetname, e)) return - keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt', - 'continuation_prompt','current_script_dir')) - self.stdin = target - self.use_rawinput = False - self.prompt = self.continuation_prompt = '' + + keepstate = Statekeeper(self, ( + 'stdin' , + 'use_rawinput' , + 'prompt' , + 'continuation_prompt' , + 'current_script_dir' + ) + ) + + self.stdin = target + self.use_rawinput = False + self.prompt = self.continuation_prompt = '' self.current_script_dir = os.path.split(targetname)[0] - stop = self._cmdloop() + stop = self._cmdloop() self.stdin.close() keepstate.restore() self.lastcmd = '' return stop and (stop != self._STOP_SCRIPT_NO_EXIT) + do__load = do_load # avoid an unfortunate legacy use of do_load from sqlpython + def do_run(self, arg): ''' run [arg]: re-runs an earlier command @@ -345,9 +380,9 @@ def do_run(self, arg): /arg enclosed in slashes/ -> run most recent by regex ''' 'run [N]: runs the SQL that was run N commands ago' - runme = self.last_matching(arg) + runme = self.last_matching(arg) self.pfeedback(runme) if runme: - stop = self.onecmd_plus_hooks(runme) + stop = self.onecmd_plus_hooks(runme) do_r = do_run
\ No newline at end of file diff --git a/cmd2/errors.py b/cmd2/errors.py index ca727aa..c736b52 100644 --- a/cmd2/errors.py +++ b/cmd2/errors.py @@ -27,11 +27,9 @@ class PasteBufferError(EnvironmentError): Download: http://sourceforge.net/projects/pywin32/ """ - elif sys.platform[:3] == 'dar': # Use built in pbcopy on Mac OSX pass - else: errmsg = """ Redirecting to or from paste buffer requires xclip @@ -61,6 +59,7 @@ pastebufferr = """ if subprocess.mswindows: try: import win32clipboard + def get_paste_buffer(): win32clipboard.OpenClipboard(0) try: @@ -69,6 +68,7 @@ if subprocess.mswindows: result = '' #non-text win32clipboard.CloseClipboard() return result + def write_to_paste_buffer(txt): win32clipboard.OpenClipboard(0) win32clipboard.EmptyClipboard() @@ -84,24 +84,28 @@ elif sys.platform == 'darwin': # Mac OS X # test for pbcopy - AFAIK, should always be installed on MacOS subprocess.check_call('pbcopy -help', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) can_clip = True - except (subprocess.CalledProcessError, OSError, IOError): + except (subprocess.CalledProcessError, OSError, IOError): pass pass + if can_clip: + def get_paste_buffer(): pbcopyproc = subprocess.Popen('pbcopy -help', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) return pbcopyproc.stdout.read() + def write_to_paste_buffer(txt): pbcopyproc = subprocess.Popen('pbcopy', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) pbcopyproc.communicate(txt.encode()) + else: def get_paste_buffer(*args): - raise OSError, pastebufferr % ('pbcopy', 'On MacOS X - error should not occur - part of the default installation') + raise OSError, pastebufferr % ('pbcopy', 'On Mac OS X - Error should not occur! (Part of default installation)') write_to_paste_buffer = get_paste_buffer else: - can_clip = False + can_clip = False try: subprocess.check_call('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) - can_clip = True + can_clip = True except AttributeError: # check_call not defined, Python < 2.5 try: teststring = 'Testing for presence of xclip.' @@ -115,10 +119,12 @@ else: pass except Exception: pass # something went wrong with xclip and we cannot use it + if can_clip: def get_paste_buffer(): xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) return xclipproc.stdout.read() + def write_to_paste_buffer(txt): xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) xclipproc.stdin.write(txt.encode()) @@ -130,4 +136,5 @@ else: else: def get_paste_buffer(*args): raise OSError, pastebufferr % ('xclip', 'On Debian/Ubuntu, install with "sudo apt-get install xclip"') + write_to_paste_buffer = get_paste_buffer
\ No newline at end of file diff --git a/cmd2/ignoreBug.py b/cmd2/ignoreBug.py index 8ede73f..285955f 100644 --- a/cmd2/ignoreBug.py +++ b/cmd2/ignoreBug.py @@ -5,12 +5,12 @@ from pyparsing import * -teststr = 'please /* ignoreme: | oops */ findme: | kthx' -parser = Word(printables)('leadWord') + SkipTo('|')('statement') +teststr = 'please /* ignoreme: | oops */ findme: | kthx' +parser = Word(printables)('leadWord') + SkipTo('|')('statement') print parser.parseString(teststr).statement parser.ignore(cStyleComment) print parser.parseString(teststr).statement -parser = Combine(parser) +parser = Combine(parser) print parser.parseString(teststr).statement parser.ignore(cStyleComment) print parser.parseString(teststr).statement diff --git a/cmd2/parsers.py b/cmd2/parsers.py index e276be8..a74f922 100644 --- a/cmd2/parsers.py +++ b/cmd2/parsers.py @@ -2,7 +2,9 @@ This file should contain all parser definitions for Cmd2. ''' + class OptionParser(optparse.OptionParser): + def exit(self, status=0, msg=None): self.values._exit = True if msg: @@ -16,12 +18,12 @@ class OptionParser(optparse.OptionParser): optparse.OptionParser.print_help(self, *args, **kwargs) def error(self, msg): - """error(msg : string) + '''error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. - If you override this in a subclass, it should not return -- it + If you override this in a subclass, it should NOT return -- it should either exit or raise an exception. - """ + ''' raise optparse.OptParseError(msg) @@ -32,24 +34,26 @@ def remaining_args(oldArgs, newArgList): >>> remaining_args('-f bar bar cow', ['bar', 'cow']) 'bar cow' ''' - pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' - matchObj = re.search(pattern, oldArgs) + pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' + matchObj = re.search(pattern, oldArgs) return oldArgs[matchObj.start():] class ParsedString(str): + def full_parsed_statement(self): - new = ParsedString('%s %s' % (self.parsed.command, self.parsed.args)) - new.parsed = self.parsed - new.parser = self.parser + new = ParsedString('%s %s' % (self.parsed.command, self.parsed.args)) + new.parsed = self.parsed + new.parser = self.parser return new + def with_args_replaced(self, newargs): - new = ParsedString(newargs) - new.parsed = self.parsed - new.parser = self.parser - new.parsed['args'] = newargs - new.parsed.statement['args'] = newargs + new = ParsedString(newargs) + new.parsed = self.parsed + new.parser = self.parser + new.parsed['args'] = newargs + new.parsed.statement['args']= newargs return new diff --git a/cmd2/tests.py b/cmd2/tests.py index e841f28..c3db87d 100644 --- a/cmd2/tests.py +++ b/cmd2/tests.py @@ -35,7 +35,10 @@ class Cmd2TestCase(unittest.TestCase): for (fname, transcript) in its: self._test_transcript(fname, transcript) - regexPattern = pyparsing.QuotedString(quoteChar=r'/', escChar='\\', multiline=True, unquoteResults=True) + regexPattern = pyparsing.QuotedString( quoteChar =r'/', + escChar ='\\', + multiline =True, + unquoteResults =True ) regexPattern.ignore(pyparsing.cStyleComment) notRegexPattern = pyparsing.Word(pyparsing.printables) @@ -51,7 +54,7 @@ class Cmd2TestCase(unittest.TestCase): lineNum += 1 tests_run = 0 - while not finished: + while not finished: # Scroll forward to where actual commands begin while not line.startswith(self.cmdapp.prompt): try: @@ -60,8 +63,9 @@ class Cmd2TestCase(unittest.TestCase): finished = True break lineNum += 1 + command = [line[len(self.cmdapp.prompt):]] - line = transcript.next() + line = transcript.next() # Read the entirety of a multi-line command while line.startswith(self.cmdapp.continuation_prompt): @@ -70,17 +74,17 @@ class Cmd2TestCase(unittest.TestCase): line = transcript.next() except StopIteration: raise (StopIteration, - 'Transcript broke off while reading command beginning at line %d with\n%s' - % (command[0])) + 'Transcript broke off while reading command beginning at line %d with\n%s'%\ + (command[0])) lineNum += 1 command = ''.join(command) # Send the command into the application and capture the resulting output - stop = self.cmdapp.onecmd_plus_hooks(command) + stop = self.cmdapp.onecmd_plus_hooks(command) #TODO: should act on ``stop`` - result = self.outputTrap.read() + result = self.outputTrap.read() # Read the expected result from transcript if line.startswith(self.cmdapp.prompt): @@ -118,15 +122,15 @@ class Cmd2TestCase(unittest.TestCase): def runTranscriptTests(self, callargs): - # @FIXME - # Add docstring - class TestMyAppCase(Cmd2TestCase): - CmdApp = self.__class__ - self.__class__.testfiles = callargs - sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() - testcase = TestMyAppCase() - runner = unittest.TextTestRunner() - result = runner.run(testcase) - result.printErrors() + # @FIXME + # Add docstring + class TestMyAppCase(Cmd2TestCase): + CmdApp = self.__class__ + self.__class__.testfiles = callargs + sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() + testcase = TestMyAppCase() + runner = unittest.TextTestRunner() + result = runner.run(testcase) + result.printErrors() |