Пример #1
0
def exception_error():
    error_message = ""
    for i in range(len(inspect.trace())):
        error_line = u"""
File:      %s - [%s]
Function:  %s
Statement: %s
-------------------------------------------------------------------------------------------""" % (
            inspect.trace()[i][1],
            inspect.trace()[i][2],
            inspect.trace()[i][3],
            inspect.trace()[i][4],
        )

        error_message = "%s%s" % (error_message, error_line)

    error_message = u"""Error!
%s
%s
======================================== Error Message ====================================%s
======================================== Error Message ======================================================""" % (
        sys.exc_info()[0],
        sys.exc_info()[1],
        error_message,
    )

    return error_message
Пример #2
0
def tback(system, e, info=None, logger=None):
        """ Log a decently informative traceback. """

        if logger == None:
            logger = logging
        exc_type, exc_value, exc_traceback = sys.exc_info()
	
        try:
            frames = inspect.trace()
            toptrace = inspect.trace()[-1]
        except:
            one_liner = "%s: %s: %s" % (e, exc_type, exc_value)
            logger.critical("======== %s exception botch: %s" % (system, one_liner))
            return
        
        tr_list = []
        tr_list.append("\n\n====== trace:\n")
        tr_list.append(pprint.pformat(toptrace))
        
        i = 0
        frames.reverse()
        for f in frames:
            tr_list.append("\n\n====== frame %d locals:\n" % (i))
            tr_list.append(pprint.pformat(f[0].f_locals, depth=4))
            i += 1

        ex_list = traceback.format_exception(exc_type, exc_value, exc_traceback)
        logger.warn("\n======== %s exception: %s\n" % (system, ''.join(ex_list)))
        logger.warn(''.join(tr_list))
Пример #3
0
	def debugex(f, *args, **kw):
		try:
			return f(*args, **kw)
		except Exception, e:
			print e
			print inspect.trace()
			raise e
Пример #4
0
        def handler(signum, frame):
            import inspect
            print inspect.getframeinfo(frame)
            print inspect.trace()
            while 1:
                s = raw_input(\
"""
 
 Enter sense switch.

    sol:  Print current best solution.
    cont: Continue calculation.
    call: Executes sigint_callback [%s].
    exit: Exits with current best solution.

 >>> """ % sigint_callback)
                if s.lower() == 'sol': 
                    print self.bestSolution
                elif s.lower() == 'cont': 
                    return
                elif s.lower() == 'call': 
                    # sigint call_back
                    if sigint_callback is not None:
                        sigint_callback(self.bestSolution)
                elif s.lower() == 'exit': 
                    self._EARLYEXIT = True
                    return
                else:
                    print "unknown option : %s" % s
            return
Пример #5
0
 def log_exception(*args: Any) -> None:
     module_name = inspect.getmodule(inspect.trace()[1][0]).__name__
     # Do not print the wrapper in the traceback
     frames = len(inspect.trace()) - 1
     exc_msg = traceback.format_exc(-frames)
     friendly_msg = format_err(*args)
     logging.getLogger(module_name).error('%s\n%s', friendly_msg, exc_msg)
Пример #6
0
    def handle_500(self, request, exception):
        logger.info("Lifeboat handling exception.")
        exctype, exc_val, tb, = sys.exc_info()
        jsonable_local_vars = {}
        local_vars = inspect.trace()[-1][0].f_locals  # For now, just use the top of the trace stack
        for k, v in local_vars.items():
            if k == "self":
                jsonable_local_vars[k] = "self"
                continue
            try:
                jsonable_local_vars[k] = str(v)
            except ValueError:
                jsonable_local_vars[k] = "Un-serializable value of " + str(type(v))


        # Modules are identified by (file_name, code_obj_name). If it exists use that, otherwise create a module obj.
        error_file_name = inspect.trace()[-1][0].f_code.co_filename
        error_code_obj_name = inspect.trace()[-1][0].f_code.co_name

        lb_module_filter = Lb_Module.objects.filter(file_name=error_file_name,
                                                    code_obj_name=error_code_obj_name)
        if lb_module_filter:
            lb_module = lb_module_filter.get()
        else:
            lb_module = Lb_Module.objects.create(file_name=error_file_name,
                                                 code_obj_name=error_code_obj_name)

        Lb_Error.objects.create(module=lb_module, exception=str(exctype),
                                traceback=traceback.format_exc(tb),
                                vars=json.dumps(jsonable_local_vars),
                                traceback_msg=str(exc_val), created_by="Lifeboat")
Пример #7
0
def class_from_module(path, defaultpaths=None):
    """
    Return a class from a module, given the module's path. This is
    primarily used to convert db_typeclass_path:s to classes.

    Args:
        path (str): Full Python dot-path to module.
        defaultpaths (iterable, optional): If a direc import from `path` fails,
            try subsequent imports by prepending those paths to `path`.

    Returns:
        class (Class): An uninstatiated class recovered from path.

    Raises:
        ImportError: If all loading failed.

    """
    cls = None
    if defaultpaths:
        paths = [path] + ["%s.%s" % (dpath, path) for dpath in make_iter(defaultpaths)] if defaultpaths else []
    else:
        paths = [path]

    for testpath in paths:
        if "." in path:
            testpath, clsname = testpath.rsplit(".", 1)
        else:
            raise ImportError("the path '%s' is not on the form modulepath.Classname." % path)
        try:
            mod = import_module(testpath, package="evennia")
        except ImportError:
            if len(trace()) > 2:
                # this means the error happened within the called module and
                # we must not hide it.
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
            else:
                # otherwise, try the next suggested path
                continue
        try:
            cls = getattr(mod, clsname)
            break
        except AttributeError:
            if len(trace()) > 2:
                # AttributeError within the module, don't hide it
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
    if not cls:
        err = "Could not load typeclass '%s'" % path
        if defaultpaths:
            err += "\nPaths searched:\n    %s" % "\n    ".join(paths)
        else:
            err += "."
        raise ImportError(err)
    return cls
Пример #8
0
def main(argv=None):
    """This is our main function"""
    # Do argv default this way, as doing it in the functional
    # declaration sets it at compile time.
    if argv is None:
        argv = sys.argv

    print DIV
    print "Part One: stack() and trace() demonstrations\n"
    print "Printing stack() from inside main():"
    print_records(inspect.stack())
    print "Printing trace() from inside main(): (will be empty)"
    print_records(inspect.trace())

    try:
        eval("raise_exception()")
    except Exception as ex:
        print "\nTraceback from inside exception handler:"
        print_traceback(sys.exc_info()[2])
        print DIV
        print "Printing stack() from inside exception handler:"
        print_records(inspect.stack())
        print "\nPrinting trace() from inside exception handler:"
        print "    (Will be the almost the same as traceback)"
        print_records(inspect.trace())

    print DIV
    print "Part two: inspect a function.\n"
    print_function(demo_function)

    print DIV
    print "Part three: modifying an exception"
    print "    (Really nothing to do with inspect directly)\n"
    try:
        exception_changer(raise_exception)
    except Exception as ex:
        traceback.print_exc()


    print "\nNow using a decorator:"
    try:
        exception_raiser_two()
    except Exception as ex:
        traceback.print_exc()

    print DIV
    print "Demonstrate returning the docstring of a caller.\n"
    print "My docstring is: ", get_docstring()
    
    print "\n\nThat's all folks.\n"
Пример #9
0
    def initialize(self, _context, includeNativeFrames=True):
        frames = []
        context = _context
        while True:
            if not context:
                break
            frames.append(compose_stack_frame(context))
            context = helpers.get_caller_context(context)
        frames.pop()
        frames.reverse()

        if includeNativeFrames:
            native_frames = []
            for frame in inspect.trace()[1:]:
                location = yaql_expression.YaqlExpressionFilePosition(
                    os.path.abspath(frame[1]), frame[2],
                    -1, -1, -1, -1, -1)
                method = frame[3]
                native_frames.append({
                    'instruction': frame[4][0].strip(),
                    'location': location,
                    'method': method,
                    'class': None
                })
            frames.extend(native_frames)

        self.set_property('frames', frames)
Пример #10
0
	def loadModuleFromSourceString_functionName_profile_(self, source, func, profile):
		try:
			kdemodule = imp.new_module("kdemodule")
			exec source in kdemodule.__dict__
			realfunc = getattr( kdemodule, func, None)
			if realfunc is not None:
				profiler = None
				if profile is True:
					profiler = cProfile.Profile()
					profiler.enable()
				
				realfunc()

				if profiler is not None:
					reportProfileStats( profiler)


		except Exception as e:
			tb = inspect.trace()[-1]
			fileName = tb[1]
			lineNumber = tb[2]
			functionName = tb[ 3]
			py80.context.reportExceptionType_description_filePath_function_lineNumber_( type(e).__name__, str(e), fileName, functionName, lineNumber)
		finally:
			return NO

		return YES
