I'm trying to make unit tests on classes that involve signals and QTimers. (see the answer to this question for an idealization of one of the classes). I'm having a hard time trying to understand where to put the app.exec_() call without freezing everything and executing the tests with the signals being emitted. Just like in the question I cite, I think the problem here is that I need an event loop but putting in the setUpClass definitely doesn't work. This is the smallest piece of code I made to reproduce my problem, which in reality is with a larger code base.
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()
and the result is a failure of the only test because "mytime" is still empty. Just for clarity, the class does work:
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_()
produces:
>>>$ python3 testConection.py
14:50:21
14:50:22
14:50:23
14:50:24