Python源码示例:twisted.python.failure.value()
示例1
def _format_error(failure):
"""
Logs the failure backtrace, and returns a json containing the error
message.
If a exception declares the 'expected' attribute as True,
we will not print a full traceback. instead, we will dispatch
the ``exception`` message attribute as the ``error`` field in the response
json.
"""
expected = getattr(failure.value, 'expected', False)
if not expected:
log.error('[DISPATCHER] Unexpected error!')
log.error('{0!r}'.format(failure.value))
log.error(failure.getTraceback())
# if needed, we could add here the exception type as an extra field
return json.dumps({'error': failure.value.message, 'result': None})
示例2
def assertFailure(self, deferred, *expectedFailures):
"""
Fail if C{deferred} does not errback with one of C{expectedFailures}.
Returns the original Deferred with callbacks added. You will need
to return this Deferred from your test case.
"""
def _cb(ignore):
raise self.failureException(
"did not catch an error, instead got %r" % (ignore,))
def _eb(failure):
if failure.check(*expectedFailures):
return failure.value
else:
output = ('\nExpected: %r\nGot:\n%s'
% (expectedFailures, str(failure)))
raise self.failureException(output)
return deferred.addCallbacks(_cb, _eb)
示例3
def getTimeout(self):
"""
Returns the timeout value set on this test. Checks on the instance
first, then the class, then the module, then packages. As soon as it
finds something with a C{timeout} attribute, returns that. Returns
L{util.DEFAULT_TIMEOUT_DURATION} if it cannot find anything. See
L{TestCase} docstring for more details.
"""
timeout = util.acquireAttribute(self._parents, 'timeout',
util.DEFAULT_TIMEOUT_DURATION)
try:
return float(timeout)
except (ValueError, TypeError):
# XXX -- this is here because sometimes people will have methods
# called 'timeout', or set timeout to 'orange', or something
# Particularly, test_news.NewsTestCase and ReactorCoreTestCase
# both do this.
warnings.warn("'timeout' attribute needs to be a number.",
category=DeprecationWarning)
return util.DEFAULT_TIMEOUT_DURATION
示例4
def lookup(self, serverAddress, clientAddress):
"""
Lookup user information about the specified address pair.
Return value should be a two-tuple of system name and username.
Acceptable values for the system name may be found online at::
U{http://www.iana.org/assignments/operating-system-names}
This method may also raise any IdentError subclass (or IdentError
itself) to indicate user information will not be provided for the
given query.
A Deferred may also be returned.
@param serverAddress: A two-tuple representing the server endpoint
of the address being queried. The first element is a string holding
a dotted-quad IP address. The second element is an integer
representing the port.
@param clientAddress: Like I{serverAddress}, but represents the
client endpoint of the address being queried.
"""
raise IdentError()
示例5
def test_cancelDeferredListWithFireOnOneErrback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneErrback} set, cancel every L{defer.Deferred} in the list.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
deferredListFailure = self.failureResultOf(deferredList,
defer.FirstError)
firstError = deferredListFailure.value
self.assertTrue(firstError.subFailure.check(defer.CancelledError))
示例6
def test_errbackWithNoArgsNoDebug(self):
"""
C{Deferred.errback()} creates a failure from the current Python
exception. When Deferred.debug is not set no globals or locals are
captured in that failure.
"""
defer.setDebugging(False)
d = defer.Deferred()
l = []
exc = GenericError("Bang")
try:
raise exc
except:
d.errback()
d.addErrback(l.append)
fail = l[0]
self.assertEqual(fail.value, exc)
localz, globalz = fail.frames[0][-2:]
self.assertEqual([], localz)
self.assertEqual([], globalz)
示例7
def test_errbackWithNoArgs(self):
"""
C{Deferred.errback()} creates a failure from the current Python
exception. When Deferred.debug is set globals and locals are captured
in that failure.
"""
defer.setDebugging(True)
d = defer.Deferred()
l = []
exc = GenericError("Bang")
try:
raise exc
except:
d.errback()
d.addErrback(l.append)
fail = l[0]
self.assertEqual(fail.value, exc)
localz, globalz = fail.frames[0][-2:]
self.assertNotEqual([], localz)
self.assertNotEqual([], globalz)
示例8
def test_timedOutCustom(self):
"""
If a custom C{onTimeoutCancel] function is provided, the
L{defer.Deferred} returns the custom function's return value if the
L{defer.Deferred} times out before callbacking or errbacking.
The custom C{onTimeoutCancel} function can return a result instead of
a failure.
"""
clock = Clock()
d = defer.Deferred()
d.addTimeout(10, clock, onTimeoutCancel=_overrideFunc)
self.assertNoResult(d)
clock.advance(15)
self.assertEqual("OVERRIDDEN", self.successResultOf(d))
示例9
def test_timedOutProvidedCancelFailure(self):
"""
If a cancellation function is provided when the L{defer.Deferred} is
initialized, the L{defer.Deferred} returns the cancellation value's
non-L{CanceledError} failure when the L{defer.Deferred} times out.
"""
clock = Clock()
error = ValueError('what!')
d = defer.Deferred(lambda c: c.errback(error))
d.addTimeout(10, clock)
self.assertNoResult(d)
clock.advance(15)
f = self.failureResultOf(d, ValueError)
self.assertIs(f.value, error)
示例10
def test_errbackAddedBeforeTimeoutSuppressesCancellation(self):
"""
An errback added before a timeout is added errbacks with a
L{defer.CancelledError} when the timeout fires. If the
errback suppresses the L{defer.CancelledError}, the deferred
successfully completes.
"""
clock = Clock()
d = defer.Deferred()
dErrbacked = [None]
def errback(f):
dErrbacked[0] = f
f.trap(defer.CancelledError)
d.addErrback(errback)
d.addTimeout(10, clock)
clock.advance(15)
self.assertIsInstance(dErrbacked[0], failure.Failure)
self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)
self.successResultOf(d)
示例11
def test_errbackAddedBeforeTimeoutCustom(self):
"""
An errback added before a timeout is added with a custom
timeout function errbacks with a L{defer.CancelledError} when
the timeout fires. The timeout function runs if the errback
returns the L{defer.CancelledError}.
"""
clock = Clock()
d = defer.Deferred()
dErrbacked = [None]
def errback(f):
dErrbacked[0] = f
return f
d.addErrback(errback)
d.addTimeout(10, clock, _overrideFunc)
clock.advance(15)
self.assertIsInstance(dErrbacked[0], failure.Failure)
self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)
self.assertEqual("OVERRIDDEN", self.successResultOf(d))
示例12
def test_errbackAddedBeforeTimeoutSuppressesCancellationCustom(self):
"""
An errback added before a timeout is added with a custom
timeout function errbacks with a L{defer.CancelledError} when
the timeout fires. The timeout function runs if the errback
suppresses the L{defer.CancelledError}.
"""
clock = Clock()
d = defer.Deferred()
dErrbacked = [None]
def errback(f):
dErrbacked[0] = f
d.addErrback(errback)
d.addTimeout(10, clock, _overrideFunc)
clock.advance(15)
self.assertIsInstance(dErrbacked[0], failure.Failure)
self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)
self.assertEqual("OVERRIDDEN", self.successResultOf(d))
示例13
def send(self, value=None):
if self.paused:
# If we're paused, we have no result to give
return self
result = getattr(self, 'result', _NO_RESULT)
if result is _NO_RESULT:
return self
if isinstance(result, failure.Failure):
# Clear the failure on debugInfo so it doesn't raise "unhandled
# exception"
self._debugInfo.failResult = None
result.value.__failure__ = result
raise result.value
else:
raise StopIteration(result)
# For PEP-492 support (async/await)
示例14
def _cancelledToTimedOutError(value, timeout):
"""
A default translation function that translates L{Failure}s that are
L{CancelledError}s to L{TimeoutError}s.
@param value: Anything
@type value: Anything
@param timeout: The timeout
@type timeout: L{int}
@rtype: C{value}
@raise: L{TimeoutError}
@since: 16.5
"""
if isinstance(value, failure.Failure):
value.trap(CancelledError)
raise TimeoutError(timeout, "Deferred")
return value
示例15
def acquire(self):
"""
Attempt to acquire the lock. Returns a L{Deferred} that fires on
lock acquisition with the L{DeferredLock} as the value. If the lock
is locked, then the Deferred is placed at the end of a waiting list.
@return: a L{Deferred} which fires on lock acquisition.
@rtype: a L{Deferred}
"""
d = Deferred(canceller=self._cancelAcquire)
if self.locked:
self.waiting.append(d)
else:
self.locked = True
d.callback(self)
return d
示例16
def assertFailure(self, deferred, *expectedFailures):
"""
Fail if C{deferred} does not errback with one of C{expectedFailures}.
Returns the original Deferred with callbacks added. You will need
to return this Deferred from your test case.
"""
def _cb(ignore):
raise self.failureException(
"did not catch an error, instead got %r" % (ignore,))
def _eb(failure):
if failure.check(*expectedFailures):
return failure.value
else:
output = ('\nExpected: %r\nGot:\n%s'
% (expectedFailures, str(failure)))
raise self.failureException(output)
return deferred.addCallbacks(_cb, _eb)
示例17
def getTimeout(self):
"""
Returns the timeout value set on this test. Checks on the instance
first, then the class, then the module, then packages. As soon as it
finds something with a C{timeout} attribute, returns that. Returns
L{util.DEFAULT_TIMEOUT_DURATION} if it cannot find anything. See
L{TestCase} docstring for more details.
"""
timeout = util.acquireAttribute(self._parents, 'timeout',
util.DEFAULT_TIMEOUT_DURATION)
try:
return float(timeout)
except (ValueError, TypeError):
# XXX -- this is here because sometimes people will have methods
# called 'timeout', or set timeout to 'orange', or something
# Particularly, test_news.NewsTestCase and ReactorCoreTestCase
# both do this.
warnings.warn("'timeout' attribute needs to be a number.",
category=DeprecationWarning)
return util.DEFAULT_TIMEOUT_DURATION
示例18
def test_cancelDeferredListWithFireOnOneErrback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneErrback} set, cancel every L{defer.Deferred} in the list.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
deferredListFailure = self.failureResultOf(deferredList,
defer.FirstError)
firstError = deferredListFailure.value
self.assertTrue(firstError.subFailure.check(defer.CancelledError))
示例19
def test_gatherResultsWithConsumeErrors(self):
"""
If a L{Deferred} in the list passed to L{gatherResults} fires with a
failure and C{consumerErrors} is C{True}, the failure is converted to a
L{None} result on that L{Deferred}.
"""
# test successful list of deferreds
dgood = defer.succeed(1)
dbad = defer.fail(RuntimeError("oh noes"))
d = defer.gatherResults([dgood, dbad], consumeErrors=True)
unconsumedErrors = []
dbad.addErrback(unconsumedErrors.append)
gatheredErrors = []
d.addErrback(gatheredErrors.append)
self.assertEqual((len(unconsumedErrors), len(gatheredErrors)),
(0, 1))
self.assertIsInstance(gatheredErrors[0].value, defer.FirstError)
firstError = gatheredErrors[0].value.subFailure
self.assertIsInstance(firstError.value, RuntimeError)
示例20
def test_errbackWithNoArgs(self):
"""
C{Deferred.errback()} creates a failure from the current Python
exception. When Deferred.debug is set globals and locals are captured
in that failure.
"""
defer.setDebugging(True)
d = defer.Deferred()
l = []
exc = GenericError("Bang")
try:
raise exc
except:
d.errback()
d.addErrback(l.append)
fail = l[0]
self.assertEqual(fail.value, exc)
localz, globalz = fail.frames[0][-2:]
self.assertNotEqual([], localz)
self.assertNotEqual([], globalz)
示例21
def test_timedOutProvidedCancelFailure(self):
"""
If a cancellation function is provided when the L{defer.Deferred} is
initialized, the L{defer.Deferred} returns the cancellation value's
non-L{CanceledError} failure when the L{defer.Deferred} times out.
"""
clock = Clock()
error = ValueError('what!')
d = defer.Deferred(lambda c: c.errback(error))
d.addTimeout(10, clock)
self.assertNoResult(d)
clock.advance(15)
f = self.failureResultOf(d, ValueError)
self.assertIs(f.value, error)
示例22
def test_errbackAddedBeforeTimeout(self):
"""
An errback added before a timeout is added errbacks with a
L{defer.CancelledError} when the timeout fires. If the
errback returns the L{defer.CancelledError}, it is translated
to a L{defer.TimeoutError} by the timeout implementation.
"""
clock = Clock()
d = defer.Deferred()
dErrbacked = [None]
def errback(f):
dErrbacked[0] = f
return f
d.addErrback(errback)
d.addTimeout(10, clock)
clock.advance(15)
self.assertIsInstance(dErrbacked[0], failure.Failure)
self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)
self.failureResultOf(d, defer.TimeoutError)
示例23
def test_errbackAddedBeforeTimeoutSuppressesCancellation(self):
"""
An errback added before a timeout is added errbacks with a
L{defer.CancelledError} when the timeout fires. If the
errback suppresses the L{defer.CancelledError}, the deferred
successfully completes.
"""
clock = Clock()
d = defer.Deferred()
dErrbacked = [None]
def errback(f):
dErrbacked[0] = f
f.trap(defer.CancelledError)
d.addErrback(errback)
d.addTimeout(10, clock)
clock.advance(15)
self.assertIsInstance(dErrbacked[0], failure.Failure)
self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)
self.successResultOf(d)
示例24
def test_errbackAddedBeforeTimeoutCustom(self):
"""
An errback added before a timeout is added with a custom
timeout function errbacks with a L{defer.CancelledError} when
the timeout fires. The timeout function runs if the errback
returns the L{defer.CancelledError}.
"""
clock = Clock()
d = defer.Deferred()
dErrbacked = [None]
def errback(f):
dErrbacked[0] = f
return f
d.addErrback(errback)
d.addTimeout(10, clock, _overrideFunc)
clock.advance(15)
self.assertIsInstance(dErrbacked[0], failure.Failure)
self.assertIsInstance(dErrbacked[0].value, defer.CancelledError)
self.assertEqual("OVERRIDDEN", self.successResultOf(d))
示例25
def _on_no_port_mapping_received(self, failure, mappings):
"""
Called when we have no more port mappings to retreive, or an
error occured while retreiving them.
Either we have a "SpecifiedArrayIndexInvalid" SOAP error, and that's ok,
it just means we have finished. If it returns some other error, then we
fail with an UPnPError.
@param mappings: the already retreived mappings
@param failure: the failure
@return: The existing mappings as defined in L{get_port_mappings}
@raise UPnPError: When we got any other error
than "SpecifiedArrayIndexInvalid"
"""
logging.debug("_on_no_port_mapping_received: %s", failure)
err = failure.value
message = err.args[0]["UPnPError"]["errorDescription"]
if "SpecifiedArrayIndexInvalid" == message:
return mappings
else:
return failure
示例26
def makeTodo(value):
"""
Return a L{Todo} object built from C{value}.
If C{value} is a string, return a Todo that expects any exception with
C{value} as a reason. If C{value} is a tuple, the second element is used
as the reason and the first element as the excepted error(s).
@param value: A string or a tuple of C{(errors, reason)}, where C{errors}
is either a single exception class or an iterable of exception classes.
@return: A L{Todo} object.
"""
if isinstance(value, str):
return Todo(reason=value)
if isinstance(value, tuple):
errors, reason = value
try:
errors = list(errors)
except TypeError:
errors = [errors]
return Todo(reason=reason, errors=errors)
示例27
def failUnlessFailure(self, deferred, *expectedFailures):
"""
Fail if C{deferred} does not errback with one of C{expectedFailures}.
Returns the original Deferred with callbacks added. You will need
to return this Deferred from your test case.
"""
def _cb(ignore):
raise self.failureException(
"did not catch an error, instead got %r" % (ignore,))
def _eb(failure):
if failure.check(*expectedFailures):
return failure.value
else:
output = ('\nExpected: %r\nGot:\n%s'
% (expectedFailures, str(failure)))
raise self.failureException(output)
return deferred.addCallbacks(_cb, _eb)
示例28
def patch(self, obj, attribute, value):
"""
Monkey patch an object for the duration of the test.
The monkey patch will be reverted at the end of the test using the
L{addCleanup} mechanism.
The L{MonkeyPatcher} is returned so that users can restore and
re-apply the monkey patch within their tests.
@param obj: The object to monkey patch.
@param attribute: The name of the attribute to change.
@param value: The value to set the attribute to.
@return: A L{monkey.MonkeyPatcher} object.
"""
monkeyPatch = monkey.MonkeyPatcher((obj, attribute, value))
monkeyPatch.patch()
self.addCleanup(monkeyPatch.restore)
return monkeyPatch
示例29
def __setattr__(self, name, value):
self.__dict__[name] = value
示例30
def _ebRender(self, failure):
if isinstance(failure.value, Fault):
return failure.value
log.err(failure)
return Fault(self.FAILURE, "error")