def deferred(timeout=None):
reactor, reactor_thread = threaded_reactor()<EOL>if reactor is None:<EOL><INDENT>raise ImportError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>timeout is None or timeout + <NUM_LIT:0><EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>def decorate(func):<EOL><INDENT>def wrapper(*args, **kargs):<EOL><INDENT>q = Queue()<EOL>def callback(value):<EOL><INDENT>q.put(None)<EOL><DEDENT>def errback(failure):<EOL><INDENT>try:<EOL><INDENT>failure.raiseException()<EOL><DEDENT>except:<EOL><INDENT>q.put(sys.exc_info())<EOL><DEDENT><DEDENT>def g():<EOL><INDENT>try:<EOL><INDENT>d = func(*args, **kargs)<EOL>try:<EOL><INDENT>d.addCallbacks(callback, errback)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TypeError("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT><DEDENT>except:<EOL><INDENT>q.put(sys.exc_info())<EOL><DEDENT><DEDENT>reactor.callFromThread(g)<EOL>try:<EOL><INDENT>error = q.get(timeout=timeout)<EOL><DEDENT>except Empty:<EOL><INDENT>raise TimeExpired("<STR_LIT>"<EOL>% timeout)<EOL><DEDENT>if error is not None:<EOL><INDENT>exc_type, exc_value, tb = error<EOL>raise exc_type(exc_value).with_traceback(tb)<EOL><DEDENT><DEDENT>wrapper = make_decorator(func)(wrapper)<EOL>return wrapper<EOL><DEDENT>return decorate<EOL>
By wrapping a test function with this decorator, you can return a
twisted Deferred and the test will wait for the deferred to be triggered.
The whole test function will run inside the Twisted event loop.

The optional timeout parameter specifies the maximum duration of the test.
The difference with timed() is that timed() will still wait for the test
to end, while deferred() will stop the test when its timeout has expired.
The latter is more desireable when dealing with network tests, because
the result may actually never arrive.

If the callback is triggered, the test has passed.
If the errback is triggered or the timeout expires, the test has failed.

Example::

    @deferred(timeout=5.0)
    def test_resolve():
        return reactor.resolve("www.python.org")

Attention! If you combine this decorator with other decorators (like
"raises"), deferred() must be called *first*!

In other words, this is good::

    @raises(DNSLookupError)
    @deferred()
    def test_error():
        return reactor.resolve("xxxjhjhj.biz")

and this is bad::

    @deferred()
    @raises(DNSLookupError)
    def test_error():
        return reactor.resolve("xxxjhjhj.biz")