Python types.TracebackType() Examples

The following are code examples for showing how to use types.TracebackType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: opentracing-python   Author: opentracing   File: test_scope.py    Apache License 2.0 6 votes vote down vote up
def test_scope_error_report():
    tracer = Tracer()
    scope = tracer.start_active_span('foo')
    error_message = 'unexpected_situation'

    with mock.patch.object(scope.span, 'log_kv') as log_kv:
        with mock.patch.object(scope.span, 'set_tag') as set_tag:
            try:
                with scope:
                    raise ValueError(error_message)
            except ValueError:
                pass

            assert set_tag.call_count == 1
            assert set_tag.call_args[0] == (tags.ERROR, True)

            assert log_kv.call_count == 1
            log_kv_args = log_kv.call_args[0][0]
            assert log_kv_args.get(logs.EVENT, None) is tags.ERROR
            assert log_kv_args.get(logs.MESSAGE, None) is error_message
            assert log_kv_args.get(logs.ERROR_KIND, None) is ValueError
            assert isinstance(log_kv_args.get(logs.ERROR_OBJECT, None),
                              ValueError)
            assert isinstance(log_kv_args.get(logs.STACK, None),
                              types.TracebackType) 
Example 2
Project: opentracing-python   Author: opentracing   File: test_noop_span.py    Apache License 2.0 6 votes vote down vote up
def test_span_error_report():
    tracer = Tracer()
    span = tracer.start_span('foo')
    error_message = 'unexpected_situation'

    with mock.patch.object(span, 'log_kv') as log_kv:
        with mock.patch.object(span, 'set_tag') as set_tag:
            try:
                with span:
                    raise ValueError(error_message)
            except ValueError:
                pass

            assert set_tag.call_count == 1
            assert set_tag.call_args[0] == (tags.ERROR, True)

            assert log_kv.call_count == 1
            log_kv_args = log_kv.call_args[0][0]
            assert log_kv_args.get(logs.EVENT, None) is tags.ERROR
            assert log_kv_args.get(logs.MESSAGE, None) is error_message
            assert log_kv_args.get(logs.ERROR_KIND, None) is ValueError
            assert isinstance(log_kv_args.get(logs.ERROR_OBJECT, None),
                              ValueError)
            assert isinstance(log_kv_args.get(logs.STACK, None),
                              types.TracebackType) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_raise.py    GNU General Public License v3.0 6 votes vote down vote up
def test_constructor(self):
        other_tb = get_tb()
        frame = sys._getframe()

        tb = types.TracebackType(other_tb, frame, 1, 2)
        self.assertEqual(tb.tb_next, other_tb)
        self.assertEqual(tb.tb_frame, frame)
        self.assertEqual(tb.tb_lasti, 1)
        self.assertEqual(tb.tb_lineno, 2)

        tb = types.TracebackType(None, frame, 1, 2)
        self.assertEqual(tb.tb_next, None)

        with self.assertRaises(TypeError):
            types.TracebackType("no", frame, 1, 2)

        with self.assertRaises(TypeError):
            types.TracebackType(other_tb, "no", 1, 2)

        with self.assertRaises(TypeError):
            types.TracebackType(other_tb, frame, "no", 2)

        with self.assertRaises(TypeError):
            types.TracebackType(other_tb, frame, 1, "nuh-uh") 
Example 4
Project: tartiflette   Author: tartiflette   File: parser.py    MIT License 6 votes vote down vote up
def __exit__(
        self,
        exc_type: Optional[Type],
        exc_value: Optional[Exception],
        traceback: Optional[TracebackType],
    ) -> None:
        """
        Frees the resource related to the parsing of the query made by the
        libgraphqlparser library.
        :param exc_type: class of the exception potentially raised
        :param exc_value: instance of the exception potentially raised
        :param traceback: traceback of the exception potentially raised
        :type exc_type: Optional[Type]
        :type exc_value: Optional[Exception]
        :type traceback: Optional[TracebackType]
        """
        self._destroy_cb(self._c_parsed) 
