如何在pyside unittest中启动事件循环?

时间:2015-05-19 12:53:31

标签: python qt pyside

我试图对涉及信号和QTimers的类进行单元测试。 (见the answer to this question for an idealization of one of the classes)。我很难理解在何处放置app.exec_()调用而不冻结所有内容并使用发出的信号执行测试。就像我引用的问题一样,我认为这里的问题是我需要一个事件循环但是放入setUpClass绝对不行。这是我为重现我的问题所做的最小的代码,实际上是一个更大的代码库。

testSignals.py:

import time
from PySide import QtCore

class TestSignals(QtCore.QObject):

    def __init__(self):
        self.timer = QtCore.QTimer()
        self.myTime = ''
        self.timer.timeout.connect(self.updateTime)
        self.timer.start(100)

    def getTime(self):
        return self.myTime

    def updateTime(self):
        self.myTime = time.strftime('%H:%M:%S')

    def stop(self):
        self.timer.stop()

unitTesting.py:

import unittest
from testSignals import TestSignals 
from PySide import QtGui, QtCore
from testSignals import TestSignals
import sys

class test(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        app = QtGui.QApplication(sys.argv)
        assert id(app) == id(QtGui.qApp) and id(app) == id(QtCore.QCoreApplication.instance())
        cls.test = TestSignals()
        # app.exec_()   # uncommenting this only causes the code to freeze

    def testStarted(self):
        mytime = self.test.getTime()
        self.assertNotEqual(mytime,'','Time is still empty')

if __name__ == '__main__':
    unittest.main()

结果是唯一的测试失败,因为" mytime"仍然是空的。为了清楚起见,课程确实有效:

class testConnection():
    def receiveMe(self):
        print(self.test.getTime())
        # print(self.test.getData())

    # signal is emmited when data is changed
    def __init__(self):
        self.test = TestSignals()
        self.test.timer.timeout.connect(self.receiveMe)
        # self.test.start()

app = QtCore.QCoreApplication([])
test = testConnection()
timer = QtCore.QTimer()
timer.singleShot(4000,app.exit)
app.exec_()

产生

>>>$ python3 testConection.py 
14:50:21
14:50:22
14:50:23
14:50:24

0 个答案:

没有答案