本文整理汇总了Python中twisted.internet.defer.fail方法的典型用法代码示例。如果您正苦于以下问题:Python defer.fail方法的具体用法?Python defer.fail怎么用?Python defer.fail使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.defer
的用法示例。
在下文中一共展示了defer.fail方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: checkSoledadToken
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def checkSoledadToken(self, username, password, service):
soledad = self._soledad_sessions.get(username)
if not soledad:
return defer.fail(Exception("No soledad"))
def match_token(token):
if token is None:
raise RuntimeError('no token')
if token == password:
return username
else:
raise RuntimeError('bad token')
d = soledad.get_or_create_service_token(service)
d.addCallback(match_token)
return d
示例2: testExtractInvalidAttachedKey
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def testExtractInvalidAttachedKey(self):
KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..."
message = MIMEMultipart()
message.add_header("from", ADDRESS_2)
key = MIMEApplication("", "pgp-keys")
key.set_payload(KEY)
message.attach(key)
self.fetcher._keymanager.put_raw_key = Mock(
return_value=defer.fail(KeyAddressMismatch()))
def put_raw_key_called(_):
self.fetcher._keymanager.put_raw_key.assert_called_once_with(
KEY, address=ADDRESS_2)
d = self._do_fetch(message.as_string())
d.addCallback(put_raw_key_called)
d.addErrback(log.err)
return d
示例3: testExtractOpenPGPHeaderIfInvalidAttachedKey
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def testExtractOpenPGPHeaderIfInvalidAttachedKey(self):
KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n..."
KEYURL = "https://leap.se/key.txt"
OpenPGP = "id=12345678; url=\"%s\"; preference=signencrypt" % (KEYURL,)
message = MIMEMultipart()
message.add_header("from", ADDRESS_2)
message.add_header("OpenPGP", OpenPGP)
key = MIMEApplication("", "pgp-keys")
key.set_payload(KEY)
message.attach(key)
self.fetcher._keymanager.put_raw_key = Mock(
return_value=defer.fail(KeyAddressMismatch()))
self.fetcher._keymanager.fetch_key = Mock()
def put_raw_key_called(_):
self.fetcher._keymanager.put_raw_key.assert_called_once_with(
KEY, address=ADDRESS_2)
self.fetcher._keymanager.fetch_key.assert_called_once_with(
ADDRESS_2, KEYURL)
d = self._do_fetch(message.as_string())
d.addCallback(put_raw_key_called)
return d
示例4: testLogErrorIfDecryptFails
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def testLogErrorIfDecryptFails(self):
def assert_failure(_):
mock_logger_error.assert_any_call('_decrypt_doc: '
'Error decrypting document with '
'ID 1')
with patch.object(Logger, 'error') as mock_logger_error:
doc = SoledadDocument()
doc.doc_id = '1'
doc.content = {'_enc_json': ''}
self.fetcher._process_decrypted_doc = Mock()
self.km.decrypt = Mock(
return_value=defer.fail(Exception()))
d = self.fetcher._decrypt_doc(doc)
d.addCallback(assert_failure)
return d
示例5: _deferToThreadPool
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def _deferToThreadPool(self, f, *args, **kwargs):
"""Defer execution of ``f(*args, **kwargs)`` to the thread pool.
This returns a deferred which will callback with the result of
that expression, or errback with a failure wrapping the raised
exception.
"""
if self._pool.joined:
return fail(
ReactorNotRunning("This thimble's threadpool already stopped.")
)
if not self._pool.started:
self._pool.start()
self._reactor.addSystemEventTrigger(
'during', 'shutdown', self._pool.stop)
return deferToThreadPool(self._reactor, self._pool, f, *args, **kwargs)
示例6: request
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def request(self, request):
"""
Send a request to the Kafka broker.
:param bytes request:
The bytes of a Kafka `RequestMessage`_ structure. It must have
a unique (to this connection) correlation ID.
:returns:
`Deferred` which will:
- Succeed with the bytes of a Kafka `ResponseMessage`_
- Fail when the connection terminates
.. _RequestMessage:: https://kafka.apache.org/protocol.html#protocol_messages
"""
if self._failed is not None:
return fail(self._failed)
correlation_id = request[4:8]
assert correlation_id not in self._pending
d = Deferred()
self.sendString(request)
self._pending[correlation_id] = d
return d
示例7: test_join_error
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_join_error(self):
"""
Get an error when joining and retry
"""
client = self.mock_client([
defer.fail(RebalanceInProgress()),
self.join_response(),
self.sync_response(),
])
coord = self.make_coordinator(client)
de = coord.join_and_sync()
self.successResultOf(de)
self.assertEqual(coord._rejoin_needed, True)
assert_delayed_calls(1, client)
de = coord.join_and_sync()
self.successResultOf(de)
self.assertEqual(coord._rejoin_needed, False)
示例8: test_sync_error
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_sync_error(self):
"""
Get an error when syncing and retry
"""
client = self.mock_client([
self.join_response(),
defer.fail(RebalanceInProgress()),
self.join_response(),
self.sync_response(),
])
coord = self.make_coordinator(client)
de = coord.join_and_sync()
self.successResultOf(de)
self.assertEqual(coord._rejoin_needed, True)
assert_delayed_calls(1, client)
de = coord.join_and_sync()
self.successResultOf(de)
self.assertEqual(coord._rejoin_needed, False)
示例9: test_get_coordinator_retry
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_get_coordinator_retry(self):
"""
fail to retrieve a coordinator and retry
"""
client = self.mock_client([
defer.succeed(Mock(error_code=0)),
])
coord = self.make_coordinator(client)
client._get_coordinator_for_group.return_value = defer.fail(
RequestTimedOutError())
client._get_brokerclient.return_value = None
de = coord.get_coordinator_broker()
self.successResultOf(de)
assert_delayed_calls(1, client) # Heartbeat scheduled.
client._get_coordinator_for_group.return_value = defer.fail(UnknownError())
de = coord.get_coordinator_broker()
self.successResultOf(de)
示例10: test_producer_send_messages_no_retry_fail
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_producer_send_messages_no_retry_fail(self):
client = Mock(reactor=MemoryReactorClock())
f = Failure(BrokerNotAvailableError())
client.send_produce_request.side_effect = [fail(f)]
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
producer = Producer(client, max_req_attempts=1)
d = producer.send_messages(self.topic, msgs=msgs)
# Check the expected request was sent
msgSet = create_message_set(
make_send_requests(msgs), producer.codec)
req = ProduceRequest(self.topic, 0, msgSet)
client.send_produce_request.assert_called_once_with(
[req], acks=producer.req_acks, timeout=producer.ack_timeout,
fail_on_error=False)
self.failureResultOf(d, BrokerNotAvailableError)
producer.stop()
示例11: test_producer_stop_during_request
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_producer_stop_during_request(self):
"""
Test stopping producer while it's waiting for reply from client
"""
clock = MemoryReactorClock()
client = Mock(reactor=clock)
f = Failure(BrokerNotAvailableError())
ret = [fail(f), Deferred()]
client.send_produce_request.side_effect = ret
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
batch_n = 2
producer = Producer(client, batch_every_n=batch_n, batch_send=True)
d = producer.send_messages(self.topic, msgs=msgs)
# At first, there's no result. Have to retry due to first failure
self.assertNoResult(d)
clock.advance(producer._retry_interval)
producer.stop()
self.failureResultOf(d, tid_CancelledError)
示例12: test_producer_stop_waiting_to_retry
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_producer_stop_waiting_to_retry(self):
"""
Test stopping producer while it's waiting to retry a request
"""
clock = MemoryReactorClock()
client = Mock(reactor=clock)
f = Failure(BrokerNotAvailableError())
ret = [fail(f)]
client.send_produce_request.side_effect = ret
client.topic_partitions = {self.topic: [0, 1, 2, 3]}
client.metadata_error_for_topic.return_value = False
msgs = [self.msg("one"), self.msg("two")]
batch_n = 2
producer = Producer(client, batch_every_n=batch_n, batch_send=True)
d = producer.send_messages(self.topic, msgs=msgs)
# At first, there's no result. Have to retry due to first failure
self.assertNoResult(d)
# Advance the clock, some, but not enough to retry
clock.advance(producer._retry_interval / 2)
# Stop the producer before the retry
producer.stop()
self.failureResultOf(d, tid_CancelledError)
示例13: request
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def request(self, method, uri, headers=None, bodyProducer=None):
"""
Issue a request to the server indicated by the given C{uri}.
An existing connection from the connection pool may be used or a new
one may be created.
I{HTTP} and I{HTTPS} schemes are supported in C{uri}.
@see: L{twisted.web.iweb.IAgent.request}
"""
parsedURI = URI.fromBytes(uri)
try:
endpoint = self._getEndpoint(parsedURI)
except SchemeNotSupported:
return defer.fail(Failure())
key = (parsedURI.scheme, parsedURI.host, parsedURI.port)
return self._requestWithEndpoint(key, endpoint, method, parsedURI,
headers, bodyProducer,
parsedURI.originForm)
示例14: test_renderNoFailure
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_renderNoFailure(self):
"""
If the L{Deferred} fails, L{DeferredResource} reports the failure via
C{processingFailed}, and does not cause an unhandled error to be
logged.
"""
request = DummyRequest([])
d = request.notifyFinish()
failure = Failure(RuntimeError())
deferredResource = DeferredResource(defer.fail(failure))
deferredResource.render(request)
self.assertEqual(self.failureResultOf(d), failure)
del deferredResource
gc.collect()
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(errors, [])
示例15: test_doubleEncodingError
# 需要导入模块: from twisted.internet import defer [as 别名]
# 或者: from twisted.internet.defer import fail [as 别名]
def test_doubleEncodingError(self):
"""
If it is not possible to encode a response to the request (for example,
because L{xmlrpclib.dumps} raises an exception when encoding a
L{Fault}) the exception which prevents the response from being
generated is logged and the request object is finished anyway.
"""
d = self.proxy().callRemote("echo", "")
# *Now* break xmlrpclib.dumps. Hopefully the client already used it.
def fakeDumps(*args, **kwargs):
raise RuntimeError("Cannot encode anything at all!")
self.patch(xmlrpclib, 'dumps', fakeDumps)
# It doesn't matter how it fails, so long as it does. Also, it happens
# to fail with an implementation detail exception right now, not
# something suitable as part of a public interface.
d = self.assertFailure(d, Exception)
def cbFailed(ignored):
# The fakeDumps exception should have been logged.
self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)
d.addCallback(cbFailed)
return d