[Twisted-Python] Calling deferToThread from a thread

David Ripton dripton at ripton.net
Thu Sep 18 11:16:23 EDT 2008

On 2008.09.18 10:42:35 +0100, Reza Lotun wrote:
> My issue is this - I'm using py.test for unit testing (I'm aware of
> trial, but for compatibility reasons with the rest of the project I
> haven't looked into using it). To test deferred-based code I have set
> up a separate thread which the reactor runs in (the setup and teardown
> code is shown below for anyone who is interested).

> I see two options:
> 1. In my unit test I write a function f which makes the api call and
> gets the deferred, and sets it to a local variable within the test
> instance. Then I schedule f to run in the reactor thread via
> reactor.callFromThread
> 2. I look into trial which has support for this kind of stuff??

trial has very good support for deferreds.  If your test method returns
a deferred then trial magically does the right thing.  You don't need to
manage the reactor yourself.  See Twisted's docs and unit tests for

trial's API is based on unittest's, which is based on JUnit's.  Works
fine, but it has the Java nature.

I recommend trying nose.  It has support for deferreds, using a
decorator.  And its API is based on the py.test API.  Unfortunately they
chose to spell setup and teardown differently, so you can't use your
py.test test modules unchanged, but the changes are usually trivial.

David Ripton    dripton at ripton.net

More information about the Twisted-Python mailing list