Example 5
Project: pyblish-win   Author: pyblish   File: inspect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example 6
Project: pyblish-win   Author: pyblish   File: RemoteDebugger.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def wrap_info(info):
    "replace info[2], a traceback instance, by its ID"
    if info is None:
        return None
    else:
        traceback = info[2]
        assert isinstance(traceback, types.TracebackType)
        traceback_id = id(traceback)
        tracebacktable[traceback_id] = traceback
        modified_info = (info[0], info[1], traceback_id)
        return modified_info 
Example 7
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: debug.py    Apache License 2.0 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 8
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: debug.py    Apache License 2.0 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 9
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: debug.py    Apache License 2.0 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 10
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: debug.py    Apache License 2.0 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 11
Project: kvmd   Author: pikvm   File: aioregion.py    GNU General Public License v3.0 5 votes vote down vote up
def __exit__(
        self,
        _exc_type: Type[BaseException],
        _exc: BaseException,
        _tb: types.TracebackType,
    ) -> None:
        self.exit() 
Example 12
Project: kvmd   Author: pikvm   File: inotify.py    GNU General Public License v3.0 5 votes vote down vote up
def __exit__(
        self,
        _exc_type: Type[BaseException],
        _exc: BaseException,
        _tb: types.TracebackType,
    ) -> None:

        if self.__fd >= 0:
            asyncio.get_event_loop().remove_reader(self.__fd)
            for wd in list(self.__wd_by_path.values()):
                _inotify_rm_watch(self.__fd, wd)
            try:
                os.close(self.__fd)
            except Exception:
                pass 
Example 13
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: sandbox.py    MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 14
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: debug.py    MIT License 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 15
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: debug.py    MIT License 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 16
Project: flasky   Author: RoseOu   File: debug.py    MIT License 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 17
Project: flasky   Author: RoseOu   File: debug.py    MIT License 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 18
Project: quart   Author: pgjones   File: app.py    MIT License 5 votes vote down vote up
def log_exception(self, exception_info: Tuple[type, BaseException, TracebackType]) -> None:
        """Log a exception to the :attr:`logger`.

        By default this is only invoked for unhandled exceptions.
        """
        if has_request_context():
            request_ = _request_ctx_stack.top.request
            self.logger.error(
                f"Exception on request {request_.method} {request_.path}", exc_info=exception_info
            )
        if has_websocket_context():
            websocket_ = _websocket_ctx_stack.top.websocket
            self.logger.error(f"Exception on websocket {websocket_.path}", exc_info=exception_info) 
Example 19
Project: quart   Author: pgjones   File: ctx.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        await _app_ctx_stack.top.pop(exc_value) 
Example 20
Project: quart   Author: pgjones   File: ctx.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        await self.app.do_teardown_request(exc_value, self)
        _request_ctx_stack.pop()
        await super().__aexit__(exc_type, exc_value, tb) 
Example 21
Project: quart   Author: pgjones   File: ctx.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        await self.app.do_teardown_websocket(exc_value, self)
        _websocket_ctx_stack.pop()
        await super().__aexit__(exc_type, exc_value, tb) 
Example 22
Project: quart   Author: pgjones   File: ctx.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        await self.pop(exc_value) 
Example 23
Project: quart   Author: pgjones   File: response.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        pass 
Example 24
Project: quart   Author: pgjones   File: response.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        pass 
Example 25
Project: quart   Author: pgjones   File: response.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        await self.file_manager.__aexit__(exc_type, exc_value, tb) 
Example 26
Project: quart   Author: pgjones   File: response.py    MIT License 5 votes vote down vote up
def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
        return None 