Пример #11
0
 def process_exception(self, request, exception):
     exc_info = sys.exc_info()
     print "######################## Exception #############################"
     print '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info())))
     print "----------------------------------------------------------------"
     pprint(inspect.trace()[-1][0].f_locals)
     print "################################################################"
Пример #12
0
 def wrapper(*args, **kwargs):
     instance.func = func
     instance.funcname = funcname
     instance.stack = inspect.stack()  # traceback.extract_stack()
     instance.inputs = inspect.getcallargs(func, *args, **kwargs)
     instance.trace = inspect.trace()
     timeit = time.time()
     instance.time = time.localtime(timeit)
     e = None
     try:
         result = func(*args, **kwargs)
         if broadcast:
             instance.broadcast()
     except:
         result = None
         # http://stackoverflow.com/a/1278740/5288758
         exc_type, exc_obj, exc_tb = e = sys.exc_info()
         fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
         print(exc_type, fname, exc_tb.tb_lineno)
     instance.exectime = time.time() - timeit
     instance.outputs = result
     instance.error = e
     if report:
         instance.report()
     instance.throwError()
     instance.renew()
     return result
Пример #13
0
def eval_statement(stmt, ctx):
    try:
        result = stmt.eval(ctx)
        return (result, False)
    except ProgramError as e:
        if e.stack_trace:
            for line in e.stack_trace:
                print(line, file=sys.stderr)
        print(e.msg, file=sys.stderr)
        return (None, True)
    except Exception as e:
        # All other exceptions shouldn't happen in theory, but they still do, so reconstruct
        # as much of the stack from Mutagen-space as we can
        traceback = inspect.trace()
        print('---------- INTERNAL COMPILER ERROR! ----------')
        print('Mutagen traceback:')
        last_index = 0
        for i, (frame, *_) in enumerate(traceback):
            # XXX this is pretty hacky--detect function calls by inspecting locals on the stack
            self = frame.f_locals.get('self', None)
            child_ctx = frame.f_locals.get('ctx', None)
            if isinstance(self, Call) and child_ctx:
                print('File "%s", line %s, in %s' % (self.info.filename, self.info.lineno, child_ctx.name))
                last_index = i
        # Below the part of the stack corresponding to the last Mutagen function call, print out
        # all the Python stack frames
        print('----------')
        print('Python traceback (below Mutagen traceback):')
        for frame, filename, lineno, function, code_context, index in traceback[last_index:]:
                print('  File "%s", line %s, in %s' % (filename, lineno, function))
                print('    ', code_context[index].strip())
        print('%s: %s' % (type(e).__name__, e))
        return (None, True)
Пример #14
0
   def serve(self, callback):
      try:
         while not self._killed:
            try:
               data = self.ws.recv()
               # Answer the heartbeat
               is_heartbeat = re.match('~m~[0-9]+~m~(~h~[0-9]+)', data)
               if is_heartbeat:
                  self._heartbeat(is_heartbeat.group(1))
                  log(self, 'HB: %s' % is_heartbeat.group(1))
                  self.last_heartbeat = datetime.now()
                  continue

               self.last_activity = datetime.now()

               data = json.loads(data[data.index('{'):])
               for i in range(0, len(self.cmds)):
                  id, clb = self.cmds[i]
                  if id == data.get('msgid', None):
                     if clb:
                        clb(self, data)
                     del self.cmds[i]
                     break

               if callback:
                  callback(self, data)
            except Exception, e:
               if str(e) == 'Bad file descriptor':
                  self.kill()

               time.sleep(1)
               f, file, line, fn_name, lines, n = inspect.trace()[-1]
               log(self, e, {'log':True, 'file':file, 'line':line, 'command':'BOT SERVE'})
         self.ws.close()
Пример #15
0
   def update_room(self, roomid, listeners, upvotes, downvotes):
      try:
         cursor = self.cnx.cursor(mdb.cursors.DictCursor)
         cursor.execute('SET NAMES utf8;')
         cursor.execute('SET CHARACTER SET utf8;')
         cursor.execute('SET character_set_connection=utf8;')

         cursor.execute("SELECT * FROM rooms WHERE roomid = '%s' LIMIT 1" % \
                         mdb.escape_string(roomid.encode('utf-8')))
         room_exists = int(cursor.rowcount)
         if room_exists > 0:
            db_room_id = cursor.fetchone()['id']
            cursor.execute("UPDATE rooms SET \
                                             listeners=%s, \
                                             downvotes=%s, \
                                             upvotes=%s \
                            WHERE id='%s'" %
                            (
                              "%s" % ("'%s'" % (int(listeners)) if listeners != None else "NULL"),
                              "%s" % ("'%s'" % (int(downvotes)) if downvotes != None else "0"),
                              "%s" % ("'%s'" % (int(upvotes)) if upvotes != None else "0"),
                              int(db_room_id),
                            ))
         else:
            cursor.close()
            raise Exception('Room id does not exists. (update_room)')
         cursor.close()
         return db_room_id
      except Exception, e:
         f, file, line, fn_name, lines, n = inspect.trace()[-1]
         log(sender, e, {'log':True, 'file':file, 'line':line, 'command':'DB UPDATE_ROOM'})
Пример #16
0
def RunWithExpandedTrace(closure):
  try:
    return closure()
  except (SystemExit, KeyboardInterrupt):
    raise
  except:
    import inspect
    import sys
    import traceback

    # Save trace and exception now. These calls look at the most recently
    # raised exception. The code that makes the report might trigger other
    # exceptions.
    original_trace = inspect.trace(3)[1:]
    formatted_exception = traceback.format_exception_only(*(sys.exc_info()[:2]))

    dashes = '%s\n' % ('-' * 60)
    dump = []
    dump.append(dashes)
    dump.extend(MakeExpandedTrace(original_trace))


    dump.append(''.join(formatted_exception))

    print ''.join(dump)
    print
    print dashes
    sys.exit(127)
Пример #17
0
    def debug(self, err):
        import IPython

        ec, ev, tb = err
        stdout = sys.stdout
        sys.stdout = sys.__stdout__
        sys.stderr.write("\n- TRACEBACK --------------------------------------------------------------------\n")
        traceback.print_exception(*err)
        sys.stderr.write("--------------------------------------------------------------------------------\n")
        try:
            # The IPython API changed a bit so we should
            # support the new version
            if hasattr(IPython, "InteractiveShell"):
                shell = IPython.InteractiveShell()
                ip = IPython.core.ipapi.get()
                p = IPython.core.debugger.Pdb(ip.colors)
            # and keep support for older versions
            else:
                shell = IPython.Shell.IPShell(argv=[""])
                ip = IPython.ipapi.get()
                p = IPython.Debugger.Pdb(ip.options.colors)

            p.reset()
            # inspect.trace() returns a list of frame information from this
            # frame to the one that raised the exception being treated
            frame, filename, line, func_name, ctx, idx = inspect.trace()[-1]
            p.interaction(frame, tb)
        finally:
            sys.stdout = stdout
Пример #18
0
def runTests(out=sys.stdout, verbosity=1):
   """Run the system and integration tests.
   
   XXX This could probably yanked out and made into a generic testing harness.

   Parameters:
      out - optionally a file like object where test output will be written. If 
            out isn't specified stdout will be used.

   Results:
      0 on success of all tests, 1 otherwise.

   Side effects:
      None

   """

   numTestsRun = 0
   numTestsFailed = 0

   for test in tests:
      if verbosity > 1:
         print test.__name__
      # Unified try:except:finally is a 2.5 feature
      try:
         try:
            test()
         except AssertionError, e:
            numTestsFailed += 1
            trace = inspect.trace()
            try:
               failedTestFrame = trace[-2]
               parentFrame = trace[-3]
            except IndexError:
               failedTestFrame = trace[-1]
               parentFrame = trace[-2]

            print "============================================================"
            print "TEST FAILED:"
            print "%s\n'%s' at %s:%d.\n'%s' at %s:%d.\n" % \
                  (test.__name__,
                  parentFrame[3], parentFrame[1], parentFrame[2],
                  failedTestFrame[3], failedTestFrame[1], failedTestFrame[2])
            print str(e)

      finally:
         numTestsRun += 1

   # Icky icky hacky! Some tests don't clean up after themselves.
   path.exists(TMP_OUT) and os.remove(TMP_OUT)

   print
   print "---------------------------------------------------------------------"
   print "Ran %d test%s" % (numTestsRun, numTestsRun != 1 and "s" or "")
   if numTestsFailed > 0:
      print "FAILED %d" % numTestsFailed
   else:
      print "OK"

   return numTestsFailed and 1
