如何在pysideunittest中启动事件循环?

2024-04-26 18:03:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试对涉及信号和qtimer的类进行单元测试。(见the answer to this question for an idealization of one of the classes)。我很难理解把应用程序执行_()调用时不冻结所有内容,并在发出信号的情况下执行测试。就像我引用的问题一样,我认为这里的问题是我需要一个事件循环,但是放入setUpClass肯定行不通。这是我为重现我的问题而制作的最小的一段代码,实际上它的代码基数更大。在

在测试信号.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()

在单元测试.py公司名称:

^{pr2}$

结果是唯一的测试失败了,因为“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

Tags: ofthe代码pytestself名称app