Python twisted.internet.defer.TimeoutError() Examples

The following are 30 code examples of twisted.internet.defer.TimeoutError(). 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.internet.defer , or try the search function .
Example #1
Source File: test_defer.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_errbackAddedBeforeTimeout(self):
        """
        An errback added before a timeout is added errbacks with a
        L{defer.CancelledError} when the timeout fires.  If the
        errback returns the L{defer.CancelledError}, it is translated
        to a L{defer.TimeoutError} by the timeout implementation.
        """
        clock = Clock()
        d = defer.Deferred()

        dErrbacked = [None]

        def errback(f):
            dErrbacked[0] = f
            return f

        d.addErrback(errback)
        d.addTimeout(10, clock)

        clock.advance(15)

        self.assertIsInstance(dErrbacked[0], failure.Failure)
        self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)

        self.failureResultOf(d, defer.TimeoutError) 
Example #2
Source File: test_memcache.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_timeOut(self):
        """
        Test the timeout on outgoing requests: when timeout is detected, all
        current commands fail with a L{TimeoutError}, and the connection is
        closed.
        """
        d1 = self.proto.get("foo")
        d2 = self.proto.get("bar")
        d3 = Deferred()
        self.proto.connectionLost = d3.callback

        self.clock.advance(self.proto.persistentTimeOut)
        self.assertFailure(d1, TimeoutError)
        self.assertFailure(d2, TimeoutError)
        def checkMessage(error):
            self.assertEquals(str(error), "Connection timeout")
        d1.addCallback(checkMessage)
        return gatherResults([d1, d2, d3]) 
Example #3
Source File: test_memcache.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_timeOut(self):
        """
        Test the timeout on outgoing requests: when timeout is detected, all
        current commands fail with a L{TimeoutError}, and the connection is
        closed.
        """
        d1 = self.proto.get(b"foo")
        d2 = self.proto.get(b"bar")
        d3 = Deferred()
        self.proto.connectionLost = d3.callback

        self.clock.advance(self.proto.persistentTimeOut)
        self.assertFailure(d1, TimeoutError)
        self.assertFailure(d2, TimeoutError)

        def checkMessage(error):
            self.assertEqual(str(error), "Connection timeout")

        d1.addCallback(checkMessage)
        self.assertFailure(d3, ConnectionDone)
        return gatherResults([d1, d2, d3]) 
Example #4
Source File: test_webclient.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_downloadTimeout(self):
        """
        If the timeout indicated by the C{timeout} parameter to
        L{client.HTTPDownloader.__init__} elapses without the complete response
        being received, the L{defer.Deferred} returned by
        L{client.downloadPage} fires with a L{Failure} wrapping a
        L{defer.TimeoutError}.
        """
        self.cleanupServerConnections = 2
        # Verify the behavior if no bytes are ever written.
        first = client.downloadPage(
            self.getURL("wait"),
            self.mktemp(), timeout=0.01)

        # Verify the behavior if some bytes are written but then the request
        # never completes.
        second = client.downloadPage(
            self.getURL("write-then-wait"),
            self.mktemp(), timeout=0.01)

        return defer.gatherResults([
            self.assertFailure(first, defer.TimeoutError),
            self.assertFailure(second, defer.TimeoutError)]) 
Example #5
Source File: test_webclient.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_downloadTimeoutsWorkWithoutReading(self):
        """
        If the timeout indicated by the C{timeout} parameter to
        L{client.HTTPDownloader.__init__} elapses without the complete response
        being received, the L{defer.Deferred} returned by
        L{client.downloadPage} fires with a L{Failure} wrapping a
        L{defer.TimeoutError}, even if the remote peer isn't reading data from
        the socket.
        """
        self.cleanupServerConnections = 1

        # The timeout here needs to be slightly longer to give the resource a
        # change to stop the reading.
        d = client.downloadPage(
            self.getURL("never-read"),
            self.mktemp(), timeout=0.05)
        return self.assertFailure(d, defer.TimeoutError) 
