1

我对扭曲很陌生,我正在尝试使用试用测试框架编写一些单元测试。我的测试按预期运行并通过,但由于某种原因,测试在测试之间挂起。我必须在每次测试后点击CTRL+C 才能让它进入下一个测试。我猜我的某些配置不正确,或者我没有调用一些我应该告诉试验测试已经完成的方法。

这是正在测试的类:

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)

这是单元测试类:

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)

这是命令行输出的样子:

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

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

PASSED (successes=2)
4

1 回答 1

1

你的问题与你的线程有关。Twisted 不是线程安全的,如果你需要与线程交互,你应该让反应器使用deferToThread, callInThread,来处理事情callFromThread。有关如何使用 Twisted 实现线程安全的信息,请参见此处。

于 2012-04-15T18:09:00.810 回答