def run_debugger(testname, python_file, dbgr_opts='', args='', outfile=None): srcdir = get_srcdir() datadir = os.path.join(srcdir, '..', 'data') progdir = os.path.join(srcdir, '..', 'example') dbgrdir = os.path.join(srcdir, '..', '..', 'trepan') dbgr_short= "cli.py" dbgr_path = os.path.join(dbgrdir, dbgr_short) rightfile = os.path.join(datadir, "%s.right" % testname) sys.path.insert(0, os.path.join(get_srcdir(), '../..')) os.environ['PYTHONPATH']=os.pathsep.join(sys.path) cmdfile = os.path.join(datadir, "%s.cmd" % testname) outfile = os.path.join(srcdir, "%s.out" % testname) if python_file: programfile = os.path.join(progdir, python_file) else: programfile = '' pass outfile_opt = '--output=%s ' % outfile if os.path.exists(outfile): os.unlink(outfile) cmd = "%s --command %s %s %s %s %s" % \ (dbgr_path, cmdfile, outfile_opt, dbgr_opts, programfile, args) print(cmd) os.system(cmd) fromfile = rightfile fromdate = time.ctime(os.stat(fromfile).st_mtime) fromlines = open(fromfile, 'U').readlines() tofile = outfile todate = time.ctime(os.stat(tofile).st_mtime) tolines = open(tofile, 'U').readlines() # Filter out <module> for Python 2.4 and before module_re = re.compile('[)]: <module>') tolines = [re.sub(module_re, '):', line) for line in tolines] diff = list(difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate)) if len(diff) == 0: os.unlink(outfile) pass for line in diff: print(line.rstrip()) pass return len(diff) == 0
def _populate_commands(self): """ Create an instance of each of the debugger commands. Commands are found by importing files in the directory 'command'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" cmd_instances = [] Mcommand = import_relative('command') eval_cmd_template = 'command_mod.%s(self)' srcdir = get_srcdir() sys.path.insert(0, srcdir) for mod_name in Mcommand.__modules__: if mod_name in ( 'info_sub', 'set_sub', 'show_sub', ): pass import_name = "command." + mod_name if False: # Sometimes we want this command_mod = getattr(__import__(import_name), mod_name) else: # FIXME give more info like the above when desired # For debugging: # command_mod = getattr(__import__(import_name), mod_name) try: command_mod = getattr(__import__(import_name), mod_name) except: print('Error importing %s: %s' % (mod_name, sys.exc_info()[0])) continue pass classnames = [ tup[0] for tup in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != tup[0] and tup[0].endswith('Command')) ] for classname in classnames: eval_cmd = eval_cmd_template % classname if False: instance = eval(eval_cmd) cmd_instances.append(instance) else: try: instance = eval(eval_cmd) cmd_instances.append(instance) except: print('Error loading %s from %s: %s' % (classname, mod_name, sys.exc_info()[0])) pass pass pass pass sys.path.remove(srcdir) return cmd_instances
def pyfiles(level=2): "All python files caller's dir without the path and trailing .py" d = get_srcdir(level) # Get the name of our directory. # A glob pattern that will get all *.py files but not __init__.py glob(os.path.join(d, '[a-zA-Z]*.py')) py_files = glob(os.path.join(d, '[a-zA-Z]*.py')) return [ os.path.basename(filename[0:-3]) for filename in py_files ]
def pyfiles(level=2): "All python files caller's dir without the path and trailing .py" d = get_srcdir(level) # Get the name of our directory. # A glob pattern that will get all *.py files but not __init__.py glob(os.path.join(d, '[a-zA-Z]*.py')) py_files = glob(os.path.join(d, '[a-zA-Z]*.py')) return [os.path.basename(filename[0:-3]) for filename in py_files]
def _load_debugger_subcommands(self, name): """ Create an instance of each of the debugger subcommands. Commands are found by importing files in the directory 'name' + 'sub'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" # Initialization cmd_instances = [] module_dir = name + '_subcmd' class_prefix = string.capitalize(name) # e.g. Info, Set, or Show mod = import_relative(module_dir) eval_cmd_template = 'command_mod.%s(self)' srcdir = get_srcdir() sys.path.insert(0, srcdir) sub_srcdir = os.path.join(srcdir, module_dir) sys.path.insert(0, sub_srcdir) # Import, instantiate, and add classes for each of the # modules found in module_dir imported above. for module_name in mod.__modules__: import_name = module_dir + '.' + module_name command_mod = getattr(__import__(import_name), module_name) try: command_mod = getattr(__import__(import_name), module_name) except ImportError: print("Error importing name %s module %s: %s" % (import_name, module_name, sys.exc_info()[0])) continue # Even though we tend not to do this, it is possible to # put more than one class into a module/file. So look for # all of them. classnames = [ classname for classname, classvalue in inspect.getmembers( command_mod, inspect.isclass) if ('DebuggerCommand' != classname and classname.startswith(class_prefix)) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) self.cmds.add(instance) except: print "Error eval'ing class %s" % classname pass pass pass sys.path.remove(srcdir) sys.path.remove(sub_srcdir) return cmd_instances
def _load_debugger_subcommands(self, name): """ Create an instance of each of the debugger subcommands. Commands are found by importing files in the directory 'name' + 'sub'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" # Initialization cmd_instances = [] module_dir = name + '_subcmd' class_prefix = string.capitalize(name) # e.g. Info, Set, or Show mod = import_relative(module_dir) eval_cmd_template = 'command_mod.%s(self)' srcdir = get_srcdir() sys.path.insert(0, srcdir) sub_srcdir = os.path.join(srcdir, module_dir) sys.path.insert(0, sub_srcdir) # Import, instantiate, and add classes for each of the # modules found in module_dir imported above. for module_name in mod.__modules__: import_name = module_dir + '.' + module_name command_mod = getattr(__import__(import_name), module_name) try: command_mod = getattr(__import__(import_name), module_name) except ImportError: print("Error importing name %s module %s: %s" % (import_name, module_name, sys.exc_info()[0])) continue # Even though we tend not to do this, it is possible to # put more than one class into a module/file. So look for # all of them. classnames = [ classname for classname, classvalue in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != classname and classname.startswith(class_prefix)) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) self.cmds.add(instance) except: print "Error eval'ing class %s" % classname pass pass pass sys.path.remove(srcdir) sys.path.remove(sub_srcdir) return cmd_instances
def test_DebuggerInput(self): cmdhelper_file=os.path.join(get_srcdir(),'cmdhelper.py') inp = Minput.TrepanUserInput(cmdhelper_file) self.assertTrue(inp, 'Should have gotten a TrepanInput object back') line = inp.readline() self.assertEqual('# -*- coding: utf-8 -*-', line) inp.close() # Should be okay inp.close() return
def test_DebuggerInput(self): cmdhelper_file=os.path.join(get_srcdir(),'cmdhelper.py') inp = Minput.DebuggerUserInput(cmdhelper_file) self.assertTrue(inp, 'Should have gotten a DebuggerInput object back') line = inp.readline() self.assertEqual('# -*- coding: utf-8 -*-', line) inp.close() # Should be okay inp.close() return
def test_DebuggerInput(self): cmdhelper_file = os.path.join(get_srcdir(), "cmdhelper.py") inp = Minput.DebuggerUserInput(cmdhelper_file) self.assertTrue(inp, "Should have gotten a DebuggerInput object back") line = inp.readline() self.assertEqual("# -*- coding: utf-8 -*-", line) inp.close() # Should be okay inp.close() return
def _populate_commands(self): """ Create an instance of each of the debugger commands. Commands are found by importing files in the directory 'command'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" cmd_instances = [] Mcommand = import_relative('command') eval_cmd_template = 'command_mod.%s(self)' srcdir = get_srcdir() sys.path.insert(0, srcdir) for mod_name in Mcommand.__modules__: if mod_name in ('info_sub', 'set_sub', 'show_sub',): pass import_name = "command." + mod_name if False: # Sometimes we want this command_mod = getattr(__import__(import_name), mod_name) else: # FIXME give more info like the above when desired # For debugging: command_mod = getattr(__import__(import_name), mod_name) try: command_mod = getattr(__import__(import_name), mod_name) except: print('Error importing %s: %s' % (mod_name, sys.exc_info()[0])) continue pass classnames = [ tup[0] for tup in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != tup[0] and tup[0].endswith('Command')) ] for classname in classnames: eval_cmd = eval_cmd_template % classname if False: instance = eval(eval_cmd) cmd_instances.append(instance) else: try: instance = eval(eval_cmd) cmd_instances.append(instance) except: print('Error loading %s from %s: %s' % (classname, mod_name, sys.exc_info()[0])) pass pass pass pass sys.path.remove(srcdir) return cmd_instances
def run_debugger(testname, python_file, dbgr_opts='', args='', outfile=None): srcdir = get_srcdir() datadir = os.path.join(srcdir, '..', 'data') progdir = os.path.join(srcdir, '..', 'example') dbgrdir = os.path.join(srcdir, '..', '..', 'trepan') dbgr_short= "cli.py" dbgr_path = os.path.join(dbgrdir, dbgr_short) rightfile = os.path.join(datadir, "%s.right" % testname) os.environ['PYTHONPATH']=os.pathsep.join(sys.path) cmdfile = os.path.join(datadir, "%s.cmd" % testname) outfile = os.path.join(srcdir, "%s.out" % testname) if python_file: programfile = os.path.join(progdir, python_file) else: programfile = '' pass outfile_opt = '--output=%s ' % outfile if os.path.exists(outfile): os.unlink(outfile) cmd = "%s --command %s %s %s %s %s" % \ (dbgr_path, cmdfile, outfile_opt, dbgr_opts, programfile, args) print(cmd) os.system(cmd) fromfile = rightfile fromdate = time.ctime(os.stat(fromfile).st_mtime) fromlines = open(fromfile, 'U').readlines() tofile = outfile todate = time.ctime(os.stat(tofile).st_mtime) tolines = open(tofile, 'U').readlines() # Filter out <module> for Python 2.4 and before module_re = re.compile('[)]: <module>') tolines = [re.sub(module_re, '):', line) for line in tolines] diff = list(difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate)) if len(diff) == 0: os.unlink(outfile) pass for line in diff: print(line.rstrip()) pass return len(diff) == 0
def populate_commands_easy_install(self, Mcommand): cmd_instances = [] eval_cmd_template = 'command_mod.%s(self)' srcdir = get_srcdir() sys.path.insert(0, srcdir) for mod_name in Mcommand.__modules__: if mod_name in ('info_sub', 'set_sub', 'show_sub',): pass import_name = "command." + mod_name if False: # Sometimes we want this command_mod = getattr(__import__(import_name), mod_name) else: # FIXME give more info like the above when desired # For debugging: command_mod = getattr(__import__(import_name), mod_name) try: command_mod = getattr(__import__(import_name), mod_name) except: print('Error importing %s: %s' % (mod_name, sys.exc_info()[0])) continue pass classnames = [ tup[0] for tup in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != tup[0] and tup[0].endswith('Command')) ] for classname in classnames: eval_cmd = eval_cmd_template % classname if False: instance = eval(eval_cmd) cmd_instances.append(instance) else: try: instance = eval(eval_cmd) cmd_instances.append(instance) except: print('Error loading %s from %s: %s' % (classname, mod_name, sys.exc_info()[0])) pass pass pass pass sys.path.remove(srcdir) return cmd_instances
def run_debugger(testname, python_file, dbgr_opts='', args='', outfile=None): srcdir = get_srcdir() datadir = os.path.join(srcdir, '..', 'data') progdir = os.path.join(srcdir, '..', 'example') dbgrdir = os.path.join(srcdir, '..', '..', 'trepan') dbgr_short= "cli.py" dbgr_path = os.path.join(dbgrdir, dbgr_short) rightfile = os.path.join(datadir, "%s.right" % testname) os.environ['PYTHONPATH']=os.pathsep.join(sys.path) cmdfile = os.path.join(datadir, "%s.cmd" % testname) outfile = os.path.join(srcdir, "%s.out" % testname) if python_file: programfile = os.path.join(progdir, python_file) else: programfile = '' pass outfile_opt = '--output=%s ' % outfile if os.path.exists(outfile): os.unlink(outfile) cmd = "%s --command %s %s %s %s %s" % \ (dbgr_path, cmdfile, outfile_opt, dbgr_opts, programfile, args) print(cmd) os.system(cmd) fromfile = rightfile fromdate = time.ctime(os.stat(fromfile).st_mtime) fileout = open(fromfile, 'U') fromlines = fileout.readlines() tofile = outfile todate = time.ctime(os.stat(tofile).st_mtime) filein = open(tofile, 'U') tolines = filein.readlines() diff = list(difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate)) if len(diff) == 0: os.unlink(outfile) pass for line in diff: print(line.rstrip()) pass filein.close(); fileout.close() return len(diff) == 0
compatible with other input routines and are ignored. EOFError will be raised on EOF. """ line = self.input.readline() if not line: raise EOFError return line.rstrip("\n") # Demo if __name__=='__main__': inp = ScriptInput('scriptin.py') line = inp.readline() print(line) inp.close() # Note opts below are aren't acted upon. They are there for # compatibility import os my_file = os.path.join(get_srcdir(), 'scriptin.py') inp.open(my_file, opts={'use_raw': False}) while True: try: inp.readline() except EOFError: break pass try: inp.readline() except EOFError: print('EOF handled correctly') pass
import os, sys from import_relative import import_relative, get_srcdir sys.path.insert(0, os.path.join(get_srcdir(), '../..')) Mdebugger = import_relative('debugger', '...trepan') Mstringarray = import_relative('inout.stringarray', '...trepan') def strarray_setup(debugger_cmds): ''' Common setup to create a debugger with stringio attached ''' stringin = Mstringarray.StringArrayInput(debugger_cmds) stringout = Mstringarray.StringArrayOutput() d_opts = {'input' : stringin, 'output': stringout} d = Mdebugger.Debugger(d_opts) d.settings['basename'] = True d.settings['different'] = False d.settings['autoeval'] = False d.settings['highlight'] = 'plain' return d import re trepan_prompt = re.compile(r'^.. \d+.*\n\(Trepan(:.+)?\) ') trepan_loc = re.compile(r'^\(.+:\d+\): ') def filter_line_cmd(a): '''Return output with source lines prompt and command removed''' # Remove extra leading spaces. # For example:
Mclient = import_relative('client', top_name=package) Mclifns = import_relative('clifns', top_name=package) Mdebugger = import_relative('debugger', top_name=package) Mexcept = import_relative('exception', top_name=package) Moutput = import_relative('output', '.io', package) Moptions = import_relative('options', '.', package) Mserver = import_relative('server', '.interfaces', package) Mfile = import_relative('file', '.lib', package) Mmisc = import_relative('misc', '.', package) # The name of the debugger we are currently going by. __title__ = package # VERSION.py sets variable VERSION. VERSION='??' exec(compile(open(os.path.join(get_srcdir(), 'VERSION.py')).read(), os.path.join(get_srcdir(), 'VERSION.py'), 'exec')) __version__ = VERSION def main(dbg=None, sys_argv=list(sys.argv)): """Routine which gets run if we were invoked directly""" global __title__ # Save the original just for use in the restart that works via exec. orig_sys_argv = list(sys_argv) opts, dbg_opts, sys_argv = Moptions.process_options(__title__, __version__, sys_argv) if opts.server: connection_opts={'IO': 'TCP', 'PORT': opts.port} intf = Mserver.ServerInterface(connection_opts=connection_opts) dbg_opts['interface'] = intf
#!/usr/bin/env python 'Unit test for trepan.interfaces.user' import os, sys, unittest from import_relative import import_relative, get_srcdir srcdir = get_srcdir() sys.path.insert(0, os.path.join(srcdir, '..', '..')) Muser = import_relative('interfaces.user', '...trepan') from cmdhelper import dbg_setup class TestInterfaceUser(unittest.TestCase): """Tests UserInterface class""" def readline(self, answer): return answer def test_confirm(self): """Test interface.user.UserInterface.confirm()""" d, cp = dbg_setup() u = Muser.UserInterface() for s in ['y', 'Y', 'Yes', ' YES ']: u.input.readline = lambda prompt=None: self.readline(s) self.assertTrue(u.confirm('Testing', True)) pass for s in ['n', 'N', 'No', ' NO ']: u.input.readline = lambda prompt=None: self.readline(s) self.assertFalse(u.confirm('Testing', True)) pass
Mclifns = import_relative('clifns', '.', package) Mdebugger = import_relative('debugger', '.', package) Mexcept = import_relative('exception', '..trepan') Moptions = import_relative('options', '.', package) Mserver = import_relative('server', '.interfaces', package) Mfile = import_relative('file', '.lib', package) Mmisc = import_relative('misc', '.', package) # The name of the debugger we are currently going by. __title__ = package + '2' # VERSION.py sets variable VERSION. VERSION = '??' exec( compile( open(os.path.join(get_srcdir(), 'VERSION.py')).read(), os.path.join(get_srcdir(), 'VERSION.py'), 'exec')) __version__ = VERSION def main(dbg=None, sys_argv=list(sys.argv)): """Routine which gets run if we were invoked directly""" global __title__ # Save the original just for use in the restart that works via exec. orig_sys_argv = list(sys_argv) opts, dbg_opts, sys_argv = Moptions.process_options( __title__, __version__, sys_argv) if opts.server: connection_opts = {'IO': 'TCP', 'PORT': opts.port}
compatible with other input routines and are ignored. EOFError will be raised on EOF. """ line = self.input.readline() if not line: raise EOFError return line.rstrip("\n") # Demo if __name__ == '__main__': inp = ScriptInput('scriptin.py') line = inp.readline() print(line) inp.close() # Note opts below are aren't acted upon. They are there for # compatibility import os my_file = os.path.join(get_srcdir(), 'scriptin.py') inp.open(my_file, opts={'use_raw': False}) while True: try: inp.readline() except EOFError: break pass try: inp.readline() except EOFError: print('EOF handled correctly') pass