Python twisted.python.reflect.safe_repr() Examples

The following are 30 code examples of twisted.python.reflect.safe_repr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.python.reflect , or try the search function .
Example #1
Source File: test_reflect.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_unsignedID(self):
        """
        L{unsignedID} is used to print ID of the object in case of error, not
        standard ID value which can be negative.
        """
        class X(BTBase):
            breakRepr = True

        ids = {X: 100}
        def fakeID(obj):
            try:
                return ids[obj]
            except (TypeError, KeyError):
                return id(obj)
        self.addCleanup(util.setIDFunction, util.setIDFunction(fakeID))

        xRepr = reflect.safe_repr(X)
        self.assertIn("0x64", xRepr) 
Example #2
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_brokenClassAttribute(self):
        """
        If an object raises an exception when accessing its C{__class__}
        attribute, L{reflect.safe_repr} uses C{type} to retrieve the class
        object.
        """
        b = NoClassAttr()
        b.breakRepr = True
        bRepr = reflect.safe_repr(b)
        self.assertIn("NoClassAttr instance at 0x", bRepr)
        self.assertIn(os.path.splitext(__file__)[0], bRepr)
        self.assertIn("RuntimeError: repr!", bRepr) 
Example #3
Source File: test_reflect.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_brokenClassNameAttribute(self):
        """
        If a class raises an exception when accessing its C{__name__} attribute
        B{and} when calling its C{__str__} implementation, L{reflect.safe_repr}
        returns 'BROKEN CLASS' instead of the class name.
        """
        class X(BTBase):
            breakName = True
        xRepr = reflect.safe_repr(X())
        self.assertIn("<BROKEN CLASS AT 0x", xRepr)
        self.assertIn(os.path.splitext(__file__)[0], xRepr)
        self.assertIn("RuntimeError: repr!", xRepr) 
Example #4
Source File: clock.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        if self._str is not None:
            return self._str
        if hasattr(self, 'func'):
            if hasattr(self.func, 'func_name'):
                func = self.func.func_name
                if hasattr(self.func, 'im_class'):
                    func = self.func.im_class.__name__ + '.' + func
            else:
                func = reflect.safe_repr(self.func)
        else:
            func = None

        now = self.seconds()
        L = ["<DelayedCall %s [%ss] called=%s cancelled=%s" % (
                id(self), self.time - now, self.called, self.cancelled)]
        if func is not None:
            L.extend((" ", func, "("))
            if self.args:
                L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
                if self.kw:
                    L.append(", ")
            if self.kw:
                L.append(", ".join([
                    '%s=%s' % (k, reflect.safe_repr(v))
                    for (k, v) in iteritems(self.kw)]))
            L.append(")")

        if self.debug:
            L.append(("\n\ntraceback at creation: \n\n%s"
                      ) % ('    '.join(self.creator)))
        L.append('>')

        return "".join(L) 
Example #5
Source File: base.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        if self._str is not None:
            return self._str
        if hasattr(self, 'func'):
            if hasattr(self.func, 'func_name'):
                func = self.func.func_name
                if hasattr(self.func, 'im_class'):
                    func = self.func.im_class.__name__ + '.' + func
            else:
                func = reflect.safe_repr(self.func)
        else:
            func = None

        now = self.seconds()
        L = ["<DelayedCall 0x%x [%ss] called=%s cancelled=%s" % (
                unsignedID(self), self.time - now, self.called,
                self.cancelled)]
        if func is not None:
            L.extend((" ", func, "("))
            if self.args:
                L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
                if self.kw:
                    L.append(", ")
            if self.kw:
                L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.iteritems()]))
            L.append(")")

        if self.debug:
            L.append("\n\ntraceback at creation: \n\n%s" % ('    '.join(self.creator)))
        L.append('>')

        return "".join(L) 
Example #6
Source File: task.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        if hasattr(self.f, 'func_name'):
            func = self.f.func_name
            if hasattr(self.f, 'im_class'):
                func = self.f.im_class.__name__ + '.' + func
        else:
            func = reflect.safe_repr(self.f)

        return 'LoopingCall<%r>(%s, *%s, **%s)' % (
            self.interval, func, reflect.safe_repr(self.a),
            reflect.safe_repr(self.kw)) 
Example #7
Source File: failure.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __getstate__(self):
        """Avoid pickling objects in the traceback.
        """
        if self.pickled:
            return self.__dict__
        c = self.__dict__.copy()

        c['frames'] = [
            [
                v[0], v[1], v[2],
                [(j[0], reflect.safe_repr(j[1])) for j in v[3]],
                [(j[0], reflect.safe_repr(j[1])) for j in v[4]]
            ] for v in self.frames
        ]

        # added 2003-06-23. See comment above in __init__
        c['tb'] = None

        if self.stack is not None:
            # XXX: This is a band-aid.  I can't figure out where these
            # (failure.stack is None) instances are coming from.
            c['stack'] = [
                [
                    v[0], v[1], v[2],
                    [(j[0], reflect.safe_repr(j[1])) for j in v[3]],
                    [(j[0], reflect.safe_repr(j[1])) for j in v[4]]
                ] for v in self.stack
            ]

        c['pickled'] = 1
        return c 
Example #8
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_workingRepr(self):
        """
        L{reflect.safe_repr} produces the same output as C{repr} on a working
        object.
        """
        x = [1, 2, 3]
        self.assertEquals(reflect.safe_repr(x), repr(x)) 
Example #9
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_brokenRepr(self):
        """
        L{reflect.safe_repr} returns a string with class name, address, and
        traceback when the repr call failed.
        """
        b = Breakable()
        b.breakRepr = True
        bRepr = reflect.safe_repr(b)
        self.assertIn("Breakable instance at 0x", bRepr)
        # Check that the file is in the repr, but without the extension as it
        # can be .py/.pyc
        self.assertIn(os.path.splitext(__file__)[0], bRepr)
        self.assertIn("RuntimeError: repr!", bRepr) 
Example #10
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_brokenClassRepr(self):
        class X(BTBase):
            breakRepr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X()) 
Example #11
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_brokenClassStr(self):
        class X(BTBase):
            breakStr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X()) 
Example #12
Source File: test_reflect.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_brokenClassStr(self):
        class X(BTBase):
            breakStr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X()) 
Example #13
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_brokenClassNameAttribute(self):
        """
        If a class raises an exception when accessing its C{__name__} attribute
        B{and} when calling its C{__str__} implementation, L{reflect.safe_repr}
        returns 'BROKEN CLASS' instead of the class name.
        """
        class X(BTBase):
            breakName = True
        xRepr = reflect.safe_repr(X())
        self.assertIn("<BROKEN CLASS AT 0x", xRepr)
        self.assertIn(os.path.splitext(__file__)[0], xRepr)
        self.assertIn("RuntimeError: repr!", xRepr) 
Example #14
Source File: base.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        if self._str is not None:
            return self._str
        if hasattr(self, 'func'):
            if hasattr(self.func, 'func_name'):
                func = self.func.func_name
                if hasattr(self.func, 'im_class'):
                    func = self.func.im_class.__name__ + '.' + func
            else:
                func = reflect.safe_repr(self.func)
        else:
            func = None

        if self.seconds is None:
            now = seconds()
        else:
            now = self.seconds()
        L = ["<DelayedCall %s [%ss] called=%s cancelled=%s" % (
                id(self), self.time - now, self.called, self.cancelled)]
        if func is not None:
            L.extend((" ", func, "("))
            if self.args:
                L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
                if self.kw:
                    L.append(", ")
            if self.kw:
                L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.iteritems()]))
            L.append(")")

        if self.debug:
            L.append("\n\ntraceback at creation: \n\n%s" % ('    '.join(self.creator)))
        L.append('>')

        return "".join(L) 
Example #15
Source File: task.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __repr__(self):
        if hasattr(self.f, 'func_name'):
            func = self.f.func_name
            if hasattr(self.f, 'im_class'):
                func = self.f.im_class.__name__ + '.' + func
        else:
            func = reflect.safe_repr(self.f)

        return 'LoopingCall<%r>(%s, *%s, **%s)' % (
            self.interval, func, reflect.safe_repr(self.a),
            reflect.safe_repr(self.kw)) 
Example #16
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testWorkingRepr(self):
        x = [1,2,3]
        self.assertEquals(reflect.safe_repr(x), repr(x)) 
Example #17
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testBrokenRepr(self):
        b = Breakable()
        b.breakRepr = True
        reflect.safe_repr(b) 
Example #18
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testBrokenStr(self):
        b = Breakable()
        b.breakStr = True
        reflect.safe_repr(b) 
Example #19
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testBrokenClassStr(self):
        class X(BTBase):
            breakStr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X()) 
Example #20
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testBroken__Class__Attr(self):
        reflect.safe_repr(NoClassAttr()) 
Example #21
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testBroken__Class__Name__Attr(self):
        class X(BTBase):
            breakName = True
        reflect.safe_repr(X()) 
Example #22
Source File: _retry.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _callable_repr(method):
    """Get a useful representation ``method``."""
    try:
        return fullyQualifiedName(method)
    except AttributeError:
        return safe_repr(method) 