Пример #19
0
 def runEnum(self):
   self.getTupleSet()
   configTog = self.initConfig(True, [-1, -1])
   self.genNotList()
   configTog[0][0] = self.pairset[0]
   config1 = self.initConfig(True)
   config2 = self.initConfig(True)
   try:
     config2 = self.iterateConfig(list(configTog)) 
     if config2:
       print "SECURE CONFIG in %s count" % self.itercount
       self.printConfig(config2)
     configTog = self.initConfig(True, [-1, -1])
     configTog[0][0] = self.pairset[0]
     config1 = self.iterateConfigwork(list(configTog)) 
     if config1:
       print "SECURE CONFIG WORK in %s count" % self.itercount
       self.printConfig(config1)
   except Exception as e:
     print "ERROR:" + str(e)
     for frame in traceback.extract_tb(sys.exc_info()[2]):
       fname,lineno,fn,text = frame
       print "Error in %s on line %d" % (fname, lineno)
       print "function:", fn, " text: ", text
     pprint(inspect.trace()[-1][0].f_locals)
Пример #20
0
	def toString(self, structure):
		filename='<input>'
		symbol='single'
		localVars = {"self" : structure, "RETURN" : ""}
		inter = InteractiveInterpreter(localVars)
		
		#if isinstance(source, types.UnicodeType):
		#    import IOBinding
		#    try:
		#        source = source.encode(IOBinding.encoding)
		#    except UnicodeError:
		console = InteractiveConsole(localVars, filename)

		try:
			code_object = compile(self.data.encode('ascii','ignore'), '<string>', 'exec')
			exec code_object in localVars
		except Exception as e :
			print ("-  ERR --Kind:%s---------------------------------------" % (self.template.kind) )
			InteractiveInterpreter.showsyntaxerror(console, filename)
			frames = inspect.trace()
			lineNumber = frames[1][2]
			print ("At line %s" % lineNumber)
			print ("- /ERR -----------------------------------------")

			print ("-  CODE -----------------------------------------")
			lines = self.data.split('\n')
			for i in range(0,lineNumber):
				print lines[i]
			print "^"*20
			
			print ("- /CODE -----------------------------------------")
			print ("")
					
		return localVars["RETURN"]
Пример #21
0
def install_failed_import_handler():
    """
        Custom __import__ function that records failed imports
        Useful if say you're using werkzeug auto reloader
        This way, failed imports are still checked for changes
    """
    original_import = __builtin__.__import__

    def new_import(name, *args, **kwargs):
        # Naively cope with the situation where this is called as a method
        if type(name) not in (str, unicode) and len(args) > 0:
            args = list(args)
            name = args.pop(0)

        failed = None
        try:
            return original_import(name, *args, **kwargs)

        except SyntaxError, s:
            # Record failed import and propogate error
            failed = (name, s.filename)
            raise

        except Exception, i:
            if not isinstance(i, ImportError):
                # ImportError is probably a legitimate fail
                failed = (name, inspect.trace()[-1][1])
            raise
Пример #22
0
    def __init__(self, this, context, include_native_frames=True):
        frames = []
        caller_context = context
        while True:
            if not caller_context:
                break
            frame = compose_stack_frame(caller_context)
            frames.append(frame)
            caller_context = helpers.get_caller_context(caller_context)
        frames.reverse()
        frames.pop()

        if include_native_frames:
            native_frames = []
            for frame in inspect.trace()[1:]:
                location = dsl_types.ExpressionFilePosition(
                    os.path.abspath(frame[1]), frame[2],
                    -1, frame[2], -1)
                method = frame[3]
                native_frames.append({
                    'instruction': frame[4][0].strip(),
                    'location': location,
                    'methodName': method,
                    'typeName': None
                })
            frames.extend(native_frames)

        this.properties.frames = frames
Пример #23
0
def print_debug():
  import traceback
  import pdb
  import inspect
  import platform
  import sys
  import os
  import copy

  def print_err(x):
    print >> sys.stderr, x;

  print_err("An error has occurred. Please see below for debugging information.");
  print_err("");
  print_err("Python executable: %s" % sys.executable);
  print_err("Platform: %s" % str(platform.uname()));
  print_err("Linux: %s" % str(platform.linux_distribution()));
  print_err("Windows: %s" % str(platform.win32_ver()));
  print_err("Mac: %s" % str(platform.mac_ver()));
  print_err("Library paths: ");
  for path in sys.path:
    print_err(".. %s" % path);
  print_err("Executing in: %s" % str(os.getcwd()));
  print_err("Called by: %s" % str(sys.argv[0]));
  print_err("");
  traceback.print_exc(file=sys.stderr);
  print_err("");
  for t in inspect.trace():
    print_err("Frame: %s" % str(" ".join(map(str,t[1:]))));
    for local,value in dict(t[0].f_locals).iteritems():
      value = str(value).replace(os.linesep,"");
      print_err("  %s : %s ..." % (local,value[0:120]));
Пример #24
0
def trace_errors(e):
    print '{0} {1}'.format(type(e), str(e))
    for i in inspect.trace()[1:]:
        frameInfo = inspect.getframeinfo(i[0])
        #print frameInfo
        print '    {0} : {1} : {2}'.format(frameInfo.filename, frameInfo.function, frameInfo.lineno)
        print '               <{0}>'.format(', '.join([ c.strip() for c in frameInfo.code_context ]))
Пример #25
0
    def run_suite(self, case):
        # Initialize the test class
        suite = case()

        # check test environment setup
        environ = TestEnviron(suite)

        methods = get_methods(suite, self.method_name)
        if not methods: return

        # Name the class
        class_name = suite.__class__.__name__
        self.writer.out_case(class_name)

        # Are we skipping?
        if safe_skip_call(environ.set_skip_if):
            self.writer.skipping()
            return

        let_map = get_let_attrs(suite)

        # Set before all if any
        self.safe_environ_call(environ.set_before_all)

        for test in methods:
            test_start_time = StopWatch(raw=True)
            suite = set_let_attrs(suite, let_map)
            self.total_cases += 1

            # Set before each if any
            self.safe_environ_call(environ.set_before_each)

            try:
                getattr(suite, test)()
                test_elapsed_time = Decimal(str(test_start_time.elapsed()))
                self.writer.green_spec(test)

            except BaseException, e:
                test_elapsed_time = Decimal(str(test_start_time.elapsed()))
                trace = inspect.trace()[-1]
                self.total_failures += 1
                self.writer.red_spec(test)
                self.failures.append(
                    dict(
                        failure  = sys.exc_info(),
                        trace    = trace,
                        exc_name = e.__class__.__name__
                       )
                    )
                if self.config.get('first_fail'):
                    raise KoniraFirstFail

            # Save profiling info
            self.profiles.append((test_elapsed_time,
                                  test,
                                  class_name))

            # Set after each if any
            self.safe_environ_call(environ.set_after_each)
Пример #26
0
def class_from_module(path, defaultpaths=None):
    """
    Return a class from a module, given the module's path. This is
    primarily used to convert db_typeclass_path:s to classes.

    if a list of `defaultpaths` is given, try subsequent runs by
    prepending those paths to the given `path`.
    """
    cls = None
    if defaultpaths:
        paths = [path] + ["%s.%s" % (dpath, path) for dpath in make_iter(defaultpaths)] if defaultpaths else []
    else:
        paths = [path]

    for testpath in paths:
        if "." in path:
            testpath, clsname = testpath.rsplit(".", 1)
        else:
            raise ImportError("the path '%s' is not on the form modulepath.Classname." % path)
        try:
            mod = import_module(testpath, package="evennia")
        except ImportError:
            if len(trace()) > 2:
                # this means the error happened within the called module and
                # we must not hide it.
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
            else:
                # otherwise, try the next suggested path
                continue
        try:
            cls = getattr(mod, clsname)
            break
        except AttributeError:
            if len(trace()) > 2:
                # AttributeError within the module, don't hide it
                exc = sys.exc_info()
                raise exc[1], None, exc[2]
    if not cls:
        err = "Could not load typeclass '%s'" % path
        if defaultpaths:
            err += "\nPaths searched:\n    %s" % "\n    ".join(paths)
        else:
            err += "."
        raise ImportError(err)
    return cls
Пример #27
0
def load_plugin(path):
    try:
        plugin = import_module(path)
    except ImportError:
        if len(trace()) > 2:
            exc = sys.exc_info()
            raise exc[1], None, exc[2]
    return plugin
Пример #28
0
def stacktrace():
    s = ""
    for frame in inspect.trace():
        s = "".join([s, " ", frame[1], ": line ", str(frame[2]), " in ", frame[3]])
        if frame[4]:
            s = ": ".join([s, frame[4][0].strip()])
        s = "".join([s, ";"])
    return s
