[Twisted-Python] Help with Simple Trial unit test

Shawn Smiley ssmiley483 at yahoo.com
Wed Jan 30 14:45:08 MST 2008


Hi all, 

I recently started learning Python & Twisted in prep for a big project at work.  So far things are going well, except that I can't quite figure out what I'm doing wrong in this simple unit test I'm writing.

One of the features of the project I'll be working on is the implementation of a simple HTTP GET Based communication layer between legacy systems.  As such, I wanted to write a simple unit test that uses the twisted client.getPage() method to test the communication process (i.e. simulates a legacy system requesting data from the server).

I have a test that sort of works.  However, I find that I have to add a reactor.run() command in the unit test for the test to actually be executed.  The unfortunate side affect of this is that you then have to ctrl+C to stop the reactor after the test runs.  If I don't put in the reactor.run() command, I get a "REACTOR UNCLEAN" error message and the test doesn't appear to run (at least the callbacks from getPage() never happen).

What am I doing wrong here?

Also, can you point me at any good references for working with Twisted and Trial?  I have the O'Reily book on Twisted which is a lot of help with the framework itself.  But it doesn't cover trial at all.

All development is occurring on an Ubuntu 7.10 machine using Python 2.5 and Twisted 2.5.

I'm executing the test from the console using: 
"trial ~/workspace/TestProject/src/tests/HttpGetTests.py"

Here is the source code for my test:

from twisted.trial import unittest
from twisted.internet import stdio, reactor, protocol, defer
from twisted.protocols import basic
from twisted.web import client

class HttpGetTests(unittest.TestCase):
    
    def testReportHit(self):
        def _handleError(reason):
            print "\n====>HttpGetTests.testReportHit()._handleError(): reason=%s\n" % reason
            self.fail("Test failed.  reason=%s" % reason)
        
        def _handleSuccess(data):
            print "\n====>HttpGetTests.testReportHit()._handleSuccess():\n"
            self.assert_(data.count>0, "No data returned")

        d = client.getPage("http://www.google.com")
        d.addCallback(_handleSuccess)
        d.addErrback(_handleError)
        reactor.run()





      ____________________________________________________________________________________
Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  http://tools.search.yahoo.com/newsearch/category.php?category=shopping




More information about the Twisted-Python mailing list