Here are the examples of the python api twisted.python.failure.Failure taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
165 Examples
3
Example 1
def test_client_connection_lost(self):
"""
Verify that connection lost causes the connection object to close.
"""
exc = Exception('a test')
self.obj_ut.clientConnectionLost(None, Failure(exc))
self.mock_connection.defunct.assert_called_with(exc)
3
Example 2
Project: Tor2web Source File: socks.py
def socks_state_1(self):
if len(self._buf) < 2:
return
if self._buf[:2] != "\x05\x00":
# Anonymous access denied
self.error(Failure(SOCKSError(0x00)))
return
self._buf = self._buf[2:]
if not self._optimistic:
self.transport.write(
struct.pack("!BBBBB", 5, 1, 0, 3, len(self._host)) + self._host + struct.pack("!H", self._port))
self.state = 2
getattr(self, 'socks_state_%s' % self.state)()
3
Example 3
Project: palaver Source File: cred.py
def requestAvatarId(self, credentials):
if credentials.username == "":
return failure.Failure(credError.UnauthorizedLogin())
if credentials.password == "":
return failure.Failure(credError.UnauthorizedLogin())
return defer.maybeDeferred(
self.login,
credentials.username,
credentials.password).addCallback(
self._cbPasswordMatch)
3
Example 4
Project: eliot Source File: test_traceback.py
def test_systemDeprecatedWriteFailure(self):
"""
L{writeTraceback} warns with C{DeprecationWarning} if a C{system}
argument is passed in.
"""
if Failure is None:
raise SkipTest("Twisted unavailable")
logger = MemoryLogger()
with catch_warnings(record=True) as warnings:
simplefilter("always")
try:
raise Exception()
except:
writeFailure(Failure(), logger, "system")
self.assertEqual(warnings[-1].category, DeprecationWarning)
3
Example 5
Project: ants Source File: defer.py
def iter_errback(iterable, errback, *a, **kw):
"""Wraps an iterable calling an errback if an error is caught while
iterating it.
"""
it = iter(iterable)
while 1:
try:
yield next(it)
except StopIteration:
break
except:
errback(failure.Failure(), *a, **kw)
3
Example 6
Project: treq Source File: test_content.py
def test_collect_failure_potential_data_loss(self):
"""
PotentialDataLoss failures are treated as success.
"""
data = []
d = collect(self.response, data.append)
self.protocol.dataReceived(b'foo')
self.protocol.connectionLost(Failure(PotentialDataLoss()))
self.assertEqual(self.successResultOf(d), None)
self.assertEqual(data, [b'foo'])
3
Example 7
Project: spinoff Source File: __init__.py
def waitForGreenlet(g):
"""Link greenlet completion to Deferred"""
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
d = defer.Deferred()
def cb(g):
try:
d.callback(g.get())
except:
d.errback(failure.Failure())
g.link(d)
return d
3
Example 8
def _error(self, failure, fetcher):
try:
self.time += time.time()
try:
failure.raiseException()
except:
logger.exception('Failed for %s in %fs' % (self.url, self.time))
self.onError(failure, fetcher)
except Exception as e:
logger.exception('Request error handler failed')
return Failure(self)
3
Example 9
Project: mark2 Source File: test_process.py
def test_process_failure(self):
fail = Failure(error.ProcessTerminated(exitCode=1))
self.proto.processEnded(fail)
self.assertFalse(self.proto.alive)
self.assertTrue(any(isinstance(event, events.FatalError) for event in self.dispatched))
3
Example 10
def resumeProducing(self):
self._paused = False
try:
# only start a new chunk if we're done loading our
# existing chunks and we actually stopped doing anything
# -- if we're still loading, load_chunk will be called
# normally from the callback
if (self.chunk_idx != None and
self.chunk_idx == self.chunk_loaded_idx):
return self.load_chunk()
except Exception, e:
self.abort(failure.Failure(e))
3
Example 11
Project: ZenPacks.zenoss.OpenStackInfrastructure Source File: __init__.py
def _cbdone(self, result, callback):
'Callback to store the results'
if isinstance(result, failure.Failure):
callback.errback(result)
else:
callback.callback(result)
3
Example 12
def _err(self, fail):
if self.failure is None:
self.failure = fail
try:
if not self.cancelled:
fail = self._failureTester(fail)
except:
self._deferred.errback()
else:
if isinstance(fail, failure.Failure):
self._deferred.errback(fail)
else:
self._call()
3
Example 13
def store_error(self, device, error):
"""
Called when an errback is fired.
Should do somethign meaningful with the errors, but for now just stores
it as it would a result.
"""
devname = str(device)
log.msg("Storing error for %s: %s" % (devname, error))
if isinstance(error, failure.Failure):
error = error.value
devobj = self.device_object(devname, error=repr(error))
log.msg("Final device object: %r" % devobj)
self.errors.append(devobj)
return True
3
Example 14
Project: powerstrip Source File: powerstrip.py
def setStreamingMode(self, streamingMode):
"""
Allow anyone with a reference to us to toggle on/off streaming mode.
Useful when we have no post-hooks (and no indication from Docker that
it's sending packets of JSON e.g. with build) and we want to avoid
buffering slow responses in memory.
"""
self._streaming = streamingMode
if streamingMode:
self._fireListener(Failure(NoPostHooks()))
3
Example 15
def test_failure(self, log_msg_mock):
exc = Exception('blah')
failure = Failure(exc)
result = self.resource.handle_error(failure, self.request)
self.assertEqual(self.request.code, 500)
self.assertEqual(result['message'], exc.message)
self._assert_log_err_called(log_msg_mock, failure)
3
Example 16
def err(self, _stuff=None, _why=None, **kw):
if _stuff is None:
_stuff = failure.Failure()
kw['isError'] = True
kw['why'] = _why
if isinstance(_stuff, failure.Failure):
self.log(failure=_stuff, **kw)
elif isinstance(_stuff, Exception):
self.log(failure=failure.Failure(_stuff), **kw)
else:
self.log(repr(_stuff), **kw)
3
Example 17
def errback(self, result=None):
if result is None:
result = Failure()
l = self.listeners
self.listeners = []
for d in l:
d.errback(result)
3
Example 18
def _defer_to_worker(deliver, worker, work, *args, **kwargs):
deferred = Deferred()
@worker.do
def container():
try:
result = work(*args, **kwargs)
except:
f = Failure()
deliver(lambda: deferred.errback(f))
else:
deliver(lambda: deferred.callback(result))
return deferred
3
Example 19
Project: silverberg Source File: test_thrift_client.py
def test_disconnect_while_disconnecting(self):
self.client.connection()
self.connect_d.callback(None)
d1 = self.client.disconnect()
self.twisted_transport.reset_mock()
d2 = self.client.disconnect()
self.connection_lost(Failure(_TestConnectionDone()))
self.assertEqual(
len(self.twisted_transport.loseConnection.mock_calls), 0,
"loseConnection should not be called since not connected")
self.assertFired(d1)
self.assertFired(d2)
3
Example 20
Project: mark2 Source File: test_process.py
def test_process_success(self):
fail = Failure(error.ProcessDone(None))
self.proto.processEnded(fail)
self.assertFalse(self.proto.alive)
self.assertEqual(len(self.dispatched), 1)
self.assertIsInstance(self.dispatched[0], events.ServerStopped)
3
Example 21
Project: petmail Source File: common.py
def anyways(self, res, cb, *args, **kwargs):
# always run the cleanup callback
d = defer.maybeDeferred(cb, *args, **kwargs)
if isinstance(res, failure.Failure):
# let the original failure passthrough
d.addBoth(lambda _: res)
# otherwise the original result was success, so just return the
# cleanup result
return d
3
Example 22
def process_chain_both(callbacks, errbacks, input, *a, **kw):
"""Return a Deferred built by chaining the given callbacks and errbacks"""
d = defer.Deferred()
for cb, eb in zip(callbacks, errbacks):
d.addCallbacks(cb, eb, callbackArgs=a, callbackKeywords=kw,
errbackArgs=a, errbackKeywords=kw)
if isinstance(input, failure.Failure):
d.errback(input)
else:
d.callback(input)
return d
3
Example 23
def test_onError(self):
"""
An observer for stream errors should trigger onError to log it.
"""
self.xmlstream.dispatch(self.xmlstream,
xmlstream.STREAM_CONNECTED_EVENT)
class TestError(Exception):
pass
reason = failure.Failure(TestError())
self.xmlstream.dispatch(reason, xmlstream.STREAM_ERROR_EVENT)
self.assertEqual(1, len(self.flushLoggedErrors(TestError)))
3
Example 24
Project: awspider Source File: admin.py
def render(self, request):
request.setHeader('Content-type', 'text/javascript; charset=UTF-8')
if len(request.postpath) > 0:
if request.postpath[0] == "clear_http_cache":
d = self.adminserver.clearHTTPCache()
d.addCallback(self._successResponse)
d.addErrback(self._errorResponse)
d.addCallback(self._immediateResponse, request)
return server.NOT_DONE_YET
return self._errorResponse(Failure(exc_value=Exception("Unknown request.")))
3
Example 25
def test_authenticate(self):
d = defer.Deferred()
def auth(u, p):
try:
self.assertEquals(u, 'u')
self.assertEquals(p, 'p')
except:
d.errback(failure.Failure())
else:
d.callback(None)
gw = _twisted.TwistedGateway({'echo': lambda x: x}, authenticator=auth)
self.service_request = gateway.ServiceRequest(None, gw.services['echo'], None)
gw.authenticateRequest(self.service_request, 'u', 'p')
return d
3
Example 26
Project: ZenPacks.zenoss.Microsoft.Windows Source File: testShellDataSource.py
Function: test_on_error
Function: test_on_error
@patch('ZenPacks.zenoss.Microsoft.Windows.datasources.ShellDataSource.log', Mock())
def test_onError(self):
f = None
try:
f = Failure('foo')
except TypeError:
f = Failure()
data = self.plugin.onError(f, sentinel)
self.assertEquals(len(data['events']), 1)
self.assertEquals(data['events'][0]['severity'], 3)
3
Example 27
def parseError(self, err, query, instMap):
if isinstance(err.value, pywbem.cim_http.AuthError):
msg = 'AuthError: Please check zWinUser and zWinPassword zProperties'
else:
msg = 'Received %s from query: %s'%(err.value[1], query)
err = Failure(err)
err.value = msg
log.error(err.getErrorMessage())
results = {}
for instances in instMap.values():
for tables in instances.values():
for table, props in tables:
results[table] = [err]
return results
3
Example 28
Project: plugin.video.streamondemand Source File: TLSTwistedProtocolWrapper.py
Function: data_received
Function: data_received
def dataReceived(self, data):
try:
if not self.tlsStarted:
ProtocolWrapper.dataReceived(self, data)
else:
self.fakeSocket.data += data
while self.fakeSocket.data:
AsyncStateMachine.inReadEvent(self)
except TLSError, e:
self.connectionLost(Failure(e))
ProtocolWrapper.loseConnection(self)
3
Example 29
def retry():
log.debug('retrying')
d = client.run('sleep 5 && ls')
def failed_or_success(result):
if isinstance(result, failure.Failure):
log.info("Failed %s" % (result, ))
else:
log.info("Success %s" % (result, ))
d.addBoth(failed_or_success)
d2 = client.run('sleep 5 && ls', timeout=6)
d2.addBoth(failed_or_success)
reactor.callLater(6, retry)
3
Example 30
def _handle_error(self, traceback, msg, details):
trace_str = str(traceback)
try:
error_message = traceback.getErrorMessage()
except:
try:
error_message = getattr(traceback, 'message')
except:
error_message = trace_str
if not (msg.startswith("downloading") and ("503 " in trace_str or "307 Temporary" in trace_str or "406 Not Acceptable" in trace_str or "was closed cleanly" in trace_str or "User timeout caused" in trace_str)):
self.log("while %s %s : %s" % (msg, details, error_message.replace('\n', '')), error=True)
if trace_str and not (msg.startswith("downloading") or "status 503" in trace_str or "ERROR 503" in trace_str or "ERROR 500" in trace_str or "ERROR 111: Network difficulties" in trace_str or '111] Connection refused' in trace_str):
if (config.DEBUG and "429" not in trace_str) or not msg.startswith("examining"):
self.log(trace_str, error=True)
self.fact.ircclient._show_error(failure.Failure(Exception("%s %s: %s" % (msg, details, error_message))), self.fact.channel, admins=True)
if ('403 Forbidden' in trace_str or '111: Connection refused' in trace_str) and self.fact.tweets_search_page:
self.fact.ircclient.breathe = datetime.today() + timedelta(minutes=20)
3
Example 31
Project: eliot Source File: test_twisted.py
def test_addActionFinishFailurePassThrough(self):
"""
L{DeferredContext.addActionFinish} passes through a failed result
unchanged.
"""
d = Deferred()
logger = MemoryLogger()
action = Action(logger, "uuid", TaskLevel(level=[1]), "sys:me")
with action.context():
DeferredContext(d).addActionFinish()
failure = Failure(RuntimeError())
d.errback(failure)
result = []
d.addErrback(result.append)
self.assertEqual(result, [failure])
3
Example 32
Project: treq Source File: test_content.py
def test_collect_failure(self):
data = []
d = collect(self.response, data.append)
self.protocol.dataReceived(b'foo')
self.protocol.connectionLost(Failure(ResponseFailed("test failure")))
self.failureResultOf(d, ResponseFailed)
self.assertEqual(data, [b'foo'])
3
Example 33
def __block(self, fn, *args, **kw):
"""Calls the given function in a thread pool."""
queue = Queue.Queue()
self.__threadPool.callInThreadWithCallback(lambda *result: queue.put(result), fn, *args, **kw)
result = queue.get()[1]
if isinstance(result, failure.Failure):
result.raiseException()
return result
3
Example 34
Project: silverberg Source File: test_thrift_client.py
def test_connect_while_disconnecting(self):
d1 = self.client.connection()
self.connect_d.callback(None)
self.assertFired(d1)
d2 = self.client.disconnect()
d3 = self.client.connection()
self.connection_lost(Failure(_TestConnectionDone()))
self.assertFired(d2)
self.assertFailed(d3, ClientDisconnecting)
3
Example 35
@defer.inlineCallbacks
def connectionMade(self):
# Get host-specific creds so we can properly # create the sasl client
peer = self.transport.getPeer()
sasl_kwargs = yield defer.maybeDeferred(
self.sasl_cred_factory, peer.host, peer.port)
self.createSASLClient(**sasl_kwargs)
try:
yield ThriftSASLClientProtocol.connectionMade(self)
except Exception, exc:
self.transport.loseConnection()
self.factory.clientConnectionFailed(self.factory.connector, failure.Failure(exc))
else:
self.factory.clientConnectionMade(self)
3
Example 36
Project: vertex Source File: gtk2hack.py
def rejectConnectionEvt(self, evt):
print "DSTRY"
if not self.done:
print "DIE!"
from twisted.python import failure
self.d.errback(failure.Failure(KeyError("Connection rejected by user")))
else:
print "OK"
3
Example 37
Project: twitty-twister Source File: test_twitter.py
def test_stopServiceConnected(self):
"""
Stopping the service while waiting to reconnect should abort.
"""
self.setUpState('connected')
# Stop the service.
self.monitor.stopService()
# Actually lose the connection
self.api.protocol.connectionLost(failure.Failure(ResponseDone()))
# No reconnect should be attempted.
self.clock.advance(DELAY_INITIAL)
self.assertEqual(1, len(self.api.filterCalls))
3
Example 38
Project: scrapy Source File: log.py
def err(_stuff=None, _why=None, **kw):
warnings.warn('log.err has been deprecated, create a python logger and '
'use its error method instead',
ScrapyDeprecationWarning, stacklevel=2)
level = kw.pop('level', logging.ERROR)
failure = kw.pop('failure', _stuff) or Failure()
message = kw.pop('why', _why) or failure.value
logger.log(level, message, *[kw] if kw else [], exc_info=failure_to_exc_info(failure))
3
Example 39
def pageEnd(self):
if self.file:
try:
self.file.close()
except IOError:
self.deferred.errback(failure.Failure())
return
self.deferred.callback(self.filenames)
3
Example 40
Project: palaver Source File: cred.py
def _cbPasswordMatch(self, xs):
if xs:
# TODO - send xmlstream
xs.send('</stream:stream>')
xs = None
return self.myJid
else:
return failure.Failure(credError.UnauthorizedLogin())
3
Example 41
def _gotResult(self, result):
self._connecting = False
if not isinstance(result, failure.Failure):
self._proto = result
self._proto.deferred.addErrback(self._lostProtocol)
waiting, self._waiting = self._waiting, []
for d in waiting:
d.callback(result)
return result
3
Example 42
def dataReceived(self, data):
"""
Receive and parse some data.
:param data: A ``str`` from Twisted.
"""
if self._disconnecting:
return
try:
self._parser.receive(data)
except Exception:
self.connectionLost(Failure())
self.transport.abortConnection()
return
3
Example 43
Project: Tor2web Source File: socks.py
def socks_state_2(self):
if len(self._buf) < 2:
return
if self._buf[:2] != "\x05\x00":
self.error(Failure(SOCKSError(ord(self._buf[1]))))
return
self._buf = self._buf[2:]
self.state = 3
getattr(self, 'socks_state_%s' % self.state)()
3
Example 44
Project: petmail Source File: eventsource.py
def _stopped(self, res):
self.es = None
# we might have stopped because of a connection error, or because of
# an intentional shutdown.
if self.active and self.running:
# we still want to be connected, so schedule a reconnection
if isinstance(res, failure.Failure):
log.err(res)
self.retry() # will eventually call _maybeStart
return
# intentional shutdown
self.stopTrying()
for d in self.when_stopped:
eventually(d.callback, None)
self.when_stopped = []
3
Example 45
Project: fmspy Source File: status.py
@staticmethod
def from_failure(fail):
"""
Build status object from failure.
@param fail: failure or exception
@type fail: C{Failure}
"""
if isinstance(fail, failure.Failure):
fail = fail.value
kwargs = { 'description' : repr(fail) }
if hasattr(fail, 'code'):
kwargs['code'] = fail.code
return Status(**kwargs)
3
Example 46
Project: airpnp Source File: test_util.py
def test_unrecognized_error_is_reraised(self, pageMock):
# Setup mock
f = failure.Failure(error.Error(http.NOT_FOUND, 'Not Found', 'Not Found'))
pageMock.return_value = defer.fail(f)
# Given
msg = SoapMessage('urn:schemas-upnp-org:service:ConnectionManager:1', 'GetCurrentConnectionIDs')
# When
d = send_soap_message_deferred('http://www.dummy.com', msg)
# Then
f = d.result
self.assertTrue(f.check(error.Error))
3
Example 47
Project: cache-busters Source File: test_driver.py
def test_invalidate_row_logs_on_cache_delete_failure(self):
f = Failure(Exception())
cache = pretend.stub(
delete=lambda key: fail(f),
)
logger = pretend.stub(
msg=lambda s, **kwargs: None,
err=pretend.call_recorder(lambda failure, table, key: None)
)
d = Driver(FormattingKeyMaker({
"foo_table": ["bar"]
}), cache, logger)
d.invalidate_row("foo_table", {})
self.assertEqual(logger.err.calls, [
pretend.call(f, table="foo_table", key="bar")
])
3
Example 48
Project: Eventlet Source File: __init__.py
def _putResultInDeferred(deferred, f, args, kwargs):
try:
result = f(*args, **kwargs)
except:
from twisted.python import failure
f = failure.Failure()
deferred.errback(f)
else:
deferred.callback(result)
3
Example 49
Project: plugin.video.streamondemand Source File: TLSTwistedProtocolWrapper.py
def connectionMade(self):
try:
ProtocolWrapper.connectionMade(self)
except TLSError, e:
self.connectionLost(Failure(e))
ProtocolWrapper.loseConnection(self)
3
Example 50
Project: ZenPacks.zenoss.Microsoft.Windows Source File: testServiceDataSource.py
@patch('ZenPacks.zenoss.Microsoft.Windows.datasources.ServiceDataSource.log', Mock())
def test_onError(self):
f = None
try:
f = Failure('foo')
except TypeError:
f = Failure()
data = self.plugin.onError(f, MagicMock(
id=sentinel.id,
datasources=self.ds,
))
self.assertEquals(len(data['events']), 1)
self.assertEquals(data['events'][0]['severity'], 4)