Пример #29
0
 def test_template_exceptions(self):
     for n in range(len(except_args)):
         try:
             self.client.get(reverse('template_exception', args=(n,)))
         except Exception:
             raising_loc = inspect.trace()[-1][-2][0].strip()
             self.assertFalse(raising_loc.find('raise BrokenException') == -1,
                 "Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" %
                     raising_loc)
Пример #30
0
Файл: api.py Проект: msports/mw
	def notify_error(self,e,silent=True):
		frm = inspect.trace()[-1]
		mod = inspect.getmodule(frm[0])
		modname = mod.__name__ if mod else frm[1]
		errtype= e.__class__.__name__
		if not silent:
			self.dialog.notification("ERROR","%s : %s"%(modname, errtype))
		if not errtype=="killbill":
			print traceback.format_exc()
Пример #31
0
def test_format_frames():
    def func_a():
        a = "A"  # noqa
        func_b()

    def func_b():
        one = 1
        zero = 0
        one / zero

    try:
        e = "E"  # noqa
        func_a()
    except Exception:
        frames = format_frames(inspect.trace())

    assert frames[0]["function"] == "func_b"
    assert frames[0]["variables"] == {"one": "1", "zero": "0"}
    assert frames[1]["function"] == "func_a"
    assert frames[1]["variables"]["a"] == '"A"'
    assert frames[2]["function"] == "test_format_frames"
    assert frames[2]["variables"]["e"] == '"E"'
Пример #32
0
 def printException(self, p_line_no, p_message):
     trace_len = len(trace())
     err_msg = "\nSKYZE EXCEPTION: " + self.__class__.__name__
     err_msg += "::" + trace()[0].function
     err_msg += "::" + str(trace()[0].lineno)
     err_msg += "\n Called: " + trace()[trace_len - 1].function
     err_msg += "   on line: " + str(trace()[trace_len - 1].lineno)
     err_msg += "\n code Context: " + str(
         trace()[trace_len - 1].code_context)
     err_msg += "\n ...." + p_message + "  ... " + str(sys.exc_info()[0])
     err_msg += "\n LOCALS ...." + str(sys.exc_info()[2].tb_frame.f_locals)
     #         pprint(str(sys.exc_info()[2].tb_frame.f_locals))
     #         print(json.dumps(sys.exc_info()[2].tb_frame.f_locals, indent=4))
     print(err_msg)
     print()
     print()
     print()
Пример #33
0
    def _on_pubmsg(self, connection, event):
        sendernick, _ = event.source().split('!', 1)
        message = event.arguments()[0].strip()

        if not message.startswith("!"):
            return

        argv = message[1:].split()

        if not argv:
            return

        command = argv[0]

        handler = self.find_command(command)
        if callable(handler):
            # Set up attributes for commands
            self.sendernick = sendernick
            self.raw_message = event.arguments()[0]
            self.target = event.target()

            if random.randint(1, 100) == 42:
                uprise_msg = random.choice(self.BOT_UPRISE_MSGS)
                self.connection.privmsg(self.CHANNEL, uprise_msg)

            try:
                reply = handler(self, *argv[1:])
            except TypeError:
                if len(inspect.trace()) == 1:
                    # Exception was caused by wrong number of args.
                    reply = "Looks like you got the arguments wrong..."
                else:
                    # Command crashed!
                    raise

            if reply is not None:
                reply = "%s: %s" % (sendernick, reply)
                self.connection.privmsg(self.CHANNEL, reply)
Пример #34
0
def process_error(log_info: str, name: str, exc_info: tuple, citizen=None, commit_id: str = None,
                  interactive: Optional[bool] = None):
    """
    Process error logging and email sending to developer
    :param interactive: Should print interactively
    :type interactive: bool
    :param log_info: String to be written in output
    :type log_info: str
    :param name: String Instance name
    :type name: str
    :param exc_info: tuple output from sys.exc_info()
    :type exc_info: tuple
    :param citizen: Citizen instance
    :type citizen: Citizen
    :param commit_id: Code's version by commit id
    :type commit_id: str
    """
    type_, value_, traceback_ = exc_info
    content = [log_info]
    if commit_id:
        content += ["Commit id: %s" % commit_id]
    content += [str(value_), str(type_), ''.join(traceback.format_tb(traceback_))]

    if interactive:
        write_interactive_log(log_info)
    elif interactive is not None:
        write_silent_log(log_info)
    trace = inspect.trace()
    if trace:
        trace = trace[-1][0].f_locals
        if trace.get('__name__') == '__main__':
            trace = {'commit_id': trace.get('COMMIT_ID'),
                     'interactive': trace.get('INTERACTIVE'),
                     'version': trace.get('__version__'),
                     'config': trace.get('CONFIG')}
    else:
        trace = dict()
    send_email(name, content, citizen, local_vars=trace)
Пример #35
0
    def __call__(self, *args, **kwargs):
        self.status.change(RunnableStatus.RUNNING)
        self.logger.test_info('Starting {} for {}'.format(
            self.__class__.__name__, self.target))
        if self._http_handler is not None:
            self._start_http_handler()

        while self.active and self.target.active:
            if self.status.tag == RunnableStatus.RUNNING:
                try:
                    uid = self._queue.pop(0)
                    operation, args, kwargs = self._operations[uid]
                except IndexError:
                    time.sleep(self.cfg.active_loop_sleep)
                else:
                    try:
                        try:
                            owner = '{}.{}, '.format(
                                self, operation.im_class.__name__)
                        except AttributeError:
                            owner = ''
                        self.logger.debug('Performing operation:{}{}'.format(
                            owner, operation.__name__))
                        start_time = time.time()
                        result = operation(*args, **kwargs)
                        self._results[uid] = result
                        self.logger.debug(
                            'Finished operation {}{} - {}s'.format(
                                owner, operation.__name__,
                                round(time.time() - start_time, 5)))
                    except Exception as exc:
                        self.logger.test_info(
                            format_trace(inspect.trace(), exc))
                        self._results[uid] = exc
                    finally:
                        del self._operations[uid]

        self.status.change(RunnableStatus.FINISHED)
Пример #36
0
 def lambda_wrapper(*args, **kwargs):
     if _is_context_already_wrapped(*args):
         return func(*args, **kwargs)
     _add_wrap_flag_to_context(*args)
     executed = False
     ret_val = None
     local_print = print
     local_logging_format = logging.Formatter.format
     try:
         if Configuration.enhanced_print:
             _enhance_output(args, local_print, local_logging_format)
         SpansContainer.create_span(*args, is_new_invocation=True)
         with lumigo_safe_execute("auto tag"):
             AutoTagEvent.auto_tag_event(args[0])
         SpansContainer.get_span().start(*args)
         try:
             executed = True
             ret_val = func(*args, **kwargs)
         except Exception as e:
             with lumigo_safe_execute("Customer's exception"):
                 SpansContainer.get_span().add_exception_event(
                     e, inspect.trace())
             raise
         finally:
             SpansContainer.get_span().end(ret_val, *args)
             if Configuration.enhanced_print:
                 builtins.print = local_print
                 logging.Formatter.format = local_logging_format
         return ret_val
     except Exception:
         # The case where our wrapping raised an exception
         if not executed:
             TimeoutMechanism.stop()
             get_logger().exception("exception in the wrapper",
                                    exc_info=True)
             return func(*args, **kwargs)
         else:
             raise
Пример #37
0
    def lambda_wrapper(*args, **kwargs):
        if str(os.environ.get(_KILL_SWITCH, "")).lower() == "true":
            return func(*args, **kwargs)

        if _is_context_already_wrapped(*args):
            return func(*args, **kwargs)
        _add_wrap_flag_to_context(*args)
        executed = False
        ret_val = None
        local_print = print
        local_logging_format = logging.Formatter.format
        try:
            if Configuration.enhanced_print:
                _enhance_output(args, local_print, local_logging_format)
            SpansContainer.create_span(*args, force=True)
            SpansContainer.get_span().start(*args)
            wrap_http_calls()
            try:
                executed = True
                ret_val = func(*args, **kwargs)
            except Exception as e:
                with lumigo_safe_execute("Customer's exception"):
                    SpansContainer.get_span().add_exception_event(e, inspect.trace())
                raise
            finally:
                SpansContainer.get_span().end(ret_val)
                if Configuration.enhanced_print:
                    builtins.print = local_print
                    logging.Formatter.format = local_logging_format
            return ret_val
        except Exception:
            # The case where our wrapping raised an exception
            if not executed:
                TimeoutMechanism.stop()
                get_logger().exception("exception in the wrapper", exc_info=True)
                return func(*args, **kwargs)
            else:
                raise
