twisted.internet.task.Clock

Here are the examples of the python api twisted.internet.task.Clock taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

233 Examples 7

3 Source : test_internet.py
with MIT License
from autofelix

    def setUp(self):
        """
        Set up a timer service to test.
        """
        self.timer = TimerService(2, self.call)
        self.clock = self.timer.clock = task.Clock()
        self.deferred = Deferred()


    def call(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_startServiceUsesGlobalReactor(self):
        """
        L{TimerService.startService} uses L{internet._maybeGlobalReactor} to
        choose the reactor to pass to L{task.LoopingCall}
        uses the global reactor.
        """
        otherClock = task.Clock()
        def getOtherClock(maybeReactor):
            return otherClock
        self.patch(internet, "_maybeGlobalReactor", getOtherClock)
        self.timer.startService()
        self.assertIdentical(otherClock, self.timer._loop.clock)


    def test_stopServiceWaits(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_stopServiceWhileRetrying(self):
        """
        When the service is stopped while retrying, the retry is cancelled.
        """
        clock = Clock()
        cq, service = self.makeReconnector(fireImmediately=False, clock=clock)
        cq.connectQueue[0].errback(Exception())
        clock.advance(AT_LEAST_ONE_ATTEMPT)
        self.assertEqual(len(cq.connectQueue), 2)
        d = service.stopService()
        cq.connectQueue[1].errback(Exception())
        self.successResultOf(d)


    def test_stopServiceWhileConnecting(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_stopServiceWhileConnecting(self):
        """
        When the service is stopped while initially connecting, the connection
        attempt is cancelled.
        """
        clock = Clock()
        cq, service = self.makeReconnector(fireImmediately=False, clock=clock)
        self.assertEqual(len(cq.connectQueue), 1)
        self.assertNoResult(cq.connectQueue[0])
        d = service.stopService()
        self.successResultOf(d)


    def test_clientConnected(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_clientConnected(self):
        """
        When a client connects, the service keeps a reference to the new
        protocol and resets the delay.
        """
        clock = Clock()
        cq, service = self.makeReconnector(clock=clock)
        awaitingProtocol = service.whenConnected()
        self.assertEqual(clock.getDelayedCalls(), [])
        self.assertIdentical(self.successResultOf(awaitingProtocol),
                             cq.applicationProtocols[0])


    def test_clientConnectionFailed(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_clientConnectionLostWhileStopping(self):
        """
        When a client connection is lost while the service is stopping, the
        protocol stopping deferred is called and the reference to the protocol
        is removed.
        """
        clock = Clock()
        cq, service = self.makeReconnector(clock=clock)
        d = service.stopService()
        cq.constructedProtocols[0].connectionLost(Failure(IndentationError()))
        self.failureResultOf(service.whenConnected(), CancelledError)
        self.assertTrue(d.called)


    def test_startTwice(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_retryCancelled(self):
        """
        When L{ClientService.stopService} is called while waiting between
        connection attempts, the pending reconnection attempt is cancelled and
        the service is stopped immediately.
        """
        clock = Clock()
        cq, service = self.makeReconnector(fireImmediately=False, clock=clock)
        cq.connectQueue[0].errback(Exception("no connection"))
        d = service.stopService()
        self.assertEqual(clock.getDelayedCalls(), [])
        self.successResultOf(d)


    def test_stopServiceBeforeStartService(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_stopServiceBeforeStartService(self):
        """
        Calling L{ClientService.stopService} before
        L{ClientService.startService} returns a L{Deferred} that has
        already fired with L{None}.
        """
        clock = Clock()
        _, service = self.makeReconnector(fireImmediately=False,
                                          startService=False,
                                          clock=clock)
        d = service.stopService()
        self.assertIsNone(self.successResultOf(d))


    def test_whenConnectedErrbacksOnStopService(self):

3 Source : test_internet.py
with MIT License
from autofelix

    def test_stopServiceOnStoppedService(self):
        """
        Calling L{ClientService.stopService} on a stopped service
        returns a L{Deferred} that has already fired with L{None}.
        """
        clock = Clock()
        _, service = self.makeReconnector(fireImmediately=False,
                                          clock=clock)
        firstStopDeferred = service.stopService()
        secondStopDeferred = service.stopService()

        self.assertIsNone(self.successResultOf(firstStopDeferred))
        self.assertIsNone(self.successResultOf(secondStopDeferred))


    def test_prepareConnectionCalledWhenServiceStarts(self):

3 Source : test_userauth.py
with MIT License
from autofelix

    def test_loginTimeout(self):
        """
        Test that the login times out.
        """
        timeoutAuthServer = userauth.SSHUserAuthServer()
        timeoutAuthServer.clock = task.Clock()
        timeoutAuthServer.transport = FakeTransport(self.portal)
        timeoutAuthServer.serviceStarted()
        timeoutAuthServer.clock.advance(11 * 60 * 60)
        timeoutAuthServer.serviceStopped()
        self.assertEqual(timeoutAuthServer.transport.packets,
                [(transport.MSG_DISCONNECT,
                b'\x00' * 3 +
                chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
                NS(b"you took too long") + NS(b''))])
        self.assertTrue(timeoutAuthServer.transport.lostConnection)


    def test_cancelLoginTimeout(self):

3 Source : test_userauth.py
with MIT License
from autofelix

    def test_cancelLoginTimeout(self):
        """
        Test that stopping the service also stops the login timeout.
        """
        timeoutAuthServer = userauth.SSHUserAuthServer()
        timeoutAuthServer.clock = task.Clock()
        timeoutAuthServer.transport = FakeTransport(self.portal)
        timeoutAuthServer.serviceStarted()
        timeoutAuthServer.serviceStopped()
        timeoutAuthServer.clock.advance(11 * 60 * 60)
        self.assertEqual(timeoutAuthServer.transport.packets, [])
        self.assertFalse(timeoutAuthServer.transport.lostConnection)


    def test_tooManyAttempts(self):

3 Source : test_userauth.py
with MIT License
from autofelix

    def test_failIfUnknownService(self):
        """
        If the user requests a service that we don't support, the
        authentication should fail.
        """
        packet = NS(b'foo') + NS(b'') + NS(b'password') + chr(0) + NS(b'foo')
        self.authServer.clock = task.Clock()
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        return d.addCallback(self._checkFailed)


    def test_tryAuthEdgeCases(self):

3 Source : test_base.py
with MIT License
from autofelix

    def __init__(self):
        self._clock = Clock()
        self.callLater = self._clock.callLater

        self._threadpool = ThreadPool()
        self._threadpool.start()
        self.getThreadPool = lambda: self._threadpool

        self._threadCalls = Queue()


    def callFromThread(self, f, *args, **kwargs):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_allASCII(self):
        """
        The string representation of L{HostnameEndpoint} includes the host and
        port passed to the constructor.
        """
        endpoint = endpoints.HostnameEndpoint(
            deterministicResolvingReactor(Clock(), []),
            'example.com', 80,
        )

        rep = repr(endpoint)

        self.assertEqual("  <  HostnameEndpoint example.com:80>", rep)
        self.assertIs(str, type(rep))


    def test_idnaHostname(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_idnaHostname(self):
        """
        When IDN is passed to the L{HostnameEndpoint} constructor the string
        representation includes the punycode version of the host.
        """
        endpoint = endpoints.HostnameEndpoint(
            deterministicResolvingReactor(Clock(), []),
            u'b\xfccher.ch', 443,
        )

        rep = repr(endpoint)

        self.assertEqual("  <  HostnameEndpoint xn--bcher-kva.ch:443>", rep)
        self.assertIs(str, type(rep))


    def test_hostIPv6Address(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_hostIPv6Address(self):
        """
        When the host passed to L{HostnameEndpoint} is an IPv6 address it is
        wrapped in brackets in the string representation, like in a URI. This
        prevents the colon separating the host from the port from being
        ambiguous.
        """
        endpoint = endpoints.HostnameEndpoint(
            deterministicResolvingReactor(Clock(), []),
            b'::1', 22,
        )

        rep = repr(endpoint)

        self.assertEqual("  <  HostnameEndpoint [::1]:22>", rep)
        self.assertIs(str, type(rep))


    def test_badEncoding(self):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_badEncoding(self):
        """
        When a bad hostname is passed to L{HostnameEndpoint}, the string
        representation displays invalid characters in backslash-escaped form.
        """
        endpoint = endpoints.HostnameEndpoint(
            deterministicResolvingReactor(Clock(), []),
            b'\xff-garbage-\xff', 80
        )

        self.assertEqual(
            '  <  HostnameEndpoint \\xff-garbage-\\xff:80>',
            repr(endpoint),
        )



class HostnameEndpointsGAIFailureTests(unittest.TestCase):

3 Source : test_endpoints.py
with MIT License
from autofelix

    def test_failure(self):
        """
        If no address is returned by GAI for a hostname, the connection attempt
        fails with L{error.DNSLookupError}.
        """
        endpoint = endpoints.HostnameEndpoint(
            deterministicResolvingReactor(Clock(), []),
            b"example.com", 80
        )
        clientFactory = object()
        dConnect = endpoint.connect(clientFactory)
        exc = self.failureResultOf(dConnect, error.DNSLookupError)
        self.assertIn("example.com", str(exc))



class HostnameEndpointsFasterConnectionTests(unittest.TestCase):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_addReader(self):
        """
        Adding a reader when there was previously no reader starts up a
        C{LoopingCall}.
        """
        poller = _ContinuousPolling(Clock())
        self.assertIsNone(poller._loop)
        reader = object()
        self.assertFalse(poller.isReading(reader))
        poller.addReader(reader)
        self.assertIsNotNone(poller._loop)
        self.assertTrue(poller._loop.running)
        self.assertIs(poller._loop.clock, poller._reactor)
        self.assertTrue(poller.isReading(reader))


    def test_addWriter(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_addWriter(self):
        """
        Adding a writer when there was previously no writer starts up a
        C{LoopingCall}.
        """
        poller = _ContinuousPolling(Clock())
        self.assertIsNone(poller._loop)
        writer = object()
        self.assertFalse(poller.isWriting(writer))
        poller.addWriter(writer)
        self.assertIsNotNone(poller._loop)
        self.assertTrue(poller._loop.running)
        self.assertIs(poller._loop.clock, poller._reactor)
        self.assertTrue(poller.isWriting(writer))


    def test_removeReader(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_removeReader(self):
        """
        Removing a reader stops the C{LoopingCall}.
        """
        poller = _ContinuousPolling(Clock())
        reader = object()
        poller.addReader(reader)
        poller.removeReader(reader)
        self.assertIsNone(poller._loop)
        self.assertEqual(poller._reactor.getDelayedCalls(), [])
        self.assertFalse(poller.isReading(reader))


    def test_removeWriter(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_removeWriter(self):
        """
        Removing a writer stops the C{LoopingCall}.
        """
        poller = _ContinuousPolling(Clock())
        writer = object()
        poller.addWriter(writer)
        poller.removeWriter(writer)
        self.assertIsNone(poller._loop)
        self.assertEqual(poller._reactor.getDelayedCalls(), [])
        self.assertFalse(poller.isWriting(writer))


    def test_removeUnknown(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_removeUnknown(self):
        """
        Removing unknown readers and writers silently does nothing.
        """
        poller = _ContinuousPolling(Clock())
        poller.removeWriter(object())
        poller.removeReader(object())


    def test_multipleReadersAndWriters(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_readerPolling(self):
        """
        Adding a reader causes its C{doRead} to be called every 1
        milliseconds.
        """
        reactor = Clock()
        poller = _ContinuousPolling(reactor)
        desc = Descriptor()
        poller.addReader(desc)
        self.assertEqual(desc.events, [])
        reactor.advance(0.00001)
        self.assertEqual(desc.events, ["read"])
        reactor.advance(0.00001)
        self.assertEqual(desc.events, ["read", "read"])
        reactor.advance(0.00001)
        self.assertEqual(desc.events, ["read", "read", "read"])


    def test_writerPolling(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_writerPolling(self):
        """
        Adding a writer causes its C{doWrite} to be called every 1
        milliseconds.
        """
        reactor = Clock()
        poller = _ContinuousPolling(reactor)
        desc = Descriptor()
        poller.addWriter(desc)
        self.assertEqual(desc.events, [])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["write"])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["write", "write"])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["write", "write", "write"])


    def test_connectionLostOnRead(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_connectionLostOnRead(self):
        """
        If a C{doRead} returns a value indicating disconnection,
        C{connectionLost} is called on it.
        """
        reactor = Clock()
        poller = _ContinuousPolling(reactor)
        desc = Descriptor()
        desc.doRead = lambda: ConnectionDone()
        poller.addReader(desc)
        self.assertEqual(desc.events, [])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["lost"])


    def test_connectionLostOnWrite(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_connectionLostOnWrite(self):
        """
        If a C{doWrite} returns a value indicating disconnection,
        C{connectionLost} is called on it.
        """
        reactor = Clock()
        poller = _ContinuousPolling(reactor)
        desc = Descriptor()
        desc.doWrite = lambda: ConnectionDone()
        poller.addWriter(desc)
        self.assertEqual(desc.events, [])
        reactor.advance(0.001)
        self.assertEqual(desc.events, ["lost"])


    def test_removeAll(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_getReaders(self):
        """
        L{_ContinuousPolling.getReaders} returns a list of the read
        descriptors.
        """
        poller = _ContinuousPolling(Clock())
        reader = object()
        poller.addReader(reader)
        self.assertIn(reader, poller.getReaders())


    def test_getWriters(self):

3 Source : test_epollreactor.py
with MIT License
from autofelix

    def test_getWriters(self):
        """
        L{_ContinuousPolling.getWriters} returns a list of the write
        descriptors.
        """
        poller = _ContinuousPolling(Clock())
        writer = object()
        poller.addWriter(writer)
        self.assertIn(writer, poller.getWriters())

    if _ContinuousPolling is None:

3 Source : test_client.py
with MIT License
from autofelix

    def test_interface(self):
        """
        L{client.getResolver} returns an object providing L{IResolver}.
        """
        with AlternateReactor(Clock()):
            resolver = client.getResolver()
        self.assertTrue(verifyObject(IResolver, resolver))


    def test_idempotent(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_idempotent(self):
        """
        Multiple calls to L{client.getResolver} return the same L{IResolver}
        implementation.
        """
        with AlternateReactor(Clock()):
            a = client.getResolver()
            b = client.getResolver()
        self.assertIs(a, b)



class CreateResolverTests(unittest.TestCase, GoodTempPathMixin):

3 Source : test_client.py
with MIT License
from autofelix

    def test_defaultHosts(self):
        """
        L{client.createResolver} returns a L{resolve.ResolverChain} including a
        L{hosts.Resolver} using I{/etc/hosts} if no alternate hosts file is
        specified.
        """
        with AlternateReactor(Clock()):
            resolver = client.createResolver()
        self._hostsTest(resolver, b"/etc/hosts")


    def test_overrideHosts(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_overrideHosts(self):
        """
        The I{hosts} parameter to L{client.createResolver} overrides the hosts
        file used by the L{hosts.Resolver} in the L{resolve.ResolverChain} it
        returns.
        """
        with AlternateReactor(Clock()):
            resolver = client.createResolver(hosts=b"/foo/bar")
        self._hostsTest(resolver, b"/foo/bar")


    def _resolvConfTest(self, resolver, filename):

3 Source : test_client.py
with MIT License
from autofelix

    def test_reactor(self):
        """
        The L{client.Resolver} included in the L{resolve.ResolverChain} returned
        by L{client.createResolver} uses the global reactor.
        """
        reactor = Clock()
        with AlternateReactor(reactor):
            resolver = client.createResolver()
        res = [r for r in resolver.resolvers if isinstance(r, client.Resolver)]
        self.assertEqual(1, len(res))
        self.assertIs(reactor, res[0]._reactor)


    def test_defaultResolvConf(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_defaultResolvConf(self):
        """
        L{client.createResolver} returns a L{resolve.ResolverChain} including a
        L{client.Resolver} using I{/etc/resolv.conf} if no alternate resolver
        configuration file is specified.
        """
        with AlternateReactor(Clock()):
            resolver = client.createResolver()
        self._resolvConfTest(resolver, b"/etc/resolv.conf")


    def test_overrideResolvConf(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_overrideResolvConf(self):
        """
        The I{resolvconf} parameter to L{client.createResolver} overrides the
        resolver configuration file used by the L{client.Resolver} in the
        L{resolve.ResolverChain} it returns.
        """
        with AlternateReactor(Clock()):
            resolver = client.createResolver(resolvconf=b"/foo/bar")
        self._resolvConfTest(resolver, b"/foo/bar")


    def test_defaultServers(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_defaultServers(self):
        """
        If no servers are given, addresses are taken from the file given by the
        I{resolvconf} parameter to L{client.createResolver}.
        """
        resolvconf = self.path()
        resolvconf.setContent(b"nameserver 127.1.2.3\n")
        with AlternateReactor(Clock()):
            resolver = client.createResolver(resolvconf=resolvconf.path)
        res = [r for r in resolver.resolvers if isinstance(r, client.Resolver)]
        self.assertEqual(1, len(res))
        self.assertEqual([], res[0].servers)
        self.assertEqual([("127.1.2.3", 53)], res[0].dynServers)


    def test_overrideServers(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_overrideServers(self):
        """
        Servers passed to L{client.createResolver} are used in addition to any
        found in the file given by the I{resolvconf} parameter.
        """
        resolvconf = self.path()
        resolvconf.setContent(b"nameserver 127.1.2.3\n")
        with AlternateReactor(Clock()):
            resolver = client.createResolver(
                servers=[("127.3.2.1", 53)], resolvconf=resolvconf.path)
        res = [r for r in resolver.resolvers if isinstance(r, client.Resolver)]
        self.assertEqual(1, len(res))
        self.assertEqual([("127.3.2.1", 53)], res[0].servers)
        self.assertEqual([("127.1.2.3", 53)], res[0].dynServers)


    def test_cache(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_cache(self):
        """
        L{client.createResolver} returns a L{resolve.ResolverChain} including a
        L{cache.CacheResolver}.
        """
        with AlternateReactor(Clock()):
            resolver = client.createResolver()
        res = [r for r in resolver.resolvers if isinstance(r, cache.CacheResolver)]
        self.assertEqual(1, len(res))




class ResolverTests(unittest.TestCase):

3 Source : test_client.py
with MIT License
from autofelix

    def test_missingConfiguration(self):
        """
        A missing nameserver configuration file results in no server information
        being loaded from it (ie, not an exception) and a default server being
        provided.
        """
        resolver = client.Resolver(resolv=self.mktemp(), reactor=Clock())
        self.assertEqual([("127.0.0.1", 53)], resolver.dynServers)


    def test_closesResolvConf(self):

3 Source : test_client.py
with MIT License
from autofelix

    def test_closesResolvConf(self):
        """
        As part of its constructor, C{StubResolver} opens C{/etc/resolv.conf};
        then, explicitly closes it and does not count on the GC to do so for
        it.
        """
        handle = FilePath(self.mktemp())
        resolvConf = handle.open(mode='w+')
        class StubResolver(client.Resolver):
            def _openFile(self, name):
                return resolvConf
        StubResolver(servers=["example.com", 53], resolv='/etc/resolv.conf',
                     reactor=Clock())
        self.assertTrue(resolvConf.closed)


    def test_domainEmptyArgument(self):

3 Source : test_dns.py
with MIT License
from autofelix

    def setUp(self):
        """
        Create a L{dns.DNSDatagramProtocol} with a deterministic clock.
        """
        self.clock = task.Clock()
        self.controller = TestController()
        self.proto = dns.DNSDatagramProtocol(self.controller)
        transport = proto_helpers.FakeDatagramTransport()
        self.proto.makeConnection(transport)
        self.proto.callLater = self.clock.callLater


    def test_truncatedPacket(self):

3 Source : test_dns.py
with MIT License
from autofelix

    def setUp(self):
        """
        Create a L{dns.DNSProtocol} with a deterministic clock.
        """
        self.clock = task.Clock()
        self.controller = TestTCPController()
        self.proto = dns.DNSProtocol(self.controller)
        self.proto.makeConnection(proto_helpers.StringTransport())
        self.proto.callLater = self.clock.callLater


    def test_connectionTracking(self):

3 Source : test_basic.py
with MIT License
from autofelix

    def test_pausing(self):
        """
        Test pause inside data receiving. It uses fake clock to see if
        pausing/resuming work.
        """
        for packet_size in range(1, 10):
            t = proto_helpers.StringIOWithoutClosing()
            clock = task.Clock()
            a = LineTester(clock)
            a.makeConnection(protocol.FileWrapper(t))
            for i in range(len(self.pauseBuf) // packet_size + 1):
                s = self.pauseBuf[i * packet_size:(i + 1) * packet_size]
                a.dataReceived(s)
            self.assertEqual(self.pauseOutput1, a.received)
            clock.advance(0)
            self.assertEqual(self.pauseOutput2, a.received)

    rawpauseBuf = b'twiddle1\ntwiddle2\nlen 5\nrawpause\n12345twiddle3\n'

3 Source : test_basic.py
with MIT License
from autofelix

    def test_rawPausing(self):
        """
        Test pause inside raw date receiving.
        """
        for packet_size in range(1, 10):
            t = proto_helpers.StringIOWithoutClosing()
            clock = task.Clock()
            a = LineTester(clock)
            a.makeConnection(protocol.FileWrapper(t))
            for i in range(len(self.rawpauseBuf) // packet_size + 1):
                s = self.rawpauseBuf[i * packet_size:(i + 1) * packet_size]
                a.dataReceived(s)
            self.assertEqual(self.rawpauseOutput1, a.received)
            clock.advance(0)
            self.assertEqual(self.rawpauseOutput2, a.received)

    stop_buf = b'twiddle1\ntwiddle2\nstop\nmore\nstuff\n'

3 Source : test_defer.py
with MIT License
from autofelix

    def setUp(self):
        self.clock = Clock()
        self.lock = defer.DeferredFilesystemLock(self.mktemp(),
                                                 scheduler=self.clock)


    def test_waitUntilLockedWithNoLock(self):

3 Source : test_defer.py
with MIT License
from autofelix

    def test_timeoutChainable(self):
        """
        L{defer.Deferred.addTimeout} returns its own L{defer.Deferred} so it
        can be called in a callback chain.
        """
        d = defer.Deferred().addTimeout(5, Clock()).addCallback(lambda _: "done")
        d.callback(None)
        self.assertEqual("done", self.successResultOf(d))


    def test_successResultBeforeTimeout(self):

3 Source : test_defer.py
with MIT License
from autofelix

    def test_timedOut(self):
        """
        The L{defer.Deferred} by default errbacks with a L{defer.TimeoutError}
        if it times out before callbacking or errbacking.
        """
        clock = Clock()
        d = defer.Deferred()
        d.addTimeout(10, clock)
        self.assertNoResult(d)

        clock.advance(15)

        self.failureResultOf(d, defer.TimeoutError)


    def test_timedOutCustom(self):

3 Source : test_defer.py
with MIT License
from autofelix

    def test_timedOutCustom(self):
        """
        If a custom C{onTimeoutCancel] function is provided, the
        L{defer.Deferred} returns the custom function's return value if the
        L{defer.Deferred} times out before callbacking or errbacking.
        The custom C{onTimeoutCancel} function can return a result instead of
        a failure.
        """
        clock = Clock()
        d = defer.Deferred()
        d.addTimeout(10, clock, onTimeoutCancel=_overrideFunc)
        self.assertNoResult(d)

        clock.advance(15)

        self.assertEqual("OVERRIDDEN", self.successResultOf(d))


    def test_timedOutProvidedCancelSuccess(self):

3 Source : test_defer.py
with MIT License
from autofelix

    def test_timedOutProvidedCancelSuccess(self):
        """
        If a cancellation function is provided when the L{defer.Deferred} is
        initialized, the L{defer.Deferred} returns the cancellation value's
        non-failure return value when the L{defer.Deferred} times out.
        """
        clock = Clock()
        d = defer.Deferred(lambda c: c.callback('I was cancelled!'))
        d.addTimeout(10, clock)
        self.assertNoResult(d)

        clock.advance(15)

        self.assertEqual(self.successResultOf(d), 'I was cancelled!')


    def test_timedOutProvidedCancelFailure(self):

See More Examples