简体   繁体   English

如何使用 Python 和 PyQt 对我的 GUI 程序进行单元测试?

[英]How do I unit testing my GUI program with Python and PyQt?

I heard Unit Testing is a great method to keep code working correctly.我听说单元测试是保持代码正常工作的好方法。

The unit testing usually puts a simple input to a function, and check its simple output.单元测试通常将一个简单的输入放入一个函数,并检查它的简单输出。 But how do I test a UI?但是我如何测试 UI?

My program is written in PyQt.我的程序是用 PyQt 编写的。 Should I choose PyUnit, or Qt's built-in QTest?我应该选择 PyUnit 还是 Qt 的内置 QTest?

There's a good tutorial about using Python's unit testing framework with QTest here .有一个关于使用Python的单元测试框架,QTEST一个很好的教程在这里

It isn't about choosing one or the other.这不是关于选择一个或另一个。 Instead, it's about using them together.相反,它是关于将它们一起使用。 The purpose of QTest is only to simulate keystrokes, mouse clicks, and mouse movement. QTest 的目的只是模拟击键、鼠标点击和鼠标移动。 Python's unit testing framework handles the rest (setup, teardown, launching tests, gathering results, etc.). Python 的单元测试框架处理其余的(设置、拆卸、启动测试、收集结果等)。

As another option there is also pytest-qt if you prefer working with pytest :作为另一种选择,如果您更喜欢使用pytest还有pytest-qt

https://pytest-qt.readthedocs.io/en/latest/intro.html https://pytest-qt.readthedocs.io/en/latest/intro.html

It lets you test pyqt and pyside applications and allows the simulation of user interaction.它允许您测试pyqtpyside应用程序,并允许模拟用户交互。 Here is a small example from its documentation:这是其文档中的一个小示例:

def test_hello(qtbot):
    widget = HelloWidget()
    qtbot.addWidget(widget)

    # click in the Greet button and make sure it updates the appropriate label
    qtbot.mouseClick(widget.button_greet, QtCore.Qt.LeftButton)

    assert widget.greet_label.text() == "Hello!"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM