示例#1
0
    def test_noBytesResult(self):
        """
        When implemented C{render} method does not return bytes an internal
        server error is returned.
        """
        class RiggedRepr(object):
            def __repr__(self):
                return 'my>repr'

        result = RiggedRepr()
        no_bytes_resource = resource.Resource()
        no_bytes_resource.render = lambda request: result
        request = self._getReq(no_bytes_resource)

        request.requestReceived(b"GET", b"/newrender", b"HTTP/1.0")

        body = request._transport.getvalue()
        self.assertEqual(request.code, 500)
        expected = [
            '', '<html>',
            '  <head><title>500 - Request did not return bytes</title></head>',
            '  <body>', '    <h1>Request did not return bytes</h1>',
            '    <p>Request: <pre>&lt;%s&gt;</pre><br />'
            'Resource: <pre>&lt;%s&gt;</pre><br />'
            'Value: <pre>my&gt;repr</pre></p>' % (
                reflect.safe_repr(request)[1:-1],
                reflect.safe_repr(no_bytes_resource)[1:-1],
            ), '  </body>', '</html>', ''
        ]
        self.assertEqual('\n'.join(expected).encode('ascii'), body)
示例#2
0
文件: task.py 项目: giadram/twisted
 def __repr__(self) -> str:
     return "LoopingCall<{!r}>({}, *{}, **{})".format(
         self.interval,
         self.f.__qualname__,
         reflect.safe_repr(self.a),
         reflect.safe_repr(self.kw),
     )
示例#3
0
 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' %
          (util.unsignedID(self), self.time - now, self.called, self.cancelled)]
     if func is not None:
         L.extend((' ', func, '('))
         if self.a:
             L.append(', '.join([reflect.safe_repr(e) for e in self.a]))
             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)
示例#4
0
文件: base.py 项目: emragins/tribal
    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 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)
示例#5
0
    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
示例#6
0
def formatUnformattableEvent(event: LogEvent, error: BaseException) -> str:
    """
    Formats an event as text that describes the event generically and a
    formatting error.

    @param event: A logging event.
    @param error: The formatting error.

    @return: A formatted string.
    """
    try:
        return "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 = ", ".join(" = ".join((safe_repr(key), safe_repr(value)))
                         for key, value in event.items())

        return ("MESSAGE LOST: unformattable object logged: {error}\n"
                "Recoverable data: {text}\n"
                "Exception during formatting:\n{failure}".format(
                    error=safe_repr(error), failure=failure, text=text))
示例#7
0
    def _renderCallback(self, result, resrc):
        body = result
        if type(body) is not types.StringType:
            self.warning('request did not return a string but %r' %
                type(body))
            body = self._error(INTERNAL_SERVER_ERROR,
                "Request did not return a string",
                "Request: " + reflect.safe_repr(self),
                "Resource: " + reflect.safe_repr(resrc),
                "Value: " + reflect.safe_repr(body))
        self.setHeader('Content-Length', str(len(body)))

        lines = []
        for key, value in self.headers.items():
            lines.append("%s: %s" % (key, value))
        # FIXME: debug response code
        self.debug('responding to %s %s with %s (%d)' % (
            self.method, self.path, self.code_message, self.code))
        self.debug('outgoing headers:\n%s\n' % "\n".join(lines))
        if body:
            self.debug('body:\n%s\n' % body)
        self.log('RTSPRequest._renderCallback(): outgoing response:\n%s\n' %
            "\n".join(lines))
        self.log("\n".join(lines))
        self.log("\n")
        self.log(body)

        self.channel.site.logReply(self.code, self.code_message, lines, body)

        self.write(body)
        self.finish()
示例#8
0
def error_page(request, resrc, value, tb=None):
    result = "Request: %s<br />\nResource: %s<br />\nValue: %s" % (
        html.PRE(reflect.safe_repr(request)),
        html.PRE(reflect.safe_repr(resrc)),
        html.PRE(reflect.safe_repr(value)),
    )
    if tb:
        result += '\n%s' % html.PRE(reflect.safe_str(tb))
    return result
示例#9
0
    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 'ScheduledCall<%s>(%s, *%s, **%s)' % (
            self.schedule, func, reflect.safe_repr(
                self.a), reflect.safe_repr(self.kw))
    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))