Example #6
Source File: test_client.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _ebRoundRobinBackoff(self, failure, fakeProto):
        failure.trap(defer.TimeoutError)

        # Assert that each server is tried with a particular timeout
        # before the timeout is increased and the attempts are repeated.

        for t in (1, 3, 11, 45):
            tries = fakeProto.queries[:len(self.testServers)]
            del fakeProto.queries[:len(self.testServers)]

            tries.sort()
            expected = list(self.testServers)
            expected.sort()

            for ((addr, query, timeout, id), expectedAddr) in zip(tries, expected):
                self.assertEqual(addr, (expectedAddr, 53))
                self.assertEqual(timeout, t)

        self.assertFalse(fakeProto.queries) 
Example #7
Source File: test_defer.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_waitUntilLockedWithTimeoutUnlocked(self):
        """
        Test that a lock can be acquired while a lock is held
        but the lock is unlocked before our timeout.
        """
        def onTimeout(f):
            f.trap(defer.TimeoutError)
            self.fail("Should not have timed out")

        self.failUnless(self.lock.lock())

        self.clock.callLater(1, self.lock.unlock)
        d = self.lock.deferUntilLocked(timeout=10)
        d.addErrback(onTimeout)

        self.clock.pump([1] * 10)

        return d 
Example #8
Source File: test_rootresolve.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_continuesWhenAllRootHintsFail(self):
        """
        The L{root.Resolver} is eventually created, even if all of the root hint
        lookups fail. Pending and new lookups will then fail with
        AttributeError.
        """
        stubResolver = StubResolver()
        deferredResolver = root.bootstrap(stubResolver)
        results = iter(stubResolver.pendingResults)
        d1 = next(results)
        for d in results:
            d.errback(TimeoutError())
        d1.errback(TimeoutError())

        def checkHints(res):
            self.assertEqual(deferredResolver.hints, [])
        d1.addBoth(checkHints)

        self.addCleanup(self.flushLoggedErrors, TimeoutError) 
Example #9
Source File: test_rootresolve.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_continuesWhenSomeRootHintsFail(self):
        """
        The L{root.Resolver} is eventually created, even if some of the root
        hint lookups fail. Only the working root hint IP addresses are supplied
        to the L{root.Resolver}.
        """
        stubResolver = StubResolver()
        deferredResolver = root.bootstrap(stubResolver)
        results = iter(stubResolver.pendingResults)
        d1 = next(results)
        for d in results:
            d.callback('192.0.2.101')
        d1.errback(TimeoutError())

        def checkHints(res):
            self.assertEqual(deferredResolver.hints, ['192.0.2.101'] * 12)
        d1.addBoth(checkHints) 
Example #10
Source File: test_names.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _ebRoundRobinBackoff(self, failure, fakeProto):
        failure.trap(defer.TimeoutError)

        # Assert that each server is tried with a particular timeout
        # before the timeout is increased and the attempts are repeated.

        for t in (1, 3, 11, 45):
            tries = fakeProto.queries[:len(self.testServers)]
            del fakeProto.queries[:len(self.testServers)]

            tries.sort()
            expected = list(self.testServers)
            expected.sort()

            for ((addr, query, timeout, id), expectedAddr) in zip(tries, expected):
                self.assertEquals(addr, (expectedAddr, 53))
                self.assertEquals(timeout, t)

        self.failIf(fakeProto.queries) 
Example #11
Source File: test_memcache.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_timeoutNotReset(self):
        """
        Check that timeout is not resetted for every command, but keep the
        timeout from the first command without response.
        """
        d1 = self.proto.get(b"foo")
        d3 = Deferred()
        self.proto.connectionLost = d3.callback

        self.clock.advance(self.proto.persistentTimeOut - 1)
        d2 = self.proto.get(b"bar")
        self.clock.advance(1)
        self.assertFailure(d1, TimeoutError)
        self.assertFailure(d2, TimeoutError)
        self.assertFailure(d3, ConnectionDone)
        return gatherResults([d1, d2, d3]) 
