问题
I have a pyqt application and like to test scripts for testing this application.
I was able to build the qapplication during my standalone testing. Not sure how to create this object while writing my unittestcases using pytest.
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout, QLabel, QLineEdit
class Example(QDialog):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.initUI()
def initUI(self):
grid = QGridLayout(self)
a1 = QLabel('alphanumeric characters')
a2 = QLabel('alphanumeric characters')
grid.addWidget(QLabel('Name'), 0, 0)
grid.addWidget(QLineEdit(), 0, 1)
grid.addWidget(QLabel('Street1'), 1, 0)
grid.addWidget(QLineEdit(), 1, 1)
grid.addWidget(QLabel('Street2'), 2, 0)
grid.addWidget(QLineEdit(), 2, 1)
grid.addWidget(QLabel('City'), 3, 0)
grid.addWidget(QLineEdit(), 3, 1)
grid.addWidget(QLabel('only alphanumeric'), 0, 2, 4, 1)
self.setGeometry(500, 500, 500, 500)
self.setWindowTitle('Lines')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
# ex.show()
sys.exit(app.exec_())
Unittest:-
import unittest
import same_label
class Test(unittest.TestCase):
def setUp(self):
ex = same_label.Example()
def tearDown(self):
pass
def testName(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Error:-
QWidget: Must construct a QApplication before a QWidget
回答1:
A QApplication must be created before creating any widget since it handles the eventloop
import unittest
import same_label
import sys
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
class Test(unittest.TestCase):
def setUp(self):
ex = same_label.Example()
def tearDown(self):
pass
def testName(self):
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
In the following link there is an example: http://johnnado.com/pyqt-qtest-example/, another option is to use the pytest-qt package
来源:https://stackoverflow.com/questions/51487226/testing-pyqt-application-qwidget-must-construct-a-qapplication-before-a-qwidg