示例#11
0
文件: task.py 项目: apjanke/twisted
    def __repr__(self) -> str:
        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),
        )
示例#12
0
文件: test_reflect.py 项目: DT021/wau
 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))
示例#13
0
 def trace_EXCEPTION(self, frame, arg):
     print("%X %s^- %s" % (
         id(threading.currentThread()),
         self.callDepth * ' ',
         reflect.safe_repr(arg),
     ))
     self.callDepth = max(0, self.callDepth - 1)
示例#14
0
 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))
示例#15
0
    def __repr__(self) -> str:
        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}>({}, *{}, **{})".format(
            self.interval,
            func,
            reflect.safe_repr(self.a),
            reflect.safe_repr(self.kw),
        )
示例#16
0
文件: base.py 项目: giadram/twisted
    def __repr__(self) -> str:
        """
        Implement C{repr()} for L{DelayedCall} instances.

        @returns: String containing details of the L{DelayedCall}.
        """
        if self._repr is not None:
            return self._repr

        now = self.seconds()
        L = [
            "<DelayedCall 0x%x [%ss] called=%s cancelled=%s" %
            (id(self), self.time - now, self.called, self.cancelled)
        ]
        if hasattr(self, "func"):
            L.extend((" ", self.func.__qualname__, "("))
            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([
                    f"{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)
示例#17
0
    def __repr__(self):
        """
        Implement C{repr()} for L{DelayedCall} instances.

        @rtype: C{str}
        @returns: String containing details of the L{DelayedCall}.
        """
        if self._repr is not None:
            return self._repr
        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)
示例#18
0
    def __repr__(self) -> str:
        """
        Implement C{repr()} for L{DelayedCall} instances.

        @returns: String containing details of the L{DelayedCall}.
        """
        if self._repr is not None:
            return self._repr
        if hasattr(self, "func"):
            # This code should be replaced by a utility function in reflect;
            # see ticket #6066:
            func = getattr(self.func, "__qualname__", None)
            if func is None:
                func = getattr(self.func, "__name__", None)
                if func is not None:
                    imClass = getattr(self.func, "im_class", None)
                    if imClass is not None:
                        func = f"{imClass}.{func}"
            if func is None:
                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([
                    f"{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)
示例#19
0
 def trace_RETURN(self, frame, arg):
     if arg is not None:
         print("%X %s<= %s" % (
             id(threading.currentThread()),
             self.callDepth * ' ',
             reflect.safe_repr(arg),
         ))
     self.callDepth = max(0, self.callDepth - 1)
示例#20
0
    def __repr__(self) -> str:
        # This code should be replaced by a utility function in reflect;
        # see ticket #6066:
        func = getattr(self.f, "__qualname__", None)
        if func is None:
            func = getattr(self.f, "__name__", None)
            if func is not None:
                imClass = getattr(self.f, "im_class", None)
                if imClass is not None:
                    func = f"{imClass}.{func}"
        if func is None:
            func = reflect.safe_repr(self.f)

        return "LoopingCall<{!r}>({}, *{}, **{})".format(
            self.interval,
            func,
            reflect.safe_repr(self.a),
            reflect.safe_repr(self.kw),
        )
示例#21
0
文件: test_reflect.py 项目: DT021/wau
 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)
示例#22
0
 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)
示例#23
0
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]
示例#24
0
    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 = f"<BrokenType instance at 0x{id(X):x} with repr error:"
        self.assertEqual(xReprExpected, xRepr.split("\n")[0])
示例#25
0
文件: test_reflect.py 项目: DT021/wau
 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)
