This module provides a very simple way to integrate your tests with the Twisted event loop.
You must import this module before importing anything from Twisted itself!
from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): return reactor.resolve("www.python.org")
Or, more realistically:
@deferred(timeout=5.0) def test_resolve(): d = reactor.resolve("www.python.org") def check_ip(ip): assert ip == "22.214.171.124" d.addCallback(check_ip) return d
Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done.
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.
@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")
Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You must do this if you mix tests using these tools and tests using twisted.trial.