Python twisted.python.reflect.fullyQualifiedName() Examples

The following are 27 code examples of twisted.python.reflect.fullyQualifiedName(). 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_regionservice.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_start_up_logs_failure_if_all_endpoint_options_fail(self):
        service = RegionService(sentinel.ipcWorker)

        error_1 = factory.make_exception_type()
        error_2 = factory.make_exception_type()

        endpoint_1 = Mock()
        endpoint_1.listen.return_value = fail(error_1())
        endpoint_2 = Mock()
        endpoint_2.listen.return_value = fail(error_2())
        service.endpoints = [[endpoint_1, endpoint_2]]

        with TwistedLoggerFixture() as logger:
            yield service.startService()

        self.assertDocTestMatches(
            """\
            RegionServer endpoint failed to listen.
            Traceback (most recent call last):
            ...
            %s:
            """
            % fullyQualifiedName(error_2),
            logger.output,
        ) 
Example #2
Source File: test_worker.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_runErrorWithFrames(self):
        """
        L{LocalWorkerAMP._buildFailure} recreates the C{Failure.frames} from
        the C{frames} argument passed to C{AddError}.
        """
        results = []
        errorClass = fullyQualifiedName(ValueError)
        d = self.worker.callRemote(managercommands.AddError,
                                   testName=self.testName, error=b'error',
                                   errorClass=errorClass.encode("ascii"),
                                   frames=[b"file.py", b"invalid code", b"3"])
        d.addCallback(lambda result: results.append(result['success']))
        self.pumpTransports()

        self.assertEqual(self.testCase, self.result.errors[0][0])
        self.assertEqual(
            [(b'file.py', b'invalid code', 3, [], [])],
            self.result.errors[0][1].frames)
        self.assertTrue(results) 
Example #3
Source File: _oldstyle.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _ensureOldClass(cls):
    """
    Ensure that C{cls} is an old-style class.

    @param cls: The class to check.

    @return: The class, if it is an old-style class.
    @raises: L{ValueError} if it is a new-style class.
    """
    if not type(cls) is types.ClassType:
        from twisted.python.reflect import fullyQualifiedName

        raise ValueError(
            ("twisted.python._oldstyle._oldStyle is being used to decorate a "
             "new-style class ({cls}). This should only be used to "
             "decorate old-style classes.").format(
                 cls=fullyQualifiedName(cls)))

    return cls 
Example #4
Source File: test_ssl.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def getHandleErrorCode(self):
        """
        Return the argument L{SSL.Error} will be constructed with for this
        case.  This is basically just a random OpenSSL implementation detail.
        It would be better if this test worked in a way which did not require
        this.
        """
        # Windows 2000 SP 4 and Windows XP SP 2 give back WSAENOTSOCK for
        # SSL.Connection.write for some reason.  The twisted.protocols.tls
        # implementation of IReactorSSL doesn't suffer from this imprecation,
        # though, since it is isolated from the Windows I/O layer (I suppose?).

        # If test_properlyCloseFiles waited for the SSL handshake to complete
        # and performed an orderly shutdown, then this would probably be a
        # little less weird: writing to a shutdown SSL connection has a more
        # well-defined failure mode (or at least it should).
        name = fullyQualifiedName(getClass(reactor))
        if platform.getType() == 'win32' and name != self._iocp:
            return errno.WSAENOTSOCK
        # This is terribly implementation-specific.
        return [('SSL routines', 'SSL_write', 'protocol is shutdown')] 
Example #5
Source File: tuntap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def doRead(self):
        """
        Called when my socket is ready for reading.
        """
        read = 0
        while read < self.maxThroughput:
            try:
                data = self._system.read(self._fileno, self.maxPacketSize)
            except EnvironmentError as e:
                if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EINTR):
                    return
                else:
                    raise
            except:
                raise
            read += len(data)
            # TODO pkt.isPartial()?
            try:
                self.protocol.datagramReceived(data, partial=0)
            except:
                cls = fullyQualifiedName(self.protocol.__class__)
                log.err(
                    None,
                    "Unhandled exception from %s.datagramReceived" % (cls,)) 
Example #6
Source File: test_worker.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_runErrorWithFrames(self):
        """
        L{LocalWorkerAMP._buildFailure} recreates the C{Failure.frames} from
        the C{frames} argument passed to C{AddError}.
        """
        results = []
        errorClass = fullyQualifiedName(ValueError)
        d = self.worker.callRemote(managercommands.AddError,
                                   testName=self.testName, error='error',
                                   errorClass=errorClass,
                                   frames=["file.py", "invalid code", "3"])
        d.addCallback(lambda result: results.append(result['success']))
        self.pumpTransports()

        self.assertEqual(self.testCase, self.result.errors[0][0])
        self.assertEqual(
            [('file.py', 'invalid code', 3, [], [])],
            self.result.errors[0][1].frames)
        self.assertTrue(results) 