Example #12
Source File: root.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def retry(t, p, *args):
    """
    Issue a query one or more times.

    This function is deprecated.  Use one of the resolver classes for retry
    logic, or implement it yourself.
    """
    warnings.warn(
        "twisted.names.root.retry is deprecated since Twisted 10.0.  Use a "
        "Resolver object for retry logic.", category=DeprecationWarning,
        stacklevel=2)

    assert t, "Timeout is required"
    t = list(t)
    def errback(failure):
        failure.trap(defer.TimeoutError)
        if not t:
            return failure
        return p.query(timeout=t.pop(0), *args
            ).addErrback(errback
            )
    return p.query(timeout=t.pop(0), *args
        ).addErrback(errback
        ) 
Example #13
Source File: test_defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_errbackAddedBeforeTimeout(self):
        """
        An errback added before a timeout is added errbacks with a
        L{defer.CancelledError} when the timeout fires.  If the
        errback returns the L{defer.CancelledError}, it is translated
        to a L{defer.TimeoutError} by the timeout implementation.
        """
        clock = Clock()
        d = defer.Deferred()

        dErrbacked = [None]

        def errback(f):
            dErrbacked[0] = f
            return f

        d.addErrback(errback)
        d.addTimeout(10, clock)

        clock.advance(15)

        self.assertIsInstance(dErrbacked[0], failure.Failure)
        self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)

        self.failureResultOf(d, defer.TimeoutError) 
Example #14
Source File: test_webclient.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_downloadTimeout(self):
        """
        If the timeout indicated by the C{timeout} parameter to
        L{client.HTTPDownloader.__init__} elapses without the complete response
        being received, the L{defer.Deferred} returned by
        L{client.downloadPage} fires with a L{Failure} wrapping a
        L{defer.TimeoutError}.
        """
        self.cleanupServerConnections = 2
        # Verify the behavior if no bytes are ever written.
        first = client.downloadPage(
            self.getURL("wait"),
            self.mktemp(), timeout=0.01)

        # Verify the behavior if some bytes are written but then the request
        # never completes.
        second = client.downloadPage(
            self.getURL("write-then-wait"),
            self.mktemp(), timeout=0.01)

        return defer.gatherResults([
            self.assertFailure(first, defer.TimeoutError),
            self.assertFailure(second, defer.TimeoutError)]) 
Example #15
Source File: test_ftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_connectionFailedAfterTimeout(self):
        """
        If L{ftp.DTPFactory.clientConnectionFailed} is called after the timeout
        specified by L{ftp.DTPFactory.setTimeout} has elapsed, nothing beyond
        the normal timeout before happens.
        """
        # Handle the error so it doesn't get logged.
        d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError)

        # Set up the timeout and then cause it to elapse so the Deferred does
        # fail.
        self.factory.setTimeout(10)
        self.reactor.advance(10)

        # Now fail the connection attempt.  This should do nothing.  In
        # particular, it should not raise an exception.
        self.factory.clientConnectionFailed(None, defer.TimeoutError("foo"))

        # Give the Deferred to trial so it can make sure it did what we
        # expected.
        return d



# -- Client Tests ----------------------------------------------------------- 
Example #16
Source File: test_defer.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_waitUntilLockedWithTimeoutUnlocked(self):
        """
        Test that a lock can be acquired while a lock is held
        but the lock is unlocked before our timeout.
        """
        def onTimeout(f):
            f.trap(defer.TimeoutError)
            self.fail("Should not have timed out")

        self.assertTrue(self.lock.lock())

        self.clock.callLater(1, self.lock.unlock)
        d = self.lock.deferUntilLocked(timeout=10)
        d.addErrback(onTimeout)

        self.clock.pump([1] * 10)

        return d 
Example #17
Source File: test_memcache.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_timeoutNotReset(self):
        """
        Check that timeout is not resetted for every command, but keep the
        timeout from the first command without response.
        """
        d1 = self.proto.get(b"foo")
        d3 = Deferred()
        self.proto.connectionLost = d3.callback

        self.clock.advance(self.proto.persistentTimeOut - 1)
        d2 = self.proto.get(b"bar")
        self.clock.advance(1)
        self.assertFailure(d1, TimeoutError)
        self.assertFailure(d2, TimeoutError)
        self.assertFailure(d3, ConnectionDone)
        return gatherResults([d1, d2, d3]) 
