[Dev] Mock Reactor for tests?
Phillip J. Eby
pje at telecommunity.com
Tue Jun 7 16:39:46 PDT 2005
At 11:55 AM 6/7/2005 -0700, Heikki Toivonen wrote:
> > By the way, if you are doing assertions in code that is called by the
> > reactor, this may be a bit of a problem; the reactor expects to log all
> > such errors, and doesn't pass them on anywhere. So, you would
> > definitely need for all your assertions to be in your test method itself
> > (i.e. *after* the waitFor/waitUntil)
>
>Uh oh. Well that could be a problem. Unit tests typically want to do
>lots of asserts all over the place.
Well, you could just do:
result = defer.Deferred()
def whatever(...): # code that's called by reactor
try:
#
#
#
# lots of test code here that includes asserts
#
#
#
except:
result.errback() # save any errors for later
else:
result.callback(return_value) # send data back to caller
return_value = reactor.waitUntil(result, timeout)
# more asserts on return_value, or run more reactor-based code
When the 'waitUntil' returns, it will re-raise the assertion error sent by
errback() if there was one, otherwise it will return the value sent by
callback().
A Deferred is a conduit for communicating errors or return values. So, you
just have to send your errors or failures over such a conduit to get them
back into the test method. This is the sort of use case I had in mind for
deferreds and waitUntil().
>How would you see this file would need to change to run two tests with
>twisted in it?
>
>http://lxr.osafoundation.org/m2crypto/source/tests/test_ssl.py
These are high-level integration tests, not unit tests, so it's hard to
say. The test reactor isn't going to help with this kind of testing. If I
were trying to unit test the wrappers that it appears to be testing, I
would do it without starting another process, and possibly without any
socket activity involved, testing only that the wrapper makes the right
calls or sends/receives the right data in response to those
operations. However, if the component was not designed for testability,
such tests might be difficult to create.
More information about the Dev
mailing list