Example #7
Source File: tuntap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def doRead(self):
        """
        Called when my socket is ready for reading.
        """
        read = 0
        while read < self.maxThroughput:
            try:
                data = self._system.read(self._fileno, self.maxPacketSize)
            except EnvironmentError as e:
                if e.errno in (errno.EWOULDBLOCK, errno.EAGAIN, errno.EINTR):
                    return
                else:
                    raise
            except:
                raise
            read += len(data)
            # TODO pkt.isPartial()?
            try:
                self.protocol.datagramReceived(data, partial=0)
            except:
                cls = fullyQualifiedName(self.protocol.__class__)
                log.err(
                    None,
                    "Unhandled exception from %s.datagramReceived" % (cls,)) 
Example #8
Source File: test_worker.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_runFailure(self):
        """
        Run a test, and fail.
        """
        results = []
        failClass = fullyQualifiedName(RuntimeError)
        d = self.worker.callRemote(managercommands.AddFailure,
                                   testName=self.testName, fail='fail',
                                   failClass=failClass,
                                   frames=[])
        d.addCallback(lambda result: results.append(result['success']))
        self.pumpTransports()

        self.assertEqual(self.testCase, self.result.failures[0][0])
        self.assertTrue(results) 
Example #9
Source File: clusterservice.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _fetch_rpc_info(self, url, orig_url):
        def catch_503_error(failure):
            # Catch `twisted.web.error.Error` if has a 503 status code. That
            # means the region is not all the way up. Ignore the error as this
            # service will try again after the calculated interval.
            failure.trap(web.error.Error)
            if failure.value.status != "503":
                failure.raiseException()
            else:
                return ({"eventloops": None}, orig_url)

        def read_body(response):
            # Read the body of the response and convert it to JSON.
            d = Deferred()
            protocol = _ReadBodyProtocol(response.code, response.phrase, d)
            response.deliverBody(protocol)
            d.addCallback(
                lambda data: (json.loads(data.decode("utf-8")), orig_url)
            )
            return d

        # Request the RPC information.
        agent = Agent(reactor)
        d = agent.request(
            b"GET",
            url,
            Headers(
                {
                    b"User-Agent": [fullyQualifiedName(type(self))],
                    b"Host": [get_domain(orig_url)],
                }
            ),
        )
        d.addCallback(read_body)
        d.addErrback(catch_503_error)

        # Timeout making HTTP request after 5 seconds.
        self.clock.callLater(5, d.cancel)

        return d 