Пример #38
0
 def PrintExTs(self, e):
     exc_type, exc_obj, exc_tb = sys.exc_info()
     fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
     inf_ = str(fname) + ' (' + str(exc_tb.tb_lineno) + ')\n' + str(
         type(e).__name__) + ' (' + str(e) + ')\n'
     frm = inspect.trace()[-1]
     mod = inspect.getmodule(frm[0])
     (filename, line_number, function_name, lines,
      index) = inspect.getframeinfo(frm[0])
     filename = filename.replace(
         '/usr/lib/enigma2/python/Plugins/Extensions/', '>> ')
     inf_ = inf_ + 'FileName: ' + str(filename) + ' (' + str(
         line_number) + ')\n'
     inf_ = inf_ + 'Function: ' + str(function_name) + '\n'
     try:
         inf_ = inf_ + 'Line: ' + str(lines[index]).strip()
     except:
         pass
     self.addMarker({
         'title': tscolor('\c00????00') + '----> Erreur <----',
         'icon': '',
         'desc': inf_
     })
Пример #39
0
    def _loop(self):
        """
        Main executor work loop - runs in a seperate thread when the Pool is
        started.
        """

        if self._start_monitor_thread:
            self.logger.debug('Starting worker monitor thread.')
            self._worker_monitor = threading.Thread(
                target=self._workers_monitoring)
            self._worker_monitor.daemon = True
            self._worker_monitor.start()

        while self.active and not self._exit_loop:
            msg = self._conn.accept()
            if msg:
                try:
                    self.logger.debug('Received message from worker: %s.', msg)
                    self.handle_request(msg)
                except Exception as exc:
                    self.logger.error(format_trace(inspect.trace(), exc))

            time.sleep(self.cfg.active_loop_sleep)
Пример #40
0
    def __init__(self, value):
        """
        __init__
        """

        # // the stupid python does not follow its rules:
        # // Exception does not inherit from object, no way to call super
        # super(BossLiteError, self).__init__(value)
        Exception.__init__(self)
        self.value = self.__class__.__name__
        self.msg = str(value)
        self.data = {}
        # take more information if it applies
        try:
            stack = inspect.trace(1)[-1]
            self.data = {
                'FileName': stack[1],
                'LineNumber': stack[2],
                'MethodName': stack[3],
                'LineContent': stack[4]
            }
        except Exception:
            pass
Пример #41
0
    def run(self):
        # self.setTerminationEnabled(True)
        # plt.clf()
        try:
            reset_matplotlib()
            self.plot()
            # change size and title
            if self._parameter_ui.customized_figure_size():
                self._fig.set_size_inches(
                    self._parameter_ui.get_size_inches_width(),
                    self._parameter_ui.get_size_inches_height())
                self._fig.set_dpi(self._parameter_ui.get_dpi())
                self._fig.set_tight_layout(self._parameter_ui.get_layout())
            if self._parameter_ui.customized_figure_title():
                self._fig.suptitle(self._parameter_ui.get_title(),
                                   **self._parameter_ui.get_title_font_dict())

            self.plotting_completed.emit(self._fig)
        except Exception as e:
            frm = inspect.trace()[-1]
            mod = inspect.getmodule(frm[0])
            self.plotting_error.emit("{}: {}".format(mod.__name__, e.message),
                                     traceback.format_exc())
Пример #42
0
 def from_exc_and_traceback(cls, fault, traceback):
     trace = inspect.trace()
     # FIXME(mgoddard): In some code paths we reach this point without being
     # inside an exception handler. This results in inspect.trace()
     # returning an empty list. Ideally we should only end up here from an
     # exception handler.
     if trace:
         trace = trace[-1]
         # TODO(gibi): apply strutils.mask_password on exception_message and
         # consider emitting the exception_message only if the safe flag is
         # true in the exception like in the REST API
         module = inspect.getmodule(trace[0])
         function_name = trace[3]
     else:
         module = None
         function_name = 'unknown'
     module_name = module.__name__ if module else 'unknown'
     return cls(
         function_name=function_name,
         module_name=module_name,
         exception=fault.__class__.__name__,
         exception_message=six.text_type(fault),
         traceback=traceback)
Пример #43
0
 def description(self, descr):
     """A context manager which wraps a group of code and adds details to any exceptions thrown
     by the enclosed lines. Upon such an exception, the context manager will also take a screenshot
     of the current state of self.driver, writing a PNG to self.img_dir, labeled by the provided
     description and a timetstamp.
     """
     socket.setdefaulttimeout(10 * self.TIMEOUT)
     try:
         yield
     except Exception as exc:
         filename = self.img_dir + "/%s%s.png" % (descr,
                                                  datetime.datetime.now())
         msg = "\n" + '=' * 70 + "\n"
         msg += "FAILED TEST CASE: '%s'\n" % descr
         msg += "SCREENSHOT MAY BE FOUND IN: %s\n" % self.img_dir
         msg += "" + '-' * 70 + "\n"
         self.driver.save_screenshot(filename)
         trace = ['\n\nFull Traceback (most recent call last):']
         for item in inspect.trace():
             trace.append(' File "{1}", line {2}, in {3}'.format(*item))
             for line in item[4]:
                 trace.append(' ' + line.strip())
         raise type(exc)(str(exc) + '\n'.join(trace) + msg)
Пример #44
0
 def set_exception(self,
                   exception,
                   traceback_data,
                   handled=True,
                   from_logs=False):
     """
     Sets exception data on event.
     :param exception: Exception object
     :param traceback_data: traceback string
     :param handled: False if the exception was raised from the wrapped
         function
     :param from_logs: True if the exception was captured from logging
     """
     self.error_code = ErrorCode.EXCEPTION
     if hasattr(type(exception), '__name__'):
         self.exception['type'] = type(exception).__name__
     else:
         self.exception['type'] = 'Unknown'
     self.exception['message'] = str(exception)
     self.exception['traceback'] = self._copy_user_data_safely(
         traceback_data)
     self.exception['time'] = time.time()
     # Check if to collect the frames
     # Adding python frames (input data of functions in stack) in python 3.
     # Ignoring filenames with /epsagon since they are ours.
     if not SHOULD_REMOVE_EXCEPTION_FRAMES:
         if sys.version_info.major == 3:
             self.exception['frames'] = {
                 '/'.join(
                     [frame.filename, frame.function,
                      str(frame.lineno)]): frame.frame.f_locals
                 for frame in inspect.trace() if
                 '/epsagon' not in frame.filename and frame.frame.f_locals
             }
     self.exception.setdefault('additional_data', {})['handled'] = handled
     if from_logs:
         self.exception['additional_data']['from_logs'] = True
Пример #45
0
    async def _invoke_with_namespace(self, interaction: Interaction, namespace: Namespace) -> T:
        values = namespace.__dict__
        for name, param in self._params.items():
            try:
                value = values[name]
            except KeyError:
                if not param.required:
                    values[name] = param.default
                else:
                    raise CommandSignatureMismatch(self) from None
            else:
                values[name] = await param.transform(interaction, value)

        # These type ignores are because the type checker doesn't quite understand the narrowing here
        # Likewise, it thinks we're missing positional arguments when there aren't any.
        try:
            if self.binding is not None:
                return await self._callback(self.binding, interaction, **values)  # type: ignore
            return await self._callback(interaction, **values)  # type: ignore
        except TypeError as e:
            # In order to detect mismatch from the provided signature and the Discord data,
            # there are many ways it can go wrong yet all of them eventually lead to a TypeError
            # from the Python compiler showcasing that the signature is incorrect. This lovely
            # piece of code essentially checks the last frame of the caller and checks if the
            # locals contains our `self` reference.
            #
            # This is because there is a possibility that a TypeError is raised within the body
            # of the function, and in that case the locals wouldn't contain a reference to
            # the command object under the name `self`.
            frame = inspect.trace()[-1].frame
            if frame.f_locals.get('self') is self:
                raise CommandSignatureMismatch(self) from None
            raise CommandInvokeError(self, e) from e
        except AppCommandError:
            raise
        except Exception as e:
            raise CommandInvokeError(self, e) from e
Пример #46
0
    def _dispatch(self, method, params):
        # Need to pop
        try:
            params = list(params)
            if method == "getServerVersion":
                return VERSION
            else:
                try:
                    assertCompatable(params.pop(0))
                except IndexError:
                    raise TypeError("Minimum version unspecified.")

            #TODO: Get rid of username argument
            if method == "authenticate":
                return authenticate(self.username, params[1])
            else:
                try:
                    assertAuthenticated(params.pop(0))
                except IndexError:
                    raise TypeError("No authentication token provided.")

            obj = self
            for i in method.split('.'):
                obj = getattr(obj, i)
                if not getattr(obj, "_export", False):
                    raise AttributeError("Method not supported.")

            try:
                return obj(*params)
            except Exception as e:
                logging.getLogger(
                    getattr(inspect.getmodule(inspect.trace()[-1]), "__name__",
                            __name__)).debug("%s: %s" %
                                             (e.__class__.__name__, e.message))
                raise e
        except KeyboardInterrupt:
            raise ServerKilled()
