在我的例子中,我收到一个错误'QPixmap:必须在QPaintDevice之前构造一个QApplication'。
如果您需要为测试提供QApplication实例(例如使用QPixmap),这是一种方法。只需创建一个单例,就可以确保只有一个QApplication实例。
这是作为PySide源测试的辅助工具。
import unittest from PySide.QtGui import QApplication _instance = None class UsesQApplication(unittest.TestCase): '''Helper class to provide QApplication instances''' qapplication = True def setUp(self): '''Creates the QApplication instance''' # Simple way of making instance a singleton super(UsesQApplication, self).setUp() global _instance if _instance is None: _instance = QApplication([]) self.app = _instance def tearDown(self): '''Deletes the reference owned by self''' del self.app super(UsesQApplication, self).tearDown()
然后继承UsesQApplication
from PySide import QtGui class Test(UsesQApplication): def setUp(self): #If you override setup, tearDown, make sure #to have a super call super(TestFilterListItem, self).setUp() def tearDown(self): super(TestFilterListItem, self).tearDown() def testName(self): pix = QtGui.QPixmap(20,20) self.assertTrue(True)
希望这可以帮助
我现在一直在玩单元测试pyside代码,并得出结合python的结论 unittest 带qt的模块 QTest 模块工作得很好。
unittest
QTest
你必须有一个 QApplication 对象实例化,但您不需要运行它 exec_ 方法,因为您不需要运行事件循环。
QApplication
exec_
这是一个关于我如何测试a的例子 QCheckBox 在对话框中执行它应该做的事情:
QCheckBox
class Test_PwsAddEntryDialog(TestCase): """Tests the class PwsAddEntryDialog.""" def test_password_strength_checking_works(self): """Tests if password strength checking works, if the corresponding check box is checked. """ d = PwsAddEntryDialog() # test default of internal flag self.assertFalse(d.testPasswordStrength) # type something QTest.keyClicks(d.editSecret, "weak", 0, 10) # make sure that entered text is not treated as a password self.assertEqual(d.labelPasswordStrength.text(), "") # click 'is password' checkbox QTest.mouseClick(d.checkIsPassword, Qt.LeftButton) # test internal flag changed self.assertTrue(d.testPasswordStrength) # test that label now contains a warning self.assertTrue(d.labelPasswordStrength.text().find("too short") > 0) # click checkbox again QTest.mouseClick(d.checkIsPassword, Qt.LeftButton) # check that internal flag once again changed self.assertFalse(d.testPasswordStrength) # make sure warning disappeared again self.assertEqual(d.labelPasswordStrength.text(), "")
这完全适用于屏幕外,包括单击小部件和在文本中键入文本 QLineEdit 。
QLineEdit
这是我测试的方式(相当简单) QAbstractListModel :
QAbstractListModel
class Test_SectionListModel(TestCase): """Tests the class SectionListModel.""" def test_model_works_as_expected(self): """Tests if the expected rows are generated from a sample pws file content. """ model = SectionListModel(SAMPLE_PASSWORDS_DICT) l = len(SAMPLE_PASSWORDS_DICT) self.assertEqual(model.rowCount(None), l) i = 0 for section in SAMPLE_PASSWORDS_DICT.iterkeys(): self.assertEqual(model.data(model.index(i)), section) i += 1
我希望这有点帮助。