Example #18
Source File: test_ftp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_connectionFailedAfterTimeout(self):
        """
        If L{ftp.DTPFactory.clientConnectionFailed} is called after the timeout
        specified by L{ftp.DTPFactory.setTimeout} has elapsed, nothing beyond
        the normal timeout before happens.
        """
        # Handle the error so it doesn't get logged.
        d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError)

        # Set up the timeout and then cause it to elapse so the Deferred does
        # fail.
        self.factory.setTimeout(10)
        self.reactor.advance(10)

        # Now fail the connection attempt.  This should do nothing.  In
        # particular, it should not raise an exception.
        self.factory.clientConnectionFailed(None, defer.TimeoutError("foo"))

        # Give the Deferred to trial so it can make sure it did what we
        # expected.
        return d 
Example #19
Source File: test_client.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _ebRoundRobinBackoff(self, failure, fakeProto):
        failure.trap(defer.TimeoutError)

        # Assert that each server is tried with a particular timeout
        # before the timeout is increased and the attempts are repeated.

        for t in (1, 3, 11, 45):
            tries = fakeProto.queries[:len(self.testServers)]
            del fakeProto.queries[:len(self.testServers)]

            tries.sort()
            expected = list(self.testServers)
            expected.sort()

            for ((addr, query, timeout, id), expectedAddr) in zip(tries, expected):
                self.assertEqual(addr, (expectedAddr, 53))
                self.assertEqual(timeout, t)

        self.assertFalse(fakeProto.queries) 
Example #20
Source File: test_rootresolve.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_continuesWhenAllRootHintsFail(self):
        """
        The L{root.Resolver} is eventually created, even if all of the root hint
        lookups fail. Pending and new lookups will then fail with
        AttributeError.
        """
        stubResolver = StubResolver()
        deferredResolver = root.bootstrap(stubResolver)
        results = iter(stubResolver.pendingResults)
        d1 = next(results)
        for d in results:
            d.errback(TimeoutError())
        d1.errback(TimeoutError())

        def checkHints(res):
            self.assertEqual(deferredResolver.hints, [])
        d1.addBoth(checkHints)

        self.addCleanup(self.flushLoggedErrors, TimeoutError) 
Example #21
Source File: test_rootresolve.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_continuesWhenSomeRootHintsFail(self):
        """
        The L{root.Resolver} is eventually created, even if some of the root
        hint lookups fail. Only the working root hint IP addresses are supplied
        to the L{root.Resolver}.
        """
        stubResolver = StubResolver()
        deferredResolver = root.bootstrap(stubResolver)
        results = iter(stubResolver.pendingResults)
        d1 = next(results)
        for d in results:
            d.callback('192.0.2.101')
        d1.errback(TimeoutError())

        def checkHints(res):
            self.assertEqual(deferredResolver.hints, ['192.0.2.101'] * 12)
        d1.addBoth(checkHints) 
Example #22
Source File: deferral.py    From p2pool-n with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        while True:
            id = random.randrange(self.max_id)
            if id not in self.map:
                break
        def cancel(df):
            df, timer = self.map.pop(id)
            timer.cancel()
        try:
            df = defer.Deferred(cancel)
        except TypeError:
            df = defer.Deferred() # handle older versions of Twisted
        def timeout():
            self.map.pop(id)
            df.errback(failure.Failure(defer.TimeoutError('in GenericDeferrer')))
            self.on_timeout()
        timer = reactor.callLater(self.timeout, timeout)
        self.map[id] = df, timer
        self.func(id, *args, **kwargs)
        return df 
Example #23
Source File: test_webclient.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_downloadTimeoutsWorkWithoutReading(self):
        """
        If the timeout indicated by the C{timeout} parameter to
        L{client.HTTPDownloader.__init__} elapses without the complete response
        being received, the L{defer.Deferred} returned by
        L{client.downloadPage} fires with a L{Failure} wrapping a
        L{defer.TimeoutError}, even if the remote peer isn't reading data from
        the socket.
        """
        self.cleanupServerConnections = 1

        # The timeout here needs to be slightly longer to give the resource a
        # change to stop the reading.
        d = client.downloadPage(
            self.getURL("never-read"),
            self.mktemp(), timeout=0.05)
        return self.assertFailure(d, defer.TimeoutError) 