Пример #47
0
 def _ecl_traceback(self, e):
     raising_frame = inspect.trace()[-1][0]
     lineno = self._ecl_get_lineno(frame=raising_frame)
     cl_file = self.getFilename()
     try:
         cl_code = open(cl_file).readlines()[lineno - 1].strip()
     except:
         cl_code = "<source code not available>"
     if hasattr(e, "_ecl_suppress_first_trace") and \
            e._ecl_suppress_first_trace:
         del e._ecl_suppress_first_trace
     else:
         self._ecl_trace("  ", repr(cl_code))
     self._ecl_trace("      line %d: %s" % (lineno, cl_file))
     parent = _ecl_parent_task()
     if parent:
         parent_lineno = self._ecl_get_lineno()
         parent_file = parent.getFilename()
         try:
             parent_code = open(parent_file).readlines()[parent_lineno -
                                                         1].strip()
             self._ecl_trace("      called as:", repr(parent_code))
         except:
             pass
Пример #48
0
        def func_wrapper(*args, **kwargs):

            try:
                response =  func(*args, **kwargs)
            except Exception as e:
                print("unhandled Exception")
                print(e)
                data = {}
                traces = inspect.trace()
                temp = traces[-1][0]
                code = temp.f_code
                data['filename'] = code.co_filename
                data['functioncode'] = inspect.getsourcelines(code)[0]
                data['localvariables'] = temp.f_locals
                data['error_lineno'] = temp.f_lineno
                data['url'] = request.url
                data['function_start_lno'] = code.co_firstlineno
                data['stacktrace'] = traceback.format_exc().replace('\n','<br>')
                data['timestamp'] = str(datetime.datetime.now())
                pool = Pool(processes=1)
                result = pool.apply_async(send_email, [data,usermailDetails])
                # send_email(data,usermailDetails)
                response = jsonify({'result':'Something went wrong.Please try again..'}),500
            return response
Пример #49
0
def _build_error_message():
    # Yaml traceback doesn't work, certainly because of the compile clause
    # that messes up line numbers
    error_msg = tools.ustr(traceback.format_exc())
    frame_list = inspect.trace()
    deepest_frame = frame_list[-1][0]
    possible_yaml_statement = None
    for frame_inf in frame_list:
        frame = frame_inf[0]
        for local in ('statements', 'code_context', 'model'):
            if local not in frame.f_locals:
                break
        else:
            # all locals found ! we are in process_python function
            possible_yaml_statement = frame.f_locals['statements']
    if possible_yaml_statement:
        numbered_line_statement = ""
        for index, line in enumerate(possible_yaml_statement.split('\n'), start=1):
            numbered_line_statement += "%03d>  %s\n" % (index, line)
        yaml_error = "For yaml file, check the line number indicated in the traceback against this statement:\n%s"
        yaml_error = yaml_error % numbered_line_statement
        error_msg += '\n%s' % yaml_error
    error_msg += """\nLocal variables in deepest are: %s """ % repr(deepest_frame.f_locals)
    return tools.ustr(error_msg.encode('utf-8'))
Пример #50
0
    def inspect_traceback(self, exception):
        CALL_DEPTH = 1
        DEFAULT = dict.fromkeys(["path", "line", "function", "code"],
                                "no info")
        traceback = inspect.trace()
        stack = []

        try:
            for index in range(CALL_DEPTH, len(traceback)):
                stack.append(dict(DEFAULT))
                stack[-1]["path"] = traceback[index][1]
                stack[-1]["line"] = traceback[index][2]
                stack[-1]["function"] = traceback[index][3]
                stack[-1]["code"] = utils.to_unicode(
                    traceback[index][4][0]).strip("\n")
        except Exception:
            pass

        des = {}
        des["stack"] = stack
        des["exception_info"] = utils.to_unicode(exception)
        des["exception_class"] = exception.__class__.__name__

        self._result.py_exception(des)
Пример #51
0
 def reload(self):
     try:
         importlib.reload(model)
         importlib.reload(impl)
         importlib.reload(plugins)
         self.newimpl = impl.TehbotImpl(self)
         modules = self.newimpl.gather_modules()
         for m in modules:
             try:
                 importlib.reload(m)
             except ImportError:
                 pass
         self.newimpl.load_plugins(modules)
     except Exception as e:
         Tehbot.print_exc()
         self.newimpl = None
         frm = inspect.trace()[-1]
         mod = inspect.getmodule(frm[0])
         lineno = frm[0].f_lineno
         try:
             modname = mod.__name__
         except:
             modname = "<unknown module>"
         return (modname, lineno, e)
Пример #52
0
    def inspect_traceback(self, exception):
        CALL_DEPTH = 1
        traceback = inspect.trace()
        stack = []
        default = dict.fromkeys(["path", "line", "function", "code"],
                                "no info")
        try:
            for index in range(CALL_DEPTH, len(traceback)):
                stack.append(copy.copy(default))
                stack[-1]["path"] = copy.copy(traceback[index][1])
                stack[-1]["line"] = copy.copy(traceback[index][2])
                stack[-1]["function"] = copy.copy(traceback[index][3])
                stack[-1]["code"] = copy.copy(
                    traceback[index][4][0].strip("\n"))
        except:
            pass
        finally:
            del traceback
        des = {}
        des["stack"] = stack
        des["exception_info"] = exception.__str__()
        des["exception_class"] = exception.__class__.__name__

        self.result.py_exception(des)
Пример #53
0
def email_exception(exception_address, message=""):
    # http://stackoverflow.com/questions/1095601/find-module-name-of-the-originating-exception-in-python
    frm = inspect.trace()[-1]
    mod = inspect.getmodule(frm[0])
    module_name = mod.__name__ if mod else frm[1]

    sender = '*****@*****.**'
    receivers = [exception_address]

    error_str = ("%s\n\n%s" % (message, traceback.format_exc()))
    msg = MIMEText(error_str.encode('utf8'), 'plain', 'utf8')
    msg['To'] = exception_address
    msg['From'] = 'Spyne <*****@*****.**>'
    msg['Date'] = formatdate()
    msg['Subject'] = "(%s@%s) %s" % (getpass.getuser(), gethostname(), module_name)

    try:
        smtp_object = smtplib.SMTP('localhost')
        smtp_object.sendmail(sender, receivers, msg.as_string())
        logger.error("Error email sent")

    except Exception, e:
        logger.error("Error: unable to send email")
        logger.exception(e)
Пример #54
0
    def compact_trace(s, trace):
        """ Format traceback compactly """
        filepath = None
        for frame, path, line, func, context, i in reversed(inspect.trace()):
            code = context[i].strip()

            # Tell us which file and function we are in!
            if filepath == path: # Skip repeating filename
                yield "In \"%s\":" % func
            else:
                filepath = path
                yield "In \"%s\" %s:" % (func, path)

            # Tell us the line number and code
            yield "<%s> %s" % (line, code)

            # Tell us the value of relevant variables (attributes using dot notation)
            all_vars = dict(frame.f_globals, **frame.f_locals)
            tokens = set(re.split(r"[^\w\.]+", code))
            tokens |= set(b for a in tokens for b in a.split(".")) # Add in partial names
            for a, b in all_vars.iteritems():
                for var, val in s.collect_vars(tokens, a, b):
                    if var != func:
                        yield "%s=%s" % (var, repr(val))
