我现在一直在玩一些单元测试 pyside 代码,并得出结论,将 python 的unittest
模块与 qt 的QTest
模块结合起来效果很好。
您必须实例化一个QApplication
对象,但您不需要运行它的exec_
方法,因为您不需要运行事件循环。
这是一个示例,说明我如何测试QCheckBox
对话框中的 a 是否执行了它应该执行的操作:
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
.
这是我测试(相当简单)的方法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
我希望这会有所帮助。