[Twisted-Python] Trial: Blocking until all deferreds have fired in test

Terry Jones terry at jon.es
Fri Sep 25 17:25:59 EDT 2009

Hi Mark.

I'd write your FooListener class like this (untested):

class FooListener(object):
    def fooBar():
        d = doSomeSetup()
        d.addCallback(lambda ign: doSomethingThatReturnsADeferred())
        d.addCallbacks(lambda ign: 'success!', lambda ign: 'failure!')
        return d

And leave your unit test as is. Then the unit test (with the yield on
fooBar() will do the right thing. And your other (non-test) code will
continue to get what it was getting before.

BTW, it's a slight red flag (to me) that you're returning the 'failure!'
string as the value of the deferred (i.e., if an error happens, that
errback function returns a string, which is going to get you back onto the
callback chain in the deferred - since you're not raising or returning a
failure).  I say it's a red flag because I tried stuff like that once and
later realized that things are much cleaner if you just let Twisted handle
errors in it's normal way. To do so you could just drop the addErrback
above and let any error flow back to the caller of fooBar in the normal way
(on the errback chain) rather than trying to catch problems and return a
result on the callback chain that indicates an error (i.e., a string like

Hope that helps.


More information about the Twisted-Python mailing list