Question

I'm pretty new to twisted and I'm attempting to write some unit tests using the trial test framework. My tests run and pass as expected, but for some reason trial is hanging between tests. I have to hit CTRL+C after each test to get it to move on to the next one. I'm guessing I have something configured incorrectly or I'm not calling some method I should be to tell trial the test is done.

Here is the class under test:

from twisted.internet import reactor, defer
import threading
import time


class SomeClass:
   def doSomething(self):
      return self.asyncMethod()

   def asyncMethod(self):
       d = defer.Deferred()
       t = SomeThread(d)
       t.start()
       return d


class SomeThread(threading.Thread):
    def __init__(self, d):
        super(SomeThread, self).__init__()
        self.d = d

    def run(self):
        time.sleep(2) # pretend to do something
        retVal = 123
        self.d.callback(retVal)

Here is the unit test class:

from twisted.trial import unittest
import tested


class SomeTest(unittest.TestCase):
    def testOne(self):
        sc = tested.SomeClass()
        d = sc.doSomething()
        return d.addCallback(self.allDone)

    def allDone(self, retVal):
        self.assertEquals(retVal, 123)

    def testTwo(self):
        sc = tested.SomeClass()
        d = sc.doSomething()
        return d.addCallback(self.allDone2)

    def allDone2(self, retVal):
        self.assertEquals(retVal, 123)

This is what the command line output looks like:

me$ trial test.py 
test
  SomeTest
    testOne ... ^C                                                           [OK]
    testTwo ... ^C                                                           [OK]

-------------------------------------------------------------------------------
Ran 2 tests in 8.499s

PASSED (successes=2)
Was it helpful?

Solution

I guess your problem has to do with your threads. Twisted is not thread-safe, and if you need to interface with threads you should let the reactor handle things by using deferToThread, callInThread, callFromThread. See here for info on how to be thread-safe with Twisted.

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