How to use the twisted.internet.defer.succeed function in Twisted

To help you get started, we’ve selected a few Twisted examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github matrix-org / synapse / tests / appservice / test_scheduler.py View on Github external
def test_single_service_up_txn_not_sent(self):
        # Test: The AS is up and the txn is not sent. A Recoverer is made and
        # started.
        service = Mock()
        events = [Mock(), Mock()]
        txn_id = "foobar"
        txn = Mock(id=txn_id, service=service, events=events)

        # mock methods
        self.store.get_appservice_state = Mock(
            return_value=defer.succeed(ApplicationServiceState.UP)
        )
        self.store.set_appservice_state = Mock(return_value=defer.succeed(True))
        txn.send = Mock(return_value=defer.succeed(False))  # fails to send
        self.store.create_appservice_txn = Mock(return_value=defer.succeed(txn))

        # actual call
        self.txnctrl.send(service, events)

        self.store.create_appservice_txn.assert_called_once_with(
            service=service, events=events
        )
        self.assertEquals(1, self.recoverer_fn.call_count)  # recoverer made
        self.assertEquals(1, self.recoverer.recover.call_count)  # and invoked
        self.assertEquals(1, len(self.txnctrl.recoverers))  # and stored
        self.assertEquals(0, txn.complete.call_count)  # txn not completed
        self.store.set_appservice_state.assert_called_once_with(
            service, ApplicationServiceState.DOWN  # service marked as down
        )
github apple / ccs-twistedextensions / twext / who / index.py View on Github external
for key in indexKeys:
            matchingRecords |= fieldIndex.get(key, frozenset())

        # Not necessary, so don't unless we know it's a performance win:
        # if records is not None:
        #     matchingRecords &= records

        if recordTypes is not None:
            for record in list(matchingRecords):
                if record.recordType not in recordTypes:
                    matchingRecords.remove(record)

        if limitResults is not None:
            matchingRecords = set(list(matchingRecords)[:limitResults])

        return succeed(matchingRecords)
github StarlitGhost / PyMoronBot / twisted / internet / endpoints.py View on Github external
Implement L{IStreamClientEndpoint.connect} to launch a child process
        and connect it to a protocol created by C{protocolFactory}.

        @param protocolFactory: A factory for an L{IProtocol} provider which
            will be notified of all events related to the created process.
        """
        proto = protocolFactory.buildProtocol(_ProcessAddress())
        try:
            self._spawnProcess(
                _WrapIProtocol(proto, self._executable, self._errFlag),
                self._executable, self._args, self._env, self._path, self._uid,
                self._gid, self._usePTY, self._childFDs)
        except:
            return defer.fail()
        else:
            return defer.succeed(proto)
github richardingham / octopus / octopus / protocol / gsioc.py View on Github external
def _select (self, id):
		if self._selected == id:
			return defer.succeed(id)

		gsioc_id = id + 128
		d = self._write(chr(gsioc_id))
		#_log("S?  %s [%s]" % (gsioc_id, id))

		def cb (result):
			result = ord(result) if len(result) > 0 else None
			#_log("S.  %s" % result)

			if result != gsioc_id:
				return task.deferLater(reactor, 0.2, self._select, id)

			self._selected = id

			if result is None:
				raise NoDevice(id)
github andrewbird / wader / core / middleware.py View on Github external
def maybecached(self, name, fn, cblist):
        if self.caches[name][0] >= time():  # cache hasn't expired
            log.msg("get '%s' (cached path)" % name, system='CACHE')
            d = defer.succeed(self.caches[name][1])
        else:
            log.msg("get '%s' (noncached path)" % name, system='CACHE')
            d = fn()
            for cb in cblist:
                d.addCallback(cb)
            d.addCallback(self.updatecache, name)
        return d
github twisted / txmongo / txmongo / _gridfs / grid_file.py View on Github external
def __flush_data(self, data):
        """Flush `data` to a chunk.
        """
        if not data:
            return defer.succeed(None)

        assert (len(data) <= self.chunk_size)
        chunk = {"files_id": self._file["_id"],
                 "n": self._chunk_number,
                 "data": Binary(data)}

        def ok(_):
            self._chunk_number += 1
            self._position += len(data)

        # Continue writing after the insert completes (non-blocking)
        return self._chunks.insert(chunk).addCallback(ok)
github Didero / DideRobot / libraries / twisted / internet / endpoints.py View on Github external
"""
        Implement L{IStreamServerEndpoint.listen} to start listening on, and
        then close, C{self._fileno}.
        """
        if self._used:
            return defer.fail(error.AlreadyListened())
        self._used = True

        try:
            self._setNonBlocking(self.fileno)
            port = self.reactor.adoptStreamPort(
                self.fileno, self.addressFamily, factory)
            self._close(self.fileno)
        except:
            return defer.fail()
        return defer.succeed(port)
github apple / ccs-twistedextensions / twext / who / opendirectory / _service.py View on Github external
self.log.debug("OD call: {}".format(expression))
            try:
                query = self._queryFromMatchExpression(
                    expression,
                    recordTypes=recordTypes,
                    limitResults=limitResults,
                )
                return self._recordsFromQuery(
                    query, timeoutSeconds=timeoutSeconds
                )

            except QueryNotSupportedError:
                pass  # Let the superclass try

            except UnsupportedRecordTypeError:
                return succeed([])

        return BaseDirectoryService.recordsFromNonCompoundExpression(
            self, expression,
            limitResults=limitResults, timeoutSeconds=timeoutSeconds
        )
github lbryio / lbry-sdk / lbrynet / lbrynet_daemon / UIManager.py View on Github external
def _get_git_info():
            try:
                # TODO: should this be switched to the non-blocking getPage?
                response = urlopen(self._git_url)
                return defer.succeed(read_sha(response))
            except Exception:
                return defer.fail()