Example #24
Source File: test_webclient.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_downloadTimeout(self):
        """
        If the timeout indicated by the C{timeout} parameter to
        L{client.HTTPDownloader.__init__} elapses without the complete response
        being received, the L{defer.Deferred} returned by
        L{client.downloadPage} fires with a L{Failure} wrapping a
        L{defer.TimeoutError}.
        """
        self.cleanupServerConnections = 2
        # Verify the behavior if no bytes are ever written.
        first = client.downloadPage(
            self.getURL("wait"),
            self.mktemp(), timeout=0.01)

        # Verify the behavior if some bytes are written but then the request
        # never completes.
        second = client.downloadPage(
            self.getURL("write-then-wait"),
            self.mktemp(), timeout=0.01)

        return defer.gatherResults([
            self.assertFailure(first, defer.TimeoutError),
            self.assertFailure(second, defer.TimeoutError)]) 
Example #25
Source File: test_ftp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_connectionFailedAfterTimeout(self):
        """
        If L{ftp.DTPFactory.clientConnectionFailed} is called after the timeout
        specified by L{ftp.DTPFactory.setTimeout} has elapsed, nothing beyond
        the normal timeout before happens.
        """
        # Handle the error so it doesn't get logged.
        d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError)

        # Set up the timeout and then cause it to elapse so the Deferred does
        # fail.
        self.factory.setTimeout(10)
        self.reactor.advance(10)

        # Now fail the connection attempt.  This should do nothing.  In
        # particular, it should not raise an exception.
        self.factory.clientConnectionFailed(None, defer.TimeoutError("foo"))

        # Give the Deferred to trial so it can make sure it did what we
        # expected.
        return d 
Example #26
Source File: test_memcache.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_timeoutNotReset(self):
        """
        Check that timeout is not resetted for every command, but keep the
        timeout from the first command without response.
        """
        d1 = self.proto.get("foo")
        d3 = Deferred()
        self.proto.connectionLost = d3.callback

        self.clock.advance(self.proto.persistentTimeOut - 1)
        d2 = self.proto.get("bar")
        self.clock.advance(1)
        self.assertFailure(d1, TimeoutError)
        self.assertFailure(d2, TimeoutError)
        return gatherResults([d1, d2, d3]) 
Example #27
Source File: client.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def timeout(self):
        self.quietLoss = True
        self.transport.loseConnection()
        self.factory.noPage(defer.TimeoutError("Getting %s took longer than %s seconds." % (self.factory.url, self.factory.timeout))) 
Example #28
Source File: test_defer.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_waitUntilLockedWithTimeoutLocked(self):
        """
        Test that the lock can not be acquired when the lock is held
        for longer than the timeout.
        """
        self.failUnless(self.lock.lock())

        d = self.lock.deferUntilLocked(timeout=5.5)
        self.assertFailure(d, defer.TimeoutError)

        self.clock.pump([1] * 10)

        return d 
Example #29
Source File: test_memcache.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_timeoutCleanDeferreds(self):
        """
        C{timeoutConnection} cleans the list of commands that it fires with
        C{TimeoutError}: C{connectionLost} doesn't try to fire them again, but
        sets the disconnected state so that future commands fail with a
        C{RuntimeError}.
        """
        d1 = self.proto.get("foo")
        self.clock.advance(self.proto.persistentTimeOut)
        self.assertFailure(d1, TimeoutError)
        d2 = self.proto.get("bar")
        self.assertFailure(d2, RuntimeError)
        return gatherResults([d1, d2]) 
Example #30
Source File: upnp.py    From p2pool-n with GNU General Public License v3.0 5 votes vote down vote up
def _on_discovery_timeout(self):
        if self._done:
            return
        self._done = True
        self.mcast.stopListening()
        self._discovery.errback(failure.Failure(defer.TimeoutError('in _on_discovery_timeout')))