Example 27
Project: ngo-addons-backport   Author: camptocamp   File: netsvc.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def post_mortem(info):
    if tools.config['debug_mode'] and isinstance(info[2], types.TracebackType):
        import pdb
        pdb.post_mortem(info[2])

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: 
Example 28
Project: pywren-ibm-cloud   Author: pywren   File: pickling_support.py    Apache License 2.0 5 votes vote down vote up
def install():
    copy_reg.pickle(TracebackType, pickle_traceback) 
Example 29
Project: starlette-cbge   Author: gvbgduh   File: test_client.py    MIT License 5 votes vote down vote up
def __aexit__(
        self,
        exc_type: Type[BaseException] = None,
        exc_value: BaseException = None,
        traceback: TracebackType = None,
    ) -> None:
        await self.wait_shutdown() 
Example 30
Project: jawfish   Author: war-and-code   File: inspect.py    MIT License 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example 31
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: _pydev_inspect.py    MIT License 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example 32
Project: autohooks   Author: greenbone   File: git.py    GNU General Public License v3.0 5 votes vote down vote up
def __exit__(
        self,
        exc_type: Optional[BaseExceptionType],
        exc_value: Optional[BaseException],
        traceback: Optional[TracebackType],
    ) -> Any:
        if not self.partially_staged:
            return

        if exc_type is not None:
            # an error has occurred
            # restore working tree and index as it was before formatting
            self.restore_working_tree()
            _read_tree(self.index)
        else:
            # save formatting changes
            formatted_tree = _write_tree()

            self.restore_working_tree()

            # restore index
            # formatted_tree will be the same as index if no changes are applied
            _read_tree(formatted_tree)

            if formatted_tree != self.index:
                # create diff between index and formatted_tree
                patch = _get_tree_diff(self.index, formatted_tree)
                try:
                    # apply diff to working tree
                    _apply_diff(patch)
                except GitError as e:
                    print(
                        'Found conflicts between plugin and local changes. '
                        'Plugin changes will be ignored for conflicted hunks.',
                        e,
                    )

                    rootpath = get_project_root_path()
                    for path in rootpath.glob('*.rej'):
                        path.unlink() 
Example 33
Project: misp42splunk   Author: remg427   File: sandbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 34
Project: misp42splunk   Author: remg427   File: debug.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 35
Project: misp42splunk   Author: remg427   File: debug.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 36
Project: TornadoWeb   Author: VxCoder   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 37
Project: TornadoWeb   Author: VxCoder   File: debug.py    Apache License 2.0 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 38
Project: TornadoWeb   Author: VxCoder   File: debug.py    Apache License 2.0 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 39
Project: Flask_Blog   Author: sugarguo   File: sandbox.py    GNU General Public License v3.0 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 40
Project: Flask_Blog   Author: sugarguo   File: debug.py    GNU General Public License v3.0 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 41
Project: Flask_Blog   Author: sugarguo   File: debug.py    GNU General Public License v3.0 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 42
Project: NiujiaoDebugger   Author: MrSrc   File: inspect.py    GNU General Public License v3.0 5 votes vote down vote up
def istraceback(object):
    """Return true if the object is a traceback.

    Traceback objects provide these attributes:
        tb_frame        frame object at this level
        tb_lasti        index of last attempted instruction in bytecode
        tb_lineno       current line number in Python source code
        tb_next         next inner traceback object (called by this level)"""
    return isinstance(object, types.TracebackType) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_raise.py    GNU General Public License v3.0 5 votes vote down vote up
def test_sets_traceback(self):
        try:
            raise IndexError()
        except IndexError as e:
            self.assertIsInstance(e.__traceback__, types.TracebackType)
        else:
            self.fail("No exception raised") 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: test_raise.py    GNU General Public License v3.0 5 votes vote down vote up