Example #10
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_method(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a method inside its
        class and its module.
        """
        self._checkFullyQualifiedName(reflect.PropertyAccessor.reallyDel,
            "twisted.python.reflect.PropertyAccessor.reallyDel")
        self._checkFullyQualifiedName(reflect.PropertyAccessor().reallyDel,
            "twisted.python.reflect.PropertyAccessor.reallyDel") 
Example #11
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_class(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a class and its
        module.
        """
        self._checkFullyQualifiedName(reflect.Settable,
                                      'twisted.python.reflect.Settable') 
Example #12
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_module(self):
        """
        L{reflect.fullyQualifiedName} returns the name of a module inside a a
        package.
        """
        self._checkFullyQualifiedName(reflect, 'twisted.python.reflect')
        import twisted.trial.unittest
        self._checkFullyQualifiedName(twisted.trial.unittest,
                                      'twisted.trial.unittest') 
Example #13
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_package(self):
        """
        L{reflect.fullyQualifiedName} returns the full name of a package and
        a subpackage.
        """
        import twisted
        self._checkFullyQualifiedName(twisted, 'twisted')
        import twisted.python
        self._checkFullyQualifiedName(twisted.python, 'twisted.python') 
Example #14
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _checkFullyQualifiedName(self, obj, expected):
        """
        Helper to check that fully qualified name of C{obj} results to
        C{expected}.
        """
        self.assertEquals(
            reflect.fullyQualifiedName(obj), expected) 
Example #15
Source File: test_deprecate.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_deprecatedPreservesName(self):
        """
        The decorated function has the same name as the original.
        """
        version = Version('Twisted', 8, 0, 0)
        dummy = deprecated(version)(dummyCallable)
        self.assertEqual(dummyCallable.__name__, dummy.__name__)
        self.assertEqual(fullyQualifiedName(dummyCallable),
                         fullyQualifiedName(dummy)) 
Example #16
Source File: tuntap.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def __repr__(self):
        args = (fullyQualifiedName(self.protocol.__class__),)
        if self.connected:
            args = args + ("",)
        else:
            args = args + ("not ",)
        args = args + (self._mode.name, self.interface)
        return "<%s %slistening on %s/%s>" % args 
Example #17
Source File: test_failure.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_repr(self):
        """
        The C{repr} of a L{failure.Failure} shows the type and string
        representation of the underlying exception.
        """
        f = getDivisionFailure()
        typeName = reflect.fullyQualifiedName(ZeroDivisionError)
        self.assertEqual(
            repr(f),
            '<twisted.python.failure.Failure '
            '%s: division by zero>' % (typeName,)) 
Example #18
Source File: test_nooldstyle.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_newStyleClassesOnly(self):
        """
        Test that C{self.module} has no old-style classes in it.
        """
        try:
            module = namedAny(self.module)
        except ImportError as e:
            raise unittest.SkipTest("Not importable: {}".format(e))

        oldStyleClasses = []

        for name, val in inspect.getmembers(module):
            if hasattr(val, "__module__") \
               and val.__module__ == self.module:
                if isinstance(val, types.ClassType):
                    oldStyleClasses.append(fullyQualifiedName(val))

        if oldStyleClasses:

            self.todo = "Not all classes are made new-style yet. See #8243."

            for x in forbiddenModules:
                if self.module.startswith(x):
                    delattr(self, "todo")

            raise unittest.FailTest(
                "Old-style classes in {module}: {val}".format(
                    module=self.module,
                    val=", ".join(oldStyleClasses))) 
Example #19
Source File: util.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def type(self, request, tag):
        """
        Render the exception type as a child of C{tag}.
        """
        return tag(fullyQualifiedName(self.failure.type)) 
Example #20
Source File: test_worker.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_runError(self):
        """
        Run a test, and encounter an error.
        """
        results = []
        errorClass = fullyQualifiedName(ValueError)
        d = self.worker.callRemote(managercommands.AddError,
                                   testName=self.testName, error='error',
                                   errorClass=errorClass,
                                   frames=[])
        d.addCallback(lambda result: results.append(result['success']))
        self.pumpTransports()

        self.assertEqual(self.testCase, self.result.errors[0][0])
        self.assertTrue(results) 
Example #21
Source File: _newclient.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _callAppFunction(function):
    """
    Call C{function}.  If it raises an exception, log it with a minimal
    description of the source.

    @return: L{None}
    """
    try:
        function()
    except:
        _moduleLog.failure(
            u"Unexpected exception from {name}",
            name=fullyQualifiedName(function)
        ) 
Example #22
Source File: util.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def type(self, request, tag):
        """
        Render the exception type as a child of C{tag}.
        """
        return tag(fullyQualifiedName(self.failure.type)) 
Example #23
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 #24
Source File: _libcloud.py    From flocker with Apache License 2.0 5 votes vote down vote up
def _retry_exception(f, steps=(0.1,) * 10, sleep=sleep):
    """
    Retry a function if it raises an exception.

    :return: Whatever the function returns.
    """
    steps = iter(steps)

    while True:
        try:
            Message.new(
                message_type=(
                    u"flocker:provision:libcloud:retry_exception:trying"
                ),
                function=fullyQualifiedName(f),
            ).write()
            return f()
        except:
            # Try to get the next sleep time from the steps iterator.  Do it
            # without raising an exception (StopIteration) to preserve the
            # current exception context.
            for step in steps:
                write_traceback()
                sleep(step)
                break
            else:
                # Didn't hit the break, so didn't iterate at all, so we're out
                # of retry steps.  Fail now.
                raise 
Example #25
Source File: tuntap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __repr__(self):
        args = (fullyQualifiedName(self.protocol.__class__),)
        if self.connected:
            args = args + ("",)
        else:
            args = args + ("not ",)
        args = args + (self._mode.name, self.interface)
        return "<%s %slistening on %s/%s>" % args 
Example #26
Source File: test_worker.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_runFailure(self):
        """
        Run a test, and fail.
        """
        results = []
        failClass = fullyQualifiedName(RuntimeError)
        d = self.worker.callRemote(managercommands.AddFailure,
                                   testName=self.testName, fail=b'fail',
                                   failClass=failClass.encode("ascii"),
                                   frames=[])
        d.addCallback(lambda result: results.append(result['success']))
        self.pumpTransports()

        self.assertEqual(self.testCase, self.result.failures[0][0])
        self.assertTrue(results) 
Example #27
Source File: test_worker.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_runError(self):
        """
        Run a test, and encounter an error.
        """
        results = []
        errorClass = fullyQualifiedName(ValueError)
        d = self.worker.callRemote(managercommands.AddError,
                                   testName=self.testName, error=b'error',
                                   errorClass=errorClass.encode("ascii"),
                                   frames=[])
        d.addCallback(lambda result: results.append(result['success']))
        self.pumpTransports()

        self.assertEqual(self.testCase, self.result.errors[0][0])
        self.assertTrue(results)