Trial adbapi tip. Was: [Twisted-Python] The Trial of the DirtyReactorError
daedalus at eigenmagic.com
Thu Apr 12 19:35:41 EDT 2007
On Thu, 2007-04-12 at 17:53 +0100, Matthew Glubb wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> Hi All,
> I have to say that I am largely getting along famously with Twisted
> (and Python) now.
> I have started writing unit tests for my application and when I run
> them using trial I sometimes get DirtyReactorErrors ('reactor left in
> unclean state'). This is a nice error. It tells me that I am not
> shutting down resources correctly which would otherwise be left
> hanging around and be difficult to debug.
On this note, I have a little tip to anyone new to writing Trial tests,
as I am:
If you use adbapi to talk to a database, be aware that it uses a
threadpool in order to make something that is synchronous into something
asynchronous. In an ordinary program, the threadpool is started and shut
down for you by the reactor, but it probably won't be in your tests
because of the way the reactor works with trial. I am using a
twisted.enterprise.adbapi.ConnectionPool, for example.
What you need is to call ConnectionPool.start() from within your
unittest setUp(), and to call ConnectionPool.close() in tearDown(). This
explicitly starts and stops the threadpool at the appropriate times.
>From memory, the start() will kindof automatically get called when you
set up the object, but close() will not. If you don't explicitly call
close(), trial will 'hang' because it's actually waiting for the
threadpool to exit, which never happens. You don't get a 'reactor left
in unclean state' error.
I hope that saves someone the couple of hours of head scratching and
reading code that I went through.
Justin Warren <daedalus at eigenmagic.com>
More information about the Twisted-Python