Example #23
Source File: base.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __str__(self):
        if self._str is not None:
            return self._str
        if hasattr(self, 'func'):
            # This code should be replaced by a utility function in reflect;
            # see ticket #6066:
            if hasattr(self.func, '__qualname__'):
                func = self.func.__qualname__
            elif hasattr(self.func, '__name__'):
                func = self.func.func_name
                if hasattr(self.func, 'im_class'):
                    func = self.func.im_class.__name__ + '.' + func
            else:
                func = reflect.safe_repr(self.func)
        else:
            func = None

        now = self.seconds()
        L = ["<DelayedCall 0x%x [%ss] called=%s cancelled=%s" % (
                id(self), self.time - now, self.called,
                self.cancelled)]
        if func is not None:
            L.extend((" ", func, "("))
            if self.args:
                L.append(", ".join([reflect.safe_repr(e) for e in self.args]))
                if self.kw:
                    L.append(", ")
            if self.kw:
                L.append(", ".join(['%s=%s' % (k, reflect.safe_repr(v)) for (k, v) in self.kw.items()]))
            L.append(")")

        if self.debug:
            L.append("\n\ntraceback at creation: \n\n%s" % ('    '.join(self.creator)))
        L.append('>')

        return "".join(L) 
Example #24
Source File: task.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self):
        if hasattr(self.f, '__qualname__'):
            func = self.f.__qualname__
        elif hasattr(self.f, '__name__'):
            func = self.f.__name__
            if hasattr(self.f, 'im_class'):
                func = self.f.im_class.__name__ + '.' + func
        else:
            func = reflect.safe_repr(self.f)

        return 'LoopingCall<%r>(%s, *%s, **%s)' % (
            self.interval, func, reflect.safe_repr(self.a),
            reflect.safe_repr(self.kw)) 
Example #25
Source File: failure.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _safeReprVars(varsDictItems):
    """
    Convert a list of (name, object) pairs into (name, repr) pairs.

    L{twisted.python.reflect.safe_repr} is used to generate the repr, so no
    exceptions will be raised by faulty C{__repr__} methods.

    @param varsDictItems: a sequence of (name, value) pairs as returned by e.g.
        C{locals().items()}.
    @returns: a sequence of (name, repr) pairs.
    """
    return [(name, reflect.safe_repr(obj)) for (name, obj) in varsDictItems]


# slyphon: make post-morteming exceptions tweakable 
Example #26
Source File: _format.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def formatUnformattableEvent(event, error):
    """
    Formats an event as a L{unicode} that describes the event generically and a
    formatting error.

    @param event: A logging event.
    @type event: L{dict}

    @param error: The formatting error.
    @type error: L{Exception}

    @return: A formatted string.
    @rtype: L{unicode}
    """
    try:
        return (
            u"Unable to format event {event!r}: {error}"
            .format(event=event, error=error)
        )
    except BaseException:
        # Yikes, something really nasty happened.
        #
        # Try to recover as much formattable data as possible; hopefully at
        # least the namespace is sane, which will help you find the offending
        # logger.
        failure = Failure()

        text = u", ".join(
            u" = ".join((safe_repr(key), safe_repr(value)))
            for key, value in event.items()
        )

        return (
            u"MESSAGE LOST: unformattable object logged: {error}\n"
            u"Recoverable data: {text}\n"
            u"Exception during formatting:\n{failure}"
            .format(error=safe_repr(error), failure=failure, text=text)
        ) 
Example #27
Source File: test_reflect.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_brokenRepr(self):
        """
        L{reflect.safe_repr} returns a string with class name, address, and
        traceback when the repr call failed.
        """
        b = Breakable()
        b.breakRepr = True
        bRepr = reflect.safe_repr(b)
        self.assertIn("Breakable instance at 0x", bRepr)
        # Check that the file is in the repr, but without the extension as it
        # can be .py/.pyc
        self.assertIn(os.path.splitext(__file__)[0], bRepr)
        self.assertIn("RuntimeError: repr!", bRepr) 
Example #28
Source File: test_reflect.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_brokenStr(self):
        """
        L{reflect.safe_repr} isn't affected by a broken C{__str__} method.
        """
        b = Breakable()
        b.breakStr = True
        self.assertEqual(reflect.safe_repr(b), repr(b)) 
Example #29
Source File: test_reflect.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_brokenClassRepr(self):
        class X(BTBase):
            breakRepr = True
        reflect.safe_repr(X)
        reflect.safe_repr(X()) 
Example #30
Source File: test_reflect.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_brokenReprIncludesID(self):
        """
        C{id} is used to print the ID of the object in case of an error.

        L{safe_repr} includes a traceback after a newline, so we only check
        against the first line of the repr.
        """
        class X(BTBase):
            breakRepr = True

        xRepr = reflect.safe_repr(X)
        xReprExpected = ('<BrokenType instance at 0x%x with repr error:'
                         % (id(X),))
        self.assertEqual(xReprExpected, xRepr.split('\n')[0])