def __init__(self, control_amp_service): """ :param ControlAMPService control_amp_service: The service managing AMP connections to the control service. """ AMP.__init__(self, locator=ControlServiceLocator(control_amp_service)) self.control_amp_service = control_amp_service
def __init__(self, agent): """ :param IConvergenceAgent agent: Convergence agent to notify of changes. """ locator = _AgentLocator(agent) AMP.__init__(self, locator=locator) self.agent = agent
def connected_amp_protocol(): """ :return: ``AMP`` hooked up to transport. """ p = AMP() p.makeConnection(StringTransport()) return p
def test_adds_user(self): """ When L{UserAdder} is connected to L{IdentityAdmin}, the L{AddUser} command is called and L{IdentityAdmin} adds the user to its factory's store. """ admin = IdentityAdmin() admin.factory = self.adminFactory serverTransport = makeFakeServer(admin) serverTransport.getQ2QHost = lambda: Q2QAddress('Q2Q Host') client = AMP() pump = connect(admin, serverTransport, client, makeFakeClient(client)) d = client.callRemote(AddUser, name='q2q username', password='******') pump.flush() # The username and password are added, along with the domain=q2q # host, to the IdentityAdmin's factory's store self.assertEqual([call('Q2Q Host', 'q2q username', 'q2q password')], self.addUser.calls) # The server responds with {} self.assertEqual({}, self.successResultOf(d))
def doMath(): destination = TCP4ClientEndpoint(reactor, '127.0.0.1', 1234) sumDeferred = connectProtocol(destination, AMP()) def connected(ampProto): return ampProto.callRemote(Sum, a=13, b=81) sumDeferred.addCallback(connected) def summed(result): return result['total'] sumDeferred.addCallback(summed) divideDeferred = connectProtocol(destination, AMP()) def connected(ampProto): return ampProto.callRemote(Divide, numerator=1234, denominator=2) divideDeferred.addCallback(connected) def trapZero(result): result.trap(ZeroDivisionError) print("Divided by zero: returning INF") return 1e1000 divideDeferred.addErrback(trapZero) def done(result): print('Done with math:', result) reactor.stop() defer.DeferredList([sumDeferred, divideDeferred]).addCallback(done)
def run_amp_command(description, command, args, reactor=None): if reactor is None: from twisted.internet import reactor endpoint = endpoints.clientFromString(reactor, description) amp = AMP() d = endpoints.connectProtocol(endpoint, amp) d.addCallback(lambda ign: amp.callRemote(command, **args)) return d
def connectionLost(self, reason): """ If a login has happened, perform a logout. """ AMP.connectionLost(self, reason) if self.logout is not None: self.logout() self.boxReceiver = self.logout = None
def connectionLost(self, reason): for id, producer in self._producers.items(): consumer = self._consumers.get(id) if consumer is None: self._finishReceiving(id, reason) else: self._finishSending(id, reason) AMP.connectionLost(self, reason)
def __init__(self, *a, **kw): AMP.__init__(self, *a, **kw) self._producers = {} self._consumers = {} self._buffers = {} self._pending = {} self._waitingOnCompletion = {} self._draining = set()
def startReceivingBoxes(self, sender): AMP.startReceivingBoxes(self, sender) counts = [] for i in range(random.randrange(1, 5)): d = self.callRemote(Count) d.addCallback(display, self.identifier) counts.append(d) gatherResults(counts).chainDeferred(self.finished)
def test_reconnected(self): """ ``IConvergenceAgent.connected()`` can be called after ``IConvergenceAgent.disconnected()``. """ agent = fixture(self) agent.connected(AMP()) agent.disconnected() agent.connected(AMP())
def __init__(self, reactor, agent): """ :param IReactorTime reactor: A reactor to use to schedule periodic ping operations. :param IConvergenceAgent agent: Convergence agent to notify of changes. """ locator = _AgentLocator(agent) AMP.__init__(self, locator=locator) self.agent = agent self._pinger = Pinger(reactor)
def __init__(self, reactor, control_amp_service): """ :param reactor: See ``ControlServiceLocator.__init__``. :param ControlAMPService control_amp_service: The service managing AMP connections to the control service. """ locator = ControlServiceLocator(reactor, control_amp_service) AMP.__init__(self, locator=locator) self.control_amp_service = control_amp_service self._pinger = Pinger(reactor)
def connectionLost(self, reason): """ Inform the associated L{conncache.ConnectionCache} that this protocol has been disconnected. """ self.nexus.conns.connectionLostForKey( (endpoint.Q2QEndpoint(self.nexus.svc, self.nexus.addr, self.transport.getQ2QPeer(), PROTOCOL_NAME), None)) AMP.connectionLost(self, reason)
def __init__(self, reactor, agent): """ :param IReactorTime reactor: A reactor to use to schedule periodic ping [email protected] :param IConvergenceAgent agent: Convergence agent to notify of changes. """ locator = _AgentLocator(agent, timeout_for_protocol(reactor, self)) AMP.__init__(self, locator=locator) self.agent = agent self._pinger = Pinger(reactor)
def connectionLost(self, reason): """ Inform the associated L{conncache.ConnectionCache} that this protocol has been disconnected. """ self.nexus.conns.connectionLostForKey((endpoint.Q2QEndpoint( self.nexus.svc, self.nexus.addr, self.transport.getQ2QPeer(), PROTOCOL_NAME), None)) AMP.connectionLost(self, reason)
def searchUserAvailableBallots(user_id): """ http://crochet.readthedocs.io/en/latest/api.html#run-in-reactor-asynchronous-results Blocking call to the ballot server to request the ballots for a particular user. :return: EventualResult """ # NOTE: using inline callbacks here so we dont have to write/wait for callbacks. destination_deferred = yield TCP4ClientEndpoint(reactor, ballotregulator_ip, ballotregulator_port) connection_deferred = yield connectProtocol(destination_deferred, AMP()) result_deferred = yield connection_deferred.callRemote(OnlineBallotRegulator_SearchBallotRegisterForUserId, user_id=user_id) def format_results(pickled_result): # First unpickle the results. result = pickle.loads(pickled_result['ok']) # Transform the list results into a dictionary. record_list = [] for record in result: mapper = {} mapper['user_id'] = record[0] mapper['ballot_id'] = record[1] mapper['timestamp'] = record[2] mapper['ballot_name'] = record[3] mapper['ballot_address'] = record[4] # Append each row's dictionary to a list record_list.append(mapper) return record_list # Inlinecallback return value. returnValue(format_results(result_deferred))
def setUp(self): self.managerTransport = StringTransport() self.managerAMP = LocalWorkerAMP() self.managerAMP.makeConnection(self.managerTransport) self.result = TestResult() self.workerTransport = StringTransport() self.worker = AMP() self.worker.makeConnection(self.workerTransport) config = trial.Options() self.testName = "twisted.doesnexist" config["tests"].append(self.testName) self.testCase = trial._getSuite(config)._tests.pop() self.managerAMP.run(self.testCase, self.result) self.managerTransport.clear()
def searchUserAddressRegisterVote(voter_address): """ http://crochet.readthedocs.io/en/latest/api.html#run-in-reactor-asynchronous-results Blocking call to the acountverifier server to request the ballots for a particular user has already registered for.. :return: EventualResult """ # NOTE: using inline callbacks here so we dont have to write/wait for callbacks. destination_deferred = yield TCP4ClientEndpoint(reactor, accountverifier_ip, accountverifier_port) connection_deferred = yield connectProtocol(destination_deferred, AMP()) result_deferred = yield connection_deferred.callRemote(OnlineAccountVerifier_SearchRegisterVoteForAddress, voter_address=voter_address) def format_results(pickled_result): # First unpickle the results. result = pickle.loads(pickled_result['ok']) # Transform the list results into a dictionary. record_list = [] for record in result: mapper = {} mapper['register_vote_id'] = record[0] mapper['signed_token_hash'] = record[1] mapper['voter_address'] = record[2] mapper['ballot_id'] = record[3] mapper['timestamp'] = record[4] # Append each row's dictionary to a list record_list.append(mapper) return record_list # Inlinecallback return value. returnValue(format_results(result_deferred))
def setUp(self): """ Create a L{CredReceiver} hooked up to a fake L{IBoxSender} which records boxes sent through it. """ self.username = '******' self.password = '******' self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = StubAvatar() self.realm = StubRealm(self.avatar) self.portal = Portal(self.realm, [self.checker]) self.server = CredReceiver() self.server.portal = self.portal self.client = AMP() self.finished = loopbackAsync(self.server, self.client)
def setUp(self): # The "local" directory service self.directory = DirectoryService(None) # The "remote" directory service if testMode == "xml": # Need a copy as it might change path = FilePath(os.path.join(os.path.dirname(__file__), "test.xml")) copy = FilePath(self.mktemp()) path.copyTo(copy) remoteDirectory = CalendarXMLDirectoryService(copy) elif testMode == "od": remoteDirectory = CalendarODDirectoryService() # Connect the two services directly via an IOPump client = AMP() server = DirectoryProxyAMPProtocol(remoteDirectory) pump = returnConnected(server, client) # Replace the normal _getConnection method with one that bypasses any # actual networking self.patch(self.directory, "_getConnection", lambda: succeed(client)) # Wrap the normal _sendCommand method with one that flushes the IOPump # afterwards origCall = self.directory._sendCommand def newCall(*args, **kwds): d = origCall(*args, **kwds) pump.flush() return d self.patch(self.directory, "_sendCommand", newCall)
def setUp(self): yield super(DPSClientAugmentedAggregateDirectoryTest, self).setUp() # The "local" directory service self.client = DirectoryService(None) # The "remote" directory service remoteDirectory = self.directory # Connect the two services directly via an IOPump client = AMP() server = DirectoryProxyAMPProtocol(remoteDirectory) pump = returnConnected(server, client) # Replace the normal _getConnection method with one that bypasses any # actual networking self.patch(self.client, "_getConnection", lambda: succeed(client)) # Wrap the normal _sendCommand method with one that flushes the IOPump # afterwards origCall = self.client._sendCommand def newCall(*args, **kwds): d = origCall(*args, **kwds) pump.flush() return d self.patch(self.client, "_sendCommand", newCall)
def test_periodic_noops(self): """ When connected, the protocol sends ``NoOp`` commands at a fixed interval. """ expected_pings = 3 reactor = Clock() locator = _NoOpCounter() peer = AMP(locator=locator) protocol = self.build_protocol(reactor) pump = connectedServerAndClient(lambda: protocol, lambda: peer)[2] for i in range(expected_pings): reactor.advance(PING_INTERVAL.total_seconds()) peer.callRemote(NoOp) # Keep the other side alive past its timeout pump.flush() self.assertEqual(locator.noops, expected_pings)
def callRemote(command, port, **kwargs): dest = TCP4ClientEndpoint(reactor, '127.0.0.1', port) d = connectProtocol(dest, AMP()) def connected(ampProto): return ampProto.callRemote(command, **kwargs) return d.addCallback(connected)
def spawnWithStore(self, here, there): """ 'here' and 'there' are the helper protocols 'there' will expect to be created with an instance of a store. """ master = yield self.spawn(AMP(), StoreCreator) yield master.callRemote(CreateStore, delegateTo=qual(there)) returnValue(swapAMP(master, here))
def test_cluster_updated(self): """ ``IConvergenceAgent.cluster_updated()`` takes two ``Deployment`` instances. """ agent = fixture(self) agent.connected(AMP()) agent.cluster_updated(Deployment(nodes=frozenset()), Deployment(nodes=frozenset()))
def setUp(self): self.numUsers = 1000 # The "local" directory service self.directory = DirectoryService(None) # The "remote" directory service remoteDirectory = CalendarInMemoryDirectoryService(None) # Add users records = [] fieldName = remoteDirectory.fieldName for i in xrange(self.numUsers): records.append( TestRecord( remoteDirectory, { fieldName.uid: u"foo{ctr:05d}".format(ctr=i), fieldName.shortNames: (u"foo{ctr:05d}".format(ctr=i), ), fieldName.fullNames: (u"foo{ctr:05d}".format(ctr=i), ), fieldName.recordType: RecordType.user, })) # Add a big group records.append( TestRecord( remoteDirectory, { fieldName.uid: u"bigGroup", fieldName.recordType: RecordType.group, })) yield remoteDirectory.updateRecords(records, create=True) group = yield remoteDirectory.recordWithUID(u"bigGroup") members = yield remoteDirectory.recordsWithRecordType(RecordType.user) yield group.setMembers(members) # Connect the two services directly via an IOPump client = AMP() self.server = DirectoryProxyAMPProtocol(remoteDirectory) pump = returnConnected(self.server, client) # Replace the normal _getConnection method with one that bypasses any # actual networking self.patch(self.directory, "_getConnection", lambda: succeed(client)) # Wrap the normal _call method with one that flushes the IOPump # afterwards origCall = self.directory._call def newCall(*args, **kwds): d = origCall(*args, **kwds) pump.flush() return d self.patch(self.directory, "_call", newCall)
def request_contract_abi(): destination_deferred = yield TCP4ClientEndpoint(reactor, ballotregulator_ip, ballotregulator_port) connection_deferred = yield connectProtocol(destination_deferred, AMP()) result_deferred = yield connection_deferred.callRemote(OnlineBallotRegulator_RequestContractABI) def format_results(pickled_result): # First unpickle the results. return pickle.loads(pickled_result['ok']) returnValue(format_results(result_deferred))
def build_agent_client(agent): """ Create convergence agent side of the protocol. :param IConvergenceAgent agent: Convergence agent to notify of changes. :return AMP: protocol instance setup for client. """ locator = _AgentLocator(agent) return AMP(boxReceiver=_AgentBoxReceiver(agent, locator), locator=locator)
def getBallotPublicKey(ballot_id): destination_deferred = yield TCP4ClientEndpoint(reactor, accountverifier_ip, accountverifier_port) connection_deferred = yield connectProtocol(destination_deferred, AMP()) result_deferred = yield connection_deferred.callRemote(OnlineAccountVerifier_GetPublicKeyForBallot, ballot_id=int(ballot_id)) def format_results(pickled_result): ballot_public_key = pickle.loads(pickled_result['ok']) return ballot_public_key # Inlinecallback return value. returnValue(format_results(result_deferred))
def spawnWithConfig(self, config, here, there): """ Similar to spawnWithStore except the child process gets a configuration object instead. """ master = yield self.spawn(AMP(), StoreCreator) subcfg = copy.deepcopy(self.config) del subcfg._postUpdateHooks[:] yield master.callRemote(PickleConfig, config=subcfg, delegateTo=qual(there)) returnValue(swapAMP(master, here))
def test_stuff(self): svc = FakeQ2QService() serverAddr = q2q.Q2QAddress("domain", "accounts") server = AMP() def respond(box): self.assertEqual(box['_command'], "add_user") self.assertEqual(box['name'], "user") self.assertEqual(box['password'], "password") return AmpBox() server.amp_ADD_USER = respond factory = Factory.forProtocol(lambda: server) chooser = {"identity-admin": factory} svc.listenQ2Q(serverAddr, chooser, "Admin") d = q2qclient.enregister(svc, q2q.Q2QAddress("domain", "user"), "password") svc.flush() self.successResultOf(d)
def main(reactor, username, password): startLogging(stdout) router = Router() proto = AMP(router) router.bindRoute(proto, None).connectTo(None) cc = ClientCreator(reactor, lambda: proto) d = cc.connectTCP(username.split('@')[1], 7805) d.addCallback(login, UsernamePassword(username, password)) d.addCallback(connectRoute, router, BoxPrinter(), u'http://divmod.org/ns/echo') d.addCallback(sendBox) return d
def requestSignOfToken(user_id, ballot_id, blind_token): destination_deferred = yield TCP4ClientEndpoint(reactor, accountverifier_ip, accountverifier_port) connection_deferred = yield connectProtocol(destination_deferred, AMP()) result_deferred = yield connection_deferred.callRemote(OnlineAccountVerifier_SignBlindToken, user_id=user_id, ballot_id=ballot_id, blind_token=blind_token) def format_results(pickled_result): signed_blind_token = pickle.loads(pickled_result['ok']) return signed_blind_token # Inlinecallback return value. returnValue(format_results(result_deferred))
def testAddUser(user_id, password): destination_deferred = yield TCP4ClientEndpoint(reactor, '127.0.0.1', 5436) connection_deferred = yield connectProtocol(destination_deferred, AMP()) result_deferred = yield connection_deferred.callRemote( ApplicationServer_RegisterNewUser, user_id=int(user_id), password=password) def format_results(result): return result['ok'] # Inlinecallback return value. returnValue(format_results(result_deferred))
def setUp(self): self.managerTransport = StringTransport() self.managerAMP = LocalWorkerAMP() self.managerAMP.makeConnection(self.managerTransport) self.result = TestResult() self.workerTransport = StringTransport() self.worker = AMP() self.worker.makeConnection(self.workerTransport) config = trial.Options() self.testName = "twisted.doesnexist" config['tests'].append(self.testName) self.testCase = trial._getSuite(config)._tests.pop() self.managerAMP.run(self.testCase, self.result) self.managerTransport.clear()
def connectionLost(self, reason): AMP.connectionLost(self, reason) self.control_amp_service.disconnected(self) self._pinger.stop()
def __init__(self, isServer, startupD): self.isServer = isServer AMP.__init__(self) self.startupD = startupD
def stopReceivingBoxes(self, reason): """ Stop observing log events. """ AMP.stopReceivingBoxes(self, reason) log.removeObserver(self._emit)
def __init__(self, identifier): AMP.__init__(self) self.identifier = identifier self.finished = Deferred()
def __init__(self, nexus): AMP.__init__(self) self.nexus = nexus self.sentTransloads = []
def connectionLost(self, reason): AMP.connectionLost(self, reason) self.agent.disconnected() self._pinger.stop()
def connectionMade(self): AMP.connectionMade(self) self.agent.connected(self) self._pinger.start(self, PING_INTERVAL)
class CredReceiverTests(TestCase): """ Tests for L{CredReceiver}, an L{IBoxReceiver} which integrates with L{twisted.cred} to provide authentication and authorization of AMP connections. """ def setUp(self): """ Create a L{CredReceiver} hooked up to a fake L{IBoxSender} which records boxes sent through it. """ self.username = '******' self.password = '******' self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = StubAvatar() self.realm = StubRealm(self.avatar) self.portal = Portal(self.realm, [self.checker]) self.server = CredReceiver() self.server.portal = self.portal self.client = AMP() self.finished = loopbackAsync(self.server, self.client) def test_otpLogin(self): """ L{CredReceiver.otpLogin} returns without error if the pad is valid. """ PAD = 'test_otpLogin' self.portal.registerChecker(OneTimePadChecker({PAD: 'user'})) d = self.server.otpLogin(PAD) def cbLoggedIn(result): self.assertEqual(result, {}) d.addCallback(cbLoggedIn) return d def test_otpLoginUnauthorized(self): """ L{CredReceiver.otpLogin} should fail with L{UnauthorizedLogin} if an invalid pad is received. """ self.portal.registerChecker(OneTimePadChecker({})) return self.assertFailure( self.server.otpLogin('test_otpLoginUnauthorized'), UnauthorizedLogin) def test_otpLoginNotImplemented(self): """ L{CredReceiver.otpLogin} should fail with L{NotImplementedError} if the realm raises L{NotImplementedError} when asked for the avatar. """ def noAvatar(avatarId, mind, *interfaces): raise NotImplementedError() self.realm.requestAvatar = noAvatar PAD = 'test_otpLoginNotImplemented' self.portal.registerChecker(OneTimePadChecker({PAD: 'user'})) return self.assertFailure( self.server.otpLogin(PAD), NotImplementedError) def test_otpLoginResponder(self): """ L{CredReceiver} responds to the L{OTPLogin} command. """ PAD = 'test_otpLoginResponder' self.portal.registerChecker(OneTimePadChecker({PAD: 'user'})) d = self.client.callRemote(OTPLogin, pad=PAD) def cbLoggedIn(result): self.assertEqual(result, {}) d.addCallback(cbLoggedIn) return d def test_passwordLoginDifferentChallenges(self): """ L{CredReceiver.passwordLogin} returns a new challenge each time it is called. """ first = self.server.passwordLogin(self.username) second = self.server.passwordLogin(self.username) self.assertNotEqual(first['challenge'], second['challenge']) def test_passwordLoginResponder(self): """ L{CredReceiver} responds to the L{PasswordLogin} L{Command} with a challenge. """ d = self.client.callRemote(PasswordLogin, username=self.username) def cbLogin(result): self.assertIn('challenge', result) d.addCallback(cbLogin) return d def test_determineFromDifferentNonces(self): """ Each time L{PasswordChallengeResponse.determineFrom} is used, it generates a different C{cnonce} value. """ first = PasswordChallengeResponse.determineFrom('a', 'b') second = PasswordChallengeResponse.determineFrom('a', 'b') self.assertNotEqual(first['cnonce'], second['cnonce']) def test_passwordChallengeResponse(self): """ L{CredReceiver.passwordChallengeResponse} returns without error if the response is valid. """ challenge = self.server.passwordLogin(self.username)['challenge'] cnonce = '123abc' cleartext = '%s %s %s' % (challenge, cnonce, self.password) response = sha1(cleartext).digest() d = self.server.passwordChallengeResponse(cnonce, response) def cbLoggedIn(result): self.assertEqual(result, {}) d.addCallback(cbLoggedIn) return d def test_passwordChallengeResponseResponder(self): """ L{CredReceiver} responds to the L{PasswordChallengeResponse} L{Command} with an empty box if the response supplied is valid. """ challenge = self.server.passwordLogin(self.username)['challenge'] d = self.client.callRemote( PasswordChallengeResponse, **PasswordChallengeResponse.determineFrom( challenge, self.password)) def cbResponded(result): self.assertEqual(result, {}) d.addCallback(cbResponded) return d def test_response(self): """ L{PasswordChallengeResponse.determineFrom} generates the correct response to a challenge issued by L{CredReceiver.passwordLogin}. """ challenge = self.server.passwordLogin(self.username)['challenge'] result = PasswordChallengeResponse.determineFrom( challenge, self.password) d = self.server.passwordChallengeResponse(**result) def cbLoggedIn(ignored): [(avatarId, mind, interfaces)] = self.realm.requests self.assertEqual(avatarId, self.username) self.assertEqual(interfaces, (IBoxReceiver,)) # The avatar is now the protocol's box receiver. self.assertIdentical(self.server.boxReceiver, self.avatar) # And the avatar has been started up with the protocol's # IBoxSender. self.assertIdentical(self.avatar.boxSender, self.server.boxSender) # After the connection is lost, the logout function should be # called. self.assertEqual(self.realm.loggedOut, 0) self.server.connectionLost( Failure(ConnectionDone("test connection lost"))) self.assertEqual(self.realm.loggedOut, 1) d.addCallback(cbLoggedIn) return d def test_invalidResponse(self): """ L{CredReceiver.passwordChallengeResponse} returns a L{Deferred} which fails with L{UnauthorizedLogin} if it is passed a response which is not valid. """ challenge = self.server.passwordLogin(self.username)['challenge'] return self.assertFailure( self.server.passwordChallengeResponse(cnonce='bar', response='baz'), UnauthorizedLogin) def test_connectionLostWithoutAvatar(self): """ L{CredReceiver.connectionLost} does not raise an exception if no login has occurred when it is called. """ self.server.connectionLost( Failure(ConnectionDone("test connection lost"))) def test_unrecognizedCredentialsLogin(self): """ L{login} raises L{UnhandledCredentials} if passed a credentials object which provides no interface explicitly supported by that function, currently L{IUsernamePassword}. """ self.assertRaises(UnhandledCredentials, login, None, None) def test_passwordChallengeLogin(self): """ L{login} issues the commands necessary to authenticate against L{CredReceiver} when given an L{IUsernamePassword} provider with its C{username} and C{password} attributes set to valid credentials. """ loginDeferred = login( self.client, UsernamePassword(self.username, self.password)) def cbLoggedIn(clientAgain): self.assertIdentical(self.client, clientAgain) self.assertIdentical(self.server.boxReceiver, self.avatar) loginDeferred.addCallback(cbLoggedIn) return loginDeferred def test_passwordChallengeInvalid(self): """ L{login} returns a L{Deferred} which fires with L{UnauthorizedLogin} if the L{UsernamePassword} credentials object given does not contain valid authentication information. """ boxReceiver = self.server.boxReceiver loginDeferred = login( self.client, UsernamePassword(self.username + 'x', self.password)) self.assertFailure(loginDeferred, UnauthorizedLogin) def cbFailed(ignored): self.assertIdentical(self.server.boxReceiver, boxReceiver) loginDeferred.addCallback(cbFailed) return loginDeferred def test_noAvatar(self): """ L{login} returns a L{Deferred} which fires with L{NotImplementedError} if the realm raises L{NotImplementedError} when asked for the avatar. """ def noAvatar(avatarId, mind, *interfaces): raise NotImplementedError() self.realm.requestAvatar = noAvatar loginDeferred = login( self.client, UsernamePassword(self.username, self.password)) return self.assertFailure(loginDeferred, NotImplementedError)
def startReceivingBoxes(self, sender): """ Start observing log events for stat events to send. """ AMP.startReceivingBoxes(self, sender) log.addObserver(self._emit)
def connectionMade(self): AMP.connectionMade(self) self.control_amp_service.connected(self) self._pinger.start(self, PING_INTERVAL)
def __init__(self, avatarId): AMP.__init__(self) self.avatarId = avatarId
def __init__(self): MultiplexingCommandLocator.__init__(self) AMP.__init__(self)
class LocalWorkerAMPTests(TestCase): """ Test case for distributed trial's manager-side local worker AMP protocol """ def setUp(self): self.managerTransport = StringTransport() self.managerAMP = LocalWorkerAMP() self.managerAMP.makeConnection(self.managerTransport) self.result = TestResult() self.workerTransport = StringTransport() self.worker = AMP() self.worker.makeConnection(self.workerTransport) config = trial.Options() self.testName = "twisted.doesnexist" config['tests'].append(self.testName) self.testCase = trial._getSuite(config)._tests.pop() self.managerAMP.run(self.testCase, self.result) self.managerTransport.clear() def pumpTransports(self): """ Sends data from C{self.workerTransport} to C{self.managerAMP}, and then data from C{self.managerTransport} back to C{self.worker}. """ self.managerAMP.dataReceived(self.workerTransport.value()) self.workerTransport.clear() self.worker.dataReceived(self.managerTransport.value()) def test_runSuccess(self): """ Run a test, and succeed. """ results = [] d = self.worker.callRemote(managercommands.AddSuccess, testName=self.testName) d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertTrue(results) def test_runExpectedFailure(self): """ Run a test, and fail expectedly. """ results = [] d = self.worker.callRemote(managercommands.AddExpectedFailure, testName=self.testName, error='error', todo='todoReason') d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertEqual(self.testCase, self.result.expectedFailures[0][0]) self.assertTrue(results) def test_runError(self): """ Run a test, and encounter an error. """ results = [] d = self.worker.callRemote(managercommands.AddError, testName=self.testName, error='error', errorClass='exceptions.ValueError', frames=[]) d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertEqual(self.testCase, self.result.errors[0][0]) self.assertTrue(results) def test_runErrorWithFrames(self): """ L{LocalWorkerAMP._buildFailure} recreates the C{Failure.frames} from the C{frames} argument passed to C{AddError}. """ results = [] d = self.worker.callRemote(managercommands.AddError, testName=self.testName, error='error', errorClass='exceptions.ValueError', 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) def test_runFailure(self): """ Run a test, and fail. """ results = [] d = self.worker.callRemote(managercommands.AddFailure, testName=self.testName, fail='fail', failClass='exceptions.RuntimeError', frames=[]) d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertEqual(self.testCase, self.result.failures[0][0]) self.assertTrue(results) def test_runSkip(self): """ Run a test, but skip it. """ results = [] d = self.worker.callRemote(managercommands.AddSkip, testName=self.testName, reason='reason') d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertEqual(self.testCase, self.result.skips[0][0]) self.assertTrue(results) def test_runUnexpectedSuccesses(self): """ Run a test, and succeed unexpectedly. """ results = [] d = self.worker.callRemote(managercommands.AddUnexpectedSuccess, testName=self.testName, todo='todo') d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertEqual(self.testCase, self.result.unexpectedSuccesses[0][0]) self.assertTrue(results) def test_testWrite(self): """ L{LocalWorkerAMP.testWrite} writes the data received to its test stream. """ results = [] stream = StringIO() self.managerAMP.setTestStream(stream) d = self.worker.callRemote(managercommands.TestWrite, out="Some output") d.addCallback(lambda result: results.append(result['success'])) self.pumpTransports() self.assertEqual("Some output\n", stream.getvalue()) self.assertTrue(results) def test_stopAfterRun(self): """ L{LocalWorkerAMP.run} calls C{stopTest} on its test result once the C{Run} commands has succeeded. """ result = object() stopped = [] def fakeCallRemote(command, testCase): return succeed(result) self.managerAMP.callRemote = fakeCallRemote class StopTestResult(TestResult): def stopTest(self, test): stopped.append(test) d = self.managerAMP.run(self.testCase, StopTestResult()) self.assertEqual([self.testCase], stopped) return d.addCallback(self.assertIdentical, result)