我现在正在尝试对pyside代码进行单元测试,并得出结论:将python的unittest
模块与qt的QTest
模块相结合效果不错。
您需要实例化一个QApplication
对象,但不需要运行其exec_
方法,因为您不需要运行事件循环。
下面是我测试对话框中的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()
self.assertFalse(d.testPasswordStrength)
QTest.keyClicks(d.editSecret, "weak", 0, 10)
self.assertEqual(d.labelPasswordStrength.text(), "")
QTest.mouseClick(d.checkIsPassword, Qt.LeftButton)
self.assertTrue(d.testPasswordStrength)
self.assertTrue(d.labelPasswordStrength.text().find("too short") > 0)
QTest.mouseClick(d.checkIsPassword, Qt.LeftButton)
self.assertFalse(d.testPasswordStrength)
self.assertEqual(d.labelPasswordStrength.text(), "")
这完全可以在屏幕外运行,涉及单击小部件并在 QLineEdit
中输入文本。
以下是我如何测试一个(相当简单的)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
我希望这能有所帮助。