Question

I just inherited some unit tests around Twisted Python, as shown below.

While the test works, I don't understand it conceptually.

Given the example below, can someone please explain the following things about it?

  • Why does this unit test 'return page'?
  • Why aren't there any calls to reactor.start()?
  • Any comments about the pros/cons of this approach, and perhaps others I could consider?

def setUp(self):
    self.listening_port = reactor.listenTCP(8118, server.Site(buildSite()))        

def tearDown(self):
    self.listening_port.stopListening()

def getUrl(self, extension=''):
    return 'http://localhost:%s/%s' % (self.listening_port.getHost().port, extension)

 def test(self):
     url = self.getUrl('foo')        
     def printResult(result):
         print result        
     page = getPage(url, method='POST').addCallback(printResult)
     return page
Was it helpful?

Solution

Why does this unit test 'return page'?

Well, it's not very clean. Twisted's Trial unittest expect Deferred as result, with assert as callback. Here the callback is printResult, thus it will be evaluated to true for any non-empty string. I think more properly it should be:

page = getPage(url, method='POST').addCallback(self.assertTrue)

or

page = getPage(url, method='POST').addCallback(self.assertIsNotNone)

Why aren't there any calls to reactor.start()?

Because TestCase class takes care of that. And it's also not using standard reactor.

Since unit tests are avoiding real I/O and real time, they can usually avoid using a real reactor. The only exceptions to this are unit tests for a real reactor implementation. Unit tests for protocol implementations or other application code should not use a reactor. Unit tests for real reactor implementations should not use the global reactor, but should instead use twisted.internet.test.reactormixins.ReactorBuilder so they can be applied to all of the reactor implementations automatically. In no case should new unit tests use the global reactor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top