Пример #55
0
    def _run_avocado(self):
        """
        Auxiliary method to run_avocado.
        """
        testMethod = getattr(self, self._testMethodName)
        self._start_logging()
        if self.sysinfo_enabled:
            self.sysinfo_logger.start_test_hook()
        test_exception = None
        cleanup_exception = None
        stdout_check_exception = None
        stderr_check_exception = None
        try:
            self.setUp()
        except exceptions.TestSkipError as details:
            stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
            raise exceptions.TestSkipError(details)
        except exceptions.TestTimeoutSkip as details:
            stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
            raise exceptions.TestTimeoutSkip(details)
        except:  # Old-style exceptions are not inherited from Exception()
            stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
            details = sys.exc_info()[1]
            raise exceptions.TestSetupFail(details)
        try:
            testMethod()
        except exceptions.TestSkipError as details:
            stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
            skip_illegal_msg = ('Calling skip() in places other than '
                                'setUp() is not allowed in avocado, you '
                                'must fix your test. Original skip exception: '
                                '%s' % details)
            raise exceptions.TestError(skip_illegal_msg)
        except:  # Old-style exceptions are not inherited from Exception()
            stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
            details = sys.exc_info()[1]
            if not isinstance(details, Exception):  # Avoid passing nasty exc
                details = exceptions.TestError("%r: %s" % (details, details))
            test_exception = details
            self.log.debug("Local variables:")
            local_vars = inspect.trace()[1][0].f_locals
            for key, value in local_vars.iteritems():
                self.log.debug(' -> %s %s: %s', key, type(value), value)
        finally:
            try:
                self.tearDown()
            except exceptions.TestSkipError as details:
                stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
                skip_illegal_msg = ('Calling skip() in places other than '
                                    'setUp() is not allowed in avocado, '
                                    'you must fix your test. Original skip '
                                    'exception: %s' % details)
                raise exceptions.TestError(skip_illegal_msg)
            except:  # avoid old-style exception failures
                stacktrace.log_exc_info(sys.exc_info(), logger='avocado.test')
                details = sys.exc_info()[1]
                cleanup_exception = exceptions.TestSetupFail(details)

        whiteboard_file = os.path.join(self.logdir, 'whiteboard')
        genio.write_file(whiteboard_file, self.whiteboard)

        if self.job is not None:
            job_standalone = getattr(self.job.args, 'standalone', False)
            output_check_record = getattr(self.job.args, 'output_check_record',
                                          'none')
            no_record_mode = (not job_standalone
                              and output_check_record == 'none')
            disable_output_check = (not job_standalone and getattr(
                self.job.args, 'output_check', 'on') == 'off')

            if job_standalone or no_record_mode:
                if not disable_output_check:
                    try:
                        self._check_reference_stdout()
                    except Exception as details:
                        stacktrace.log_exc_info(sys.exc_info(),
                                                logger='avocado.test')
                        stdout_check_exception = details
                    try:
                        self._check_reference_stderr()
                    except Exception as details:
                        stacktrace.log_exc_info(sys.exc_info(),
                                                logger='avocado.test')
                        stderr_check_exception = details
            elif not job_standalone:
                if output_check_record in ['all', 'stdout']:
                    self._record_reference_stdout()
                if output_check_record in ['all', 'stderr']:
                    self._record_reference_stderr()

        # pylint: disable=E0702
        if test_exception is not None:
            raise test_exception
        elif cleanup_exception is not None:
            raise cleanup_exception
        elif stdout_check_exception is not None:
            raise stdout_check_exception
        elif stderr_check_exception is not None:
            raise stderr_check_exception
        elif self.__log_warn_used:
            raise exceptions.TestWarn("Test passed but there were warnings "
                                      "during execution. Check the log for "
                                      "details.")

        self.status = 'PASS'
        if self.sysinfo_enabled:
            self.sysinfo_logger.end_test_hook()
Пример #56
0
def RunWithCrashHandler(f):
    try:
        exit_code = f()
        sys.exit(exit_code)
    except (SystemExit, KeyboardInterrupt):
        raise
    except:
        import inspect
        import traceback

        # Save trace and exception now. These calls look at the most recently
        # raised exception. The code that makes the report might trigger other
        # exceptions.
        original_trace = inspect.trace(3)[1:]
        formatted_exception = traceback.format_exception_only(
            *(sys.exc_info()[:2]))

        apology = """Yikes, the program threw an unexpected exception!

Hopefully a complete report has been saved to transitfeedcrash.txt,
though if you are seeing this message we've already disappointed you once
today. Please include the report in a new issue at
https://github.com/google/transitfeed/issues
or an email to the public group [email protected]. Sorry!

"""
        dashes = '%s\n' % ('-' * 60)
        dump = []
        dump.append(apology)
        dump.append(dashes)
        try:
            import transitfeed
            dump.append("transitfeed version %s\n\n" % __version__)
        except NameError:
            # Oh well, guess we won't put the version in the report
            pass

        for (frame_obj, filename, line_num, fun_name, context_lines,
             context_index) in original_trace:
            dump.append('File "%s", line %d, in %s\n' %
                        (filename, line_num, fun_name))
            if context_lines:
                for (i, line) in enumerate(context_lines):
                    if i == context_index:
                        dump.append(' --> %s' % line)
                    else:
                        dump.append('     %s' % line)
            for local_name, local_val in list(frame_obj.f_locals.items()):
                try:
                    truncated_val = str(local_val)[0:500]
                except Exception as e:
                    dump.append('    Exception in str(%s): %s' %
                                (local_name, e))
                else:
                    if len(truncated_val) >= 500:
                        truncated_val = '%s...' % truncated_val[0:499]
                    dump.append('    %s = %s\n' % (local_name, truncated_val))
            dump.append('\n')

        dump.append(''.join(formatted_exception))

        open('transitfeedcrash.txt', 'w').write(''.join(dump))

        print(''.join(dump))
        print()
        print(dashes)
        print(apology)

        try:
            input('Press enter to continue...')
        except EOFError:
            # Ignore stdin being closed. This happens during some tests.
            pass
        sys.exit(127)
Пример #57
0
def html(context=5, i18n=None):
    _ = get_translator(i18n)
    etype, evalue = sys.exc_info()[0], sys.exc_info()[1]
    if type(etype) is type:
        etype = etype.__name__
    pyver = 'Python ' + sys.version.split()[0] + '<br>' + sys.executable
    head = pydoc.html.heading(
        _('<font size=+1><strong>%(exc_type)s</strong>: %(exc_value)s</font>')
        % {
            'exc_type': etype,
            'exc_value': evalue
        }, '#ffffff', '#777777', pyver)

    head = head + (_('<p>A problem occurred while running a Python script. '
                     'Here is the sequence of function calls leading up to '
                     'the error, with the most recent (innermost) call first. '
                     'The exception attributes are:'))

    indent = '<tt><small>%s</small>&nbsp;</tt>' % ('&nbsp;' * 5)
    traceback = []
    for frame, file, lnum, func, lines, index in inspect.trace(context):
        if file is None:
            link = _("&lt;file is None - probably inside <tt>eval</tt> "
                     "or <tt>exec</tt>&gt;")
        else:
            file = os.path.abspath(file)
            link = '<a href="file:%s">%s</a>' % (file, pydoc.html.escape(file))
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        if func == '?':
            call = ''
        else:
            call = _(
                'in <strong>%s</strong>') % func + inspect.formatargvalues(
                    args,
                    varargs,
                    varkw,
                    locals,
                    formatvalue=lambda value: '=' + pydoc.html.repr(value))

        level = '''
<table width="100%%" bgcolor="#dddddd" cellspacing=0 cellpadding=2 border=0>
<tr><td>%s %s</td></tr></table>''' % (link, call)

        if index is None or file is None:
            traceback.append('<p>' + level)
            continue

        # do a file inspection
        names = []

        def tokeneater(type, token, start, end, line, names=names):
            if type == tokenize.NAME and token not in keyword.kwlist:
                if token not in names:
                    names.append(token)
            if type == tokenize.NEWLINE: raise IndexError

        def linereader(file=file, lnum=[lnum]):
            line = s2b(linecache.getline(file, lnum[0]))
            lnum[0] = lnum[0] + 1
            return line

        # The interface that is tokenize.tokenize in Python 3 is
        # called tokenize.generate_tokens in Python 2.  However,
        # Python 2 has tokenize.tokenize with a different interface,
        # and Python 3 has an undocumented generate_tokens function,
        # also with a different interface, so a version check is
        # needed instead of checking for which functions exist.
        if sys.version_info[0] > 2:
            tokenize_fn = tokenize.tokenize
        else:
            tokenize_fn = tokenize.generate_tokens
        try:
            for t in tokenize_fn(linereader):
                tokeneater(*t)
        except IndexError:
            pass
        lvals = []
        for name in names:
            if name in frame.f_code.co_varnames:
                if name in locals:
                    value = pydoc.html.repr(locals[name])
                else:
                    value = _('<em>undefined</em>')
                name = '<strong>%s</strong>' % name
            else:
                if name in frame.f_globals:
                    value = pydoc.html.repr(frame.f_globals[name])
                else:
                    value = _('<em>undefined</em>')
                name = '<em>global</em> <strong>%s</strong>' % name
            lvals.append('%s&nbsp;= %s' % (name, value))
        if lvals:
            lvals = ', '.join(lvals)
            lvals = indent + '<small><font color="#909090">%s'\
                '</font></small><br>'%lvals
        else:
            lvals = ''

        excerpt = []
        i = lnum - index
        for line in lines:
            number = '&nbsp;' * (5 - len(str(i))) + str(i)
            number = '<small><font color="#909090">%s</font></small>' % number
            line = '<tt>%s&nbsp;%s</tt>' % (number, pydoc.html.preformat(line))
            if i == lnum:
                line = '''
<table width="100%%" bgcolor="white" cellspacing=0 cellpadding=0 border=0>
<tr><td>%s</td></tr></table>''' % line
            excerpt.append('\n' + line)
            if i == lnum:
                excerpt.append(lvals)
            i = i + 1
        traceback.append('<p>' + level + '\n'.join(excerpt))

    traceback.reverse()

    exception = '<p><strong>%s</strong>: %s' % (str(etype), str(evalue))
    attribs = []
    for name in dir(evalue):
        value = pydoc.html.repr(getattr(evalue, name))
        attribs.append('<br>%s%s&nbsp;= %s' % (indent, name, value))

    return head + ' '.join(attribs) + ' '.join(traceback) + '<p>&nbsp;</p>'