示例#26
0
    def useChangedSettings(self, config):
        """Take a new config, compare it to the last one, and update settings.

        Given a ``config`` object created from the configuration file, compare
        it to the last :class:`~bridgedb.configure.Conf` that was stored, and apply
        any settings which were changed to be attributes of the :class:`State`
        instance.
        """
        updated = []
        new = []

        for key, value in config.__dict__.items():
            try:
                # If state.config doesn't have the same value as the new
                # config, then update the state setting.
                #
                # Be sure, when updating settings while parsing the config
                # file, to assign the new settings as attributes of the
                # :class:`bridgedb.configure.Conf` instance.
                if value != self.config.__dict__[key]:
                    setattr(self, key, value)
                    updated.append(key)
                    logging.debug("Updated %s setting: %r → %r" %
                                  (safe_repr(key), self.config.__dict__[key],
                                   safe_repr(value)))
            except (KeyError, AttributeError):
                setattr(self, key, value)
                new.append(key)
                logging.debug("New setting: %s = %r" %
                              (safe_repr(key), safe_repr(value)))

        logging.info("Updated setting(s): %s" % ' '.join([x for x in updated]))
        logging.info("New setting(s): %s" % ' '.join([x for x in new]))
        logging.debug(
            "Saving newer config as `state.config` for later comparison")
        self.config = config
示例#27
0
    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)
示例#28
0
    def render(self, resrc):
        """
        Ask a resource to render itself.

        @param resrc: a L{twisted.web.resource.IResource}.
        """
        try:
            body = resrc.render(self)
        except UnsupportedMethod as e:
            allowedMethods = e.allowedMethods
            if (self.method == b"HEAD") and (b"GET" in allowedMethods):
                # We must support HEAD (RFC 2616, 5.1.1).  If the
                # resource doesn't, fake it by giving the resource
                # a 'GET' request and then return only the headers,
                # not the body.
                log.msg("Using GET to fake a HEAD request for %s" % (resrc, ))
                self.method = b"GET"
                self._inFakeHead = True
                body = resrc.render(self)

                if body is NOT_DONE_YET:
                    log.msg("Tried to fake a HEAD request for %s, but "
                            "it got away from me." % resrc)
                    # Oh well, I guess we won't include the content length.
                else:
                    self.setHeader(b'content-length', intToBytes(len(body)))

                self._inFakeHead = False
                self.method = b"HEAD"
                self.write(b'')
                self.finish()
                return

            if self.method in (supportedMethods):
                # We MUST include an Allow header
                # (RFC 2616, 10.4.6 and 14.7)
                self.setHeader('Allow', ', '.join(allowedMethods))
                s = ('''Your browser approached me (at %(URI)s) with'''
                     ''' the method "%(method)s".  I only allow'''
                     ''' the method%(plural)s %(allowed)s here.''' % {
                         'URI': escape(self.uri),
                         'method': self.method,
                         'plural': ((len(allowedMethods) > 1) and 's') or '',
                         'allowed': ', '.join(allowedMethods)
                     })
                epage = resource.ErrorPage(http.NOT_ALLOWED,
                                           "Method Not Allowed", s)
                body = epage.render(self)
            else:
                epage = resource.ErrorPage(
                    http.NOT_IMPLEMENTED, "Huh?",
                    "I don't know how to treat a %s request." %
                    (escape(self.method.decode("charmap")), ))
                body = epage.render(self)
        # end except UnsupportedMethod

        if body == NOT_DONE_YET:
            return
        if not isinstance(body, bytes):
            body = resource.ErrorPage(
                http.INTERNAL_SERVER_ERROR, "Request did not return bytes",
                "Request: " + html.PRE(reflect.safe_repr(self)) + "<br />" +
                "Resource: " + html.PRE(reflect.safe_repr(resrc)) + "<br />" +
                "Value: " + html.PRE(reflect.safe_repr(body))).render(self)

        if self.method == b"HEAD":
            if len(body) > 0:
                # This is a Bad Thing (RFC 2616, 9.4)
                log.msg("Warning: HEAD request %s for resource %s is"
                        " returning a message body."
                        "  I think I'll eat it." % (self, resrc))
                self.setHeader(b'content-length', intToBytes(len(body)))
            self.write(b'')
        else:
            self.setHeader(b'content-length', intToBytes(len(body)))
            self.write(body)
        self.finish()
示例#29
0
def formatArgs(args):
    return ', '.join(
        ['='.join((k, reflect.safe_repr(v))) for (k, v) in args.items()])
示例#30
0
文件: test_reflect.py 项目: DT021/wau
    def test_brokenClassStr(self):
        class X(BTBase):
            breakStr = True

        reflect.safe_repr(X)
        reflect.safe_repr(X())