def test_attrs(self):
        try:
            self.raiser()
        except Exception as exc:
            tb = exc.__traceback__

        self.assertIsInstance(tb.tb_next, types.TracebackType)
        self.assertIs(tb.tb_frame, sys._getframe())
        self.assertIsInstance(tb.tb_lasti, int)
        self.assertIsInstance(tb.tb_lineno, int)

        self.assertIs(tb.tb_next.tb_next, None)

        # Invalid assignments
        with self.assertRaises(TypeError):
            del tb.tb_next

        with self.assertRaises(TypeError):
            tb.tb_next = "asdf"

        # Loops
        with self.assertRaises(ValueError):
            tb.tb_next = tb

        with self.assertRaises(ValueError):
            tb.tb_next.tb_next = tb

        # Valid assignments
        tb.tb_next = None
        self.assertIs(tb.tb_next, None)

        new_tb = get_tb()
        tb.tb_next = new_tb
        self.assertIs(tb.tb_next, new_tb) 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: debugger_r.py    GNU General Public License v3.0 5 votes vote down vote up
def wrap_info(info):
    "replace info[2], a traceback instance, by its ID"
    if info is None:
        return None
    else:
        traceback = info[2]
        assert isinstance(traceback, types.TracebackType)
        traceback_id = id(traceback)
        tracebacktable[traceback_id] = traceback
        modified_info = (info[0], info[1], traceback_id)
        return modified_info 
Example 46
Project: tomodachi   Author: kalaspuff   File: container.py    MIT License 5 votes vote down vote up
def __init__(self, module_import: ModuleType, configuration: Optional[Dict] = None) -> None:
        self.module_import = module_import

        self.file_path = module_import.__file__
        self.module_name = (module_import.__name__.rsplit('/', 1)[1] if '/' in module_import.__name__ else module_import.__name__).rsplit('.', 1)[-1]
        self.configuration = configuration
        self.logger = logging.getLogger('services.{}'.format(self.module_name))

        self._close_waiter = asyncio.Future()  # type: asyncio.Future
        self.started_waiter = asyncio.Future()  # type: asyncio.Future

        def catch_uncaught_exceptions(type_: type, value: BaseException, traceback: TracebackType) -> None:
            raise value

        sys.excepthook = catch_uncaught_exceptions 
Example 47
Project: Health-Checker   Author: KriAga   File: sandbox.py    MIT License 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__') 
Example 48
Project: Health-Checker   Author: KriAga   File: debug.py    MIT License 5 votes vote down vote up
def make_frame_proxy(frame):
    proxy = TracebackFrameProxy(frame)
    if tproxy is None:
        return proxy
    def operation_handler(operation, *args, **kwargs):
        if operation in ('__getattribute__', '__getattr__'):
            return getattr(proxy, args[0])
        elif operation == '__setattr__':
            proxy.__setattr__(*args, **kwargs)
        else:
            return getattr(proxy, operation)(*args, **kwargs)
    return tproxy(TracebackType, operation_handler) 
Example 49
Project: Health-Checker   Author: KriAga   File: debug.py    MIT License 5 votes vote down vote up
def standard_exc_info(self):
        """Standard python exc_info for re-raising"""
        tb = self.frames[0]
        # the frame will be an actual traceback (or transparent proxy) if
        # we are on pypy or a python implementation with support for tproxy
        if type(tb) is not TracebackType:
            tb = tb.tb
        return self.exc_type, self.exc_value, tb 
Example 50
Project: recruit   Author: Frank-qlu   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def is_internal_attribute(obj, attr):
    """Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    """
    if isinstance(obj, types.FunctionType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES:
            return True
    elif isinstance(obj, types.MethodType):
        if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
           attr in UNSAFE_METHOD_ATTRIBUTES:
            return True
    elif isinstance(obj, type):
        if attr == 'mro':
            return True
    elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):
        return True
    elif isinstance(obj, types.GeneratorType):
        if attr in UNSAFE_GENERATOR_ATTRIBUTES:
            return True
    elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):
        if attr in UNSAFE_COROUTINE_ATTRIBUTES:
            return True
    elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):
        if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:
            return True
    return attr.startswith('__')