How to use Twisted - 10 common examples

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 OpenObservatory / ooniprobe-debian / ooni / nettests / blocking / web_connectivity.py View on Github external
def experiment_tcp_connect(self, socket):
        log.msg("* connecting to {}".format(socket))
        ip_address, port = socket.split(":")
        port = int(port)
        result = {
            'ip': ip_address,
            'port': port,
            'status': {
                'success': None,
                'failure': None,
                'blocked': None
            }
        }
        point = TCP4ClientEndpoint(reactor, ip_address, port)
        d = point.connect(TCPConnectFactory())
        @d.addCallback
        def cb(p):
            result['status']['success'] = True
            result['status']['blocked'] = False
            self.report['tcp_connect'].append(result)

        @d.addErrback
        def eb(failure):
            result['status']['success'] = False
            result['status']['failure'] = failureToString(failure)
            self.report['tcp_connect'].append(result)

        return d
github twisted / txmongo / tests / test_filters.py View on Github external
    @defer.inlineCallbacks
    def test_FilterMerge(self):
        self.assertEqual(qf.sort(qf.ASCENDING('x') + qf.DESCENDING('y')),
                         qf.sort(qf.ASCENDING('x')) + qf.sort(qf.DESCENDING('y')))

        comment = "hello world"

        yield self.db.command("profile", 2)
        yield self.coll.find({}, filter=qf.sort(qf.ASCENDING('x')) + qf.comment(comment))
        yield self.db.command("profile", 0)

        if (yield self.__3_6_or_higher()):
            profile_filter = {"command.sort.x": 1, "command.comment": comment}
        elif (yield self.__3_2_or_higher()):
            profile_filter = {"query.sort.x": 1, "query.comment": comment}
        else:
            profile_filter = {"query.$orderby.x": 1, "query.$comment": comment}
github leapcode / bitmask-dev / tests / integration / keymanager / test_keymanager.py View on Github external
    @defer.inlineCallbacks
    def test_decrypt_does_not_update_sign_used_for_recipient(self):
        # given
        km = self._key_manager()
        yield km._openpgp.put_raw_key(PRIVATE_KEY, ADDRESS)
        yield km._openpgp.put_raw_key(PRIVATE_KEY_2, ADDRESS_2)
        encdata = yield km.encrypt('data', ADDRESS, sign=ADDRESS_2,
                                   fetch_remote=False)
        yield km.decrypt(
            encdata, ADDRESS, verify=ADDRESS_2, fetch_remote=False)

        # when
        key = yield km.get_key(
            ADDRESS, private=False, fetch_remote=False)

        # then
        self.assertEqual(False, key.sign_used)
github xiaowangwindow / scrapy-httpcache / tests / test_downloadermiddleware_httpcache.py View on Github external
    @defer.inlineCallbacks
    def test_middleware(self):
        with self._middleware() as mw:
            _ = yield mw.process_request(self.request, self.spider)
            assert _ is None
            yield mw.process_response(self.request, self.response, self.spider)
            response = yield mw.process_request(self.request, self.spider)
            assert isinstance(response, HtmlResponse)
            self.assertEqualResponse(self.response, response)
            assert 'cached' in response.flags
github telepresenceio / telepresence / k8s-proxy / test_socks.py View on Github external
def resolve(self, hostname):
        """
        Resolve a hostname by looking it up in the C{names} dictionary.
        """
        try:
            return defer.succeed(self.names[hostname])
        except KeyError:
            return defer.fail(
                DNSLookupError(
                    "FakeResolverReactor couldn't find {}".format(hostname)
                )
github buildbot / buildbot / buildbot / broken_test / runutils.py View on Github external
def myGetProcessOutputAndValue(executable, args=(), env={}, path='.',
                               _reactor_ignored=None, stdin=None):
    """Like twisted.internet.utils.getProcessOutputAndValue but takes
    stdin, too."""
    d = defer.Deferred()
    p = _PutEverythingGetter(d, stdin)
    reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path)
    return d
github twisted / twisted / sandbox / z3p / test_simpleconch.py View on Github external
if os.name != 'posix':
            raise unittest.SkipTest("cannot run on non-posix") # why?
        global theTest
        theTest = self
        realm = ConchTestRealm()
        p = portal.Portal(realm)
        sshpc = ConchTestSSHChecker()
        sshpc.registerChecker(ConchTestPasswordChecker())
        sshpc.registerChecker(ConchTestPublicKeyChecker())
        p.registerChecker(sshpc)
        self.fac = fac = SSHTestFactory()
        fac.portal = p
        theTest.fac = fac
        self.server = reactor.listenTCP(0, fac, interface="127.0.0.1")
        port = self.server.getHost()[2]
        d = defer.Deferred()
        cc = protocol.ClientCreator(reactor, simpleconch.SimpleTransport, d)
        d.addCallback(self._cbSimpleConnected)
        d.addErrback(self._ebFailTest, "failed before connection")
        def _failTest():
            reactor.crash()
            self.fail('test took too long') # logged but caught by reactor
        self.sessions = []
        timeout = reactor.callLater(10, _failTest)
        d = cc.connectTCP('localhost', port)
        d.addErrback(self._ebFailTest)
        reactor.run()
        # test finished.. might have passed, might have failed. Must cleanup.
        fac.proto.done = 1
        fac.proto.transport.loseConnection()
        reactor.iterate()
        reactor.iterate()
github mozilla-services / autopush-loadtester / aplt / runner.py View on Github external
scenario,
                self._endpoint,
                self._endpoint_ssl_cert,
                self._endpoint_ssl_key,
                *scenario_args[0],
                **scenario_args[1]
            )
            self._harnesses.append(harness)
            iterations = quantity / stagger
            for delay in range(iterations):
                def runall():
                    for _ in range(stagger):
                        harness.run()
                    self._queued_calls -= 1
                self._queued_calls += 1
                reactor.callLater(overall_delay+delay, runall)
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 twisted / twisted / sandbox / slyphon / ftp_refactor / test_ftp.py View on Github external
def cleanup(self):
        self.c.connectionLost(failure.Failure(main.CONNECTION_DONE))
        self.s.connectionLost(failure.Failure(main.CONNECTION_DONE))
        reactor.iterate() # last gasp before I go away