[Twisted-Python] Writing unit tests with Trial for Twisted Applications

Travis B. Hartwell slt5v at cc.usu.edu
Wed Oct 1 23:30:19 EDT 2003

Christopher Armstrong <radix at twistedmatrix.com> writes:

> On Wed, Oct 01, 2003 at 08:24:35PM -0600, Travis B. Hartwell wrote:
>> 1.  Does proper testing necessitate or at least include actually
>>     communicating over a port for the client and server?  I see this
>>     is done for the PB tests and several others, but not for many.
> Well, this is actually usually the easiest way to test your code;
> otherwise, you need to deal with crap like fake transports, etc. If
> you do test over the network, make sure you listen on a local-only
> interface (i.e., '') and use a portno of 0. e.g.:
>         self.port = reactor.listenTCP(0, self.svr, interface="")
>         self.portno = self.port.getHost()[-1]
>> 2.  Closely related, what is the proper way to connect the client and
>>     server?  When I made changes, the t.test.test_pb.IOPump that the
>>     tests were using didn't seem to work.  According to spiv, this may
>>     not be the preferred connecting method to use anymore.
> Well, if you do what I said above, then you just need to use regular
> connectTCP(self.portno, fac).

The combination of this answer and the above worked just great.

>> 3.  [moot question deleted]
>> 4.  Regardless of the method used, what is the proper way to have the
>>     reactor keep going until there are no more events?  I need
>>     something analogous to test_pb.IOPump.pump() or flush(), if IOPump
>>     is not to be used.
>>     trial.unittest.TestCase.runReactor()?
> Well, you don't really need "until there are no more events" --
> usually, you just run the reactor until some state is reached, e.g.:
>         while not l:
>             reactor.iterate()

This worked great for some cases.  Sort of.  It doesn't quite
approximate what pump does so I'm a bit at a loss.  I have cases where
I don't know what condition to test, or what I am testing might be the
only condition.  For example:

    def testCacheObjectToClient(self): 
        myObj = SimObject(id=12345)
        myPresence = self.rlm.presences[1]
        # Crank
        assert self.c.localCache[12345], 'Object not received!'

The # Crank comment is where self.pump.flush() was located before.  If
I look based on if there is something in localCache, I would keep
looping if the object was not received.  This is the very thing I am
testing, so when it should fail it would just sit there endlessly
instead of failing.  So what else could I try?


Thanks for the answers to the rest of my questions.  I am slowly
getting this.


More information about the Twisted-Python mailing list