How to simplify life (that is, we read the code) using @inlineCallbacks .
In fact, I even went so far as to suggest not using Deferred directly if it is absolutely necessary for performance or in a specific use case, but instead always stick with @inlineCallbacks - this way I will keep your code like normal code, while still getting advantage of non-blocking behavior:
from twisted.internet import reactor from twisted.web.client import Agent from twisted.internet.defer import inlineCallbacks from twisted.trial import unittest from twisted.web.http_headers import Headers from twisted.internet.error import DNSLookupError class SomeTestCase(unittest.TestCase): @inlineCallbacks def test_smth(self): ag = Agent(reactor) response = yield ag.request('GET', 'http://example.com/', Headers({'User-Agent': ['Twisted Web Client Example']}), None) self.assertEquals(response.code, 200) @inlineCallbacks def test_exception(self): ag = Agent(reactor) try: yield ag.request('GET', 'http://exampleeee.com/', Headers({'User-Agent': ['Twisted Web Client Example']}), None) except DNSLookupError: pass else: self.fail()
The trial should take care of the rest (i.e. waiting on Deferred returned from the test functions ( @inlineCallbacks broken calls also “magically” return Deferred - I highly recommend reading more on @inlineCallbacks if you are not already familiar with it).
PS There is also a Twisted “plug-in” for media that allows you to return Deferred from your test functions and wait for your nose to be fired before exiting: http://nose.readthedocs.org/en/latest/api/ twistedtools.html
source share