Пример #58
0
def pt_html(context=5, i18n=None):
    _ = get_translator(i18n)
    esc = html_escape
    exc_info = [esc(str(value)) for value in sys.exc_info()[:2]]
    l = [
        _('<h1>Templating Error</h1>\n'
          '<p><b>%(exc_type)s</b>: %(exc_value)s</p>\n'
          '<p class="help">Debugging information follows</p>') % {
              'exc_type': exc_info[0],
              'exc_value': exc_info[1]
          },
        '<ol>',
    ]
    from roundup.cgi.PageTemplates.Expressions import TraversalError
    t = inspect.trace(context)
    t.reverse()
    for frame, file, lnum, func, lines, index in t:
        args, varargs, varkw, locals = inspect.getargvalues(frame)
        if '__traceback_info__' in locals:
            ti = locals['__traceback_info__']
            if isinstance(ti, TraversalError):
                s = []
                for name, info in ti.path:
                    s.append(
                        _('<li>"%(name)s" (%(info)s)</li>') % {
                            'name': name,
                            'info': esc(repr(info))
                        })
                s = '\n'.join(s)
                l.append(
                    _('<li>Looking for "%(name)s", '
                      'current path:<ol>%(path)s</ol></li>') % {
                          'name': ti.name,
                          'path': s
                      })
            else:
                l.append(_('<li>In %s</li>') % esc(str(ti)))
        if '__traceback_supplement__' in locals:
            ts = locals['__traceback_supplement__']
            if len(ts) == 2:
                supp, context = ts
                s = _('A problem occurred in your template "%s".') \
                    % str(context.id)
                if context._v_errors:
                    s = s + '<br>' + '<br>'.join(
                        [esc(x) for x in context._v_errors])
                l.append('<li>%s</li>' % s)
            elif len(ts) == 3:
                supp, context, info = ts
                l.append(
                    _('''
<li>While evaluating the %(info)r expression on line %(line)d
<table class="otherinfo" style="font-size: 90%%">
 <tr><th colspan="2" class="header">Current variables:</th></tr>
 %(globals)s
 %(locals)s
</table></li>
''') % {
                        'info': info,
                        'line': context.position[0],
                        'globals': niceDict('    ', context.global_vars),
                        'locals': niceDict('    ', context.local_vars)
                    })

    l.append(
        '''
</ol>
<table style="font-size: 80%%; color: gray">
 <tr><th class="header" align="left">%s</th></tr>
 <tr><td><pre>%s</pre></td></tr>
</table>''' %
        (_('Full traceback:'),
         html_escape(''.join(traceback.format_exception(*sys.exc_info())))))
    l.append('<p>&nbsp;</p>')
    return '\n'.join(l)
Пример #59
0
def get_pretty_traceback(req=None, exc_info=None, skip_frames=0):
    """
    Given an optional request object and an optional exc_info,
    returns a text string representing many details about an exception.
    """
    if exc_info is None:
        exc_info = sys.exc_info()
    if exc_info[0]:
        # We found an exception.

        # We want to extract the name of the Exception
        exc_name = exc_info[0].__name__
        exc_value = str(exc_info[1])
        filename, line_no, function_name = _get_filename_and_line(exc_info)

        # Let's record when and where and what
        www_data = (
            "%(time)s -> %(name)s: %(value)s (%(file)s:%(line)s:%(function)s)"
            % {
                'time': time.strftime("%Y-%m-%d %H:%M:%S"),
                'name': exc_name,
                'value': exc_value,
                'file': filename,
                'line': line_no,
                'function': function_name
            })

        # Let's retrieve contextual user related info, if any
        try:
            client_data = get_pretty_wide_client_info(req)
        except Exception as err:
            client_data = "Error in retrieving " \
                "contextual information: %s" % err

        # Let's extract the traceback:
        traceback_data_stream = StringIO()
        print("\n** Traceback details \n", file=traceback_data_stream)
        traceback.print_exc(file=traceback_data_stream)
        stack = [frame[0] for frame in inspect.trace()]
        try:
            stack.reverse()
            print("\n** Stack frame details", file=traceback_data_stream)
            values_to_hide = set()
            for frame in stack:
                try:
                    print(file=traceback_data_stream)
                    print("Frame %s in %s at line %s" %
                          (frame.f_code.co_name, frame.f_code.co_filename,
                           frame.f_lineno),
                          file=traceback_data_stream)
                    # Dereferencing f_locals
                    # See: http://utcc.utoronto.ca/~cks/space/blog/python/
                    # FLocalsAndTraceFunctions
                    local_values = frame.f_locals
                    try:
                        values_to_hide |= find_all_values_to_hide(local_values)

                        code = open(frame.f_code.co_filename).readlines()
                        first_line = max(1, frame.f_lineno - 3)
                        last_line = min(len(code), frame.f_lineno + 3)
                        print("-" * 79, file=traceback_data_stream)
                        for line in xrange(first_line, last_line + 1):
                            code_line = code[line - 1].rstrip()
                            if line == frame.f_lineno:
                                print("----> %4i %s" % (line, code_line),
                                      file=traceback_data_stream)
                            else:
                                print("      %4i %s" % (line, code_line),
                                      file=traceback_data_stream)
                        print("-" * 79, file=traceback_data_stream)
                    except:
                        pass
                    for key, value in local_values.items():
                        print("\t%20s = " % key,
                              end=' ',
                              file=traceback_data_stream)
                        try:
                            value = repr(value)
                        except Exception as err:
                            # We shall gracefully accept errors when repr() of
                            # a value fails (e.g. when we are trying to repr()
                            # a variable that was not fully initialized as the
                            # exception was raised during its __init__ call).
                            value = "ERROR: when representing the value: %s" \
                                    % (err)
                        try:
                            print(_truncate_dynamic_string(value),
                                  file=traceback_data_stream)
                        except:
                            print("<ERROR WHILE PRINTING VALUE>",
                                  file=traceback_data_stream)
                finally:
                    del frame
        finally:
            del stack
        traceback_data = traceback_data_stream.getvalue()
        for to_hide in values_to_hide:
            # Let's hide passwords
            traceback_data = traceback_data.replace(to_hide, '<*****>')

        # Okay, start printing:
        output = StringIO()

        print("* %s" % www_data, file=output)
        print("\n** User details", file=output)
        print(client_data, file=output)

        if traceback_data:
            print(traceback_data, file=output)
        return output.getvalue()
    else:
        return ""
Пример #60
0
    def test(self,
             cr,
             uid,
             module_list='all',
             xunit=True,
             ignores=None,
             context=None):
        """
        module_list should equal 'all' or a list of module name
        ignores is a dict containing: {'module1': ['test_file_to_ignore1', 'test_file_to_ignore2' ], 'module2': ...}
        """
        if module_list == 'all' or 'all' in module_list:
            module_list = self.get_all_installed_module_list(
                cr, ('installed', 'to upgrade'))
        # get a dict containing: {'module1': ['test_file1', 'test_file2' ], 'module2': ...}
        module_test_files = self.build_test_list_from_modules(module_list)

        ignores = ignores or {}

        new_cr = pooler.get_db(cr.dbname).cursor()

        test_suite = {
            'name': 'smile.test',
            'tests': 0,
            'errors': 0,
            'failures': 0,
            'skip': 0,
            'test_cases': [],
        }
        try:
            for module_name in module_test_files:
                ignored_files = ignores.get(module_name, [])
                for filename in module_test_files[module_name]:
                    test_case = {
                        'classname': module_name,
                        'name': filename,
                        'time': 0,
                        'error': {},
                        'skipped': filename in ignored_files
                    }
                    start = time.time()
                    test_suite['tests'] += 1
                    if not test_case['skipped']:
                        try:
                            self._run_test(new_cr, module_name, filename)
                        except Exception, e:
                            test_suite['errors'] += 1
                            traceback_msg = traceback.format_exc()
                            frame_list = inspect.trace()

                            test_case['error'] = {
                                'type':
                                str(type(e)),
                                'message':
                                repr(e),
                                'stack_trace':
                                self.build_error_msg(traceback_msg,
                                                     frame_list),
                            }
                    else:
                        test_suite['skip'] += 1

                    test_case['time'] = (time.time() - start)
                    test_suite['test_cases'].append(test_case)
                new_cr.rollback()
        finally:
            new_cr.close()
        if xunit:
            return self.test_suite_to_xunit(test_suite)
        return test_suite